@swishapp/sdk 0.91.0 → 0.98.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.
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import { IntentHandler } from "../intent-handler";
|
|
3
|
+
import { IntentResponse, SuccessIntentResponse } from "../types";
|
|
4
|
+
export declare const OpenOrderMenuIntentDataSchema: v.ObjectSchema<{
|
|
5
|
+
readonly orderId: v.StringSchema<undefined>;
|
|
6
|
+
}, undefined>;
|
|
7
|
+
export type OpenOrderMenuIntentData = v.InferInput<typeof OpenOrderMenuIntentDataSchema>;
|
|
8
|
+
export type OpenOrderMenuSuccessResponse = SuccessIntentResponse<void>;
|
|
9
|
+
export declare class OpenOrderMenuHandler extends IntentHandler<"open:order-menu"> {
|
|
10
|
+
invoke(data: OpenOrderMenuIntentData): Promise<IntentResponse<"open:order-menu">>;
|
|
11
|
+
}
|
package/dist/intents/types.d.ts
CHANGED
|
@@ -19,8 +19,9 @@ import { OpenProfileSuccessResponse } from "./handlers/open-profile-handler";
|
|
|
19
19
|
import { OpenListIntentData, OpenListSuccessResponse } from "./handlers/open-list-handler";
|
|
20
20
|
import { OpenProductIntentData, OpenProductSuccessResponse } from "./handlers/open-product-handler";
|
|
21
21
|
import { OpenOrderIntentData, OpenOrderSuccessResponse } from "./handlers/open-order-handler";
|
|
22
|
+
import type { OpenOrderMenuIntentData, OpenOrderMenuSuccessResponse } from "./handlers/open-order-menu-handler";
|
|
22
23
|
export type { DeleteItemSuccessResponse, EditItemVariantSuccessResponse, EditItemListsSuccessResponse, SaveItemSuccessResponse, EditListSuccessResponse, DeleteListSuccessResponse, CreateListSuccessResponse, ToastSuccessResponse, };
|
|
23
|
-
export type Intent = "save:item" | "edit:item-variant" | "edit:item-lists" | "delete:item" | "edit:list" | "delete:list" | "create:list" | "open:home" | "open:list" | "open:lists" | "open:orders" | "open:order" | "open:saves" | "open:notifications" | "open:profile" | "open:product" | "open:list-menu" | "open:list-detail-page-menu" | "open:sign-in" | "open:quick-buy" | "show:toast";
|
|
24
|
+
export type Intent = "save:item" | "edit:item-variant" | "edit:item-lists" | "delete:item" | "edit:list" | "delete:list" | "create:list" | "open:home" | "open:list" | "open:lists" | "open:orders" | "open:order" | "open:saves" | "open:notifications" | "open:profile" | "open:product" | "open:list-menu" | "open:order-menu" | "open:list-detail-page-menu" | "open:sign-in" | "open:quick-buy" | "show:toast";
|
|
24
25
|
export type IntentQueryParam = `${string}=${string}`;
|
|
25
26
|
export type IntentQueryWithParams = `${Intent},${IntentQueryParam}`;
|
|
26
27
|
export type IntentResponse<I extends Intent = Intent> = ClosedIntentResponse<I> | ErrorIntentResponse<I> | IntentToSuccessResponse<I>;
|
|
@@ -64,6 +65,7 @@ interface IntentDataMap {
|
|
|
64
65
|
"open:profile": void;
|
|
65
66
|
"open:product": OpenProductIntentData;
|
|
66
67
|
"open:list-menu": OpenListMenuIntentData;
|
|
68
|
+
"open:order-menu": OpenOrderMenuIntentData;
|
|
67
69
|
"open:list-detail-page-menu": OpenListDetailPageMenuIntentData;
|
|
68
70
|
"open:sign-in": OpenSignInIntentData | undefined;
|
|
69
71
|
"open:quick-buy": OpenQuickBuyIntentData;
|
|
@@ -87,6 +89,7 @@ interface IntentSuccessResponseMap {
|
|
|
87
89
|
"open:profile": OpenProfileSuccessResponse;
|
|
88
90
|
"open:product": OpenProductSuccessResponse;
|
|
89
91
|
"open:list-menu": OpenListMenuSuccessResponse;
|
|
92
|
+
"open:order-menu": OpenOrderMenuSuccessResponse;
|
|
90
93
|
"open:list-detail-page-menu": OpenListDetailPageMenuSuccessResponse;
|
|
91
94
|
"open:sign-in": OpenSignInSuccessResponse;
|
|
92
95
|
"open:quick-buy": OpenQuickBuySuccessResponse;
|
package/dist/options/types.d.ts
CHANGED
|
@@ -65,6 +65,8 @@ export interface SwishComponentOptions {
|
|
|
65
65
|
export interface SwishListDetailPageOptions {
|
|
66
66
|
desktopColumns: number;
|
|
67
67
|
showBuyButton: boolean;
|
|
68
|
+
showVariantOptionNames: boolean;
|
|
69
|
+
enableVariantChange: boolean;
|
|
68
70
|
}
|
|
69
71
|
export interface SwishProductRowOptions {
|
|
70
72
|
showVariantTitle: boolean;
|
|
@@ -104,6 +106,10 @@ export interface SwishDrawerMiniMenuItem {
|
|
|
104
106
|
export interface SwishDrawerMiniMenuOptions {
|
|
105
107
|
items: SwishDrawerMiniMenuItem[];
|
|
106
108
|
}
|
|
109
|
+
export interface SwishDrawerListDetailViewOptions {
|
|
110
|
+
enableVariantChange: boolean;
|
|
111
|
+
showVariantOptionNames: boolean;
|
|
112
|
+
}
|
|
107
113
|
export interface SwishDrawerLogoOptions {
|
|
108
114
|
url: string;
|
|
109
115
|
altText: string;
|
|
@@ -113,4 +119,5 @@ export interface SwishDrawerOptions {
|
|
|
113
119
|
logo: SwishDrawerLogoOptions;
|
|
114
120
|
navigation: SwishDrawerNavigationOptions;
|
|
115
121
|
miniMenu: SwishDrawerMiniMenuOptions;
|
|
122
|
+
listDetailView: SwishDrawerListDetailViewOptions;
|
|
116
123
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { StorefrontContext, SwishUiOptions } from "../options/types";
|
|
2
2
|
import type { SwishUiElement } from "./swish-ui-element";
|
|
3
|
-
import { DeleteListAlertOptions, DrawerOptions, ListDetailPageOptions, ListDetailPageMenuOptions, ListEditorOptions, ListEditorSubmitData, ListMenuOptions, ListMenuResponse, ListSelectOptions, ListSelectResponse, QuickBuyOptions, QuickBuySubmitData, RequireUiComponentOptions, SignInOptions, Toast, UiResponse, UnsaveAlertOptions, UnsaveAlertSubmitData, VariantSelectOptions, VariantSelectSubmitData } from "./types";
|
|
3
|
+
import { DeleteListAlertOptions, DrawerOptions, ListDetailPageOptions, ListDetailPageMenuOptions, ListEditorOptions, ListEditorSubmitData, ListMenuOptions, ListMenuResponse, ListSelectOptions, ListSelectResponse, OrderMenuOptions, OrderMenuResponse, QuickBuyOptions, QuickBuySubmitData, RequireUiComponentOptions, SignInOptions, Toast, UiResponse, UnsaveAlertOptions, UnsaveAlertSubmitData, VariantSelectOptions, VariantSelectSubmitData } from "./types";
|
|
4
4
|
export declare class SwishUi {
|
|
5
5
|
private storefrontContext;
|
|
6
6
|
private swishUiOptions;
|
|
@@ -17,6 +17,7 @@ export declare class SwishUi {
|
|
|
17
17
|
showDeleteListAlert(options: DeleteListAlertOptions): Promise<UiResponse<void>>;
|
|
18
18
|
showDrawer(options?: DrawerOptions): Promise<UiResponse<void>>;
|
|
19
19
|
showListMenu(options: ListMenuOptions): Promise<ListMenuResponse>;
|
|
20
|
+
showOrderMenu(options: OrderMenuOptions): Promise<OrderMenuResponse>;
|
|
20
21
|
showListDetailPageMenu(options: ListDetailPageMenuOptions): Promise<UiResponse<void>>;
|
|
21
22
|
showListSelect(options: ListSelectOptions): Promise<ListSelectResponse>;
|
|
22
23
|
initListDetailPage(options: ListDetailPageOptions, refElement: HTMLElement): Promise<void>;
|
package/dist/swish-ui/types.d.ts
CHANGED
|
@@ -48,6 +48,9 @@ export interface DrawerOptions {
|
|
|
48
48
|
export interface ListMenuOptions {
|
|
49
49
|
listId: string;
|
|
50
50
|
}
|
|
51
|
+
export interface OrderMenuOptions {
|
|
52
|
+
orderId: string;
|
|
53
|
+
}
|
|
51
54
|
export type ListEditorSubmitData = ExtractSuccessData<EditListSuccessResponse>;
|
|
52
55
|
export type ListMenuResponse = UiResponse<{
|
|
53
56
|
action: "edit";
|
|
@@ -55,6 +58,7 @@ export type ListMenuResponse = UiResponse<{
|
|
|
55
58
|
} | {
|
|
56
59
|
action: "delete";
|
|
57
60
|
}>;
|
|
61
|
+
export type OrderMenuResponse = UiResponse<void>;
|
|
58
62
|
export interface ListDetailPageMenuOptions {
|
|
59
63
|
listId: string;
|
|
60
64
|
}
|
package/dist/swish.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var
|
|
1
|
+
var wr=Object.create;var ot=Object.defineProperty;var br=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var Er=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var s=(n,e)=>ot(n,"name",{value:e,configurable:!0});var Cr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var kr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Sr(e))!xr.call(n,i)&&i!==t&&ot(n,i,{get:()=>e[i],enumerable:!(r=br(e,i))||r.enumerable});return n};var Rr=(n,e,t)=>(t=n!=null?wr(Er(n)):{},kr(e||!n||!n.__esModule?ot(t,"default",{value:n,enumerable:!0}):t,n));var mr=Cr((hc,hr)=>{"use strict";var ls=(function(){function n(t,r){if(typeof t!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+t+"."));this._batchLoadFn=t,this._maxBatchSize=fs(r),this._batchScheduleFn=hs(r),this._cacheKeyFn=ms(r),this._cacheMap=ys(r),this._batch=null,this.name=vs(r)}s(n,"DataLoader");var e=n.prototype;return e.load=s(function(r){if(r==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(r)+"."));var i=ps(this),o=this._cacheMap,u;if(o){u=this._cacheKeyFn(r);var a=o.get(u);if(a){var l=i.cacheHits||(i.cacheHits=[]);return new Promise(function(p){l.push(function(){p(a)})})}}i.keys.push(r);var c=new Promise(function(p,h){i.callbacks.push({resolve:p,reject:h})});return o&&o.set(u,c),c},"load"),e.loadMany=s(function(r){if(!fr(r))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+r+"."));for(var i=[],o=0;o<r.length;o++)i.push(this.load(r[o]).catch(function(u){return u}));return Promise.all(i)},"loadMany"),e.clear=s(function(r){var i=this._cacheMap;if(i){var o=this._cacheKeyFn(r);i.delete(o)}return this},"clear"),e.clearAll=s(function(){var r=this._cacheMap;return r&&r.clear(),this},"clearAll"),e.prime=s(function(r,i){var o=this._cacheMap;if(o){var u=this._cacheKeyFn(r);if(o.get(u)===void 0){var a;i instanceof Error?(a=Promise.reject(i),a.catch(function(){})):a=Promise.resolve(i),o.set(u,a)}}return this},"prime"),n})(),cs=typeof process=="object"&&typeof process.nextTick=="function"?function(n){Gt||(Gt=Promise.resolve()),Gt.then(function(){process.nextTick(n)})}:typeof setImmediate=="function"?function(n){setImmediate(n)}:function(n){setTimeout(n)},Gt;function ps(n){var e=n._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<n._maxBatchSize)return e;var t={hasDispatched:!1,keys:[],callbacks:[]};return n._batch=t,n._batchScheduleFn(function(){ds(n,t)}),t}s(ps,"getCurrentBatch");function ds(n,e){if(e.hasDispatched=!0,e.keys.length===0){jt(e);return}var t;try{t=n._batchLoadFn(e.keys)}catch(r){return Ft(n,e,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(r)+".")))}if(!t||typeof t.then!="function")return Ft(n,e,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(t)+".")));t.then(function(r){if(!fr(r))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(r)+"."));if(r.length!==e.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
|
|
2
2
|
|
|
3
3
|
Keys:
|
|
4
4
|
`+String(e.keys))+(`
|
|
5
5
|
|
|
6
6
|
Values:
|
|
7
|
-
`+String(r)));Mt(e);for(var i=0;i<e.callbacks.length;i++){var o=r[i];o instanceof Error?e.callbacks[i].reject(o):e.callbacks[i].resolve(o)}}).catch(function(r){Ft(n,e,r)})}s(cs,"dispatchBatch");function Ft(n,e,t){Mt(e);for(var r=0;r<e.keys.length;r++)n.clear(e.keys[r]),e.callbacks[r].reject(t)}s(Ft,"failedDispatch");function Mt(n){if(n.cacheHits)for(var e=0;e<n.cacheHits.length;e++)n.cacheHits[e]()}s(Mt,"resolveCacheHits");function ps(n){var e=!n||n.batch!==!1;if(!e)return 1;var t=n&&n.maxBatchSize;if(t===void 0)return 1/0;if(typeof t!="number"||t<1)throw new TypeError("maxBatchSize must be a positive number: "+t);return t}s(ps,"getValidMaxBatchSize");function ds(n){var e=n&&n.batchScheduleFn;if(e===void 0)return us;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}s(ds,"getValidBatchScheduleFn");function fs(n){var e=n&&n.cacheKeyFn;if(e===void 0)return function(t){return t};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}s(fs,"getValidCacheKeyFn");function hs(n){var e=!n||n.cache!==!1;if(!e)return null;var t=n&&n.cacheMap;if(t===void 0)return new Map;if(t!==null){var r=["get","set","delete","clear"],i=r.filter(function(o){return t&&typeof t[o]!="function"});if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return t}s(hs,"getValidCacheMap");function ms(n){return n&&n.name?n.name:null}s(ms,"getValidName");function dr(n){return typeof n=="object"&&n!==null&&typeof n.length=="number"&&(n.length===0||n.length>0&&Object.prototype.hasOwnProperty.call(n,n.length-1))}s(dr,"isArrayLike");fr.exports=as});var x=s(n=>n.split("/").pop()??"","shopifyGidToId"),E=s((n,e)=>`gid://shopify/${n}/${e}`,"shopifyIdToGid"),j=s(n=>n.toLowerCase().replace(".myshopify.com",""),"toShopName");var X=class{constructor(e,t,r=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=t,this.keyPrefix=r}static{s(this,"FetchCache")}async get(e){try{let t=await caches.open(this.cacheName),r=await t.match(e);if(r&&this.isExpired(r)){await t.delete(e);return}return r}catch(t){console.warn("Cache get error:",t);return}}async set(e,t,r){try{if(r?.includes("no-cache"))return;let i=this.createCacheableResponse(t,r);await(await caches.open(this.cacheName)).put(e,i)}catch(i){console.warn("Cache set error:",i)}}async fetchWithCache(e,t,r){let i=await this.getCacheKey(e,t);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(i))return this.inFlightRequests.get(i).then(u=>u.clone());let o=(async()=>{let u=await this.get(i);if(u)return this.isStaleButRevalidatable(u)&&this.revalidateInBackground(i,e,t,r),u.clone();let a=await fetch(e,t);return a.ok&&await this.set(i,a.clone(),r??this.defaultCacheControl),a})().finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,o),o}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(t){return console.warn("Cache delete error:",t),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,t)=>{try{let r=await caches.open(this.cacheName),i=await r.keys();await Promise.all(i.map(o=>r.delete(o))),e()}catch(r){console.warn("Cache clear error:",r),t(r)}}),this.clearCachePromise.then(()=>{this.clearCachePromise=null}).catch(e=>{console.warn("Cache clear error:",e)}))}async keys(){try{return(await(await caches.open(this.cacheName)).keys()).map(r=>r.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let t=await caches.open(this.cacheName),r=await t.match(e);return r&&this.isExpired(r)?(await t.delete(e),!1):r!==void 0}catch(t){return console.warn("Cache has error:",t),!1}}async getStats(){try{return{total:(await(await caches.open(this.cacheName)).keys()).length}}catch(e){return console.warn("Cache stats error:",e),{total:0}}}async cleanupExpiredEntries(){try{let e=await caches.open(this.cacheName),t=await e.keys(),r=0;for(let o of t){let u=await e.match(o);u&&this.isExpired(u)&&(await e.delete(o),r++)}let i=t.length-r;return{removed:r,remaining:i}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,t){let r=this.getInputUrl(e),i=`${this.keyPrefix}${r}/${JSON.stringify(t)}`,u=new TextEncoder().encode(i),a=await crypto.subtle.digest("SHA-256",u);return`/${Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")}`}getInputUrl(e){return e instanceof URL?e.toString():typeof e=="string"?e:e.url}isExpired(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(r===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let u=new Date(o).getTime(),l=(Date.now()-u)/1e3,c=r+(i??0);return l>c}isStaleButRevalidatable(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(r===null||i===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let u=new Date(o).getTime(),l=(Date.now()-u)/1e3;return l>r&&l<=r+i}async revalidateInBackground(e,t,r,i){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let u=await fetch(t,r);u.ok&&await this.set(e,u.clone(),i??this.defaultCacheControl)}catch(u){console.warn("Background revalidation error:",u)}finally{this.revalidationPromises.delete(e)}})();this.revalidationPromises.set(e,o)}parseMaxAge(e){let t=new RegExp(/max-age=(\d+)/).exec(e);return t?parseInt(t[1],10):null}parseStaleWhileRevalidate(e){let t=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return t?parseInt(t[1],10):null}createCacheableResponse(e,t){let r=new Headers(e.headers);return r.set("Cache-Control",t),r.has("Date")||r.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}};var he=class{static{s(this,"AjaxApiClient")}constructor(e){this.config=e;let t=j(e.storeDomain);this.cache=new X(`ajax-api-${t}`,"max-age=60, stale-while-revalidate=3600"),this.cache.cleanupExpiredEntries().catch(r=>{console.warn("Ajax API cache initialization cleanup error:",r)})}patchFetch(){if(!window.fetch||typeof window.fetch!="function")return;let e=window.fetch,t=this.config.responseInterceptor,r=this.getFetchRequest.bind(this);window.fetch=function(...i){let o=e.apply(this,i);if(typeof t=="function"){let u=r(i[0]);o.then(a=>t(a,u))}return o}}getFetchRequest(e){return e instanceof Request?e:new Request(e)}getBaseUrl(){if(!this.config?.storeDomain)throw new Error("Cart API client not initialized - missing store domain");return`https://${this.config.storeDomain}`}fetch(e,t){return(e instanceof Request?e.method:t?.method??"GET")==="GET"?this.cache.fetchWithCache(e,t):fetch(e,t)}async request(e,t={}){let r=`${this.getBaseUrl()}${e}`,i={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(r,{...t,headers:{...i,...t.headers}});if(!o.ok){let u;try{u=await o.json()}catch{u={message:`HTTP ${o.status}: ${o.statusText}`,status:o.status.toString(),description:o.statusText}}throw new Error(u.message||u.description)}return o.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let t={...e,items:e.items.map(r=>{let i=x(r.id);if(!i)throw new Error(`Invalid Shopify GID format: ${r.id}`);let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid numeric ID extracted from GID: ${r.id}`);return{...r,id:o}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(t)})}async clearCache(){await this.cache.clear()}};var me=class{constructor(e){this.eventMap={"/cart/add":"cart-add","/cart/update":"cart-update","/cart/change":"cart-change","/cart/clear":"cart-clear"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{s(this,"AjaxApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.url);if(r){let i=await e.clone().json();this.eventBus.publish(r,i)}}catch(r){console.warn(r)}}getEventName(e){for(let[t,r]of Object.entries(this.eventMap))if(e.includes(t))return r;return null}};function Rr(){let n=document.body||document.documentElement;return n?Promise.resolve(n):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(n))})}s(Rr,"waitForDOM");function ce({onElementFound:n,selector:e,observerOptions:t}){let r=new WeakSet,i=new MutationObserver(l=>{let c=!1;for(let p of l)if(p.addedNodes.length>0){c=!0;break}c&&o()}),o=s(()=>{document.querySelectorAll(e).forEach(l=>{r.has(l)||(u(l),r.add(l))})},"locateElements"),u=s(l=>{if(!t){n(l);return}let c=new IntersectionObserver(p=>{for(let h of p)h.isIntersecting&&(c.disconnect(),n(l))},t);c.observe(l)},"observeElement");return s(async()=>{let l=await Rr();o(),i.observe(l,{childList:!0,subtree:!0})},"locateAndObserveElements")(),i}s(ce,"createElementLocator");function ae({onLocationChange:n,fireOnInit:e=!1}){let t=s(()=>{n(window.location)},"handleChange");window.addEventListener("popstate",t);let r=history.pushState,i=history.replaceState;return history.pushState=function(...o){r.apply(this,o),t()},history.replaceState=function(...o){i.apply(this,o),t()},e&&t(),()=>{window.removeEventListener("popstate",t),history.pushState=r,history.replaceState=i}}s(ae,"createLocationObserver");function Kt({element:n,onHrefChange:e}){let t=s(()=>{e(n.href)},"handleChange"),r=new MutationObserver(()=>{t()});return r.observe(n,{attributes:!0,attributeFilter:["href"]}),()=>{r.disconnect()}}s(Kt,"createHrefObserver");var ye=class{constructor(){this.eventBus=new EventTarget}static{s(this,"EventBus")}subscribe(e,t,r){return Array.isArray(e)||(e=[e]),e.forEach(i=>{this.eventBus.addEventListener(i,t,r)}),()=>{e.forEach(i=>{this.eventBus.removeEventListener(i,t,r)})}}unsubscribe(e,t,r){this.eventBus.removeEventListener(e,t,r)}publish(e,t){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:t}))}};var ot;function Jt(n){return{lang:n?.lang??ot?.lang,message:n?.message,abortEarly:n?.abortEarly??ot?.abortEarly,abortPipeEarly:n?.abortPipeEarly??ot?.abortPipeEarly}}s(Jt,"getGlobalConfig");var Ar;function Dr(n){return Ar?.get(n)}s(Dr,"getGlobalMessage");var Pr;function Tr(n){return Pr?.get(n)}s(Tr,"getSchemaMessage");var _r;function Or(n,e){return _r?.get(n)?.get(e)}s(Or,"getSpecificMessage");function at(n){let e=typeof n;return e==="string"?`"${n}"`:e==="number"||e==="bigint"||e==="boolean"?`${n}`:e==="object"||e==="function"?(n&&Object.getPrototypeOf(n)?.constructor?.name)??"null":e}s(at,"_stringify");function Y(n,e,t,r,i){let o=i&&"input"in i?i.input:t.value,u=i?.expected??n.expects??null,a=i?.received??at(o),l={kind:n.kind,type:n.type,input:o,expected:u,received:a,message:`Invalid ${e}: ${u?`Expected ${u} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},c=n.kind==="schema",p=i?.message??n.message??Or(n.reference,l.lang)??(c?Tr(l.lang):null)??r.message??Dr(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),c&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}s(Y,"_addIssue");function ne(n){return{version:1,vendor:"valibot",validate(e){return n["~run"]({value:e},Jt())}}}s(ne,"_getStandardProps");function Lr(n,e){let t=[...new Set(n)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}s(Lr,"_joinExpects");function ut(n,e){return{kind:"validation",type:"min_value",reference:ut,async:!1,expects:`>=${n instanceof Date?n.toJSON():at(n)}`,requirement:n,message:e,"~run"(t,r){return t.typed&&!(t.value>=this.requirement)&&Y(this,"value",t,r,{received:t.value instanceof Date?t.value.toJSON():at(t.value)}),t}}}s(ut,"minValue");function A(n){return{kind:"transformation",type:"transform",reference:A,async:!1,operation:n,"~run"(e){return e.value=this.operation(e.value),e}}}s(A,"transform");function qr(n,e,t){return typeof n.fallback=="function"?n.fallback(e,t):n.fallback}s(qr,"getFallback");function Zt(n,e,t){return typeof n.default=="function"?n.default(e,t):n.default}s(Zt,"getDefault");function lt(n,e){return{kind:"schema",type:"array",reference:lt,expects:"Array",async:!1,item:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i=t.value;if(Array.isArray(i)){t.typed=!0,t.value=[];for(let o=0;o<i.length;o++){let u=i[o],a=this.item["~run"]({value:u},r);if(a.issues){let l={type:"array",origin:"value",input:i,key:o,value:u};for(let c of a.issues)c.path?c.path.unshift(l):c.path=[l],t.issues?.push(c);if(t.issues||(t.issues=a.issues),r.abortEarly){t.typed=!1;break}}a.typed||(t.typed=!1),t.value.push(a.value)}}else Y(this,"type",t,r);return t}}}s(lt,"array");function k(n){return{kind:"schema",type:"number",reference:k,expects:"number",async:!1,message:n,get"~standard"(){return ne(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Y(this,"type",e,t),e}}}s(k,"number");function w(n,e){return{kind:"schema",type:"object",reference:w,expects:"Object",async:!1,entries:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let o in this.entries){let u=this.entries[o];if(o in i||(u.type==="exact_optional"||u.type==="optional"||u.type==="nullish")&&u.default!==void 0){let a=o in i?i[o]:Zt(u),l=u["~run"]({value:a},r);if(l.issues){let c={type:"object",origin:"value",input:i,key:o,value:a};for(let p of l.issues)p.path?p.path.unshift(c):p.path=[c],t.issues?.push(p);if(t.issues||(t.issues=l.issues),r.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[o]=l.value}else if(u.fallback!==void 0)t.value[o]=qr(u);else if(u.type!=="exact_optional"&&u.type!=="optional"&&u.type!=="nullish"&&(Y(this,"key",t,r,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),r.abortEarly))break}}else Y(this,"type",t,r);return t}}}s(w,"object");function L(n,e){return{kind:"schema",type:"optional",reference:L,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:e,get"~standard"(){return ne(this)},"~run"(t,r){return t.value===void 0&&(this.default!==void 0&&(t.value=Zt(this,t,r)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,r)}}}s(L,"optional");function y(n){return{kind:"schema",type:"string",reference:y,expects:"string",async:!1,message:n,get"~standard"(){return ne(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:Y(this,"type",e,t),e}}}s(y,"string");function Yt(n){let e;if(n)for(let t of n)e?e.push(...t.issues):e=t.issues;return e}s(Yt,"_subIssues");function V(n,e){return{kind:"schema",type:"union",reference:V,expects:Lr(n.map(t=>t.expects),"|"),async:!1,options:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i,o,u;for(let a of this.options){let l=a["~run"]({value:t.value},r);if(l.typed)if(l.issues)o?o.push(l):o=[l];else{i=l;break}else u?u.push(l):u=[l]}if(i)return i;if(o){if(o.length===1)return o[0];Y(this,"type",t,r,{issues:Yt(o)}),t.typed=!0}else{if(u?.length===1)return u[0];Y(this,"type",t,r,{issues:Yt(u)})}return t}}}s(V,"union");function R(...n){return{...n[0],pipe:n,get"~standard"(){return ne(this)},"~run"(e,t){for(let r of n)if(r.kind!=="metadata"){if(e.issues&&(r.kind==="schema"||r.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=r["~run"](e,t))}return e}}}s(R,"pipe");function D(n,e,t){let r=n["~run"]({value:e},Jt(t));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}s(D,"safeParse");var m=class{constructor(e,t,r,i){this.swish=e;this.ui=t;this.eventBus=r;this.options=i}static{s(this,"IntentHandler")}};var $r=w({productId:R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k()),variantId:L(R(V([R(y(),A(x)),k()]),A(Number),k())),quantity:L(R(k(),ut(1))),tags:L(lt(y()))}),ve=class extends m{static{s(this,"SaveItemHandler")}async invoke(e){let t=D($r,e);if(!t.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:t.issues.map(f=>f.message)};let{productId:r,variantId:i,quantity:o,tags:u}=t.output,a=await this.swish.storefront.loadSaveIntentData({productId:E("Product",r),variantId:i?E("ProductVariant",i):void 0});if(a.errors)return{intent:"save:item",code:"error",message:a.errors.message??"Failed to load save intent data",issues:a.errors.graphQLErrors?.map(f=>f.message)??[]};if(!a.data||!a.data.product)return{intent:"save:item",code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:l}=a.data,c=l.variantsCount?.count&&l.variantsCount.count>1,p=!!i,h=!this.options.save.requireVariant||!this.options.save.requireVariantConfirmation&&p;if(!c||h){let f=s(()=>!c&&l.selectedOrFirstAvailableVariant?Number(x(l.selectedOrFirstAvailableVariant.id)):i,"variantIdToUse"),P=await this.swish.api.items.create({productId:r,variantId:f(),quantity:o,tags:u});if("error"in P)return{intent:"save:item",code:"error",message:"Failed to create item",issues:[P.error.message]};if(!P.data)return{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let v="variant"in a.data?a.data.variant:void 0;return{intent:"save:item",code:"ok",data:{item:P.data,product:l,variant:c?v:l.selectedOrFirstAvailableVariant}}}let g=await this.ui.showVariantSelect({productId:r,variantId:i});return g.code==="closed"?{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:g.data}}};var ge=class extends m{static{s(this,"CreateListHandler")}async invoke(e){let t=await this.ui.showListEditor();if(t.code==="closed")return{intent:"create:list",code:"closed"};let{list:r}=t.data;return{intent:"create:list",code:"ok",data:{list:r}}}};var Br=w({itemId:y()}),Ie=class extends m{static{s(this,"DeleteItemHandler")}async invoke(e){let t=D(Br,e);if(!t.success)return{intent:"delete:item",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{itemId:r}=t.output;if(!this.options.unsave.requireConfirmation){let o=await this.swish.api.items.deleteById(r);return"error"in o?{intent:"delete:item",code:"error",message:"Failed to delete item",issues:[o.error.message]}:{intent:"delete:item",code:"ok",data:{itemId:r}}}return(await this.ui.showUnsaveAlert({itemId:r})).code==="closed"?{intent:"delete:item",code:"closed"}:{intent:"delete:item",code:"ok",data:{itemId:r}}}};var Vr=w({listId:y()}),we=class extends m{static{s(this,"DeleteListHandler")}async invoke(e){let t=D(Vr,e);if(!t.success)return{intent:"delete:list",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return(await this.ui.showDeleteListAlert({listId:r})).code==="closed"?{intent:"delete:list",code:"closed"}:{intent:"delete:list",code:"ok",data:{listId:r}}}};var Nr=w({itemId:y()}),be=class extends m{static{s(this,"EditItemListsHandler")}async invoke(e){let t=D(Nr,e);if(!t.success)return{intent:"edit:item-lists",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{itemId:r}=t.output,i=await this.ui.showListSelect({itemId:r});if(i.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(i.data.action==="submit"){let{item:o,product:u,variant:a}=i.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:o,product:u,variant:a}}}return{intent:"delete:item",code:"ok",data:{itemId:i.data.data.itemId}}}};var Ur=w({itemId:R(y()),productId:R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k()),variantId:L(R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k()))}),Se=class extends m{static{s(this,"EditItemVariantHandler")}async invoke(e){let t=D(Ur,e);if(!t.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:t.issues.map(g=>g.message)};let{itemId:r,productId:i,variantId:o}=t.output;if(!(!o||this.swish.options.swishUi.intents.edit.requireVariantConfirmation)){let g=await this.swish.api.items.updateById(r,{productId:i,variantId:o});if("error"in g)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[g.error.message]};if(!g.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let f=await this.swish.storefront.loadSaveIntentData({productId:E("Product",i),variantId:o?E("ProductVariant",o):void 0});if(!f.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load save intent data",issues:[f.errors?.message??"No product data returned from API"]};let P=f.data?.product,v="variant"in f.data?f.data.variant:void 0;return{intent:"edit:item-variant",code:"ok",data:{item:g.data,product:P,variant:v}}}let a=await this.ui.showVariantSelect({itemId:r,productId:i,variantId:o});if(a.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:l,product:c,variant:p}=a.data;return{intent:"edit:item-variant",code:"ok",data:{item:l,product:c,variant:p}}}};var Gr=w({listId:y()}),Ee=class extends m{static{s(this,"EditListHandler")}async invoke(e){let t=D(Gr,e);if(!t.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r}=t.output,i=await this.ui.showListEditor({listId:r});if(i.code==="closed")return{intent:"edit:list",code:"closed"};let{list:o}=i.data;return{intent:"edit:list",code:"ok",data:{list:o}}}};var xe=class extends m{static{s(this,"OpenHomeHandler")}async invoke(e){return{intent:"open:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var Fr=w({listId:y()}),Ce=class extends m{static{s(this,"OpenListHandler")}async invoke(e){let t=D(Fr,e);if(!t.success)return{intent:"open:list",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return{intent:"open:list",code:(await this.ui.showDrawer({view:"list",listId:r})).code,data:void 0}}};var ke=class extends m{static{s(this,"OpenListsHandler")}async invoke(e){return{intent:"open:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var Re=class extends m{static{s(this,"OpenOrdersHandler")}async invoke(e){return{intent:"open:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Ae=class extends m{static{s(this,"OpenSavesHandler")}async invoke(e){return{intent:"open:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var De=class extends m{static{s(this,"OpenNotificationsHandler")}async invoke(e){return{intent:"open:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var Pe=class extends m{static{s(this,"OpenProfileHandler")}async invoke(e){return{intent:"open:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var Mr=w({productId:R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k()),variantId:L(R(V([R(y(),A(x)),k()]),A(Number),k()))}),Te=class extends m{static{s(this,"OpenProductHandler")}async invoke(e){let t=D(Mr,e);if(!t.success)return{intent:"open:product",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{productId:r,variantId:i}=t.output;return{intent:"open:product",code:(await this.ui.showDrawer({view:"product",productId:r.toString(),variantId:i?.toString()})).code,data:void 0}}};var jr=w({listId:y()}),_e=class extends m{static{s(this,"OpenListMenuHandler")}async invoke(e){let t=D(jr,e);if(!t.success)return{intent:"open:list-menu",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output,i=await this.ui.showListMenu({listId:r});return i.code==="closed"?{intent:"open:list-menu",code:"closed"}:i.data.action==="edit"?{intent:"edit:list",code:"ok",data:i.data.data}:{intent:"delete:list",code:"ok",data:{listId:r}}}};var Hr=w({listId:y()}),Oe=class extends m{static{s(this,"OpenListDetailPageMenuHandler")}async invoke(e){let t=D(Hr,e);if(!t.success)return{intent:"open:list-detail-page-menu",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return{intent:"open:list-detail-page-menu",code:(await this.ui.showListDetailPageMenu({listId:r})).code,data:void 0}}};var Bo=w({returnTo:L(y())}),Le=class extends m{static{s(this,"OpenSignInHandler")}async invoke(e){return{intent:"open:sign-in",code:(await this.ui.showSignIn({returnTo:e?.returnTo})).code,data:void 0}}};var Qr=w({productId:R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k()),variantId:L(R(V([R(y(),A(x)),k()]),A(Number),k()))}),qe=class extends m{static{s(this,"OpenQuickBuyHandler")}async invoke(e){let t=D(Qr,e);if(!t.success)return{intent:"open:quick-buy",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{productId:r,variantId:i}=t.output,o=await this.ui.showQuickBuy({productId:r,variantId:i});return o.code==="closed"?{intent:"open:quick-buy",code:"closed"}:{intent:"open:quick-buy",code:"ok",data:o.data}}};var J=class{constructor(e,t,r){this.swish=e;this.ui=t;this.options=r}static{s(this,"IntentHook")}};var $e=class extends J{static{s(this,"AfterSaveItemHook")}async invoke(e){if(this.options.save.showToast&&e.code==="ok"){let{item:t,product:r,variant:i}=e.data;r&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:r.title,image:i?.image?.url??r.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:t.id})}}};var Be=class extends J{static{s(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.edit.showToast&&e.code==="ok"){if("itemId"in e.data)return;let{product:t,variant:r}=e.data;t&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:t.title,image:r?.image?.url??t.featuredImage?.url,action:{label:"View"}})).complete).code==="ok"&&this.swish.intents.invoke("open:home")}}};var Ve=class extends J{static{s(this,"AfterOpenHomeHook")}async invoke(e){if(e.code==="closed"){let t=new URL(window.location.href);(t.hash==="#swish-home"||t.hash==="#swish")&&(t.hash="",window.history.replaceState({},document.title,t.toString()))}}};var na=w({title:L(y()),text:y(),image:L(y()),action:L(w({label:y(),url:L(y())}))}),Ne=class extends m{static{s(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var zr=w({orderId:R(V([R(y(),A(x)),k()]),A(n=>Number(n)),k())}),Ue=class extends m{static{s(this,"OpenOrderHandler")}async invoke(e){let t=D(zr,e);if(!t.success)return{intent:"open:order",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{orderId:r}=t.output;return{intent:"open:order",code:(await this.ui.showDrawer({view:"order",orderId:r.toString()})).code,data:void 0}}};var Ge=class{static{s(this,"Intents")}constructor(e,t){this.swish=e,this.ui=t,this.eventBus=new EventTarget,this.options=e.options.swishUi.intents,this.handlers={"save:item":new ve(this.swish,this.ui,this.eventBus,this.options),"delete:item":new Ie(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Se(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new be(this.swish,this.ui,this.eventBus,this.options),"create:list":new ge(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Ee(this.swish,this.ui,this.eventBus,this.options),"delete:list":new we(this.swish,this.ui,this.eventBus,this.options),"open:home":new xe(this.swish,this.ui,this.eventBus,this.options),"open:list":new Ce(this.swish,this.ui,this.eventBus,this.options),"open:lists":new ke(this.swish,this.ui,this.eventBus,this.options),"open:orders":new Re(this.swish,this.ui,this.eventBus,this.options),"open:order":new Ue(this.swish,this.ui,this.eventBus,this.options),"open:saves":new Ae(this.swish,this.ui,this.eventBus,this.options),"open:notifications":new De(this.swish,this.ui,this.eventBus,this.options),"open:profile":new Pe(this.swish,this.ui,this.eventBus,this.options),"open:product":new Te(this.swish,this.ui,this.eventBus,this.options),"open:list-menu":new _e(this.swish,this.ui,this.eventBus,this.options),"open:list-detail-page-menu":new Oe(this.swish,this.ui,this.eventBus,this.options),"open:sign-in":new Le(this.swish,this.ui,this.eventBus,this.options),"open:quick-buy":new qe(this.swish,this.ui,this.eventBus,this.options),"show:toast":new Ne(this.swish,this.ui,this.eventBus,this.options)},this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,t){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,t)}async invoke(e,...t){let r=t[0],i={lifecycle:"before",intent:e,data:r};return this.publishAnalyticsEvent("swish-intent",i),this.publishAnalyticsEvent(`swish-intent=${e}`,i),{intent:e,data:r,complete:this.handleIntent(e,r).then(o=>{let u={lifecycle:"after",intent:e,data:r,response:o};return this.publishAnalyticsEvent("swish-intent",u),this.publishAnalyticsEvent(`swish-intent=${e}`,u),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:o})),o})}}listen(e,t){let r=s(o=>{"detail"in o&&o.detail?t(o.detail):console.warn("Intent response event without detail",o)},"eventListener"),i=s(()=>{this.eventBus.removeEventListener(e,r)},"unsubscribe");return this.eventBus.addEventListener(e,r),i}parseIntentFromString(e){if(typeof e=="string"){let[t,...r]=e.split(","),i=r.reduce((o,u)=>{let[a,l]=u.split("=");return o[a]=l,o},{});return{intent:t,data:i}}return{intent:e,data:{}}}parseIntentFromHash(e){let t=e.startsWith("#")?e.slice(1):e;return{swish:"open:home","swish-home":"open:home","swish-lists":"open:lists","swish-orders":"open:orders","swish-saves":"open:saves","swish-notifications":"open:notifications","swish-profile":"open:profile"}[t]||null}async handleIntent(e,t){let r=this.handlers[e];return r?r.invoke(t):{intent:e,code:"error",message:"Invalid intent",issues:[`Intent ${e} not found`]}}initIntentHooks(){this.eventBus.addEventListener("save:item",e=>{new $e(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new Be(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("open:home",e=>{new Ve(this.swish,this.ui,this.options).invoke(e.detail)})}initIntentWatcher(){ce({selector:"[swish-intent]",onElementFound:s(e=>{let t=e.getAttribute("swish-intent");t&&e.addEventListener("click",()=>{let{intent:r,data:i}=this.parseIntentFromString(t);Object.keys(i).length>0?this.invoke(r,i):this.invoke(r)})},"onElementFound")}),ce({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:s(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",t=>{if(!t.metaKey&&!t.ctrlKey&&!t.shiftKey&&!t.altKey){let r=new URL(e.href),i=r.hash,o=r.searchParams.get("swish-intent");if(o){let{intent:u,data:a}=this.parseIntentFromString(o);u&&(t.preventDefault(),t.stopPropagation(),Object.keys(a).length>0?this.invoke(u,a):this.invoke(u))}else if(i){let u=this.parseIntentFromHash(i);u&&(t.preventDefault(),t.stopPropagation(),this.invoke(u))}}})},"onElementFound")}),ae({fireOnInit:!0,onLocationChange:s(e=>{let t=new URL(e.href),r=t.hash,i=t.searchParams.get("swish-intent");if(i){let{intent:o,data:u}=this.parseIntentFromString(i);o&&(Object.keys(u).length>0?this.invoke(o,u):this.invoke(o))}else if(r){let o=this.parseIntentFromHash(r);o&&this.invoke(o)}},"onLocationChange")})}};var en=s(n=>({storefrontApi:{storeDomain:n.storefrontApi?.storeDomain??"",accessToken:n.storefrontApi?.accessToken??""},storefrontContext:{...n.storefrontContext,localization:{country:n.storefrontContext.localization.country.toUpperCase(),language:n.storefrontContext.localization.language.toUpperCase(),market:n.storefrontContext.localization.market}},badges:{getBadges:n.badges?.getBadges??(({defaultBadges:e})=>e)},metafields:{product:n.metafields?.product??[],productVariant:n.metafields?.productVariant??[]},swishApi:{authProxy:n.swishApi?.authProxy??"/apps/wishlist/api",version:n.swishApi?.version??"2026-01"},swishUi:{baseUrl:n.swishUi?.baseUrl??"https://swish.app/cdn",version:n.swishUi?.version??Fe,components:{productRow:{showVariantTitle:n.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:n.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:n.swishUi?.components?.variantSelect?.displayType??"pills"},icons:n.swishUi?.components?.icons??{},imageSlider:{flush:n.swishUi?.components?.imageSlider?.flush??!1,loop:n.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:n.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:n.swishUi?.components?.buyButtons?.shopPay??!1},listDetailPage:{desktopColumns:n.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:n.swishUi?.components?.listDetailPage?.showBuyButton??!0},drawer:{title:n.swishUi?.components?.drawer?.title??"",logo:{url:n.swishUi?.components?.drawer?.logo?.url??"",altText:n.swishUi?.components?.drawer?.logo?.altText??""},navigation:{variant:n.swishUi?.components?.drawer?.navigation?.variant??"floating",items:n.swishUi?.components?.drawer?.navigation?.items??[{id:"home",enabled:!0,intent:"open:home"},{id:"saves",enabled:!0,intent:"open:saves"},{id:"lists",enabled:!0,intent:"open:lists"},{id:"orders",enabled:!0,intent:"open:orders"},{id:"profile",enabled:!0,intent:"open:profile"},{id:"notifications",enabled:!0,intent:"open:notifications"}]},miniMenu:{items:n.swishUi?.components?.drawer?.miniMenu?.items??[]}}},css:n.swishUi?.css??[],intents:{save:{requireVariant:n.swishUi?.intents?.save?.requireVariant??!1,requireVariantConfirmation:n.swishUi?.intents?.save?.requireVariantConfirmation??!1,showToast:n.swishUi?.intents?.save?.showToast??!1},edit:{requireVariantConfirmation:n.swishUi?.intents?.edit?.requireVariantConfirmation??!1,showToast:n.swishUi?.intents?.edit?.showToast??!1},unsave:{requireConfirmation:n.swishUi?.intents?.unsave?.requireConfirmation??!1,openEditor:n.swishUi?.intents?.unsave?.openEditor??!1,showToast:n.swishUi?.intents?.unsave?.showToast??!1}},theme:n.swishUi?.theme??{}}}),"createSwishOptions");var Wr=Symbol.for("preact-signals");function je(){if(Z>1)Z--;else{for(var n,e=!1;pe!==void 0;){var t=pe;for(pe=void 0,ct++;t!==void 0;){var r=t.o;if(t.o=void 0,t.f&=-3,!(8&t.f)&&rn(t))try{t.c()}catch(i){e||(n=i,e=!0)}t=r}}if(ct=0,Z--,e)throw n}}s(je,"t");function ee(n){if(Z>0)return n();Z++;try{return n()}finally{je()}}s(ee,"r");var b=void 0;function tn(n){var e=b;b=void 0;try{return n()}finally{b=e}}s(tn,"n");var pe=void 0,Z=0,ct=0,Me=0;function nn(n){if(b!==void 0){var e=n.n;if(e===void 0||e.t!==b)return e={i:0,S:n,p:b.s,n:void 0,t:b,e:void 0,x:void 0,r:e},b.s!==void 0&&(b.s.n=e),b.s=e,n.n=e,32&b.f&&n.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=b.s,e.n=void 0,b.s.n=e,b.s=e),e}}s(nn,"e");function N(n,e){this.v=n,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s(N,"u");N.prototype.brand=Wr;N.prototype.h=function(){return!0};N.prototype.S=function(n){var e=this,t=this.t;t!==n&&n.e===void 0&&(n.x=t,this.t=n,t!==void 0?t.e=n:tn(function(){var r;(r=e.W)==null||r.call(e)}))};N.prototype.U=function(n){var e=this;if(this.t!==void 0){var t=n.e,r=n.x;t!==void 0&&(t.x=r,n.e=void 0),r!==void 0&&(r.e=t,n.x=void 0),n===this.t&&(this.t=r,r===void 0&&tn(function(){var i;(i=e.Z)==null||i.call(e)}))}};N.prototype.subscribe=function(n){var e=this;return H(function(){var t=e.value,r=b;b=void 0;try{n(t)}finally{b=r}},{name:"sub"})};N.prototype.valueOf=function(){return this.value};N.prototype.toString=function(){return this.value+""};N.prototype.toJSON=function(){return this.value};N.prototype.peek=function(){var n=b;b=void 0;try{return this.value}finally{b=n}};Object.defineProperty(N.prototype,"value",{get:s(function(){var n=nn(this);return n!==void 0&&(n.i=this.i),this.v},"get"),set:s(function(n){if(n!==this.v){if(ct>100)throw new Error("Cycle detected");this.v=n,this.i++,Me++,Z++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{je()}}},"set")});function T(n,e){return new N(n,e)}s(T,"d");function rn(n){for(var e=n.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}s(rn,"c");function sn(n){for(var e=n.s;e!==void 0;e=e.n){var t=e.S.n;if(t!==void 0&&(e.r=t),e.S.n=e,e.i=-1,e.n===void 0){n.s=e;break}}}s(sn,"a");function on(n){for(var e=n.s,t=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):t=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}n.s=t}s(on,"l");function re(n,e){N.call(this,void 0),this.x=n,this.s=void 0,this.g=Me-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s(re,"y");re.prototype=new N;re.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Me))return!0;if(this.g=Me,this.f|=1,this.i>0&&!rn(this))return this.f&=-2,!0;var n=b;try{sn(this),b=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(t){this.v=t,this.f|=16,this.i++}return b=n,on(this),this.f&=-2,!0};re.prototype.S=function(n){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}N.prototype.S.call(this,n)};re.prototype.U=function(n){if(this.t!==void 0&&(N.prototype.U.call(this,n),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};re.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var n=this.t;n!==void 0;n=n.x)n.t.N()}};Object.defineProperty(re.prototype,"value",{get:s(function(){if(1&this.f)throw new Error("Cycle detected");var n=nn(this);if(this.h(),n!==void 0&&(n.i=this.i),16&this.f)throw this.v;return this.v},"get")});function F(n,e){return new re(n,e)}s(F,"w");function an(n){var e=n.u;if(n.u=void 0,typeof e=="function"){Z++;var t=b;b=void 0;try{e()}catch(r){throw n.f&=-2,n.f|=8,pt(n),r}finally{b=t,je()}}}s(an,"_");function pt(n){for(var e=n.s;e!==void 0;e=e.n)e.S.U(e);n.x=void 0,n.s=void 0,an(n)}s(pt,"b");function Xr(n){if(b!==this)throw new Error("Out-of-order effect");on(this),b=n,this.f&=-2,8&this.f&&pt(this),je()}s(Xr,"g");function ue(n,e){this.x=n,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}s(ue,"p");ue.prototype.c=function(){var n=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{n()}};ue.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,an(this),sn(this),Z++;var n=b;return b=this,Xr.bind(this,n)};ue.prototype.N=function(){2&this.f||(this.f|=2,this.o=pe,pe=this)};ue.prototype.d=function(){this.f|=8,1&this.f||pt(this)};ue.prototype.dispose=function(){this.d()};function H(n,e){var t=new ue(n,e);try{t.c()}catch(i){throw t.d(),i}var r=t.d.bind(t);return r[Symbol.dispose]=r,r}s(H,"E");var Kr=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,dt=s(n=>{let e=n.match(Kr);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),un=s(({source:n,onProductUrlChange:e})=>{let t=s(r=>{let i=dt(r);i?.productHandle&&e(i)},"handleChange");if(n instanceof HTMLAnchorElement)return Kt({element:n,onHrefChange:s(r=>t(r),"onHrefChange")});if(n instanceof Location)return ae({onLocationChange:s(r=>t(r.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var ln=s(n=>e=>{let{productHandle:t,productId:r,variantId:i,itemId:o}=e?.dataset??{},l=!!(r||t)||!!o,c=T({loading:!1,productId:r,variantId:i,itemId:o});if(!l){let p=e instanceof HTMLAnchorElement?e:window.location,h=dt(p.href);h?.productHandle&&h.productHandle!==c.value.productHandle&&(c.value={...c.value,...h,productId:void 0},un({source:p,onProductUrlChange:s(g=>{c.value={...c.value,...g,productId:g.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return H(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},n.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?x(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var cn=s(n=>e=>{let t=F(()=>{let{productId:C,variantId:I,loading:q}=e.value;return!C||q?null:I?`variant:${x(I)}`:`product:${x(C)}`}),r=F(()=>e.value.loading||!!e.value.itemId||!e.value.productId),i=F(()=>({limit:1,query:t.value??void 0})),o=T(!r.value),u=T(null),a=T(!1),l=T(!1),{data:c,loading:p,error:h,refetching:g}=n.state.swishQuery(C=>n.api.items.list(C),{refetch:["item-create","item-update","item-delete"],variables:i,skip:r}),f=T(e.value.itemId??null);H(()=>{ee(()=>{if(o.value=p.value,u.value=h.value,!e.value.itemId){let C=c.value?.[0]?.id??null;C!==f.value&&(f.value=C)}})});async function P(){if(!f.value)return;a.value=!0,(await(await n.intents.invoke("delete:item",{itemId:f.value})).complete).code==="ok"&&(f.value=null),a.value=!1}s(P,"unsave");async function v(){if(!f.value)return;a.value=!0;let I=await(await n.intents.invoke("edit:item-lists",{itemId:f.value})).complete;I.code==="ok"&&"itemId"in I.data&&(f.value=null),a.value=!1}s(v,"update");async function _(){let{productId:C,variantId:I}=e.value;if(!C)return;a.value=!0,l.value=!0;let $=await(await n.intents.invoke("save:item",{productId:C,variantId:I})).complete;if($.code==="ok"){let le=$.data;f.value=le.item.id,a.value=!1}else $.code==="error"&&console.warn("Failed to create item",$),ee(()=>{a.value=!1,l.value=!1})}s(_,"save");let B=F(()=>o.value||a.value||e.value.loading);H(()=>{l.value&&!a.value&&!g.value&&(l.value=!1)});let O=F(()=>{let C=g.value&&l.value,I=!!f.value,q=!I&&(a.value||C),$=I&&(a.value||C),le=F(()=>q?"saving":$?"unsaving":I?"saved":"unsaved");return{error:u.value,status:le.value,savedItemId:f.value,loading:B.value,submitting:a.value,saved:I,saving:q,unsaving:$}});async function z(){B.value||(O.value.saved&&O.value.savedItemId?v():O.value.saved||await _())}return s(z,"toggle"),Object.assign(O,{save:_,unsave:P,update:v,toggle:z})},"itemStateSignal");var pn=s(n=>()=>{let{data:e,loading:t,error:r}=n.state.swishQuery(()=>n.api.items.count(),{refetch:["item-create","item-delete"]}),i=T(0),o=T(!0),u=T(null);return H(()=>{ee(()=>{o.value=t.value,u.value=r.value,i.value=e.value?.count??0})}),F(()=>({count:i.value,loading:o.value,error:u.value}))},"itemCountSignal");var Yr="token-update",dn=s(n=>(e,t)=>{let r=T(null),i=T(null),o=T(null),u=T(!t?.skip),a=T(!1),l=F(()=>u.value&&a.value);async function c(){if(!t?.skip?.value)try{u.value=!0;let p=await e(t?.variables?.value);ee(()=>{o.value="error"in p?p.error:null,r.value="data"in p?p.data:null,i.value="pageInfo"in p?p.pageInfo:null,u.value=!1,a.value=!0})}catch(p){ee(()=>{o.value=p,u.value=!1,a.value=!0})}}return s(c,"executeFetch"),H(()=>{if(c(),t?.refetch?.length){let p=[...t.refetch,Yr];return n.events.subscribe(p,c)}}),{data:r,pageInfo:i,error:o,loading:u,refetching:l}},"swishQuerySignals");var ie="GraphQL Client";var ft="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",ht="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.",He={json:"application/json",multipart:"multipart/mixed"},yt="X-SDK-Variant",vt="X-SDK-Version",hn="shopify-graphql-client",mn="1.4.1",Qe=1e3,yn=[429,503],gt=/@(defer)\b/i,fn=`\r
|
|
8
|
-
`,
|
|
7
|
+
`+String(r)));jt(e);for(var i=0;i<e.callbacks.length;i++){var o=r[i];o instanceof Error?e.callbacks[i].reject(o):e.callbacks[i].resolve(o)}}).catch(function(r){Ft(n,e,r)})}s(ds,"dispatchBatch");function Ft(n,e,t){jt(e);for(var r=0;r<e.keys.length;r++)n.clear(e.keys[r]),e.callbacks[r].reject(t)}s(Ft,"failedDispatch");function jt(n){if(n.cacheHits)for(var e=0;e<n.cacheHits.length;e++)n.cacheHits[e]()}s(jt,"resolveCacheHits");function fs(n){var e=!n||n.batch!==!1;if(!e)return 1;var t=n&&n.maxBatchSize;if(t===void 0)return 1/0;if(typeof t!="number"||t<1)throw new TypeError("maxBatchSize must be a positive number: "+t);return t}s(fs,"getValidMaxBatchSize");function hs(n){var e=n&&n.batchScheduleFn;if(e===void 0)return cs;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}s(hs,"getValidBatchScheduleFn");function ms(n){var e=n&&n.cacheKeyFn;if(e===void 0)return function(t){return t};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}s(ms,"getValidCacheKeyFn");function ys(n){var e=!n||n.cache!==!1;if(!e)return null;var t=n&&n.cacheMap;if(t===void 0)return new Map;if(t!==null){var r=["get","set","delete","clear"],i=r.filter(function(o){return t&&typeof t[o]!="function"});if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return t}s(ys,"getValidCacheMap");function vs(n){return n&&n.name?n.name:null}s(vs,"getValidName");function fr(n){return typeof n=="object"&&n!==null&&typeof n.length=="number"&&(n.length===0||n.length>0&&Object.prototype.hasOwnProperty.call(n,n.length-1))}s(fr,"isArrayLike");hr.exports=ls});var x=s(n=>n.split("/").pop()??"","shopifyGidToId"),E=s((n,e)=>`gid://shopify/${n}/${e}`,"shopifyIdToGid"),j=s(n=>n.toLowerCase().replace(".myshopify.com",""),"toShopName");var X=class{constructor(e,t,r=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=t,this.keyPrefix=r}static{s(this,"FetchCache")}async get(e){try{let t=await caches.open(this.cacheName),r=await t.match(e);if(r&&this.isExpired(r)){await t.delete(e);return}return r}catch(t){console.warn("Cache get error:",t);return}}async set(e,t,r){try{if(r?.includes("no-cache"))return;let i=this.createCacheableResponse(t,r);await(await caches.open(this.cacheName)).put(e,i)}catch(i){console.warn("Cache set error:",i)}}async fetchWithCache(e,t,r){let i=await this.getCacheKey(e,t);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(i))return this.inFlightRequests.get(i).then(u=>u.clone());let o=(async()=>{let u=await this.get(i);if(u)return this.isStaleButRevalidatable(u)&&this.revalidateInBackground(i,e,t,r),u.clone();let a=await fetch(e,t);return a.ok&&await this.set(i,a.clone(),r??this.defaultCacheControl),a})().finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,o),o}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(t){return console.warn("Cache delete error:",t),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,t)=>{try{let r=await caches.open(this.cacheName),i=await r.keys();await Promise.all(i.map(o=>r.delete(o))),e()}catch(r){console.warn("Cache clear error:",r),t(r)}}),this.clearCachePromise.then(()=>{this.clearCachePromise=null}).catch(e=>{console.warn("Cache clear error:",e)}))}async keys(){try{return(await(await caches.open(this.cacheName)).keys()).map(r=>r.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let t=await caches.open(this.cacheName),r=await t.match(e);return r&&this.isExpired(r)?(await t.delete(e),!1):r!==void 0}catch(t){return console.warn("Cache has error:",t),!1}}async getStats(){try{return{total:(await(await caches.open(this.cacheName)).keys()).length}}catch(e){return console.warn("Cache stats error:",e),{total:0}}}async cleanupExpiredEntries(){try{let e=await caches.open(this.cacheName),t=await e.keys(),r=0;for(let o of t){let u=await e.match(o);u&&this.isExpired(u)&&(await e.delete(o),r++)}let i=t.length-r;return{removed:r,remaining:i}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,t){let r=this.getInputUrl(e),i=`${this.keyPrefix}${r}/${JSON.stringify(t)}`,u=new TextEncoder().encode(i),a=await crypto.subtle.digest("SHA-256",u);return`/${Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")}`}getInputUrl(e){return e instanceof URL?e.toString():typeof e=="string"?e:e.url}isExpired(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(r===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let u=new Date(o).getTime(),l=(Date.now()-u)/1e3,c=r+(i??0);return l>c}isStaleButRevalidatable(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(r===null||i===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let u=new Date(o).getTime(),l=(Date.now()-u)/1e3;return l>r&&l<=r+i}async revalidateInBackground(e,t,r,i){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let u=await fetch(t,r);u.ok&&await this.set(e,u.clone(),i??this.defaultCacheControl)}catch(u){console.warn("Background revalidation error:",u)}finally{this.revalidationPromises.delete(e)}})();this.revalidationPromises.set(e,o)}parseMaxAge(e){let t=new RegExp(/max-age=(\d+)/).exec(e);return t?parseInt(t[1],10):null}parseStaleWhileRevalidate(e){let t=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return t?parseInt(t[1],10):null}createCacheableResponse(e,t){let r=new Headers(e.headers);return r.set("Cache-Control",t),r.has("Date")||r.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}};var he=class{static{s(this,"AjaxApiClient")}constructor(e){this.config=e;let t=j(e.storeDomain);this.cache=new X(`ajax-api-${t}`,"max-age=60, stale-while-revalidate=3600"),this.cache.cleanupExpiredEntries().catch(r=>{console.warn("Ajax API cache initialization cleanup error:",r)})}patchFetch(){if(!window.fetch||typeof window.fetch!="function")return;let e=window.fetch,t=this.config.responseInterceptor,r=this.getFetchRequest.bind(this);window.fetch=function(...i){let o=e.apply(this,i);if(typeof t=="function"){let u=r(i[0]);o.then(a=>t(a,u))}return o}}getFetchRequest(e){return e instanceof Request?e:new Request(e)}getBaseUrl(){if(!this.config?.storeDomain)throw new Error("Cart API client not initialized - missing store domain");return`https://${this.config.storeDomain}`}fetch(e,t){return(e instanceof Request?e.method:t?.method??"GET")==="GET"?this.cache.fetchWithCache(e,t):fetch(e,t)}async request(e,t={}){let r=`${this.getBaseUrl()}${e}`,i={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(r,{...t,headers:{...i,...t.headers}});if(!o.ok){let u;try{u=await o.json()}catch{u={message:`HTTP ${o.status}: ${o.statusText}`,status:o.status.toString(),description:o.statusText}}throw new Error(u.message||u.description)}return o.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let t={...e,items:e.items.map(r=>{let i=x(r.id);if(!i)throw new Error(`Invalid Shopify GID format: ${r.id}`);let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid numeric ID extracted from GID: ${r.id}`);return{...r,id:o}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(t)})}async clearCache(){await this.cache.clear()}};var me=class{constructor(e){this.eventMap={"/cart/add":"cart-add","/cart/update":"cart-update","/cart/change":"cart-change","/cart/clear":"cart-clear"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{s(this,"AjaxApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.url);if(r){let i=await e.clone().json();this.eventBus.publish(r,i)}}catch(r){console.warn(r)}}getEventName(e){for(let[t,r]of Object.entries(this.eventMap))if(e.includes(t))return r;return null}};function Ar(){let n=document.body||document.documentElement;return n?Promise.resolve(n):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(n))})}s(Ar,"waitForDOM");function ce({onElementFound:n,selector:e,observerOptions:t}){let r=new WeakSet,i=new MutationObserver(l=>{let c=!1;for(let p of l)if(p.addedNodes.length>0){c=!0;break}c&&o()}),o=s(()=>{document.querySelectorAll(e).forEach(l=>{r.has(l)||(u(l),r.add(l))})},"locateElements"),u=s(l=>{if(!t){n(l);return}let c=new IntersectionObserver(p=>{for(let h of p)h.isIntersecting&&(c.disconnect(),n(l))},t);c.observe(l)},"observeElement");return s(async()=>{let l=await Ar();o(),i.observe(l,{childList:!0,subtree:!0})},"locateAndObserveElements")(),i}s(ce,"createElementLocator");function ae({onLocationChange:n,fireOnInit:e=!1}){let t=s(()=>{n(window.location)},"handleChange");window.addEventListener("popstate",t);let r=history.pushState,i=history.replaceState;return history.pushState=function(...o){r.apply(this,o),t()},history.replaceState=function(...o){i.apply(this,o),t()},e&&t(),()=>{window.removeEventListener("popstate",t),history.pushState=r,history.replaceState=i}}s(ae,"createLocationObserver");function Yt({element:n,onHrefChange:e}){let t=s(()=>{e(n.href)},"handleChange"),r=new MutationObserver(()=>{t()});return r.observe(n,{attributes:!0,attributeFilter:["href"]}),()=>{r.disconnect()}}s(Yt,"createHrefObserver");var ye=class{constructor(){this.eventBus=new EventTarget}static{s(this,"EventBus")}subscribe(e,t,r){return Array.isArray(e)||(e=[e]),e.forEach(i=>{this.eventBus.addEventListener(i,t,r)}),()=>{e.forEach(i=>{this.eventBus.removeEventListener(i,t,r)})}}unsubscribe(e,t,r){this.eventBus.removeEventListener(e,t,r)}publish(e,t){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:t}))}};var at;function Zt(n){return{lang:n?.lang??at?.lang,message:n?.message,abortEarly:n?.abortEarly??at?.abortEarly,abortPipeEarly:n?.abortPipeEarly??at?.abortPipeEarly}}s(Zt,"getGlobalConfig");var Dr;function Pr(n){return Dr?.get(n)}s(Pr,"getGlobalMessage");var Tr;function _r(n){return Tr?.get(n)}s(_r,"getSchemaMessage");var Or;function Lr(n,e){return Or?.get(n)?.get(e)}s(Lr,"getSpecificMessage");function ut(n){let e=typeof n;return e==="string"?`"${n}"`:e==="number"||e==="bigint"||e==="boolean"?`${n}`:e==="object"||e==="function"?(n&&Object.getPrototypeOf(n)?.constructor?.name)??"null":e}s(ut,"_stringify");function Y(n,e,t,r,i){let o=i&&"input"in i?i.input:t.value,u=i?.expected??n.expects??null,a=i?.received??ut(o),l={kind:n.kind,type:n.type,input:o,expected:u,received:a,message:`Invalid ${e}: ${u?`Expected ${u} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},c=n.kind==="schema",p=i?.message??n.message??Lr(n.reference,l.lang)??(c?_r(l.lang):null)??r.message??Pr(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),c&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}s(Y,"_addIssue");function ne(n){return{version:1,vendor:"valibot",validate(e){return n["~run"]({value:e},Zt())}}}s(ne,"_getStandardProps");function qr(n,e){let t=[...new Set(n)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}s(qr,"_joinExpects");function lt(n,e){return{kind:"validation",type:"min_value",reference:lt,async:!1,expects:`>=${n instanceof Date?n.toJSON():ut(n)}`,requirement:n,message:e,"~run"(t,r){return t.typed&&!(t.value>=this.requirement)&&Y(this,"value",t,r,{received:t.value instanceof Date?t.value.toJSON():ut(t.value)}),t}}}s(lt,"minValue");function D(n){return{kind:"transformation",type:"transform",reference:D,async:!1,operation:n,"~run"(e){return e.value=this.operation(e.value),e}}}s(D,"transform");function $r(n,e,t){return typeof n.fallback=="function"?n.fallback(e,t):n.fallback}s($r,"getFallback");function en(n,e,t){return typeof n.default=="function"?n.default(e,t):n.default}s(en,"getDefault");function ct(n,e){return{kind:"schema",type:"array",reference:ct,expects:"Array",async:!1,item:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i=t.value;if(Array.isArray(i)){t.typed=!0,t.value=[];for(let o=0;o<i.length;o++){let u=i[o],a=this.item["~run"]({value:u},r);if(a.issues){let l={type:"array",origin:"value",input:i,key:o,value:u};for(let c of a.issues)c.path?c.path.unshift(l):c.path=[l],t.issues?.push(c);if(t.issues||(t.issues=a.issues),r.abortEarly){t.typed=!1;break}}a.typed||(t.typed=!1),t.value.push(a.value)}}else Y(this,"type",t,r);return t}}}s(ct,"array");function R(n){return{kind:"schema",type:"number",reference:R,expects:"number",async:!1,message:n,get"~standard"(){return ne(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:Y(this,"type",e,t),e}}}s(R,"number");function w(n,e){return{kind:"schema",type:"object",reference:w,expects:"Object",async:!1,entries:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let o in this.entries){let u=this.entries[o];if(o in i||(u.type==="exact_optional"||u.type==="optional"||u.type==="nullish")&&u.default!==void 0){let a=o in i?i[o]:en(u),l=u["~run"]({value:a},r);if(l.issues){let c={type:"object",origin:"value",input:i,key:o,value:a};for(let p of l.issues)p.path?p.path.unshift(c):p.path=[c],t.issues?.push(p);if(t.issues||(t.issues=l.issues),r.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[o]=l.value}else if(u.fallback!==void 0)t.value[o]=$r(u);else if(u.type!=="exact_optional"&&u.type!=="optional"&&u.type!=="nullish"&&(Y(this,"key",t,r,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),r.abortEarly))break}}else Y(this,"type",t,r);return t}}}s(w,"object");function L(n,e){return{kind:"schema",type:"optional",reference:L,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:e,get"~standard"(){return ne(this)},"~run"(t,r){return t.value===void 0&&(this.default!==void 0&&(t.value=en(this,t,r)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,r)}}}s(L,"optional");function y(n){return{kind:"schema",type:"string",reference:y,expects:"string",async:!1,message:n,get"~standard"(){return ne(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:Y(this,"type",e,t),e}}}s(y,"string");function Jt(n){let e;if(n)for(let t of n)e?e.push(...t.issues):e=t.issues;return e}s(Jt,"_subIssues");function B(n,e){return{kind:"schema",type:"union",reference:B,expects:qr(n.map(t=>t.expects),"|"),async:!1,options:n,message:e,get"~standard"(){return ne(this)},"~run"(t,r){let i,o,u;for(let a of this.options){let l=a["~run"]({value:t.value},r);if(l.typed)if(l.issues)o?o.push(l):o=[l];else{i=l;break}else u?u.push(l):u=[l]}if(i)return i;if(o){if(o.length===1)return o[0];Y(this,"type",t,r,{issues:Jt(o)}),t.typed=!0}else{if(u?.length===1)return u[0];Y(this,"type",t,r,{issues:Jt(u)})}return t}}}s(B,"union");function A(...n){return{...n[0],pipe:n,get"~standard"(){return ne(this)},"~run"(e,t){for(let r of n)if(r.kind!=="metadata"){if(e.issues&&(r.kind==="schema"||r.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=r["~run"](e,t))}return e}}}s(A,"pipe");function C(n,e,t){let r=n["~run"]({value:e},Zt(t));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}s(C,"safeParse");var m=class{constructor(e,t,r,i){this.swish=e;this.ui=t;this.eventBus=r;this.options=i}static{s(this,"IntentHandler")}};var Vr=w({productId:A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R()),variantId:L(A(B([A(y(),D(x)),R()]),D(Number),R())),quantity:L(A(R(),lt(1))),tags:L(ct(y()))}),ve=class extends m{static{s(this,"SaveItemHandler")}async invoke(e){let t=C(Vr,e);if(!t.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:t.issues.map(f=>f.message)};let{productId:r,variantId:i,quantity:o,tags:u}=t.output,a=await this.swish.storefront.loadSaveIntentData({productId:E("Product",r),variantId:i?E("ProductVariant",i):void 0});if(a.errors)return{intent:"save:item",code:"error",message:a.errors.message??"Failed to load save intent data",issues:a.errors.graphQLErrors?.map(f=>f.message)??[]};if(!a.data||!a.data.product)return{intent:"save:item",code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:l}=a.data,c=l.variantsCount?.count&&l.variantsCount.count>1,p=!!i,h=!this.options.save.requireVariant||!this.options.save.requireVariantConfirmation&&p;if(!c||h){let f=s(()=>!c&&l.selectedOrFirstAvailableVariant?Number(x(l.selectedOrFirstAvailableVariant.id)):i,"variantIdToUse"),P=await this.swish.api.items.create({productId:r,variantId:f(),quantity:o,tags:u});if("error"in P)return{intent:"save:item",code:"error",message:"Failed to create item",issues:[P.error.message]};if(!P.data)return{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let v="variant"in a.data?a.data.variant:void 0;return{intent:"save:item",code:"ok",data:{item:P.data,product:l,variant:c?v:l.selectedOrFirstAvailableVariant}}}let g=await this.ui.showVariantSelect({productId:r,variantId:i});return g.code==="closed"?{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:g.data}}};var ge=class extends m{static{s(this,"CreateListHandler")}async invoke(e){let t=await this.ui.showListEditor();if(t.code==="closed")return{intent:"create:list",code:"closed"};let{list:r}=t.data;return{intent:"create:list",code:"ok",data:{list:r}}}};var Br=w({itemId:y()}),Ie=class extends m{static{s(this,"DeleteItemHandler")}async invoke(e){let t=C(Br,e);if(!t.success)return{intent:"delete:item",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{itemId:r}=t.output;if(!this.options.unsave.requireConfirmation){let o=await this.swish.api.items.deleteById(r);return"error"in o?{intent:"delete:item",code:"error",message:"Failed to delete item",issues:[o.error.message]}:{intent:"delete:item",code:"ok",data:{itemId:r}}}return(await this.ui.showUnsaveAlert({itemId:r})).code==="closed"?{intent:"delete:item",code:"closed"}:{intent:"delete:item",code:"ok",data:{itemId:r}}}};var Nr=w({listId:y()}),we=class extends m{static{s(this,"DeleteListHandler")}async invoke(e){let t=C(Nr,e);if(!t.success)return{intent:"delete:list",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return(await this.ui.showDeleteListAlert({listId:r})).code==="closed"?{intent:"delete:list",code:"closed"}:{intent:"delete:list",code:"ok",data:{listId:r}}}};var Ur=w({itemId:y()}),be=class extends m{static{s(this,"EditItemListsHandler")}async invoke(e){let t=C(Ur,e);if(!t.success)return{intent:"edit:item-lists",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{itemId:r}=t.output,i=await this.ui.showListSelect({itemId:r});if(i.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(i.data.action==="submit"){let{item:o,product:u,variant:a}=i.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:o,product:u,variant:a}}}return{intent:"delete:item",code:"ok",data:{itemId:i.data.data.itemId}}}};var Mr=w({itemId:A(y()),productId:A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R()),variantId:L(A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R()))}),Se=class extends m{static{s(this,"EditItemVariantHandler")}async invoke(e){let t=C(Mr,e);if(!t.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:t.issues.map(g=>g.message)};let{itemId:r,productId:i,variantId:o}=t.output;if(!(!o||this.swish.options.swishUi.intents.edit.requireVariantConfirmation)){let g=await this.swish.api.items.updateById(r,{productId:i,variantId:o});if("error"in g)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[g.error.message]};if(!g.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let f=await this.swish.storefront.loadSaveIntentData({productId:E("Product",i),variantId:o?E("ProductVariant",o):void 0});if(!f.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load save intent data",issues:[f.errors?.message??"No product data returned from API"]};let P=f.data?.product,v="variant"in f.data?f.data.variant:void 0;return{intent:"edit:item-variant",code:"ok",data:{item:g.data,product:P,variant:v}}}let a=await this.ui.showVariantSelect({itemId:r,productId:i,variantId:o});if(a.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:l,product:c,variant:p}=a.data;return{intent:"edit:item-variant",code:"ok",data:{item:l,product:c,variant:p}}}};var Gr=w({listId:y()}),Ee=class extends m{static{s(this,"EditListHandler")}async invoke(e){let t=C(Gr,e);if(!t.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r}=t.output,i=await this.ui.showListEditor({listId:r});if(i.code==="closed")return{intent:"edit:list",code:"closed"};let{list:o}=i.data;return{intent:"edit:list",code:"ok",data:{list:o}}}};var xe=class extends m{static{s(this,"OpenHomeHandler")}async invoke(e){return{intent:"open:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var Fr=w({listId:y()}),Ce=class extends m{static{s(this,"OpenListHandler")}async invoke(e){let t=C(Fr,e);if(!t.success)return{intent:"open:list",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return{intent:"open:list",code:(await this.ui.showDrawer({view:"list",listId:r})).code,data:void 0}}};var ke=class extends m{static{s(this,"OpenListsHandler")}async invoke(e){return{intent:"open:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var Re=class extends m{static{s(this,"OpenOrdersHandler")}async invoke(e){return{intent:"open:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Ae=class extends m{static{s(this,"OpenSavesHandler")}async invoke(e){return{intent:"open:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var De=class extends m{static{s(this,"OpenNotificationsHandler")}async invoke(e){return{intent:"open:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var Pe=class extends m{static{s(this,"OpenProfileHandler")}async invoke(e){return{intent:"open:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var jr=w({productId:A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R()),variantId:L(A(B([A(y(),D(x)),R()]),D(Number),R()))}),Te=class extends m{static{s(this,"OpenProductHandler")}async invoke(e){let t=C(jr,e);if(!t.success)return{intent:"open:product",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{productId:r,variantId:i}=t.output;return{intent:"open:product",code:(await this.ui.showDrawer({view:"product",productId:r.toString(),variantId:i?.toString()})).code,data:void 0}}};var Hr=w({listId:y()}),_e=class extends m{static{s(this,"OpenListMenuHandler")}async invoke(e){let t=C(Hr,e);if(!t.success)return{intent:"open:list-menu",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output,i=await this.ui.showListMenu({listId:r});return i.code==="closed"?{intent:"open:list-menu",code:"closed"}:i.data.action==="edit"?{intent:"edit:list",code:"ok",data:i.data.data}:{intent:"delete:list",code:"ok",data:{listId:r}}}};var Qr=w({orderId:y()}),Oe=class extends m{static{s(this,"OpenOrderMenuHandler")}async invoke(e){let t=C(Qr,e);if(!t.success)return{intent:"open:order-menu",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{orderId:r}=t.output;return{intent:"open:order-menu",code:(await this.ui.showOrderMenu({orderId:r})).code,data:void 0}}};var zr=w({listId:y()}),Le=class extends m{static{s(this,"OpenListDetailPageMenuHandler")}async invoke(e){let t=C(zr,e);if(!t.success)return{intent:"open:list-detail-page-menu",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{listId:r}=t.output;return{intent:"open:list-detail-page-menu",code:(await this.ui.showListDetailPageMenu({listId:r})).code,data:void 0}}};var Go=w({returnTo:L(y())}),qe=class extends m{static{s(this,"OpenSignInHandler")}async invoke(e){return{intent:"open:sign-in",code:(await this.ui.showSignIn({returnTo:e?.returnTo})).code,data:void 0}}};var Wr=w({productId:A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R()),variantId:L(A(B([A(y(),D(x)),R()]),D(Number),R()))}),$e=class extends m{static{s(this,"OpenQuickBuyHandler")}async invoke(e){let t=C(Wr,e);if(!t.success)return{intent:"open:quick-buy",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{productId:r,variantId:i}=t.output,o=await this.ui.showQuickBuy({productId:r,variantId:i});return o.code==="closed"?{intent:"open:quick-buy",code:"closed"}:{intent:"open:quick-buy",code:"ok",data:o.data}}};var J=class{constructor(e,t,r){this.swish=e;this.ui=t;this.options=r}static{s(this,"IntentHook")}};var Ve=class extends J{static{s(this,"AfterSaveItemHook")}async invoke(e){if(this.options.save.showToast&&e.code==="ok"){let{item:t,product:r,variant:i}=e.data;r&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:r.title,image:i?.image?.url??r.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:t.id})}}};var Be=class extends J{static{s(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.edit.showToast&&e.code==="ok"){if("itemId"in e.data)return;let{product:t,variant:r}=e.data;t&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:t.title,image:r?.image?.url??t.featuredImage?.url,action:{label:"View"}})).complete).code==="ok"&&this.swish.intents.invoke("open:home")}}};var Ne=class extends J{static{s(this,"AfterOpenHomeHook")}async invoke(e){if(e.code==="closed"){let t=new URL(window.location.href);(t.hash==="#swish-home"||t.hash==="#swish")&&(t.hash="",window.history.replaceState({},document.title,t.toString()))}}};var aa=w({title:L(y()),text:y(),image:L(y()),action:L(w({label:y(),url:L(y())}))}),Ue=class extends m{static{s(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var Xr=w({orderId:A(B([A(y(),D(x)),R()]),D(n=>Number(n)),R())}),Me=class extends m{static{s(this,"OpenOrderHandler")}async invoke(e){let t=C(Xr,e);if(!t.success)return{intent:"open:order",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let{orderId:r}=t.output;return{intent:"open:order",code:(await this.ui.showDrawer({view:"order",orderId:r.toString()})).code,data:void 0}}};var Ge=class{static{s(this,"Intents")}constructor(e,t){this.swish=e,this.ui=t,this.eventBus=new EventTarget,this.options=e.options.swishUi.intents,this.handlers={"save:item":new ve(this.swish,this.ui,this.eventBus,this.options),"delete:item":new Ie(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Se(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new be(this.swish,this.ui,this.eventBus,this.options),"create:list":new ge(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Ee(this.swish,this.ui,this.eventBus,this.options),"delete:list":new we(this.swish,this.ui,this.eventBus,this.options),"open:home":new xe(this.swish,this.ui,this.eventBus,this.options),"open:list":new Ce(this.swish,this.ui,this.eventBus,this.options),"open:lists":new ke(this.swish,this.ui,this.eventBus,this.options),"open:orders":new Re(this.swish,this.ui,this.eventBus,this.options),"open:order":new Me(this.swish,this.ui,this.eventBus,this.options),"open:saves":new Ae(this.swish,this.ui,this.eventBus,this.options),"open:notifications":new De(this.swish,this.ui,this.eventBus,this.options),"open:profile":new Pe(this.swish,this.ui,this.eventBus,this.options),"open:product":new Te(this.swish,this.ui,this.eventBus,this.options),"open:list-menu":new _e(this.swish,this.ui,this.eventBus,this.options),"open:order-menu":new Oe(this.swish,this.ui,this.eventBus,this.options),"open:list-detail-page-menu":new Le(this.swish,this.ui,this.eventBus,this.options),"open:sign-in":new qe(this.swish,this.ui,this.eventBus,this.options),"open:quick-buy":new $e(this.swish,this.ui,this.eventBus,this.options),"show:toast":new Ue(this.swish,this.ui,this.eventBus,this.options)},this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,t){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,t)}async invoke(e,...t){let r=t[0],i={lifecycle:"before",intent:e,data:r};return this.publishAnalyticsEvent("swish-intent",i),this.publishAnalyticsEvent(`swish-intent=${e}`,i),{intent:e,data:r,complete:this.handleIntent(e,r).then(o=>{let u={lifecycle:"after",intent:e,data:r,response:o};return this.publishAnalyticsEvent("swish-intent",u),this.publishAnalyticsEvent(`swish-intent=${e}`,u),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:o})),o})}}listen(e,t){let r=s(o=>{"detail"in o&&o.detail?t(o.detail):console.warn("Intent response event without detail",o)},"eventListener"),i=s(()=>{this.eventBus.removeEventListener(e,r)},"unsubscribe");return this.eventBus.addEventListener(e,r),i}parseIntentFromString(e){if(typeof e=="string"){let[t,...r]=e.split(","),i=r.reduce((o,u)=>{let[a,l]=u.split("=");return o[a]=l,o},{});return{intent:t,data:i}}return{intent:e,data:{}}}parseIntentFromHash(e){let t=e.startsWith("#")?e.slice(1):e;return{swish:"open:home","swish-home":"open:home","swish-lists":"open:lists","swish-orders":"open:orders","swish-saves":"open:saves","swish-notifications":"open:notifications","swish-profile":"open:profile"}[t]||null}async handleIntent(e,t){let r=this.handlers[e];return r?r.invoke(t):{intent:e,code:"error",message:"Invalid intent",issues:[`Intent ${e} not found`]}}initIntentHooks(){this.eventBus.addEventListener("save:item",e=>{new Ve(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new Be(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("open:home",e=>{new Ne(this.swish,this.ui,this.options).invoke(e.detail)})}initIntentWatcher(){ce({selector:"[swish-intent]",onElementFound:s(e=>{let t=e.getAttribute("swish-intent");t&&e.addEventListener("click",()=>{let{intent:r,data:i}=this.parseIntentFromString(t);Object.keys(i).length>0?this.invoke(r,i):this.invoke(r)})},"onElementFound")}),ce({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:s(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",t=>{if(!t.metaKey&&!t.ctrlKey&&!t.shiftKey&&!t.altKey){let r=new URL(e.href),i=r.hash,o=r.searchParams.get("swish-intent");if(o){let{intent:u,data:a}=this.parseIntentFromString(o);u&&(t.preventDefault(),t.stopPropagation(),Object.keys(a).length>0?this.invoke(u,a):this.invoke(u))}else if(i){let u=this.parseIntentFromHash(i);u&&(t.preventDefault(),t.stopPropagation(),this.invoke(u))}}})},"onElementFound")}),ae({fireOnInit:!0,onLocationChange:s(e=>{let t=new URL(e.href),r=t.hash,i=t.searchParams.get("swish-intent");if(i){let{intent:o,data:u}=this.parseIntentFromString(i);o&&(Object.keys(u).length>0?this.invoke(o,u):this.invoke(o))}else if(r){let o=this.parseIntentFromHash(r);o&&this.invoke(o)}},"onLocationChange")})}};var tn=s(n=>({storefrontApi:{storeDomain:n.storefrontApi?.storeDomain??"",accessToken:n.storefrontApi?.accessToken??""},storefrontContext:{...n.storefrontContext,localization:{country:n.storefrontContext.localization.country.toUpperCase(),language:n.storefrontContext.localization.language.toUpperCase(),market:n.storefrontContext.localization.market}},badges:{getBadges:n.badges?.getBadges??(({defaultBadges:e})=>e)},metafields:{product:n.metafields?.product??[],productVariant:n.metafields?.productVariant??[]},swishApi:{authProxy:n.swishApi?.authProxy??"/apps/wishlist/api",version:n.swishApi?.version??"2026-01"},swishUi:{baseUrl:n.swishUi?.baseUrl??"https://swish.app/cdn",version:n.swishUi?.version??Fe,components:{productRow:{showVariantTitle:n.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:n.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:n.swishUi?.components?.variantSelect?.displayType??"pills"},icons:n.swishUi?.components?.icons??{},imageSlider:{flush:n.swishUi?.components?.imageSlider?.flush??!1,loop:n.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:n.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:n.swishUi?.components?.buyButtons?.shopPay??!1},listDetailPage:{desktopColumns:n.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:n.swishUi?.components?.listDetailPage?.showBuyButton??!0,showVariantOptionNames:n.swishUi?.components?.listDetailPage?.showVariantOptionNames??!1,enableVariantChange:n.swishUi?.components?.listDetailPage?.enableVariantChange??!0},drawer:{title:n.swishUi?.components?.drawer?.title??"",logo:{url:n.swishUi?.components?.drawer?.logo?.url??"",altText:n.swishUi?.components?.drawer?.logo?.altText??""},navigation:{variant:n.swishUi?.components?.drawer?.navigation?.variant??"floating",items:n.swishUi?.components?.drawer?.navigation?.items??[{id:"home",enabled:!0,intent:"open:home"},{id:"saves",enabled:!0,intent:"open:saves"},{id:"lists",enabled:!0,intent:"open:lists"},{id:"orders",enabled:!0,intent:"open:orders"},{id:"profile",enabled:!0,intent:"open:profile"},{id:"notifications",enabled:!0,intent:"open:notifications"}]},miniMenu:{items:n.swishUi?.components?.drawer?.miniMenu?.items??[]},listDetailView:{enableVariantChange:n.swishUi?.components?.drawer?.listDetailView?.enableVariantChange??!1,showVariantOptionNames:n.swishUi?.components?.drawer?.listDetailView?.showVariantOptionNames??!1}}},css:n.swishUi?.css??[],intents:{save:{requireVariant:n.swishUi?.intents?.save?.requireVariant??!1,requireVariantConfirmation:n.swishUi?.intents?.save?.requireVariantConfirmation??!1,showToast:n.swishUi?.intents?.save?.showToast??!1},edit:{requireVariantConfirmation:n.swishUi?.intents?.edit?.requireVariantConfirmation??!1,showToast:n.swishUi?.intents?.edit?.showToast??!1},unsave:{requireConfirmation:n.swishUi?.intents?.unsave?.requireConfirmation??!1,openEditor:n.swishUi?.intents?.unsave?.openEditor??!1,showToast:n.swishUi?.intents?.unsave?.showToast??!1}},theme:n.swishUi?.theme??{}}}),"createSwishOptions");var Kr=Symbol.for("preact-signals");function He(){if(Z>1)Z--;else{for(var n,e=!1;pe!==void 0;){var t=pe;for(pe=void 0,pt++;t!==void 0;){var r=t.o;if(t.o=void 0,t.f&=-3,!(8&t.f)&&sn(t))try{t.c()}catch(i){e||(n=i,e=!0)}t=r}}if(pt=0,Z--,e)throw n}}s(He,"t");function ee(n){if(Z>0)return n();Z++;try{return n()}finally{He()}}s(ee,"r");var b=void 0;function nn(n){var e=b;b=void 0;try{return n()}finally{b=e}}s(nn,"n");var pe=void 0,Z=0,pt=0,je=0;function rn(n){if(b!==void 0){var e=n.n;if(e===void 0||e.t!==b)return e={i:0,S:n,p:b.s,n:void 0,t:b,e:void 0,x:void 0,r:e},b.s!==void 0&&(b.s.n=e),b.s=e,n.n=e,32&b.f&&n.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=b.s,e.n=void 0,b.s.n=e,b.s=e),e}}s(rn,"e");function U(n,e){this.v=n,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s(U,"u");U.prototype.brand=Kr;U.prototype.h=function(){return!0};U.prototype.S=function(n){var e=this,t=this.t;t!==n&&n.e===void 0&&(n.x=t,this.t=n,t!==void 0?t.e=n:nn(function(){var r;(r=e.W)==null||r.call(e)}))};U.prototype.U=function(n){var e=this;if(this.t!==void 0){var t=n.e,r=n.x;t!==void 0&&(t.x=r,n.e=void 0),r!==void 0&&(r.e=t,n.x=void 0),n===this.t&&(this.t=r,r===void 0&&nn(function(){var i;(i=e.Z)==null||i.call(e)}))}};U.prototype.subscribe=function(n){var e=this;return H(function(){var t=e.value,r=b;b=void 0;try{n(t)}finally{b=r}},{name:"sub"})};U.prototype.valueOf=function(){return this.value};U.prototype.toString=function(){return this.value+""};U.prototype.toJSON=function(){return this.value};U.prototype.peek=function(){var n=b;b=void 0;try{return this.value}finally{b=n}};Object.defineProperty(U.prototype,"value",{get:s(function(){var n=rn(this);return n!==void 0&&(n.i=this.i),this.v},"get"),set:s(function(n){if(n!==this.v){if(pt>100)throw new Error("Cycle detected");this.v=n,this.i++,je++,Z++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{He()}}},"set")});function T(n,e){return new U(n,e)}s(T,"d");function sn(n){for(var e=n.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}s(sn,"c");function on(n){for(var e=n.s;e!==void 0;e=e.n){var t=e.S.n;if(t!==void 0&&(e.r=t),e.S.n=e,e.i=-1,e.n===void 0){n.s=e;break}}}s(on,"a");function an(n){for(var e=n.s,t=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):t=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}n.s=t}s(an,"l");function re(n,e){U.call(this,void 0),this.x=n,this.s=void 0,this.g=je-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s(re,"y");re.prototype=new U;re.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===je))return!0;if(this.g=je,this.f|=1,this.i>0&&!sn(this))return this.f&=-2,!0;var n=b;try{on(this),b=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(t){this.v=t,this.f|=16,this.i++}return b=n,an(this),this.f&=-2,!0};re.prototype.S=function(n){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}U.prototype.S.call(this,n)};re.prototype.U=function(n){if(this.t!==void 0&&(U.prototype.U.call(this,n),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};re.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var n=this.t;n!==void 0;n=n.x)n.t.N()}};Object.defineProperty(re.prototype,"value",{get:s(function(){if(1&this.f)throw new Error("Cycle detected");var n=rn(this);if(this.h(),n!==void 0&&(n.i=this.i),16&this.f)throw this.v;return this.v},"get")});function G(n,e){return new re(n,e)}s(G,"w");function un(n){var e=n.u;if(n.u=void 0,typeof e=="function"){Z++;var t=b;b=void 0;try{e()}catch(r){throw n.f&=-2,n.f|=8,dt(n),r}finally{b=t,He()}}}s(un,"_");function dt(n){for(var e=n.s;e!==void 0;e=e.n)e.S.U(e);n.x=void 0,n.s=void 0,un(n)}s(dt,"b");function Yr(n){if(b!==this)throw new Error("Out-of-order effect");an(this),b=n,this.f&=-2,8&this.f&&dt(this),He()}s(Yr,"g");function ue(n,e){this.x=n,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}s(ue,"p");ue.prototype.c=function(){var n=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{n()}};ue.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,un(this),on(this),Z++;var n=b;return b=this,Yr.bind(this,n)};ue.prototype.N=function(){2&this.f||(this.f|=2,this.o=pe,pe=this)};ue.prototype.d=function(){this.f|=8,1&this.f||dt(this)};ue.prototype.dispose=function(){this.d()};function H(n,e){var t=new ue(n,e);try{t.c()}catch(i){throw t.d(),i}var r=t.d.bind(t);return r[Symbol.dispose]=r,r}s(H,"E");var Jr=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,ft=s(n=>{let e=n.match(Jr);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),ln=s(({source:n,onProductUrlChange:e})=>{let t=s(r=>{let i=ft(r);i?.productHandle&&e(i)},"handleChange");if(n instanceof HTMLAnchorElement)return Yt({element:n,onHrefChange:s(r=>t(r),"onHrefChange")});if(n instanceof Location)return ae({onLocationChange:s(r=>t(r.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var cn=s(n=>e=>{let{productHandle:t,productId:r,variantId:i,itemId:o}=e?.dataset??{},l=!!(r||t)||!!o,c=T({loading:!1,productId:r,variantId:i,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},ln({source:p,onProductUrlChange:s(g=>{c.value={...c.value,...g,productId:g.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return H(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},n.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?x(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var pn=s(n=>e=>{let t=G(()=>{let{productId:k,variantId:I,loading:q}=e.value;return!k||q?null:I?`variant:${x(I)}`:`product:${x(k)}`}),r=G(()=>e.value.loading||!!e.value.itemId||!e.value.productId),i=G(()=>({limit:1,query:t.value??void 0})),o=T(!r.value),u=T(null),a=T(!1),l=T(!1),{data:c,loading:p,error:h,refetching:g}=n.state.swishQuery(k=>n.api.items.list(k),{refetch:["item-create","item-update","item-delete"],variables:i,skip:r}),f=T(e.value.itemId??null);H(()=>{ee(()=>{if(o.value=p.value,u.value=h.value,!e.value.itemId){let k=c.value?.[0]?.id??null;k!==f.value&&(f.value=k)}})});async function P(){if(!f.value)return;a.value=!0,(await(await n.intents.invoke("delete:item",{itemId:f.value})).complete).code==="ok"&&(f.value=null),a.value=!1}s(P,"unsave");async function v(){if(!f.value)return;a.value=!0;let I=await(await n.intents.invoke("edit:item-lists",{itemId:f.value})).complete;I.code==="ok"&&"itemId"in I.data&&(f.value=null),a.value=!1}s(v,"update");async function _(){let{productId:k,variantId:I}=e.value;if(!k)return;a.value=!0,l.value=!0;let $=await(await n.intents.invoke("save:item",{productId:k,variantId:I})).complete;if($.code==="ok"){let le=$.data;f.value=le.item.id,a.value=!1}else $.code==="error"&&console.warn("Failed to create item",$),ee(()=>{a.value=!1,l.value=!1})}s(_,"save");let V=G(()=>o.value||a.value||e.value.loading);H(()=>{l.value&&!a.value&&!g.value&&(l.value=!1)});let O=G(()=>{let k=g.value&&l.value,I=!!f.value,q=!I&&(a.value||k),$=I&&(a.value||k),le=G(()=>q?"saving":$?"unsaving":I?"saved":"unsaved");return{error:u.value,status:le.value,savedItemId:f.value,loading:V.value,submitting:a.value,saved:I,saving:q,unsaving:$}});async function z(){V.value||(O.value.saved&&O.value.savedItemId?v():O.value.saved||await _())}return s(z,"toggle"),Object.assign(O,{save:_,unsave:P,update:v,toggle:z})},"itemStateSignal");var dn=s(n=>()=>{let{data:e,loading:t,error:r}=n.state.swishQuery(()=>n.api.items.count(),{refetch:["item-create","item-delete"]}),i=T(0),o=T(!0),u=T(null);return H(()=>{ee(()=>{o.value=t.value,u.value=r.value,i.value=e.value?.count??0})}),G(()=>({count:i.value,loading:o.value,error:u.value}))},"itemCountSignal");var Zr="token-update",fn=s(n=>(e,t)=>{let r=T(null),i=T(null),o=T(null),u=T(!t?.skip),a=T(!1),l=G(()=>u.value&&a.value);async function c(){if(!t?.skip?.value)try{u.value=!0;let p=await e(t?.variables?.value);ee(()=>{o.value="error"in p?p.error:null,r.value="data"in p?p.data:null,i.value="pageInfo"in p?p.pageInfo:null,u.value=!1,a.value=!0})}catch(p){ee(()=>{o.value=p,u.value=!1,a.value=!0})}}return s(c,"executeFetch"),H(()=>{if(c(),t?.refetch?.length){let p=[...t.refetch,Zr];return n.events.subscribe(p,c)}}),{data:r,pageInfo:i,error:o,loading:u,refetching:l}},"swishQuerySignals");var ie="GraphQL Client";var ht="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",mt="Response returned unexpected Content-Type:",yt="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",mn="shopify-graphql-client",yn="1.4.1",ze=1e3,vn=[429,503],It=/@(defer)\b/i,hn=`\r
|
|
8
|
+
`,gn=/boundary="?([^=";]+)"?/i,wt=hn+hn;function W(n,e=ie){return n.startsWith(`${e}`)?n:`${e}: ${n}`}s(W,"formatErrorMessage");function K(n){return n instanceof Error?n.message:JSON.stringify(n)}s(K,"getErrorMessage");function bt(n){return n instanceof Error&&n.cause?n.cause:void 0}s(bt,"getErrorCause");function St(n){return n.flatMap(({errors:e})=>e??[])}s(St,"combineErrors");function We({client:n,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${n}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}s(We,"validateRetries");function M(n,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[n]:e}:{}}s(M,"getKeyValueIfValid");function Et(n,e){if(n.length===0)return e;let r={[n.pop()]:e};return n.length===0?r:Et(n,r)}s(Et,"buildDataObjectByPath");function bn(n,e){return Object.keys(e||{}).reduce((t,r)=>(typeof e[r]=="object"||Array.isArray(e[r]))&&n[r]?(t[r]=bn(n[r],e[r]),t):(t[r]=e[r],t),Array.isArray(n)?[...n]:{...n})}s(bn,"combineObjects");function xt([n,...e]){return e.reduce(bn,{...n})}s(xt,"buildCombinedDataObject");function Ct({clientLogger:n,customFetchApi:e=fetch,client:t=ie,defaultRetryWaitTime:r=ze,retriableCodes:i=vn}){let o=s(async(u,a,l)=>{let c=a+1,p=l+1,h;try{if(h=await e(...u),n({type:"HTTP-Response",content:{requestParams:u,response:h}}),!h.ok&&i.includes(h.status)&&c<=p)throw new Error;let g=h?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return g&&n({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:u,deprecationNotice:g}}),h}catch(g){if(c<=p){let f=h?.headers.get("Retry-After");return await ei(f?parseInt(f,10):r),n({type:"HTTP-Retry",content:{requestParams:u,lastResponse:h,retryAttempt:a,maxRetries:l}}),o(u,c,l)}throw new Error(W(`${l>0?`Attempted maximum number of ${l} network retries. Last message - `:""}${K(g)}`,t))}},"httpFetch");return o}s(Ct,"generateHttpFetch");async function ei(n){return new Promise(e=>setTimeout(e,n))}s(ei,"sleep");function kt({headers:n,url:e,customFetchApi:t=fetch,retries:r=0,logger:i}){We({client:ie,retries:r});let o={headers:n,url:e,retries:r},u=ti(i),a=Ct({customFetchApi:t,clientLogger:u,defaultRetryWaitTime:ze}),l=ni(a,o),c=ri(l),p=ci(l);return{config:o,fetch:l,request:c,requestStream:p}}s(kt,"createGraphQLClient");function ti(n){return e=>{n&&n(e)}}s(ti,"generateClientLogger");async function Sn(n){let{errors:e,data:t,extensions:r}=await n.json();return{...M("data",t),...M("extensions",r),headers:n.headers,...e||!t?{errors:{networkStatusCode:n.status,message:W(e?ht:yt),...M("graphQLErrors",e),response:n}}:{}}}s(Sn,"processJSONResponse");function ni(n,{url:e,headers:t,retries:r}){return async(i,o={})=>{let{variables:u,headers:a,url:l,retries:c,keepalive:p,signal:h}=o,g=JSON.stringify({query:i,variables:u});We({client:ie,retries:c});let f=Object.entries({...t,...a}).reduce((v,[_,V])=>(v[_]=Array.isArray(V)?V.join(", "):V.toString(),v),{});return!f[vt]&&!f[gt]&&(f[vt]=mn,f[gt]=yn),n([l??e,{method:"POST",headers:f,body:g,signal:h,keepalive:p}],1,c??r)}}s(ni,"generateFetch");function ri(n){return async(...e)=>{if(It.test(e[0]))throw new Error(W("This operation will result in a streamable response - use requestStream() instead."));let t=null;try{t=await n(...e);let{status:r,statusText:i}=t,o=t.headers.get("content-type")||"";return t.ok?o.includes(Qe.json)?await Sn(t):{errors:{networkStatusCode:r,message:W(`${mt} ${o}`),response:t}}:{errors:{networkStatusCode:r,message:W(i),response:t}}}catch(r){return{errors:{message:K(r),...t==null?{}:{networkStatusCode:t.status,response:t}}}}}}s(ri,"generateRequest");async function*ii(n){let e=new TextDecoder;if(n.body[Symbol.asyncIterator])for await(let t of n.body)yield e.decode(t);else{let t=n.body.getReader(),r;try{for(;!(r=await t.read()).done;)yield e.decode(r.value)}finally{t.cancel()}}}s(ii,"getStreamBodyIterator");function si(n,e){return{async*[Symbol.asyncIterator](){try{let t="";for await(let r of n)if(t+=r,t.indexOf(e)>-1){let i=t.lastIndexOf(e),u=t.slice(0,i).split(e).filter(a=>a.trim().length>0).map(a=>a.slice(a.indexOf(wt)+wt.length).trim());u.length>0&&(yield u),t=t.slice(i+e.length),t.trim()==="--"&&(t="")}}catch(t){throw new Error(`Error occured while processing stream payload - ${K(t)}`)}}}}s(si,"readStreamChunk");function oi(n){return{async*[Symbol.asyncIterator](){yield{...await Sn(n),hasNext:!1}}}}s(oi,"createJsonResponseAsyncIterator");function ai(n){return n.map(e=>{try{return JSON.parse(e)}catch(t){throw new Error(`Error in parsing multipart response - ${K(t)}`)}}).map(e=>{let{data:t,incremental:r,hasNext:i,extensions:o,errors:u}=e;if(!r)return{data:t||{},...M("errors",u),...M("extensions",o),hasNext:i};let a=r.map(({data:l,path:c,errors:p})=>({data:l&&c?Et(c,l):{},...M("errors",p)}));return{data:a.length===1?a[0].data:xt([...a.map(({data:l})=>l)]),...M("errors",St(a)),hasNext:i}})}s(ai,"getResponseDataFromChunkBodies");function ui(n,e){if(n.length>0)throw new Error(ht,{cause:{graphQLErrors:n}});if(Object.keys(e).length===0)throw new Error(yt)}s(ui,"validateResponseData");function li(n,e){let t=(e??"").match(gn),r=`--${t?t[1]:"-"}`;if(!n.body?.getReader&&!n.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:n});let i=ii(n),o={},u;return{async*[Symbol.asyncIterator](){try{let a=!0;for await(let l of si(i,r)){let c=ai(l);u=c.find(h=>h.extensions)?.extensions??u;let p=St(c);o=xt([o,...c.map(({data:h})=>h)]),a=c.slice(-1)[0].hasNext,ui(p,o),yield{...M("data",o),...M("extensions",u),hasNext:a}}if(a)throw new Error("Response stream terminated unexpectedly")}catch(a){let l=bt(a);yield{...M("data",o),...M("extensions",u),errors:{message:W(K(a)),networkStatusCode:n.status,...M("graphQLErrors",l?.graphQLErrors),response:n},hasNext:!1}}}}}s(li,"createMultipartResponseAsyncInterator");function ci(n){return async(...e)=>{if(!It.test(e[0]))throw new Error(W("This operation does not result in a streamable response - use request() instead."));try{let t=await n(...e),{statusText:r}=t;if(!t.ok)throw new Error(r,{cause:t});let i=t.headers.get("content-type")||"";switch(!0){case i.includes(Qe.json):return oi(t);case i.includes(Qe.multipart):return li(t,i);default:throw new Error(`${mt} ${i}`,{cause:t})}}catch(t){return{async*[Symbol.asyncIterator](){let r=bt(t);yield{errors:{message:W(K(t)),...M("networkStatusCode",r?.status),...M("response",r)},hasNext:!1}}}}}}s(ci,"generateRequestStream");function Rt({client:n,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let t=e.trim(),r=t.match(/^https?:/)?t:`https://${t}`,i=new URL(r);return i.protocol="https",i.origin}catch(t){throw new Error(`${n}: a valid store domain ("${e}") must be provided`,{cause:t})}}s(Rt,"validateDomainAndGetStoreUrl");function Xe({client:n,currentSupportedApiVersions:e,apiVersion:t,logger:r}){let i=`${n}: the provided apiVersion ("${t}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!t||typeof t!="string")throw new Error(`${i} is invalid. ${o}`);let u=t.trim();e.includes(u)||(r?r({type:"Unsupported_Api_Version",content:{apiVersion:t,supportedApiVersions:e}}):console.warn(`${i} is likely deprecated or not supported. ${o}`))}s(Xe,"validateApiVersion");function Ke(n){let e=n*3-2;return e===10?e:`0${e}`}s(Ke,"getQuarterMonth");function At(n,e,t){let r=e-t;return r<=0?`${n-1}-${Ke(r+4)}`:`${n}-${Ke(r)}`}s(At,"getPrevousVersion");function En(){let n=new Date,e=n.getUTCMonth(),t=n.getUTCFullYear(),r=Math.floor(e/3+1);return{year:t,quarter:r,version:`${t}-${Ke(r)}`}}s(En,"getCurrentApiVersion");function Dt(){let{year:n,quarter:e,version:t}=En(),r=e===4?`${n+1}-01`:`${n}-${Ke(e+1)}`;return[At(n,e,3),At(n,e,2),At(n,e,1),t,r,"unstable"]}s(Dt,"getCurrentSupportedApiVersions");function Pt(n){return e=>({...e??{},...n.headers})}s(Pt,"generateGetHeaders");function Tt({getHeaders:n,getApiUrl:e}){return(t,r)=>{let i=[t];if(r&&Object.keys(r).length>0){let{variables:o,apiVersion:u,headers:a,retries:l,signal:c}=r;i.push({...o?{variables:o}:{},...a?{headers:n(a)}:{},...u?{url:e(u)}:{},...l?{retries:l}:{},...c?{signal:c}:{}})}return i}}s(Tt,"generateGetGQLClientParams");var _t="application/json",xn="storefront-api-client",Cn="1.0.9",kn="X-Shopify-Storefront-Access-Token",Rn="Shopify-Storefront-Private-Token",An="X-SDK-Variant",Dn="X-SDK-Version",Pn="X-SDK-Variant-Source",se="Storefront API Client";function Tn(n){if(n&&typeof window<"u")throw new Error(`${se}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}s(Tn,"validatePrivateAccessTokenUsage");function _n(n,e){if(!n&&!e)throw new Error(`${se}: a public or private access token must be provided`);if(n&&e)throw new Error(`${se}: only provide either a public or private access token`)}s(_n,"validateRequiredAccessTokens");function Ot({storeDomain:n,apiVersion:e,publicAccessToken:t,privateAccessToken:r,clientName:i,retries:o=0,customFetchApi:u,logger:a}){let l=Dt(),c=Rt({client:se,storeDomain:n}),p={client:se,currentSupportedApiVersions:l,logger:a};Xe({...p,apiVersion:e}),_n(t,r),Tn(r);let h=pi(c,e,p),g={storeDomain:c,apiVersion:e,...t?{publicAccessToken:t}:{privateAccessToken:r},headers:{"Content-Type":_t,Accept:_t,[An]:xn,[Dn]:Cn,...i?{[Pn]:i}:{},...t?{[kn]:t}:{[Rn]:r}},apiUrl:h(),clientName:i},f=kt({headers:g.headers,url:g.apiUrl,retries:o,customFetchApi:u,logger:a}),P=Pt(g),v=di(g,h),_=Tt({getHeaders:P,getApiUrl:v});return Object.freeze({config:g,getHeaders:P,getApiUrl:v,fetch:s((...O)=>f.fetch(..._(...O)),"fetch"),request:s((...O)=>f.request(..._(...O)),"request"),requestStream:s((...O)=>f.requestStream(..._(...O)),"requestStream")})}s(Ot,"createStorefrontApiClient");function pi(n,e,t){return r=>{r&&Xe({...t,apiVersion:r});let i=(r??e).trim();return`${n}/api/${i}/graphql.json`}}s(pi,"generateApiUrlFormatter");function di(n,e){return t=>t?e(t):n.apiUrl}s(di,"generateGetApiUrl");var F=`
|
|
9
9
|
fragment productImageFields on Image {
|
|
10
10
|
id
|
|
11
11
|
altText
|
|
12
12
|
url
|
|
13
13
|
thumbhash
|
|
14
14
|
}
|
|
15
|
-
`,
|
|
15
|
+
`,Lt=`
|
|
16
16
|
fragment saveIntentProductFields on Product {
|
|
17
17
|
id
|
|
18
18
|
availableForSale
|
|
@@ -86,7 +86,7 @@ Values:
|
|
|
86
86
|
value
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
|
-
`,
|
|
89
|
+
`,qt=`
|
|
90
90
|
fragment productVariantDataFields on ProductVariant {
|
|
91
91
|
id
|
|
92
92
|
availableForSale
|
|
@@ -115,7 +115,7 @@ Values:
|
|
|
115
115
|
value
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
|
-
|
|
118
|
+
`,$t=`
|
|
119
119
|
fragment productOptionsVariantFields on ProductVariant {
|
|
120
120
|
id
|
|
121
121
|
selectedOptions {
|
|
@@ -123,7 +123,7 @@ Values:
|
|
|
123
123
|
value
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
|
-
|
|
126
|
+
`,Vt=`
|
|
127
127
|
fragment selectedVariantFields on Product {
|
|
128
128
|
id
|
|
129
129
|
availableForSale
|
|
@@ -198,7 +198,7 @@ Values:
|
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
|
-
`;var
|
|
201
|
+
`;var On=`
|
|
202
202
|
query GetSaveIntentData(
|
|
203
203
|
$productId: ID!
|
|
204
204
|
$country: CountryCode!
|
|
@@ -208,9 +208,9 @@ Values:
|
|
|
208
208
|
...saveIntentProductFields
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
|
-
${
|
|
212
|
-
${
|
|
213
|
-
`,
|
|
211
|
+
${Lt}
|
|
212
|
+
${F}
|
|
213
|
+
`,Ln=`
|
|
214
214
|
query GetSaveIntentDataWithVariant(
|
|
215
215
|
$productId: ID!
|
|
216
216
|
$variantId: ID!
|
|
@@ -224,9 +224,9 @@ Values:
|
|
|
224
224
|
...saveIntentVariantFields
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
${
|
|
228
|
-
${
|
|
229
|
-
`,
|
|
227
|
+
${Lt}
|
|
228
|
+
${F}
|
|
229
|
+
`,qn=`
|
|
230
230
|
query GetProductCardData(
|
|
231
231
|
$productId: ID!
|
|
232
232
|
$productMetafields: [HasMetafieldsIdentifier!]!
|
|
@@ -238,8 +238,8 @@ Values:
|
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
240
|
${de}
|
|
241
|
-
${
|
|
242
|
-
|
|
241
|
+
${F}
|
|
242
|
+
`,$n=`
|
|
243
243
|
query GetProductCardDataWithVariant(
|
|
244
244
|
$productId: ID!
|
|
245
245
|
$variantId: ID!
|
|
@@ -256,9 +256,9 @@ Values:
|
|
|
256
256
|
}
|
|
257
257
|
}
|
|
258
258
|
${de}
|
|
259
|
-
${
|
|
260
|
-
${
|
|
261
|
-
|
|
259
|
+
${qt}
|
|
260
|
+
${F}
|
|
261
|
+
`,Vn=`
|
|
262
262
|
query GetProductOptions(
|
|
263
263
|
$productId: ID!
|
|
264
264
|
$country: CountryCode!
|
|
@@ -269,7 +269,7 @@ Values:
|
|
|
269
269
|
}
|
|
270
270
|
}
|
|
271
271
|
${oe}
|
|
272
|
-
${
|
|
272
|
+
${F}
|
|
273
273
|
`,Bn=`
|
|
274
274
|
query GetProductOptionsByHandle(
|
|
275
275
|
$handle: String!
|
|
@@ -281,8 +281,8 @@ Values:
|
|
|
281
281
|
}
|
|
282
282
|
}
|
|
283
283
|
${oe}
|
|
284
|
-
${
|
|
285
|
-
`,
|
|
284
|
+
${F}
|
|
285
|
+
`,Nn=`
|
|
286
286
|
query GetProductOptionsWithVariant(
|
|
287
287
|
$productId: ID!
|
|
288
288
|
$variantId: ID!
|
|
@@ -297,9 +297,9 @@ Values:
|
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
299
|
${oe}
|
|
300
|
-
${
|
|
301
|
-
${
|
|
302
|
-
`,
|
|
300
|
+
${$t}
|
|
301
|
+
${F}
|
|
302
|
+
`,Un=`
|
|
303
303
|
query GetProductOptionsByHandleWithVariant(
|
|
304
304
|
$handle: String!
|
|
305
305
|
$variantId: ID!
|
|
@@ -314,9 +314,9 @@ Values:
|
|
|
314
314
|
}
|
|
315
315
|
}
|
|
316
316
|
${oe}
|
|
317
|
-
${
|
|
318
|
-
${
|
|
319
|
-
`,
|
|
317
|
+
${$t}
|
|
318
|
+
${F}
|
|
319
|
+
`,Mn=`
|
|
320
320
|
query GetSelectedVariant(
|
|
321
321
|
$productId: ID!
|
|
322
322
|
$selectedOptions: [SelectedOptionInput!]!
|
|
@@ -327,8 +327,8 @@ Values:
|
|
|
327
327
|
...selectedVariantFields
|
|
328
328
|
}
|
|
329
329
|
}
|
|
330
|
-
${
|
|
331
|
-
${
|
|
330
|
+
${Vt}
|
|
331
|
+
${F}
|
|
332
332
|
`,Gn=`
|
|
333
333
|
query GetSelectedVariantByHandle(
|
|
334
334
|
$handle: String!
|
|
@@ -340,8 +340,8 @@ Values:
|
|
|
340
340
|
...selectedVariantFields
|
|
341
341
|
}
|
|
342
342
|
}
|
|
343
|
-
${
|
|
344
|
-
${
|
|
343
|
+
${Vt}
|
|
344
|
+
${F}
|
|
345
345
|
`,Fn=`
|
|
346
346
|
query GetProductDetailData(
|
|
347
347
|
$productId: ID!
|
|
@@ -358,8 +358,8 @@ Values:
|
|
|
358
358
|
${de}
|
|
359
359
|
${oe}
|
|
360
360
|
${Bt}
|
|
361
|
-
${
|
|
362
|
-
`,
|
|
361
|
+
${F}
|
|
362
|
+
`,jn=`
|
|
363
363
|
query GetProductDetailDataWithVariant(
|
|
364
364
|
$productId: ID!
|
|
365
365
|
$variantId: ID!
|
|
@@ -379,10 +379,10 @@ Values:
|
|
|
379
379
|
}
|
|
380
380
|
${de}
|
|
381
381
|
${oe}
|
|
382
|
-
${
|
|
382
|
+
${qt}
|
|
383
383
|
${Bt}
|
|
384
|
-
${
|
|
385
|
-
`,
|
|
384
|
+
${F}
|
|
385
|
+
`,Hn=`
|
|
386
386
|
query GetProductImagesById(
|
|
387
387
|
$ids: [ID!]!
|
|
388
388
|
$country: CountryCode!
|
|
@@ -406,8 +406,8 @@ Values:
|
|
|
406
406
|
}
|
|
407
407
|
}
|
|
408
408
|
}
|
|
409
|
-
${
|
|
410
|
-
`,
|
|
409
|
+
${F}
|
|
410
|
+
`,Qn=`
|
|
411
411
|
query GetProductRecommendationsById(
|
|
412
412
|
$productId: ID!
|
|
413
413
|
$intent: ProductRecommendationIntent
|
|
@@ -418,7 +418,7 @@ Values:
|
|
|
418
418
|
id
|
|
419
419
|
}
|
|
420
420
|
}
|
|
421
|
-
`,
|
|
421
|
+
`,zn=`
|
|
422
422
|
query GetProductRecommendationsByHandle(
|
|
423
423
|
$handle: String!
|
|
424
424
|
$intent: ProductRecommendationIntent
|
|
@@ -429,17 +429,17 @@ Values:
|
|
|
429
429
|
id
|
|
430
430
|
}
|
|
431
431
|
}
|
|
432
|
-
`,
|
|
432
|
+
`,Wn=`
|
|
433
433
|
query GetProductIdByHandle($handle: String!) {
|
|
434
434
|
product(handle: $handle) {
|
|
435
435
|
id
|
|
436
436
|
}
|
|
437
437
|
}
|
|
438
|
-
`;var
|
|
438
|
+
`;var Xn=s(async(n,{productId:e,variantId:t,productMetafields:r=[],variantMetafields:i=[],country:o,language:u})=>{if(!e)throw new Error("A productId must be provided");let a=s(()=>{if(e&&!t)return qn;if(e&&t)return $n},"getProductOptionsQuery"),l=s(()=>{if(e&&!t)return{productId:E("Product",e),productMetafields:r,country:o,language:u};if(e&&t)return{productId:E("Product",e),variantId:E("ProductVariant",t),productMetafields:r,variantMetafields:i,country:o,language:u}},"getVariables"),c=a(),p=l();if(!p||!c)throw new Error("Invalid query arguments");return n.query(c,p)},"loadProductCardData");var Kn=s(async(n,{productId:e,variantId:t,productMetafields:r=[],variantMetafields:i=[],country:o,language:u})=>{if(!e)throw new Error("A productId must be provided");let a=s(()=>{if(e&&!t)return Fn;if(e&&t)return jn},"getProductOptionsQuery"),l=s(()=>{if(e&&!t)return{productId:E("Product",e),productMetafields:r,country:o,language:u};if(e&&t)return{productId:E("Product",e),variantId:E("ProductVariant",t),productMetafields:r,variantMetafields:i,country:o,language:u}},"getVariables"),c=a(),p=l();if(!p||!c)throw new Error("Invalid query arguments");return n.query(c,p)},"loadProductDetailData");var Yn=s(async(n,{productHandle:e})=>{if(!e)throw new Error("A product handle must be provided");return n.query(Wn,{handle:e})},"loadProductId");var Jn=s(async(n,{items:e,country:t,language:r})=>{if(!e?.length)throw new Error("A list of items must be provided");let i={ids:e.map(o=>o.variantId?E("ProductVariant",o.variantId.toString()):E("Product",o.productId.toString())),country:t,language:r};try{return{data:(await n.query(Hn,i)).data?.nodes.map(a=>a===null?null:"image"in a?a.image:"featuredImage"in a?a.featuredImage:null).filter(a=>a!==null)??[],error:null}}catch(o){return console.error(o),{data:null,error:o}}},"loadProductImages");var Zn=s(async(n,{productId:e,productHandle:t,variantId:r,country:i,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let u=s(()=>{if(e&&!r)return Vn;if(t&&!r)return Bn;if(e&&r)return Nn;if(t&&r)return Un},"getProductOptionsQuery"),a=s(()=>{if(e&&!r)return{productId:E("Product",e),country:i,language:o};if(t&&!r)return{handle:t,country:i,language:o};if(e&&r)return{productId:E("Product",e),variantId:E("ProductVariant",r),country:i,language:o};if(t&&r)return{handle:t,variantId:E("ProductVariant",r),country:i,language:o}},"getVariables"),l=u(),c=a();if(!c||!l)throw new Error("Invalid query arguments");return n.query(l,c)},"loadProductOptions");var er=s(async(n,{productId:e,productHandle:t,intent:r,country:i,language:o})=>{if(!e&&!t)throw new Error("Either productId or productHandle must be provided");if(e){let a={productId:E("Product",e),intent:r,country:i,language:o};return n.query(Qn,a)}let u={handle:t,intent:r,country:i,language:o};return n.query(zn,u)},"loadProductRecommendations");var tr=s(async(n,{productId:e,variantId:t,country:r,language:i})=>{let o=s(()=>{if(e&&!t)return On;if(e&&t)return Ln},"getProductOptionsQuery"),u=s(()=>{if(e&&!t)return{productId:E("Product",x(e)),country:r,language:i};if(e&&t)return{productId:E("Product",x(e)),variantId:E("ProductVariant",x(t)),country:r,language:i}},"getVariables"),a=o(),l=u();if(!l||!a)throw new Error("Invalid query arguments");return n.query(a,l)},"loadSaveIntentData");var nr=s(async(n,{productId:e,productHandle:t,selectedOptions:r,country:i,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let u=e?Mn:Gn,a=e?{productId:`gid://shopify/Product/${e}`,selectedOptions:r,country:i,language:o}:{handle:t,selectedOptions:r,country:i,language:o};return n.query(u,a)},"loadSelectedVariant");var fi="2025-10",hi=["GetProductIdByHandle"],Ye=class{constructor(e,t,r,i){this.client=null;this.query=s(async(e,t)=>{if(!this.client)throw new Error("Storefront API client not initialized");let r=await this.client.request(e,{variables:t});return{data:r.data,errors:r.errors??null}},"query");this.loadProductOptions=s(async e=>Zn(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductOptions");this.loadSelectedVariant=s(async e=>nr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSelectedVariant");this.loadProductCardData=s(async e=>Xn(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}).then(t=>t.data?"variant"in t.data?{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product,variant:t.data.variant})}}:{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product})}}:t),"loadProductCardData");this.loadProductDetailData=s(async e=>Kn(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}).then(t=>t.data?"variant"in t.data?{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product,variant:t.data.variant})}}:{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product})}}:t),"loadProductDetailData");this.loadProductImages=s(async e=>Jn(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductImages");this.loadProductRecommendations=s(async e=>er(this,{...e,country:this.context.localization.country,language:this.context.localization.language}),"loadProductRecommendations");this.loadProductId=s(async e=>Yn(this,e),"loadProductId");this.loadSaveIntentData=s(async e=>tr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSaveIntentData");this.options=e,this.context=t,this.badges=r,this.metafields={productMetafields:i?.product.map(u=>({namespace:u.split(".")[0],key:u.split(".")[1]}))??[],variantMetafields:i?.productVariant.map(u=>({namespace:u.split(".")[0],key:u.split(".")[1]}))??[]};let o=j(t.myshopifyDomain);this.shortCache=new X(`storefront-api-short-${o}`,"max-age=60, stale-while-revalidate=3600"),this.longCache=new X(`storefront-api-long-${o}`,"max-age=3600, stale-while-revalidate=86400"),this.shortCache.cleanupExpiredEntries().catch(u=>{console.warn("Storefront API cache initialization cleanup error:",u)}),this.longCache.cleanupExpiredEntries().catch(u=>{console.warn("Storefront API cache initialization cleanup error:",u)}),this.client=Ot({apiVersion:fi,customFetchApi:s((u,a)=>a?.method==="OPTIONS"?this.fetch(u,a):hi.some(l=>a?.body?.toString().includes(`query ${l}`))?this.longCache.fetchWithCache(u,a):this.shortCache.fetchWithCache(u,a),"customFetchApi"),publicAccessToken:this.options.accessToken,storeDomain:this.options.storeDomain})}static{s(this,"StorefrontApiClient")}fetch(e,t){return t?.method==="OPTIONS"?fetch(e,t):this.shortCache.fetchWithCache(e,t)}async clearCache(){await this.shortCache.clear()}};var mi=Object.defineProperty,d=s((n,e)=>mi(n,"name",{value:e,configurable:!0}),"n"),yi={bodySerializer:d(n=>JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t),"bodySerializer")},vi={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},lc=Object.entries(vi),gi=d(({onRequest:n,onSseError:e,onSseEvent:t,responseTransformer:r,responseValidator:i,sseDefaultRetryDelay:o,sseMaxRetryAttempts:u,sseMaxRetryDelay:a,sseSleepFn:l,url:c,...p})=>{let h,g=l??(f=>new Promise(P=>setTimeout(P,f)));return{stream:d(async function*(){let f=o??3e3,P=0,v=p.signal??new AbortController().signal;for(;!v.aborted;){P++;let _=p.headers instanceof Headers?p.headers:new Headers(p.headers);h!==void 0&&_.set("Last-Event-ID",h);try{let V={redirect:"follow",...p,body:p.serializedBody,headers:_,signal:v},O=new Request(c,V);n&&(O=await n(c,V));let z=await(p.fetch??globalThis.fetch)(O);if(!z.ok)throw new Error(`SSE failed: ${z.status} ${z.statusText}`);if(!z.body)throw new Error("No body in SSE response");let k=z.body.pipeThrough(new TextDecoderStream).getReader(),I="",q=d(()=>{try{k.cancel()}catch{}},"abortHandler");v.addEventListener("abort",q);try{for(;;){let{done:$,value:le}=await k.read();if($)break;I+=le;let Qt=I.split(`
|
|
439
439
|
|
|
440
|
-
`);I=
|
|
441
|
-
`),fe=[],
|
|
442
|
-
`);try{te=JSON.parse(Q),zt=!0}catch{te=Q}}zt&&(i&&await i(te),r&&(te=await r(te))),t?.({data:te,event:Qt,id:h,retry:f}),fe.length&&(yield te)}}}finally{v.removeEventListener("abort",q),C.releaseLock()}break}catch(B){if(e?.(B),u!==void 0&&P>=u)break;let O=Math.min(f*2**(P-1),a??3e4);await g(O)}}},"createStream")()}},"createSseClient"),vi=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),gi=d(n=>{switch(n){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),Ii=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),ir=d(({allowReserved:n,explode:e,name:t,style:r,value:i})=>{if(!e){let a=(n?i:i.map(l=>encodeURIComponent(l))).join(gi(r));switch(r){case"label":return`.${a}`;case"matrix":return`;${t}=${a}`;case"simple":return a;default:return`${t}=${a}`}}let o=vi(r),u=i.map(a=>r==="label"||r==="simple"?n?a:encodeURIComponent(a):Je({allowReserved:n,name:t,value:a})).join(o);return r==="label"||r==="matrix"?o+u:u},"serializeArrayParam"),Je=d(({allowReserved:n,name:e,value:t})=>{if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${n?t:encodeURIComponent(t)}`},"serializePrimitiveParam"),sr=d(({allowReserved:n,explode:e,name:t,style:r,value:i,valueOnly:o})=>{if(i instanceof Date)return o?i.toISOString():`${t}=${i.toISOString()}`;if(r!=="deepObject"&&!e){let l=[];Object.entries(i).forEach(([p,h])=>{l=[...l,p,n?h:encodeURIComponent(h)]});let c=l.join(",");switch(r){case"form":return`${t}=${c}`;case"label":return`.${c}`;case"matrix":return`;${t}=${c}`;default:return c}}let u=Ii(r),a=Object.entries(i).map(([l,c])=>Je({allowReserved:n,name:r==="deepObject"?`${t}[${l}]`:l,value:c})).join(u);return r==="label"||r==="matrix"?u+a:a},"serializeObjectParam"),wi=/\{[^{}]+\}/g,bi=d(({path:n,url:e})=>{let t=e,r=e.match(wi);if(r)for(let i of r){let o=!1,u=i.substring(1,i.length-1),a="simple";u.endsWith("*")&&(o=!0,u=u.substring(0,u.length-1)),u.startsWith(".")?(u=u.substring(1),a="label"):u.startsWith(";")&&(u=u.substring(1),a="matrix");let l=n[u];if(l==null)continue;if(Array.isArray(l)){t=t.replace(i,ir({explode:o,name:u,style:a,value:l}));continue}if(typeof l=="object"){t=t.replace(i,sr({explode:o,name:u,style:a,value:l,valueOnly:!0}));continue}if(a==="matrix"){t=t.replace(i,`;${Je({name:u,value:l})}`);continue}let c=encodeURIComponent(a==="label"?`.${l}`:l);t=t.replace(i,c)}return t},"defaultPathSerializer"),Si=d(({baseUrl:n,path:e,query:t,querySerializer:r,url:i})=>{let o=i.startsWith("/")?i:`/${i}`,u=(n??"")+o;e&&(u=bi({path:e,url:u}));let a=t?r(t):"";return a.startsWith("?")&&(a=a.substring(1)),a&&(u+=`?${a}`),u},"getUrl");function or(n){let e=n.body!==void 0;if(e&&n.bodySerializer)return"serializedBody"in n?n.serializedBody!==void 0&&n.serializedBody!==""?n.serializedBody:null:n.body!==""?n.body:null;if(e)return n.body}s(or,"K");d(or,"getValidRequestBody");var Ei=d(async(n,e)=>{let t=typeof e=="function"?await e(n):e;if(t)return n.scheme==="bearer"?`Bearer ${t}`:n.scheme==="basic"?`Basic ${btoa(t)}`:t},"getAuthToken"),ar=d(({allowReserved:n,array:e,object:t}={})=>d(r=>{let i=[];if(r&&typeof r=="object")for(let o in r){let u=r[o];if(u!=null)if(Array.isArray(u)){let a=ir({allowReserved:n,explode:!0,name:o,style:"form",value:u,...e});a&&i.push(a)}else if(typeof u=="object"){let a=sr({allowReserved:n,explode:!0,name:o,style:"deepObject",value:u,...t});a&&i.push(a)}else{let a=Je({allowReserved:n,name:o,value:u});a&&i.push(a)}}return i.join("&")},"querySerializer"),"createQuerySerializer"),xi=d(n=>{var e;if(!n)return"stream";let t=(e=n.split(";")[0])==null?void 0:e.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(r=>t.startsWith(r)))return"blob";if(t.startsWith("text/"))return"text"}},"getParseAs"),Ci=d((n,e)=>{var t,r;return e?!!(n.headers.has(e)||(t=n.query)!=null&&t[e]||(r=n.headers.get("Cookie"))!=null&&r.includes(`${e}=`)):!1},"checkForExistence"),ki=d(async({security:n,...e})=>{for(let t of n){if(Ci(e,t.name))continue;let r=await Ei(t,e.auth);if(!r)continue;let i=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[i]=r;break;case"cookie":e.headers.append("Cookie",`${i}=${r}`);break;case"header":default:e.headers.set(i,r);break}}},"setAuthParams"),nr=d(n=>Si({baseUrl:n.baseUrl,path:n.path,query:n.query,querySerializer:typeof n.querySerializer=="function"?n.querySerializer:ar(n.querySerializer),url:n.url}),"buildUrl"),rr=d((n,e)=>{var t;let r={...n,...e};return(t=r.baseUrl)!=null&&t.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=ur(n.headers,e.headers),r},"mergeConfigs"),Ri=d(n=>{let e=[];return n.forEach((t,r)=>{e.push([r,t])}),e},"headersEntries"),ur=d((...n)=>{let e=new Headers;for(let t of n){if(!t)continue;let r=t instanceof Headers?Ri(t):Object.entries(t);for(let[i,o]of r)if(o===null)e.delete(i);else if(Array.isArray(o))for(let u of o)e.append(i,u);else o!==void 0&&e.set(i,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),lr=class{static{s(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let r=this.getInterceptorIndex(e);return this.fns[r]?(this.fns[r]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(lr,"Interceptors");var Vt=lr,Ai=d(()=>({error:new Vt,request:new Vt,response:new Vt}),"createInterceptors"),Di=ar({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Pi={"Content-Type":"application/json"},Ye=d((n={})=>({...hi,headers:Pi,parseAs:"auto",querySerializer:Di,...n}),"createConfig"),Nt=d((n={})=>{let e=rr(Ye(),n),t=d(()=>({...e}),"getConfig"),r=d(c=>(e=rr(e,c),t()),"setConfig"),i=Ai(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:ur(e.headers,c.headers),serializedBody:void 0};p.security&&await ki({...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=nr(p);return{opts:p,url:h}},"beforeRequest"),u=d(async c=>{let{opts:p,url:h}=await o(c),g={redirect:"follow",...p,body:or(p)},f=new Request(h,g);for(let I of i.request.fns)I&&(f=await I(f,p));let P=p.fetch,v=await P(f);for(let I of i.response.fns)I&&(v=await I(v,f,p));let _={request:f,response:v};if(v.ok){let I=(p.parseAs==="auto"?xi(v.headers.get("Content-Type")):p.parseAs)??"json";if(v.status===204||v.headers.get("Content-Length")==="0"){let $;switch(I){case"arrayBuffer":case"blob":case"text":$=await v[I]();break;case"formData":$=new FormData;break;case"stream":$=v.body;break;case"json":default:$={};break}return p.responseStyle==="data"?$:{data:$,..._}}let q;switch(I){case"arrayBuffer":case"blob":case"formData":case"json":case"text":q=await v[I]();break;case"stream":return p.responseStyle==="data"?v.body:{data:v.body,..._}}return I==="json"&&(p.responseValidator&&await p.responseValidator(q),p.responseTransformer&&(q=await p.responseTransformer(q))),p.responseStyle==="data"?q:{data:q,..._}}let B=await v.text(),O;try{O=JSON.parse(B)}catch{}let z=O??B,C=z;for(let I of i.error.fns)I&&(C=await I(z,v,f,p));if(C=C||{},p.throwOnError)throw C;return p.responseStyle==="data"?void 0:{error:C,..._}},"request"),a=d(c=>p=>u({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:h,url:g}=await o(p);return yi({...h,body:h.body,headers:h.headers,method:c,onRequest:d(async(f,P)=>{let v=new Request(f,P);for(let _ of i.request.fns)_&&(v=await _(v,h));return v},"onRequest"),url:g})},"makeSseFn");return{buildUrl:nr,connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:t,head:a("HEAD"),interceptors:i,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:u,setConfig:r,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:a("TRACE")}},"createClient"),S=Nt(Ye({baseUrl:"https://swish.app/api/2026-01"})),Ti=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n}),"listControllerFind"),_i=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerCreate"),Oi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerDeleteById"),Li=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerFindById"),qi=d(n=>(n.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerUpdateById"),$i=d(n=>(n.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerSetListItemsOrder"),Bi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerAddItemsToList"),Vi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...n}),"listControllerRemoveItemFromList"),Ni=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerDelete"),Ui=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...n}),"itemControllerFind"),Gi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerCreate"),Fi=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...n}),"itemControllerCount"),Mi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerDeleteById"),ji=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerFindById"),Hi=d(n=>(n.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerUpdateById"),Qi=d(n=>(n.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerSetListsById"),zi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerIdentify"),Wi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerCreateToken"),Xi=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...n}),"profileControllerGetProfile"),Ki=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...n}),"analyticsControllerLoadSavedItems"),Yi=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...n}),"analyticsControllerLoadSessions"),Ji=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...n}),"analyticsControllerLoadNewLists"),Zi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/tracking",...n,headers:{"Content-Type":"application/json",...n.headers}}),"trackingControllerTrack"),es=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...n}),"ordersControllerFind"),ts=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...n}),"ordersControllerFindOne"),ns=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}/save",...n}),"sharedListsControllerSave"),rs=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerDeleteById"),is=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerFindById"),ss=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...n}),"sharedListsControllerFindAll"),Ut="2026-01",cr=d(n=>new os(n),"createApiClient"),pr=class{static{s(this,"H")}constructor(e){this.version=Ut,this.items={list:d(a=>this.handlePaginatedRequest(Ui({query:a,client:this.directClient})),"list"),create:d(a=>this.handleRequest(Gi({body:a,client:this.directClient})),"create"),delete:d(a=>this.handleRequest(Ni({body:{itemIds:a},client:this.directClient})),"delete"),findById:d(a=>this.handleRequest(ji({path:{itemId:a},client:this.directClient})),"findById"),updateById:d((a,l)=>this.handleRequest(Hi({body:l,path:{itemId:a},client:this.directClient})),"updateById"),deleteById:d(a=>this.handleRequest(Mi({path:{itemId:a},client:this.directClient})),"deleteById"),setListsById:d((a,l)=>this.handleRequest(Qi({body:{listIds:l},path:{itemId:a},client:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(Fi({client:this.directClient})),"count")},this.lists={list:d(a=>this.handlePaginatedRequest(Ti({query:a,client:this.directClient})),"list"),create:d(a=>this.handleRequest(_i({body:a,client:this.directClient})),"create"),findById:d(a=>this.handleRequest(Li({path:{listId:a},client:this.directClient})),"findById"),updateById:d((a,l)=>this.handleRequest(qi({body:l,path:{listId:a},client:this.directClient})),"updateById"),deleteById:d(a=>this.handleRequest(Oi({path:{listId:a},client:this.directClient})),"deleteById"),orderItems:d((a,l)=>this.handleRequest($i({body:{itemIds:l},path:{listId:a},client:this.directClient})),"orderItems"),addItemsToList:d((a,l)=>this.handleRequest(Bi({body:{itemIds:l},path:{listId:a},client:this.directClient})),"addItemsToList"),removeItemFromList:d((a,l)=>this.handleRequest(Vi({path:{listId:a,itemId:l},client:this.directClient})),"removeItemFromList")},this.profiles={createToken:d((a={})=>this.handleRequest(Wi({body:a,client:this.proxyClient??this.directClient})),"createToken"),identify:d(a=>this.handleRequest(zi({body:a,client:this.directClient})),"identify"),getProfile:d(()=>this.handleRequest(Xi({client:this.directClient})),"getProfile")},this.orders={list:d(a=>this.handlePaginatedRequest(es({query:a,client:this.directClient})),"list"),findById:d(a=>this.handleRequest(ts({path:{orderId:a},client:this.directClient})),"findById")},this.sharedLists={list:d(a=>this.handlePaginatedRequest(ss({query:a,client:this.directClient})),"list"),save:d(a=>this.handleRequest(ns({path:{listId:a},client:this.directClient})),"save"),findById:d(a=>this.handleRequest(is({path:{listId:a},client:this.directClient})),"findById"),deleteById:d(a=>this.handleRequest(rs({path:{listId:a},client:this.directClient})),"deleteById")},this.analytics={savedItems:d(a=>this.handleRequest(Ki({query:a,client:this.directClient})),"savedItems"),sessions:d(a=>this.handleRequest(Yi({query:a,client:this.directClient})),"sessions"),newLists:d(a=>this.handleRequest(Ji({query:a,client:this.directClient})),"newLists")},this.tracking={track:d((a,l)=>this.handleRequest(Zi({body:a,headers:l,client:this.directClient})),"track")},this.handleRequest=d(async a=>{let{data:l,error:c}=await a;return c!=null&&c.error?{error:c.error}:{data:l?.data}},"handleRequest"),this.handlePaginatedRequest=d(async a=>{var l;let{data:c,error:p}=await a;return p!=null&&p.error?{error:p.error}:{data:c?.data??[],pageInfo:c?.pageInfo??{next:null,previous:null,totalCount:((l=c?.data)==null?void 0:l.length)??0}}},"handlePaginatedRequest");var t,r,i,o,u;(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=Nt(Ye({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),(r=e.config)!=null&&r.authProxy&&(this.proxyClient=Nt(Ye({...e.config,baseUrl:e.config.authProxy}))),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&((i=this.proxyClient)==null||i.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&((o=this.proxyClient)==null||o.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),(u=this.proxyClient)==null||u.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setAuthToken(e){this.authToken=e}proxyRequestInterceptor(e){return this.version&&e.headers.set("Swish-Api-Version",this.version),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(pr,"SwishClient");var os=pr;var mr=kr(hr(),1);var yr=s(n=>new mr.default(async e=>{let t=[...new Set(e)].sort((i,o)=>i.localeCompare(o)),r=await n.items.list({query:t.join(" "),limit:200});return"error"in r?(console.error("Failed to load items",r.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let o=r.data.find(u=>i===`variant:${u.variantId}`||i===`product:${u.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:s(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var Ze=class{constructor(e,t,r){this.tokenHasProfile=!1;this.api=e,this.context=t,this.eventBus=r}static{s(this,"SwishApiAuth")}hasProfile(){return this.tokenHasProfile}hasToken(){return!!this.getSwishToken()}async renewToken(){return this._renewPromise?this._renewPromise:(this._renewPromise=(async()=>{this._initPromise=void 0,this.deleteSwishToken(),await this.init(),this._renewPromise=void 0})(),this._renewPromise)}async init(){return this._initPromise?this._initPromise:(this._initPromise=(async()=>{this.migrateLegacySession();let e=this.context.customer.id;e?(this.hasSessionToken()&&await this.api.clearCache(),await this.initCustomer(e)):(this.hasCustomerToken()&&await this.resetSession(),await this.initSession()),this.eventBus.publish("token-update",null)})(),this._initPromise)}async initCustomer(e){let t=`gid://shopify/Customer/${e}`,r=this.getTokenBySub(t);if(r){this.initToken(r);return}let i=this.getSessionId();await this.acquireToken(i,t)}async initSession(){let e=this.getSessionId(),t=e?this.getTokenBySub(e):null;if(t){this.initToken(t);return}await this.acquireToken(e)}initToken(e){let t=this.getTokenData(e);if(!t)throw new Error("Invalid Swish token.");this.tokenHasProfile=t.has_profile!==!1,this.api.setAuthToken(e)}async acquireToken(e,t){let r=await this.api.profiles.createToken({customer:t,session:e});if("error"in r)throw console.error("Failed to create customer token",r.error),new Error("Failed to create customer token");if(!r.data?.token)throw console.error("Failed to create customer token empty response"),new Error("Failed to create customer token");r.data.profile.startsWith("gid://swish/Session/")&&this.setSessionId(r.data.profile),this.setSwishToken(r.data.token),this.initToken(r.data.token)}async resetSession(){this.deleteSessionId(),this.deleteSwishToken(),await this.api.clearCache()}getTokenData(e){try{return JSON.parse(atob(e.split(".")[1]))}catch(t){return console.error("Failed to parse Swish token",{cause:t}),null}}willTokenExpire(e,t=60){let r=this.getTokenData(e);return!!(r&&r.exp&&r.exp<Date.now()/1e3+t)}hasCustomerToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://shopify/Customer/")??!1:!1}hasSessionToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://swish/Session/")??!1:!1}getTokenBySub(e){if(!e)return null;let t=this.getSwishToken();if(!t)return null;let r=this.getTokenData(t);return!r||r.sub!==e||this.willTokenExpire(t,60)?null:t}getSessionId(){let e=j(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let t=j(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${t}`,e)}deleteSessionId(){let e=j(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=j(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let t=j(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${t}`,e)}deleteSwishToken(){let e=j(this.context.myshopifyDomain);sessionStorage.removeItem(`swish-token-${e}`)}migrateLegacySession(){try{let e=localStorage.getItem("wk_session_id")??localStorage.getItem("swish-profile")?.split("/").pop()??localStorage.getItem("swish-session")?.split("/").pop();e&&(this.setSessionId(`gid://swish/Session/${e}`),localStorage.removeItem("wk_session_id"),localStorage.removeItem("swish-profile"),localStorage.removeItem("swish-session"))}catch(e){console.warn("Failed to migrate legacy session id to Swish session",{cause:e})}}};var et=class{static{s(this,"SwishApi")}constructor(e,t,r,i){this.config=e,this.storefrontContext=t;let o=j(t.myshopifyDomain);this.cache=new X(`swish-api-${o}`,"max-age=60, stale-while-revalidate=3600",i+(e.version??Ut)),this.cache.cleanupExpiredEntries().catch(u=>{console.warn("Swish API cache initialization cleanup error:",u)}),this.auth=new Ze(this,t,r),this.apiClient=cr({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=yr(this)}async fetchFunction(e,t){let r=e instanceof Request?e.method:t?.method??"GET",o=(e instanceof Request?e.url:typeof e=="string"?e:e.toString()).includes("/orders");return r==="GET"&&!o?this.cache.fetchWithCache(e,t):fetch(e,t)}async requestInterceptor(e){let t=new URL(e.url,window.location.origin);!!this.config.authProxy&&t.pathname.startsWith(this.config.authProxy)||await this.auth.init();try{e.headers.set("Country",this.storefrontContext.localization.country),e.headers.set("Language",this.storefrontContext.localization.language),e.headers.set("Market",this.storefrontContext.localization.market)}catch(i){console.warn("Failed to set storefront context headers:",i)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,t){let r=t.method!=="GET",i=t.url.includes("/profiles/token");if(r&&!i){let o=this.auth.hasToken(),u=!this.auth.hasProfile(),a=e.ok;await this.cache.clear(),o&&u&&a&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,t),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}withFallback(e,t){return this.auth.hasProfile()?e():Promise.resolve(t)}get items(){return{...this.apiClient.items,count:s(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:s(async(e,t)=>this.withFallback(()=>{if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let r=e.query.split(" ");r.length>1&&console.warn("Batching will only support one query parameter");let i=r[0];if(!i.match(/^product:\d+$/)&&!i.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(i)}return this.apiClient.items.list(e)},{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:s(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>this.apiClient.lists.findById(e),{data:null}),"findById")}}get orders(){return{...this.apiClient.orders,list:s(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>(typeof e=="string"&&(e=parseInt(e.split("/").pop()??e)),this.apiClient.orders.findById(e)),{data:null}),"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{s(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.method,e.status,t.url);if(!r)return;let i=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{i=JSON.parse(i).data}catch(o){console.warn(o)}this.eventBus.publish(r,i)}catch(r){console.warn(r)}}getEventName(e,t,r){e=e.toUpperCase();let i=new URL(r).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([u])=>{let[a,l]=u.split(" ");return a!==e?!1:new RegExp(l).test(i)})?.[1]}};var nt=class{constructor(e,t){this.inflightModals=new Map;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._lockScroll=s(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=s(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{s(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")!=="true")&&e.setAttribute("open","false")})().finally(()=>{this.inflightModals.delete(e)});return this.unlockScroll(),this.inflightModals.set(e,t),t}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&e.setAttribute("open","true")})().finally(()=>{this.inflightModals.delete(e)});return this.lockScroll(),this.inflightModals.set(e,t),t}waitForEvent(e,t){return new Promise(r=>{let i=[],o=s(()=>{i.forEach(({event:u,listener:a})=>{e.removeEventListener(u,a)})},"cleanup");Object.entries(t).forEach(([u,a])=>{let l=s(c=>{let p=a(c);o(),r(p)},"listener");i.push({event:u,listener:l}),e.addEventListener(u,l)})})}async showSignIn(e){let t=await this.requireUiComponent("sign-in");t.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let t=await this.requireUiComponent("unsave-alert");t.setAttribute("item-id",e.itemId),await this.showModal(t);let r=await this.waitForEvent(t,{submit:s(i=>i instanceof CustomEvent?{code:"ok",data:i.detail}:(console.warn("Unsave alert submitted without detail",i),{code:"closed"}),"submit"),close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let t=await this.requireUiComponent("delete-list-alert");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{submit:s(()=>({code:"ok",data:void 0}),"submit"),close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showDrawer(e){await this.hideAllToasts();let t=await this.requireUiComponent("drawer");t.setAttribute("account-url",this.storefrontContext.routes.accountUrl),this.storefrontContext.customer.id&&t.setAttribute("customer-id",this.storefrontContext.customer.id),t.setAttribute("view",e?.view??"home"),e?.listId&&t.setAttribute("list-id",e.listId),e?.productId&&t.setAttribute("product-id",e.productId),e?.variantId&&t.setAttribute("variant-id",e.variantId),e?.orderId&&t.setAttribute("order-id",e.orderId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-menu");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),edit:s(i=>i instanceof CustomEvent?{code:"ok",data:{action:"edit",data:i.detail}}:(console.warn("List menu edit without detail",i),{code:"closed"}),"edit"),delete:s(()=>({code:"ok",data:{action:"delete"}}),"delete")});return await this.hideModal(t),r}async showListDetailPageMenu(e){await this.hideAllToasts();let t=await this.requireUiComponent("list-detail-page-menu");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-select");t.setAttribute("item-id",e.itemId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:{action:"submit",data:i.detail}}:(console.warn("List select submit without detail",i),{code:"closed"}),"submit"),unsave:s(i=>i instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:i.detail}}:(console.warn("List select unsave without detail",i),{code:"closed"}),"unsave")});return await this.hideModal(t),r}async initListDetailPage(e,t){let r=await this.requireUiComponent("list-detail-page",{refElement:t});e.listId&&r.setAttribute("list-id",e.listId)}async showToast(e){let t=Date.now(),r=await this.requireUiComponent("toast-manager",{onHydrated:s(i=>{i.current.show(e,t)},"onHydrated")});return this.waitForEvent(r,{[`close-${t}`]:()=>({code:"closed"}),[`submit-${t}`]:()=>({code:"ok",data:void 0})})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:s(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let t=await this.requireUiComponent("variant-select");if(e?.itemId&&t.setAttribute("item-id",e.itemId),e?.productId)t.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId.toString()),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Variant select submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async showQuickBuy(e){await this.hideAllToasts();let t=await this.requireUiComponent("quick-buy");if(e?.productId)t.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("ProductId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId.toString()),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Quick buy submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async showListEditor(e){let t=await this.requireUiComponent("list-editor");e?.listId&&t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("List editor submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async requireUiComponent(e,t){this.loadCricalResources();let r=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`,i=await fetch(r).then(a=>a.text()),o=t?.instance,u=this.queryComponent(e,o)??await this.insertComponent({name:e,template:i,refElement:t?.refElement??document.body,position:"beforeend",instance:o});if(u.shadowRoot&&!u.hasAttribute("hydrated")){let a=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;Promise.all([this.loadNonCriticalResources(),import(a)]).then(([{bundleCssStylesheet:l,customCssStylesheets:c},{hydrate:p}])=>{u.shadowRoot&&l&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,...c,l],u.shadowRoot?.querySelector(":host > style")?.remove()),p(u),u.setAttribute("hydrated",""),t?.onHydrated?.(u.getComponentRef())})}else u.hasAttribute("hydrated")&&t?.onHydrated?.(u.getComponentRef());return u}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/theme.css`,t=await fetch(e).then(i=>i.text()),r=new CSSStyleSheet;return r.replaceSync(t),this.swishUiOptions.theme&&Object.entries(this.swishUiOptions.theme).forEach(([i,o])=>{r.cssRules[0].cssRules[0].style.setProperty(i,o)}),{themeVariablesStylesheet:r}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/bundle.css`,t=s(o=>{let u=new CSSStyleSheet;return u.replaceSync(o),u},"createCssStylesheet"),[r,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(t),...this.swishUiOptions.css.map(async o=>o instanceof URL?t(await fetch(o).then(u=>u.text())):t(o))]);return{bundleCssStylesheet:r,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,instance:t,template:r,position:i,refElement:o}){let{themeVariablesStylesheet:u}=await this.loadCricalResources();o.insertAdjacentHTML(i,r.replace(' shadowrootmode="open"',""));let a=this.queryComponent(e,t);if(!a)throw new Error(`Element ${e} not found in DOM`);return a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[u]),a}queryComponent(e,t){let r=`swish-ui[ref="${e}${t?`-${t}`:""}"]`;return document.querySelector(r)}lockScroll(){this.scrollLockRefCount++,this.scrollLockRefCount===1&&(this.scrollPositionBeforeLock=window.scrollY,this.scrollLockStyleSheet||(this.scrollLockStyleSheet=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,this.scrollLockStyleSheet]),this.scrollLockStyleSheet.replaceSync(`
|
|
440
|
+
`);I=Qt.pop()??"";for(let gr of Qt){let Ir=gr.split(`
|
|
441
|
+
`),fe=[],zt;for(let Q of Ir)if(Q.startsWith("data:"))fe.push(Q.replace(/^data:\s*/,""));else if(Q.startsWith("event:"))zt=Q.replace(/^event:\s*/,"");else if(Q.startsWith("id:"))h=Q.replace(/^id:\s*/,"");else if(Q.startsWith("retry:")){let Xt=Number.parseInt(Q.replace(/^retry:\s*/,""),10);Number.isNaN(Xt)||(f=Xt)}let te,Wt=!1;if(fe.length){let Q=fe.join(`
|
|
442
|
+
`);try{te=JSON.parse(Q),Wt=!0}catch{te=Q}}Wt&&(i&&await i(te),r&&(te=await r(te))),t?.({data:te,event:zt,id:h,retry:f}),fe.length&&(yield te)}}}finally{v.removeEventListener("abort",q),k.releaseLock()}break}catch(V){if(e?.(V),u!==void 0&&P>=u)break;let O=Math.min(f*2**(P-1),a??3e4);await g(O)}}},"createStream")()}},"createSseClient"),Ii=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),wi=d(n=>{switch(n){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),bi=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),sr=d(({allowReserved:n,explode:e,name:t,style:r,value:i})=>{if(!e){let a=(n?i:i.map(l=>encodeURIComponent(l))).join(wi(r));switch(r){case"label":return`.${a}`;case"matrix":return`;${t}=${a}`;case"simple":return a;default:return`${t}=${a}`}}let o=Ii(r),u=i.map(a=>r==="label"||r==="simple"?n?a:encodeURIComponent(a):Ze({allowReserved:n,name:t,value:a})).join(o);return r==="label"||r==="matrix"?o+u:u},"serializeArrayParam"),Ze=d(({allowReserved:n,name:e,value:t})=>{if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${n?t:encodeURIComponent(t)}`},"serializePrimitiveParam"),or=d(({allowReserved:n,explode:e,name:t,style:r,value:i,valueOnly:o})=>{if(i instanceof Date)return o?i.toISOString():`${t}=${i.toISOString()}`;if(r!=="deepObject"&&!e){let l=[];Object.entries(i).forEach(([p,h])=>{l=[...l,p,n?h:encodeURIComponent(h)]});let c=l.join(",");switch(r){case"form":return`${t}=${c}`;case"label":return`.${c}`;case"matrix":return`;${t}=${c}`;default:return c}}let u=bi(r),a=Object.entries(i).map(([l,c])=>Ze({allowReserved:n,name:r==="deepObject"?`${t}[${l}]`:l,value:c})).join(u);return r==="label"||r==="matrix"?u+a:a},"serializeObjectParam"),Si=/\{[^{}]+\}/g,Ei=d(({path:n,url:e})=>{let t=e,r=e.match(Si);if(r)for(let i of r){let o=!1,u=i.substring(1,i.length-1),a="simple";u.endsWith("*")&&(o=!0,u=u.substring(0,u.length-1)),u.startsWith(".")?(u=u.substring(1),a="label"):u.startsWith(";")&&(u=u.substring(1),a="matrix");let l=n[u];if(l==null)continue;if(Array.isArray(l)){t=t.replace(i,sr({explode:o,name:u,style:a,value:l}));continue}if(typeof l=="object"){t=t.replace(i,or({explode:o,name:u,style:a,value:l,valueOnly:!0}));continue}if(a==="matrix"){t=t.replace(i,`;${Ze({name:u,value:l})}`);continue}let c=encodeURIComponent(a==="label"?`.${l}`:l);t=t.replace(i,c)}return t},"defaultPathSerializer"),xi=d(({baseUrl:n,path:e,query:t,querySerializer:r,url:i})=>{let o=i.startsWith("/")?i:`/${i}`,u=(n??"")+o;e&&(u=Ei({path:e,url:u}));let a=t?r(t):"";return a.startsWith("?")&&(a=a.substring(1)),a&&(u+=`?${a}`),u},"getUrl");function ar(n){let e=n.body!==void 0;if(e&&n.bodySerializer)return"serializedBody"in n?n.serializedBody!==void 0&&n.serializedBody!==""?n.serializedBody:null:n.body!==""?n.body:null;if(e)return n.body}s(ar,"K");d(ar,"getValidRequestBody");var Ci=d(async(n,e)=>{let t=typeof e=="function"?await e(n):e;if(t)return n.scheme==="bearer"?`Bearer ${t}`:n.scheme==="basic"?`Basic ${btoa(t)}`:t},"getAuthToken"),ur=d(({allowReserved:n,array:e,object:t}={})=>d(r=>{let i=[];if(r&&typeof r=="object")for(let o in r){let u=r[o];if(u!=null)if(Array.isArray(u)){let a=sr({allowReserved:n,explode:!0,name:o,style:"form",value:u,...e});a&&i.push(a)}else if(typeof u=="object"){let a=or({allowReserved:n,explode:!0,name:o,style:"deepObject",value:u,...t});a&&i.push(a)}else{let a=Ze({allowReserved:n,name:o,value:u});a&&i.push(a)}}return i.join("&")},"querySerializer"),"createQuerySerializer"),ki=d(n=>{var e;if(!n)return"stream";let t=(e=n.split(";")[0])==null?void 0:e.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(r=>t.startsWith(r)))return"blob";if(t.startsWith("text/"))return"text"}},"getParseAs"),Ri=d((n,e)=>{var t,r;return e?!!(n.headers.has(e)||(t=n.query)!=null&&t[e]||(r=n.headers.get("Cookie"))!=null&&r.includes(`${e}=`)):!1},"checkForExistence"),Ai=d(async({security:n,...e})=>{for(let t of n){if(Ri(e,t.name))continue;let r=await Ci(t,e.auth);if(!r)continue;let i=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[i]=r;break;case"cookie":e.headers.append("Cookie",`${i}=${r}`);break;case"header":default:e.headers.set(i,r);break}}},"setAuthParams"),rr=d(n=>xi({baseUrl:n.baseUrl,path:n.path,query:n.query,querySerializer:typeof n.querySerializer=="function"?n.querySerializer:ur(n.querySerializer),url:n.url}),"buildUrl"),ir=d((n,e)=>{var t;let r={...n,...e};return(t=r.baseUrl)!=null&&t.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=lr(n.headers,e.headers),r},"mergeConfigs"),Di=d(n=>{let e=[];return n.forEach((t,r)=>{e.push([r,t])}),e},"headersEntries"),lr=d((...n)=>{let e=new Headers;for(let t of n){if(!t)continue;let r=t instanceof Headers?Di(t):Object.entries(t);for(let[i,o]of r)if(o===null)e.delete(i);else if(Array.isArray(o))for(let u of o)e.append(i,u);else o!==void 0&&e.set(i,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),cr=class{static{s(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let r=this.getInterceptorIndex(e);return this.fns[r]?(this.fns[r]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(cr,"Interceptors");var Nt=cr,Pi=d(()=>({error:new Nt,request:new Nt,response:new Nt}),"createInterceptors"),Ti=ur({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_i={"Content-Type":"application/json"},Je=d((n={})=>({...yi,headers:_i,parseAs:"auto",querySerializer:Ti,...n}),"createConfig"),Ut=d((n={})=>{let e=ir(Je(),n),t=d(()=>({...e}),"getConfig"),r=d(c=>(e=ir(e,c),t()),"setConfig"),i=Pi(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:lr(e.headers,c.headers),serializedBody:void 0};p.security&&await Ai({...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=rr(p);return{opts:p,url:h}},"beforeRequest"),u=d(async c=>{let{opts:p,url:h}=await o(c),g={redirect:"follow",...p,body:ar(p)},f=new Request(h,g);for(let I of i.request.fns)I&&(f=await I(f,p));let P=p.fetch,v=await P(f);for(let I of i.response.fns)I&&(v=await I(v,f,p));let _={request:f,response:v};if(v.ok){let I=(p.parseAs==="auto"?ki(v.headers.get("Content-Type")):p.parseAs)??"json";if(v.status===204||v.headers.get("Content-Length")==="0"){let $;switch(I){case"arrayBuffer":case"blob":case"text":$=await v[I]();break;case"formData":$=new FormData;break;case"stream":$=v.body;break;case"json":default:$={};break}return p.responseStyle==="data"?$:{data:$,..._}}let q;switch(I){case"arrayBuffer":case"blob":case"formData":case"json":case"text":q=await v[I]();break;case"stream":return p.responseStyle==="data"?v.body:{data:v.body,..._}}return I==="json"&&(p.responseValidator&&await p.responseValidator(q),p.responseTransformer&&(q=await p.responseTransformer(q))),p.responseStyle==="data"?q:{data:q,..._}}let V=await v.text(),O;try{O=JSON.parse(V)}catch{}let z=O??V,k=z;for(let I of i.error.fns)I&&(k=await I(z,v,f,p));if(k=k||{},p.throwOnError)throw k;return p.responseStyle==="data"?void 0:{error:k,..._}},"request"),a=d(c=>p=>u({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:h,url:g}=await o(p);return gi({...h,body:h.body,headers:h.headers,method:c,onRequest:d(async(f,P)=>{let v=new Request(f,P);for(let _ of i.request.fns)_&&(v=await _(v,h));return v},"onRequest"),url:g})},"makeSseFn");return{buildUrl:rr,connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:t,head:a("HEAD"),interceptors:i,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:u,setConfig:r,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:a("TRACE")}},"createClient"),S=Ut(Je({baseUrl:"https://swish.app/api/2026-01"})),Oi=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n}),"listControllerFind"),Li=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerCreate"),qi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerDeleteById"),$i=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerFindById"),Vi=d(n=>(n.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerUpdateById"),Bi=d(n=>(n.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerSetListItemsOrder"),Ni=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerAddItemsToList"),Ui=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...n}),"listControllerRemoveItemFromList"),Mi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerDelete"),Gi=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...n}),"itemControllerFind"),Fi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerCreate"),ji=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...n}),"itemControllerCount"),Hi=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerDeleteById"),Qi=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerFindById"),zi=d(n=>(n.client??S).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerUpdateById"),Wi=d(n=>(n.client??S).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerSetListsById"),Xi=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerIdentify"),Ki=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerCreateToken"),Yi=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...n}),"profileControllerGetProfile"),Ji=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...n}),"analyticsControllerLoadSavedItems"),Zi=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...n}),"analyticsControllerLoadSessions"),es=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...n}),"analyticsControllerLoadNewLists"),ts=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/tracking",...n,headers:{"Content-Type":"application/json",...n.headers}}),"trackingControllerTrack"),ns=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...n}),"ordersControllerFind"),rs=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...n}),"ordersControllerFindOne"),is=d(n=>(n.client??S).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}/save",...n}),"sharedListsControllerSave"),ss=d(n=>(n.client??S).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerDeleteById"),os=d(n=>(n.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerFindById"),as=d(n=>(n?.client??S).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...n}),"sharedListsControllerFindAll"),Mt="2026-01",pr=d(n=>new us(n),"createApiClient"),dr=class{static{s(this,"H")}constructor(e){this.version=Mt,this.items={list:d(a=>this.handlePaginatedRequest(Gi({query:a,client:this.directClient})),"list"),create:d(a=>this.handleRequest(Fi({body:a,client:this.directClient})),"create"),delete:d(a=>this.handleRequest(Mi({body:{itemIds:a},client:this.directClient})),"delete"),findById:d(a=>this.handleRequest(Qi({path:{itemId:a},client:this.directClient})),"findById"),updateById:d((a,l)=>this.handleRequest(zi({body:l,path:{itemId:a},client:this.directClient})),"updateById"),deleteById:d(a=>this.handleRequest(Hi({path:{itemId:a},client:this.directClient})),"deleteById"),setListsById:d((a,l)=>this.handleRequest(Wi({body:{listIds:l},path:{itemId:a},client:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(ji({client:this.directClient})),"count")},this.lists={list:d(a=>this.handlePaginatedRequest(Oi({query:a,client:this.directClient})),"list"),create:d(a=>this.handleRequest(Li({body:a,client:this.directClient})),"create"),findById:d(a=>this.handleRequest($i({path:{listId:a},client:this.directClient})),"findById"),updateById:d((a,l)=>this.handleRequest(Vi({body:l,path:{listId:a},client:this.directClient})),"updateById"),deleteById:d(a=>this.handleRequest(qi({path:{listId:a},client:this.directClient})),"deleteById"),orderItems:d((a,l)=>this.handleRequest(Bi({body:{itemIds:l},path:{listId:a},client:this.directClient})),"orderItems"),addItemsToList:d((a,l)=>this.handleRequest(Ni({body:{itemIds:l},path:{listId:a},client:this.directClient})),"addItemsToList"),removeItemFromList:d((a,l)=>this.handleRequest(Ui({path:{listId:a,itemId:l},client:this.directClient})),"removeItemFromList")},this.profiles={createToken:d((a={})=>this.handleRequest(Ki({body:a,client:this.proxyClient??this.directClient})),"createToken"),identify:d(a=>this.handleRequest(Xi({body:a,client:this.directClient})),"identify"),getProfile:d(()=>this.handleRequest(Yi({client:this.directClient})),"getProfile")},this.orders={list:d(a=>this.handlePaginatedRequest(ns({query:a,client:this.directClient})),"list"),findById:d(a=>this.handleRequest(rs({path:{orderId:a},client:this.directClient})),"findById")},this.sharedLists={list:d(a=>this.handlePaginatedRequest(as({query:a,client:this.directClient})),"list"),save:d(a=>this.handleRequest(is({path:{listId:a},client:this.directClient})),"save"),findById:d(a=>this.handleRequest(os({path:{listId:a},client:this.directClient})),"findById"),deleteById:d(a=>this.handleRequest(ss({path:{listId:a},client:this.directClient})),"deleteById")},this.analytics={savedItems:d(a=>this.handleRequest(Ji({query:a,client:this.directClient})),"savedItems"),sessions:d(a=>this.handleRequest(Zi({query:a,client:this.directClient})),"sessions"),newLists:d(a=>this.handleRequest(es({query:a,client:this.directClient})),"newLists")},this.tracking={track:d((a,l)=>this.handleRequest(ts({body:a,headers:l,client:this.directClient})),"track")},this.handleRequest=d(async a=>{let{data:l,error:c}=await a;return c!=null&&c.error?{error:c.error}:{data:l?.data}},"handleRequest"),this.handlePaginatedRequest=d(async a=>{var l;let{data:c,error:p}=await a;return p!=null&&p.error?{error:p.error}:{data:c?.data??[],pageInfo:c?.pageInfo??{next:null,previous:null,totalCount:((l=c?.data)==null?void 0:l.length)??0}}},"handlePaginatedRequest");var t,r,i,o,u;(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=Ut(Je({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),(r=e.config)!=null&&r.authProxy&&(this.proxyClient=Ut(Je({...e.config,baseUrl:e.config.authProxy}))),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&((i=this.proxyClient)==null||i.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&((o=this.proxyClient)==null||o.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),(u=this.proxyClient)==null||u.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setAuthToken(e){this.authToken=e}proxyRequestInterceptor(e){return this.version&&e.headers.set("Swish-Api-Version",this.version),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(dr,"SwishClient");var us=dr;var yr=Rr(mr(),1);var vr=s(n=>new yr.default(async e=>{let t=[...new Set(e)].sort((i,o)=>i.localeCompare(o)),r=await n.items.list({query:t.join(" "),limit:200});return"error"in r?(console.error("Failed to load items",r.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let o=r.data.find(u=>i===`variant:${u.variantId}`||i===`product:${u.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:s(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var et=class{constructor(e,t,r){this.tokenHasProfile=!1;this.api=e,this.context=t,this.eventBus=r}static{s(this,"SwishApiAuth")}hasProfile(){return this.tokenHasProfile}hasToken(){return!!this.getSwishToken()}async renewToken(){return this._renewPromise?this._renewPromise:(this._renewPromise=(async()=>{this._initPromise=void 0,this.deleteSwishToken(),await this.init(),this._renewPromise=void 0})(),this._renewPromise)}async init(){return this._initPromise?this._initPromise:(this._initPromise=(async()=>{this.migrateLegacySession();let e=this.context.customer.id;e?(this.hasSessionToken()&&await this.api.clearCache(),await this.initCustomer(e)):(this.hasCustomerToken()&&await this.resetSession(),await this.initSession()),this.eventBus.publish("token-update",null)})(),this._initPromise)}async initCustomer(e){let t=`gid://shopify/Customer/${e}`,r=this.getTokenBySub(t);if(r){this.initToken(r);return}let i=this.getSessionId();await this.acquireToken(i,t)}async initSession(){let e=this.getSessionId(),t=e?this.getTokenBySub(e):null;if(t){this.initToken(t);return}await this.acquireToken(e)}initToken(e){let t=this.getTokenData(e);if(!t)throw new Error("Invalid Swish token.");this.tokenHasProfile=t.has_profile!==!1,this.api.setAuthToken(e)}async acquireToken(e,t){let r=await this.api.profiles.createToken({customer:t,session:e});if("error"in r)throw console.error("Failed to create customer token",r.error),new Error("Failed to create customer token");if(!r.data?.token)throw console.error("Failed to create customer token empty response"),new Error("Failed to create customer token");r.data.profile.startsWith("gid://swish/Session/")&&this.setSessionId(r.data.profile),this.setSwishToken(r.data.token),this.initToken(r.data.token)}async resetSession(){this.deleteSessionId(),this.deleteSwishToken(),await this.api.clearCache()}getTokenData(e){try{return JSON.parse(atob(e.split(".")[1]))}catch(t){return console.error("Failed to parse Swish token",{cause:t}),null}}willTokenExpire(e,t=60){let r=this.getTokenData(e);return!!(r&&r.exp&&r.exp<Date.now()/1e3+t)}hasCustomerToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://shopify/Customer/")??!1:!1}hasSessionToken(){let e=this.getSwishToken();return e?this.getTokenData(e)?.sub?.startsWith("gid://swish/Session/")??!1:!1}getTokenBySub(e){if(!e)return null;let t=this.getSwishToken();if(!t)return null;let r=this.getTokenData(t);return!r||r.sub!==e||this.willTokenExpire(t,60)?null:t}getSessionId(){let e=j(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let t=j(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${t}`,e)}deleteSessionId(){let e=j(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=j(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let t=j(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${t}`,e)}deleteSwishToken(){let e=j(this.context.myshopifyDomain);sessionStorage.removeItem(`swish-token-${e}`)}migrateLegacySession(){try{let e=localStorage.getItem("wk_session_id")??localStorage.getItem("swish-profile")?.split("/").pop()??localStorage.getItem("swish-session")?.split("/").pop();e&&(this.setSessionId(`gid://swish/Session/${e}`),localStorage.removeItem("wk_session_id"),localStorage.removeItem("swish-profile"),localStorage.removeItem("swish-session"))}catch(e){console.warn("Failed to migrate legacy session id to Swish session",{cause:e})}}};var tt=class{static{s(this,"SwishApi")}constructor(e,t,r,i){this.config=e,this.storefrontContext=t;let o=j(t.myshopifyDomain);this.cache=new X(`swish-api-${o}`,"max-age=60, stale-while-revalidate=3600",i+(e.version??Mt)),this.cache.cleanupExpiredEntries().catch(u=>{console.warn("Swish API cache initialization cleanup error:",u)}),this.auth=new et(this,t,r),this.apiClient=pr({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=vr(this)}async fetchFunction(e,t){let r=e instanceof Request?e.method:t?.method??"GET",o=(e instanceof Request?e.url:typeof e=="string"?e:e.toString()).includes("/orders");return r==="GET"&&!o?this.cache.fetchWithCache(e,t):fetch(e,t)}async requestInterceptor(e){let t=new URL(e.url,window.location.origin);!!this.config.authProxy&&t.pathname.startsWith(this.config.authProxy)||await this.auth.init();try{e.headers.set("Country",this.storefrontContext.localization.country),e.headers.set("Language",this.storefrontContext.localization.language),e.headers.set("Market",this.storefrontContext.localization.market)}catch(i){console.warn("Failed to set storefront context headers:",i)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,t){let r=t.method!=="GET",i=t.url.includes("/profiles/token");if(r&&!i){let o=this.auth.hasToken(),u=!this.auth.hasProfile(),a=e.ok;await this.cache.clear(),o&&u&&a&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,t),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}withFallback(e,t){return this.auth.hasProfile()?e():Promise.resolve(t)}get items(){return{...this.apiClient.items,count:s(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:s(async(e,t)=>this.withFallback(()=>{if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let r=e.query.split(" ");r.length>1&&console.warn("Batching will only support one query parameter");let i=r[0];if(!i.match(/^product:\d+$/)&&!i.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(i)}return this.apiClient.items.list(e)},{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:s(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>this.apiClient.lists.findById(e),{data:null}),"findById")}}get orders(){return{...this.apiClient.orders,list:s(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:s(async e=>this.withFallback(()=>(typeof e=="string"&&(e=parseInt(e.split("/").pop()??e)),this.apiClient.orders.findById(e)),{data:null}),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var nt=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{s(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.method,e.status,t.url);if(!r)return;let i=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{i=JSON.parse(i).data}catch(o){console.warn(o)}this.eventBus.publish(r,i)}catch(r){console.warn(r)}}getEventName(e,t,r){e=e.toUpperCase();let i=new URL(r).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([u])=>{let[a,l]=u.split(" ");return a!==e?!1:new RegExp(l).test(i)})?.[1]}};var rt=class{constructor(e,t){this.inflightModals=new Map;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._lockScroll=s(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=s(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{s(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")!=="true")&&e.setAttribute("open","false")})().finally(()=>{this.inflightModals.delete(e)});return this.unlockScroll(),this.inflightModals.set(e,t),t}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&e.setAttribute("open","true")})().finally(()=>{this.inflightModals.delete(e)});return this.lockScroll(),this.inflightModals.set(e,t),t}waitForEvent(e,t){return new Promise(r=>{let i=[],o=s(()=>{i.forEach(({event:u,listener:a})=>{e.removeEventListener(u,a)})},"cleanup");Object.entries(t).forEach(([u,a])=>{let l=s(c=>{let p=a(c);o(),r(p)},"listener");i.push({event:u,listener:l}),e.addEventListener(u,l)})})}async showSignIn(e){let t=await this.requireUiComponent("sign-in");t.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showUnsaveAlert(e){if(!e.itemId)throw new Error("An itemId is required to show the unsave alert");await this.hideAllToasts();let t=await this.requireUiComponent("unsave-alert");t.setAttribute("item-id",e.itemId),await this.showModal(t);let r=await this.waitForEvent(t,{submit:s(i=>i instanceof CustomEvent?{code:"ok",data:i.detail}:(console.warn("Unsave alert submitted without detail",i),{code:"closed"}),"submit"),close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showDeleteListAlert(e){if(!e.listId)throw new Error("A listId is required to show the delete list alert");await this.hideAllToasts();let t=await this.requireUiComponent("delete-list-alert");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{submit:s(()=>({code:"ok",data:void 0}),"submit"),close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showDrawer(e){await this.hideAllToasts();let t=await this.requireUiComponent("drawer");t.setAttribute("account-url",this.storefrontContext.routes.accountUrl),this.storefrontContext.customer.id&&t.setAttribute("customer-id",this.storefrontContext.customer.id),t.setAttribute("view",e?.view??"home"),e?.listId&&t.setAttribute("list-id",e.listId),e?.productId&&t.setAttribute("product-id",e.productId),e?.variantId&&t.setAttribute("variant-id",e.variantId),e?.orderId&&t.setAttribute("order-id",e.orderId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-menu");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),edit:s(i=>i instanceof CustomEvent?{code:"ok",data:{action:"edit",data:i.detail}}:(console.warn("List menu edit without detail",i),{code:"closed"}),"edit"),delete:s(()=>({code:"ok",data:{action:"delete"}}),"delete")});return await this.hideModal(t),r}async showOrderMenu(e){if(!e.orderId)throw new Error("orderId is required");await this.hideAllToasts();let t=await this.requireUiComponent("order-menu");t.setAttribute("order-id",e.orderId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showListDetailPageMenu(e){await this.hideAllToasts();let t=await this.requireUiComponent("list-detail-page-menu");t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-select");t.setAttribute("item-id",e.itemId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:{action:"submit",data:i.detail}}:(console.warn("List select submit without detail",i),{code:"closed"}),"submit"),unsave:s(i=>i instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:i.detail}}:(console.warn("List select unsave without detail",i),{code:"closed"}),"unsave")});return await this.hideModal(t),r}async initListDetailPage(e,t){let r=await this.requireUiComponent("list-detail-page",{refElement:t});e.listId&&r.setAttribute("list-id",e.listId)}async showToast(e){let t=Date.now(),r=await this.requireUiComponent("toast-manager",{onHydrated:s(i=>{i.current.show(e,t)},"onHydrated")});return this.waitForEvent(r,{[`close-${t}`]:()=>({code:"closed"}),[`submit-${t}`]:()=>({code:"ok",data:void 0})})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:s(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let t=await this.requireUiComponent("variant-select");if(e?.itemId&&t.setAttribute("item-id",e.itemId),e?.productId)t.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("Either productId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId.toString()),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Variant select submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async showQuickBuy(e){await this.hideAllToasts();let t=await this.requireUiComponent("quick-buy");if(e?.productId)t.setAttribute("product-id",e.productId.toString());else if(e?.productHandle)t.setAttribute("product-handle",e.productHandle);else throw new Error("ProductId or productHandle must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId.toString()),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("Quick buy submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async showListEditor(e){let t=await this.requireUiComponent("list-editor");e?.listId&&t.setAttribute("list-id",e.listId),await this.showModal(t);let r=await this.waitForEvent(t,{close:s(()=>({code:"closed"}),"close"),submit:s(i=>"detail"in i&&i.detail?{code:"ok",data:i.detail}:(console.warn("List editor submit without detail",i),{code:"closed"}),"submit")});return await this.hideModal(t),r}async requireUiComponent(e,t){this.loadCricalResources();let r=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`,i=await fetch(r).then(a=>a.text()),o=t?.instance,u=this.queryComponent(e,o)??await this.insertComponent({name:e,template:i,refElement:t?.refElement??document.body,position:"beforeend",instance:o});if(u.shadowRoot&&!u.hasAttribute("hydrated")){let a=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;Promise.all([this.loadNonCriticalResources(),import(a)]).then(([{bundleCssStylesheet:l,customCssStylesheets:c},{hydrate:p}])=>{u.shadowRoot&&l&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,...c,l],u.shadowRoot?.querySelector(":host > style")?.remove()),p(u),u.setAttribute("hydrated",""),t?.onHydrated?.(u.getComponentRef())})}else u.hasAttribute("hydrated")&&t?.onHydrated?.(u.getComponentRef());return u}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/theme.css`,t=await fetch(e).then(i=>i.text()),r=new CSSStyleSheet;return r.replaceSync(t),this.swishUiOptions.theme&&Object.entries(this.swishUiOptions.theme).forEach(([i,o])=>{r.cssRules[0].cssRules[0].style.setProperty(i,o)}),{themeVariablesStylesheet:r}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/bundle.css`,t=s(o=>{let u=new CSSStyleSheet;return u.replaceSync(o),u},"createCssStylesheet"),[r,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(t),...this.swishUiOptions.css.map(async o=>o instanceof URL?t(await fetch(o).then(u=>u.text())):t(o))]);return{bundleCssStylesheet:r,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,instance:t,template:r,position:i,refElement:o}){let{themeVariablesStylesheet:u}=await this.loadCricalResources();o.insertAdjacentHTML(i,r.replace(' shadowrootmode="open"',""));let a=this.queryComponent(e,t);if(!a)throw new Error(`Element ${e} not found in DOM`);return a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[u]),a}queryComponent(e,t){let r=`swish-ui[ref="${e}${t?`-${t}`:""}"]`;return document.querySelector(r)}lockScroll(){this.scrollLockRefCount++,this.scrollLockRefCount===1&&(this.scrollPositionBeforeLock=window.scrollY,this.scrollLockStyleSheet||(this.scrollLockStyleSheet=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,this.scrollLockStyleSheet]),this.scrollLockStyleSheet.replaceSync(`
|
|
443
443
|
html[swish-locked] body {
|
|
444
444
|
overflow: hidden;
|
|
445
445
|
position: fixed;
|
|
@@ -447,4 +447,4 @@ Values:
|
|
|
447
447
|
left: 0px;
|
|
448
448
|
right: 0px;
|
|
449
449
|
}
|
|
450
|
-
`),document.documentElement.setAttribute("swish-locked",""))}unlockScroll(){this.scrollLockRefCount>0&&this.scrollLockRefCount--,this.scrollLockRefCount===0&&(this.scrollLockStyleSheet&&this.scrollLockStyleSheet.replaceSync(""),window.scrollTo({top:this.scrollPositionBeforeLock,behavior:"instant"}),this.scrollPositionBeforeLock=0,document.documentElement.removeAttribute("swish-locked"))}};var
|
|
450
|
+
`),document.documentElement.setAttribute("swish-locked",""))}unlockScroll(){this.scrollLockRefCount>0&&this.scrollLockRefCount--,this.scrollLockRefCount===0&&(this.scrollLockStyleSheet&&this.scrollLockStyleSheet.replaceSync(""),window.scrollTo({top:this.scrollPositionBeforeLock,behavior:"instant"}),this.scrollPositionBeforeLock=0,document.documentElement.removeAttribute("swish-locked"))}};var gs=typeof HTMLElement<"u"?HTMLElement:class{},it=class extends gs{constructor(){super();this.getComponentRef=s(()=>this.componentRef,"getComponentRef");this.setComponentRef=s(t=>{this.componentRef=t},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let t=this.querySelector("template");t&&this.shadowRoot&&(this.shadowRoot.appendChild(t.content),t.remove())}static{s(this,"SwishUiElement")}};var st=class{static{s(this,"ShopifyBadgesUtils")}#e;constructor({getBadges:e}){this.#e=e?.bind(this)}getBadges({product:e,variant:t}){try{let r=this.getDefaultBadges({product:e,variant:t});return this.#e?this.mapBadges(this.#e({product:e,variant:t,defaultBadges:r})??[]):this.mapBadges(r)}catch(r){return console.error("Error getting badges",r),[]}}getDefaultBadges({product:e,variant:t}){let r=[];if(e?.availableForSale===!1||t?.availableForSale===!1)return r.push("Sold out"),r;let i=t?t.price.amount:e?.priceRange?.minVariantPrice.amount,o=t?t.compareAtPrice?.amount:e?.compareAtPriceRange?.minVariantPrice.amount;return o&&parseFloat(o)>parseFloat(i)&&r.push("Sale"),r}mapBadges(e){return e.map(t=>typeof t=="string"?{id:t.toLowerCase().replace(/[^a-z0-9]/g,"_"),label:t}:t)}};var Fe="0.98.0",lp=`https://swish.app/cdn/sdk@${Fe}/swish.js`,cp=s(async n=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;let e=tn(n),t=new Ht(e);return window.swish=t,document.dispatchEvent(new Event("swish-ready")),t.api.initAuth().then(()=>{typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{market:e.storefrontContext.localization.market,country:e.storefrontContext.localization.country,language:e.storefrontContext.localization.language,rootUrl:e.storefrontContext.routes.rootUrl})}),t},"createSwish"),Ht=class{constructor(e){this.dom={createElementLocator:ce,createQueryParamsObserver:ae};this.state={itemContext:cn(this),itemState:pn(this),itemCount:dn(this),swishQuery:fn(this),effect:H,signal:T,computed:G};this.swishOptions=e,this.events=new ye,this.swishBadges=new st({getBadges:this.swishOptions.badges?.getBadges}),this.swishApiPublisher=new nt(this.events);let t=[Fe,e.swishUi?.version].join("-");this.swishApi=new tt({...this.swishOptions.swishApi,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,this.events,t),this.ajaxApiPublisher=new me(this.events),this.ajaxApi=new he({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ye(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishBadges,this.swishOptions.metafields),this.swishUi=new rt(this.swishOptions.swishUi,this.swishOptions.storefrontContext),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",it),this.intents=new Ge(this,this.swishUi)}static{s(this,"SwishApp")}get options(){return this.swishOptions}get storefrontContext(){return this.swishOptions.storefrontContext}get badges(){return this.swishBadges}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}};export{Fe as VERSION,cp as createSwish,lp as swishSdkUrl};
|