@swishapp/sdk 0.109.0 → 0.111.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.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { IntentOptions } from "../intents/intents";
|
|
2
2
|
import { StorefrontApiOptions, SwishClientConfig } from "../swish";
|
|
3
|
-
import { StorefrontContext,
|
|
3
|
+
import { StorefrontContext, SwishFeaturesOptions, SwishMetafieldOptions, SwishOptions, SwishProductOptions, SwishUiOptions } from "./types";
|
|
4
4
|
export type SwishOptionsInput = {
|
|
5
5
|
storefrontApi: StorefrontApiOptions;
|
|
6
6
|
storefrontContext: StorefrontContext;
|
|
@@ -8,7 +8,6 @@ export type SwishOptionsInput = {
|
|
|
8
8
|
version: string;
|
|
9
9
|
};
|
|
10
10
|
swishUi?: SwishUiOptions;
|
|
11
|
-
badges?: SwishBadgeOptions;
|
|
12
11
|
productOptions?: SwishProductOptions;
|
|
13
12
|
metafields?: SwishMetafieldOptions;
|
|
14
13
|
features?: SwishFeaturesOptions;
|
package/dist/options/types.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { IntentOptions } from "../intents/intents";
|
|
2
2
|
import { CountryCode, LanguageCode } from "../storefront-api/types/storefront.types";
|
|
3
|
-
import {
|
|
4
|
-
import { Badge } from "../utils/shopify-badge-utils";
|
|
3
|
+
import { GetProductOptionsQuery, Intent, StorefrontApiOptions, SwishClientConfig } from "../swish";
|
|
5
4
|
export interface SwishOptions {
|
|
6
5
|
storefrontApi: StorefrontApiOptions;
|
|
7
6
|
storefrontContext: StorefrontContext;
|
|
@@ -12,20 +11,12 @@ export interface SwishOptions {
|
|
|
12
11
|
features: SwishFeaturesOptions;
|
|
13
12
|
intents: IntentOptions;
|
|
14
13
|
metafields: SwishMetafieldOptions;
|
|
15
|
-
badges: SwishBadgeOptions;
|
|
16
14
|
productOptions: SwishProductOptions;
|
|
17
15
|
}
|
|
18
16
|
export interface SwishMetafieldOptions {
|
|
19
17
|
product: `${string}.${string}`[];
|
|
20
18
|
productVariant: `${string}.${string}`[];
|
|
21
19
|
}
|
|
22
|
-
export interface SwishBadgeOptions {
|
|
23
|
-
getBadges: (args: {
|
|
24
|
-
product: GetProductCardDataQuery["product"];
|
|
25
|
-
variant?: GetProductCardDataWithVariantQuery["variant"];
|
|
26
|
-
defaultBadges: string[];
|
|
27
|
-
}) => (string | Badge)[];
|
|
28
|
-
}
|
|
29
20
|
export interface SwishProductOptions {
|
|
30
21
|
sortValues: (args: {
|
|
31
22
|
option: NonNullable<GetProductOptionsQuery["product"]>["options"][number];
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { ResponseErrors } from "@shopify/graphql-client";
|
|
2
2
|
import { StorefrontContext, SwishMetafieldOptions, SwishProductOptions } from "../options/types";
|
|
3
|
-
import { ShopifyBadgesUtils } from "../utils/shopify-badge-utils";
|
|
4
3
|
import { LoadProductCardDataArgs } from "./load-product-card-data";
|
|
5
4
|
import { LoadProductDetailDataArgs } from "./load-product-detail-data";
|
|
6
5
|
import { LoadProductIdArgs } from "./load-product-id";
|
|
@@ -30,9 +29,8 @@ export declare class StorefrontApiClient {
|
|
|
30
29
|
private readonly options;
|
|
31
30
|
private readonly context;
|
|
32
31
|
private readonly metafields;
|
|
33
|
-
private readonly badges;
|
|
34
32
|
private readonly productOptions;
|
|
35
|
-
constructor(options: StorefrontApiOptions, context: StorefrontContext,
|
|
33
|
+
constructor(options: StorefrontApiOptions, context: StorefrontContext, productOptions: SwishProductOptions, metafields?: SwishMetafieldOptions);
|
|
36
34
|
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
37
35
|
query: <TData, TVariables extends Record<string, unknown>>(query: string, variables: TVariables) => Promise<{
|
|
38
36
|
data: (TData extends undefined ? any : TData) | undefined;
|
|
@@ -49,78 +47,10 @@ export declare class StorefrontApiClient {
|
|
|
49
47
|
loadProductCardData: (args: ArgsWithoutDefaults<LoadProductCardDataArgs>) => Promise<{
|
|
50
48
|
data: import("./storefront-api-client").GetProductCardDataQuery | import("./storefront-api-client").GetProductCardDataWithVariantQuery | undefined;
|
|
51
49
|
errors: ResponseErrors | null;
|
|
52
|
-
} | {
|
|
53
|
-
data: {
|
|
54
|
-
badges: import("../utils/shopify-badge-utils").Badge[];
|
|
55
|
-
product?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").Product, "id" | "availableForSale" | "isGiftCard" | "onlineStoreUrl" | "description" | "descriptionHtml" | "handle" | "productType" | "tags" | "title"> & {
|
|
56
|
-
category?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").TaxonomyCategory, "id" | "name">>;
|
|
57
|
-
compareAtPriceRange: {
|
|
58
|
-
maxVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
59
|
-
minVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
60
|
-
};
|
|
61
|
-
featuredImage?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
62
|
-
options: Array<Pick<import("./types/storefront.types").ProductOption, "id" | "name">>;
|
|
63
|
-
priceRange: {
|
|
64
|
-
maxVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
65
|
-
minVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
66
|
-
};
|
|
67
|
-
variantsCount?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Count, "count">>;
|
|
68
|
-
metafields: Array<import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Metafield, "key" | "namespace" | "value">>>;
|
|
69
|
-
})>;
|
|
70
|
-
variant?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").ProductVariant, "id" | "availableForSale" | "currentlyNotInStock" | "sku" | "title"> & {
|
|
71
|
-
compareAtPrice?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">>;
|
|
72
|
-
image?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
73
|
-
price: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
74
|
-
selectedOptions: Array<Pick<import("./types/storefront.types").SelectedOption, "name" | "value">>;
|
|
75
|
-
metafields: Array<import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Metafield, "key" | "namespace" | "value">>>;
|
|
76
|
-
})>;
|
|
77
|
-
};
|
|
78
|
-
errors: ResponseErrors | null;
|
|
79
50
|
}>;
|
|
80
51
|
loadProductDetailData: (args: ArgsWithoutDefaults<LoadProductDetailDataArgs>) => Promise<{
|
|
81
52
|
data: import("./storefront-api-client").GetProductDetailDataQuery | import("./storefront-api-client").GetProductDetailDataWithVariantQuery | undefined;
|
|
82
53
|
errors: ResponseErrors | null;
|
|
83
|
-
} | {
|
|
84
|
-
data: {
|
|
85
|
-
badges: import("../utils/shopify-badge-utils").Badge[];
|
|
86
|
-
product?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").Product, "id" | "availableForSale" | "isGiftCard" | "onlineStoreUrl" | "description" | "descriptionHtml" | "handle" | "productType" | "tags" | "title" | "encodedVariantAvailability" | "encodedVariantExistence"> & {
|
|
87
|
-
category?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").TaxonomyCategory, "id" | "name">>;
|
|
88
|
-
compareAtPriceRange: {
|
|
89
|
-
maxVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
90
|
-
minVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
91
|
-
};
|
|
92
|
-
featuredImage?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
93
|
-
options: Array<(Pick<import("./types/storefront.types").ProductOption, "id" | "name"> & {
|
|
94
|
-
optionValues: Array<(Pick<import("./types/storefront.types").ProductOptionValue, "name"> & {
|
|
95
|
-
swatch?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").ProductOptionValueSwatch, "color"> & {
|
|
96
|
-
image?: import("./types/storefront.types").Maybe<{
|
|
97
|
-
previewImage?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "url">>;
|
|
98
|
-
}>;
|
|
99
|
-
})>;
|
|
100
|
-
firstSelectableVariant?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").ProductVariant, "id"> & {
|
|
101
|
-
image?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
102
|
-
})>;
|
|
103
|
-
})>;
|
|
104
|
-
})>;
|
|
105
|
-
priceRange: {
|
|
106
|
-
maxVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
107
|
-
minVariantPrice: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
108
|
-
};
|
|
109
|
-
variantsCount?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Count, "count" | "precision">>;
|
|
110
|
-
metafields: Array<import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Metafield, "key" | "namespace" | "value">>>;
|
|
111
|
-
images: {
|
|
112
|
-
nodes: Array<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
113
|
-
};
|
|
114
|
-
})>;
|
|
115
|
-
variant?: import("./types/storefront.types").Maybe<(Pick<import("./types/storefront.types").ProductVariant, "id" | "availableForSale" | "currentlyNotInStock" | "sku" | "title"> & {
|
|
116
|
-
compareAtPrice?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">>;
|
|
117
|
-
image?: import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash">>;
|
|
118
|
-
price: Pick<import("./types/storefront.types").MoneyV2, "amount" | "currencyCode">;
|
|
119
|
-
selectedOptions: Array<Pick<import("./types/storefront.types").SelectedOption, "name" | "value">>;
|
|
120
|
-
metafields: Array<import("./types/storefront.types").Maybe<Pick<import("./types/storefront.types").Metafield, "key" | "namespace" | "value">>>;
|
|
121
|
-
})>;
|
|
122
|
-
};
|
|
123
|
-
errors: ResponseErrors | null;
|
|
124
54
|
}>;
|
|
125
55
|
loadProductImages: (args: ArgsWithoutDefaults<LoadProductImagesArgs>) => Promise<{
|
|
126
56
|
data: (Pick<import("./types/storefront.types").Image, "id" | "altText" | "url" | "thumbhash"> | undefined)[];
|
package/dist/swish.d.ts
CHANGED
|
@@ -11,7 +11,6 @@ import { SwishApi } from "./swish-api/swish-api-client";
|
|
|
11
11
|
import { SwishUiElement } from "./swish-ui/swish-ui-element";
|
|
12
12
|
import { copyToClipboard } from "./utils/copy-to-clipboard";
|
|
13
13
|
import { RequireUiComponentOptions } from "./swish-ui/types";
|
|
14
|
-
import { ShopifyBadgesUtils } from "./utils/shopify-badge-utils";
|
|
15
14
|
export declare const VERSION: string;
|
|
16
15
|
export declare const swishSdkUrl: string;
|
|
17
16
|
export declare const createSwish: (optionsInput: SwishOptionsInput) => Promise<SwishApp>;
|
|
@@ -21,7 +20,6 @@ declare class SwishApp {
|
|
|
21
20
|
private readonly storefrontApi;
|
|
22
21
|
private readonly ajaxApi;
|
|
23
22
|
private readonly ajaxApiPublisher;
|
|
24
|
-
private readonly swishBadges;
|
|
25
23
|
private readonly swishOptions;
|
|
26
24
|
private readonly swishUi;
|
|
27
25
|
readonly events: EventBus;
|
|
@@ -29,7 +27,6 @@ declare class SwishApp {
|
|
|
29
27
|
constructor(options: SwishOptions);
|
|
30
28
|
get options(): SwishOptions;
|
|
31
29
|
get storefrontContext(): import("./swish").StorefrontContext;
|
|
32
|
-
get badges(): ShopifyBadgesUtils;
|
|
33
30
|
get api(): SwishApi;
|
|
34
31
|
get storefront(): StorefrontApiClient;
|
|
35
32
|
get ajax(): AjaxApiClient;
|
package/dist/swish.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Ur=Object.create;var
|
|
1
|
+
var Ur=Object.create;var bt=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var jr=Object.getPrototypeOf,Hr=Object.prototype.hasOwnProperty;var i=(n,e)=>bt(n,"name",{value:e,configurable:!0});var Gr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Qr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fr(e))!Hr.call(n,s)&&s!==t&&bt(n,s,{get:()=>e[s],enumerable:!(r=Br(e,s))||r.enumerable});return n};var zr=(n,e,t)=>(t=n!=null?Ur(jr(n)):{},Qr(e||!n||!n.__esModule?bt(t,"default",{value:n,enumerable:!0}):t,n));var $r=Gr((ed,Lr)=>{"use strict";var eo=(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=so(r),this._batchScheduleFn=io(r),this._cacheKeyFn=oo(r),this._cacheMap=ao(r),this._batch=null,this.name=uo(r)}i(n,"DataLoader");var e=n.prototype;return e.load=i(function(r){if(r==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(r)+"."));var s=no(this),o=this._cacheMap,a;if(o){a=this._cacheKeyFn(r);var u=o.get(a);if(u){var c=s.cacheHits||(s.cacheHits=[]);return new Promise(function(l){c.push(function(){l(u)})})}}s.keys.push(r);var p=new Promise(function(l,f){s.callbacks.push({resolve:l,reject:f})});return o&&o.set(a,p),p},"load"),e.loadMany=i(function(r){if(!Or(r))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+r+"."));for(var s=[],o=0;o<r.length;o++)s.push(this.load(r[o]).catch(function(a){return a}));return Promise.all(s)},"loadMany"),e.clear=i(function(r){var s=this._cacheMap;if(s){var o=this._cacheKeyFn(r);s.delete(o)}return this},"clear"),e.clearAll=i(function(){var r=this._cacheMap;return r&&r.clear(),this},"clearAll"),e.prime=i(function(r,s){var o=this._cacheMap;if(o){var a=this._cacheKeyFn(r);if(o.get(a)===void 0){var u;s instanceof Error?(u=Promise.reject(s),u.catch(function(){})):u=Promise.resolve(s),o.set(a,u)}}return this},"prime"),n})(),to=typeof process=="object"&&typeof process.nextTick=="function"?function(n){tn||(tn=Promise.resolve()),tn.then(function(){process.nextTick(n)})}:typeof setImmediate=="function"?function(n){setImmediate(n)}:function(n){setTimeout(n)},tn;function no(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(){ro(n,t)}),t}i(no,"getCurrentBatch");function ro(n,e){if(e.hasDispatched=!0,e.keys.length===0){rn(e);return}var t;try{t=n._batchLoadFn(e.keys)}catch(r){return nn(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 nn(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(!Or(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)));sn(e);for(var s=0;s<e.callbacks.length;s++){var o=r[s];o instanceof Error?e.callbacks[s].reject(o):e.callbacks[s].resolve(o)}}).catch(function(r){rn(n,e,r)})}i(so,"dispatchBatch");function rn(n,e,t){sn(e);for(var r=0;r<e.keys.length;r++)n.clear(e.keys[r]),e.callbacks[r].reject(t)}i(rn,"failedDispatch");function sn(n){if(n.cacheHits)for(var e=0;e<n.cacheHits.length;e++)n.cacheHits[e]()}i(sn,"resolveCacheHits");function io(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}i(io,"getValidMaxBatchSize");function oo(n){var e=n&&n.batchScheduleFn;if(e===void 0)return no;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}i(oo,"getValidBatchScheduleFn");function ao(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}i(ao,"getValidCacheKeyFn");function uo(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"],s=r.filter(function(o){return t&&typeof t[o]!="function"});if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return t}i(uo,"getValidCacheMap");function co(n){return n&&n.name?n.name:null}i(co,"getValidName");function Lr(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))}i(Lr,"isArrayLike");$r.exports=to});var A=i(n=>n.split("/").pop()??"","shopifyGidToId"),D=i((n,e)=>`gid://shopify/${n}/${e}`,"shopifyIdToGid"),H=i(n=>n.toLowerCase().replace(".myshopify.com",""),"toShopName");var J=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{i(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 s=this.createCacheableResponse(t,r);await(await caches.open(this.cacheName)).put(e,s)}catch(s){console.warn("Cache set error:",s)}}async fetchWithCache(e,t,r){let s=await this.getCacheKey(e,t);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(s))return this.inFlightRequests.get(s).then(a=>a.clone());let o=(async()=>{let a=await this.get(s);if(a)return this.isStaleButRevalidatable(a)&&this.revalidateInBackground(s,e,t,r),a.clone();let u=await fetch(e,t);return u.ok&&await this.set(s,u.clone(),r??this.defaultCacheControl),u})().finally(()=>{this.inFlightRequests.delete(s)});return this.inFlightRequests.set(s,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),s=await r.keys();await Promise.all(s.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 a=await e.match(o);a&&this.isExpired(a)&&(await e.delete(o),r++)}let s=t.length-r;return{removed:r,remaining:s}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,t){let r=this.getInputUrl(e),s=`${this.keyPrefix}${r}/${JSON.stringify(t)}`,a=new TextEncoder().encode(s),u=await crypto.subtle.digest("SHA-256",a);return`/${Array.from(new Uint8Array(u)).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),s=this.parseStaleWhileRevalidate(t);if(r===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3,l=r+(s??0);return c>l}isStaleButRevalidatable(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),s=this.parseStaleWhileRevalidate(t);if(r===null||s===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3;return c>r&&c<=r+s}async revalidateInBackground(e,t,r,s){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let a=await fetch(t,r);a.ok&&await this.set(e,a.clone(),s??this.defaultCacheControl)}catch(a){console.warn("Background revalidation error:",a)}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 be=class{static{i(this,"AjaxApiClient")}constructor(e){this.config=e;let t=H(e.storeDomain);this.cache=new J(`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(...s){let o=e.apply(this,s);if(typeof t=="function"){let a=r(s[0]);o.then(u=>t(u,a))}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}`,s={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(r,{...t,headers:{...s,...t.headers}});if(!o.ok){let a;try{a=await o.json()}catch{a={message:`HTTP ${o.status}: ${o.statusText}`,status:o.status.toString(),description:o.statusText}}throw new Error(a.message||a.description)}return o.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let t={...e,items:e.items.map(r=>{let s=Number(A(String(r.id)));if(!Number.isFinite(s)||s<=0)throw new Error(`Invalid Shopify ID: ${r.id}`);return{...r,id:s}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(t)})}async clearCache(){await this.cache.clear()}};var Se=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{i(this,"AjaxApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.url);if(r){let s=await e.clone().json();this.eventBus.publish(r,s)}}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 Kr(){let n=document.body||document.documentElement;return n?Promise.resolve(n):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(n))})}i(Kr,"waitForDOM");function ie({onElementFound:n,selector:e,observerOptions:t,mustMatch:r}){let s=new WeakSet,o=new MutationObserver(l=>{let p=!1;for(let f of l)if(f.addedNodes.length>0){p=!0;break}p&&a()}),a=i(()=>{document.querySelectorAll(e).forEach(l=>{s.has(l)||(s.add(l),r?.(l)!==!1&&u(l))})},"locateElements"),u=i(l=>{if(!t){n(l);return}let p=new IntersectionObserver(f=>{for(let y of f)y.isIntersecting&&(p.disconnect(),n(l))},t);p.observe(l)},"observeElement");return i(async()=>{let l=await Kr();a(),o.observe(l,{childList:!0,subtree:!0})},"locateAndObserveElements")(),o}i(ie,"createElementLocator");function pe({onLocationChange:n,fireOnInit:e=!1}){let t=i(()=>{n(window.location)},"handleChange");window.addEventListener("popstate",t);let r=history.pushState,s=history.replaceState;return history.pushState=function(...o){r.apply(this,o),t()},history.replaceState=function(...o){s.apply(this,o),t()},e&&t(),()=>{window.removeEventListener("popstate",t),history.pushState=r,history.replaceState=s}}i(pe,"createLocationObserver");function dn({element:n,onHrefChange:e}){let t=i(()=>{e(n.href)},"handleChange"),r=new MutationObserver(()=>{t()});return r.observe(n,{attributes:!0,attributeFilter:["href"]}),()=>{r.disconnect()}}i(dn,"createHrefObserver");function mn(n,e){if(!e.element)throw new Error("Element must be provided");let t=null,r=new Map,s=i(()=>{if(t){console.warn("Placement already mounted. Skipping mount.");return}Yr(e),t=ie({selector:e.target.selector,observerOptions:e.target.observerOptions,mustMatch:e.target.mustMatch,onElementFound:i(l=>o(l),"onElementFound")})},"mount"),o=i(l=>{r.has(l)||l.hasAttribute("swish-ignore")||l.getAttribute("swish-placement-target")===e.id||(l.setAttribute("swish-placement-target",e.id),a(l))},"evaluateAndMount"),a=i(async l=>{let p=[],f=e.mount.mode,y=as(l,e.mount.at);if(!y)return;let h=await(typeof e.element=="function"?e.element(e):ds(n,e.element));if(!h)return;if(h.setAttribute("swish-placement-element",e.id),typeof e.element!="function"){let C=e.element;C.props&&fs(h,C.props),C.classNames&&vn(h,C.classNames)}let x;e.container&&(x=ps(e.id,e.container),x.appendChild(h));let w,O=x??h;if(e.layout?.type==="overlay"){cs(y);let C=e.layout.anchor??"bottom-right";O.setAttribute("swish-placement-overlay",e.id),O.setAttribute("swish-placement-anchor",C)}let N=!1,L;if(e.layout?.type==="inline"){let C=e.layout,te=C.rowSelector?y.closest(C.rowSelector):null;te?w=te:(w=ls(e.id,y,C),N=!0),L=w.getAttribute("swish-placement-inline-row"),w.setAttribute("swish-placement-inline-row",e.id)}let G=x??h;if(!us(y,G,f)){try{G.remove()}catch{}return}let I={targetEl:l,renderTargetEl:y,mountEl:h,containerEl:x,rowEl:w,rowWasCreated:N,rowInlineAttrPrevValue:L,cleanupFns:p,ownsNode:!0};r.set(l,I);let q={id:e.id,targetEl:l,renderTargetEl:y,mountEl:I.mountEl,containerEl:x,rowEl:w,cleanup:i(C=>p.push(C),"cleanup")};e.element?.name==="save-button"&&Xr(n,q),e.onMount?.(q)},"mountElement"),u=i(l=>{let p=r.get(l);if(p){if(e.onUnmount?.({id:e.id,targetEl:p.targetEl,renderTargetEl:p.renderTargetEl,mountEl:p.mountEl,containerEl:p.containerEl,rowEl:p.rowEl}),p.cleanupFns.forEach(f=>f()),p.targetEl.getAttribute("swish-placement-target")===e.id&&p.targetEl.removeAttribute("swish-placement-target"),p.ownsNode&&(p.containerEl||p.mountEl).remove(),p.rowEl){if(p.rowWasCreated){let f=p.rowEl.parentElement;f&&p.targetEl.parentElement===p.rowEl?p.rowEl.replaceWith(p.targetEl):f?f.removeChild(p.rowEl):p.rowEl.remove()}else if(p.rowInlineAttrPrevValue!==void 0){let f=p.rowInlineAttrPrevValue;f===null?p.rowEl.removeAttribute("swish-placement-inline-row"):p.rowEl.setAttribute("swish-placement-inline-row",f)}}r.delete(l)}},"unmountElement");return{mount:s,unmount:i(()=>{t&&(t.disconnect(),t=null),r.forEach((l,p)=>u(p)),r.clear()},"unmount")}}i(mn,"createPlacement");var Xr=i((n,{mountEl:e,targetEl:t,cleanup:r})=>{let s=n.state.itemContext(t),o=n.state.effect(()=>{let{loading:a,productId:u,variantId:c}=s.value;a||(e.setAttribute("product-id",u??""),e.setAttribute("variant-id",c??""))});r(()=>o?.())},"saveButtonMount");function Yr(n){let e=Jr(n.id),t=os(n),r=document.getElementById(e);if(r){r.textContent=t;return}let s=document.createElement("style");s.id=e,s.setAttribute("swish-placement-style",n.id),s.textContent=t,document.head.appendChild(s)}i(Yr,"ensurePlacementStylesheet");function Jr(n){return`swish-placement-style-${Zr(n)}`}i(Jr,"getPlacementStyleId");function Zr(n){return n.replace(/[^a-zA-Z0-9\-_]/g,"_")}i(Zr,"cssEscapeId");function fn(n){return`--swish-placement-${es(String(n))}`}i(fn,"designKeyToCSSVar");function es(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}i(es,"toKebabCase");function ts(n){return Object.entries(n??{sm:500,lg:700}).map(([r,s])=>({name:r,minWidth:s})).sort((r,s)=>r.minWidth-s.minWidth)}i(ts,"getBreakpoints");function yn(n,e){if(n==null)return{};if(typeof n=="object"&&!Array.isArray(n)){if(e&&e.size){let t=Object.keys(n);return"base"in n||t.some(s=>e.has(s))?n:{base:n}}return n}return{base:n}}i(yn,"normalizeResponsiveValue");var ns=new Set(["fontWeight","lineHeight","pressedScale","backgroundAlpha","pressedOpacity","pressedScale"]);function hn(n,e){if(e!=null)return typeof e=="number"&&!ns.has(n)?`${e}px`:String(e)}i(hn,"formatDesignValue");function rs(n,e,t){if(!e)return"";let r=new Set(t.map(c=>c.name)),s=[],o={},a=Object.entries(e).map(([c,l])=>[c,l]);for(let[c,l]of a){let p=yn(l,r),f=hn(String(c),p.base);f!==void 0&&s.push(`${fn(c)}:${f};`);for(let y of t){let h=p[y.name],x=hn(String(c),h);x!==void 0&&(o[y.name]||(o[y.name]=[]),o[y.name].push(`${fn(c)}:${x};`))}}let u=[];s.length&&u.push(`[swish-placement-element="${n}"]{${s.join("")}}`);for(let c of t){let l=o[c.name];l?.length&&u.push(`@media(min-width:${c.minWidth}px){[swish-placement-element="${n}"]{${l.join("")}}}`)}return u.join("")}i(rs,"emitDesignCSS");function Ee(n){return n==null?"0px":typeof n=="number"?`${n}px`:n}i(Ee,"formatOffsetValue");function ss(n){return n==null?"":typeof n=="number"?`${n}`:n}i(ss,"formatZIndexValue");function is(n,e,t){let r=new Set(t.map(l=>l.name)),s=yn(e,r),o=s.base??{},a=Ee(o.x),u=Ee(o.y),c=[];c.push(`[swish-placement-overlay="${n}"]{--swish-placement-offset-x:${a};--swish-placement-offset-y:${u};}`);for(let l of t){let p=s[l.name];if(!p)continue;let f=Ee(p.x),y=Ee(p.y);c.push(`@media(min-width:${l.minWidth}px){[swish-placement-overlay="${n}"]{--swish-placement-offset-x:${f};--swish-placement-offset-y:${y};}}`)}return c.join("")}i(is,"emitOverlayOffsetCSS");function os(n){let e=n.id,t=ts(n.breakpoints),r=`[swish-placement-inline-row="${e}"]{display:flex;flex-direction:row;align-items:center;gap:var(--swish-placement-inline-gap,8px);width:100%}[swish-placement-inline-row="${e}"]>*:not([swish-placement-element="${e}"]){flex:1;min-width:0}`,s=`[swish-placement-overlay="${e}"]{position:absolute;z-index:var(--swish-placement-overlay-z,10);transform:translate(calc(var(--swish-placement-sign-x,1)*var(--swish-placement-offset-x,0px)),calc(var(--swish-placement-sign-y,1)*var(--swish-placement-offset-y,0px)));}[swish-placement-overlay="${e}"][swish-placement-anchor="top-left"]{top:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="top-right"]{top:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-left"]{bottom:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-right"]{bottom:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor$="left"]{--swish-placement-sign-x:1;}[swish-placement-overlay="${e}"][swish-placement-anchor$="right"]{--swish-placement-sign-x:-1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="top"]{--swish-placement-sign-y:1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="bottom"]{--swish-placement-sign-y:-1;}`,o="";if(n.layout?.type==="overlay"){let a=is(e,n.layout.offset,t),u=n.layout.zIndex?`[swish-placement-overlay="${e}"]{--swish-placement-overlay-z:${ss(n.layout.zIndex)};}`:"";o+=a+u+s}else n.layout?.type==="inline"&&(o+=r);if(n.design){let a=rs(e,n.design,t);a&&(o+=a)}return n.css&&(o+=n.css.trim()),o}i(os,"buildPlacementCSS");function as(n,e){if(!e||e==="target")return n;if("closest"in e)return n.closest(e.closest);if("query"in e)return n.querySelector(e.query);if("withinClosest"in e){let t=n.closest(e.withinClosest.root);return t?t.querySelector(e.withinClosest.selector):null}return n}i(as,"resolveMountTarget");function us(n,e,t){switch(t){case"before":return n.parentElement?(n.before(e),!0):!1;case"after":{let r=n.parentElement;return r?(r.insertBefore(e,n.nextSibling),!0):!1}case"append":return n.appendChild(e),!0;case"prepend":return n.insertBefore(e,n.firstChild),!0;case"replace":return n.parentElement?(n.replaceWith(e),!0):!1}}i(us,"insertIntoDOM");function cs(n){let e=n.parentElement;return e?(window.getComputedStyle(e).position==="static"&&(e.style.position="relative"),e):null}i(cs,"ensureRelativeParent");function ls(n,e,t){if(!e.parentElement)throw new Error("Cannot inline-wrap: refEl has no parentElement");let s=document.createElement("div");return s.setAttribute("swish-placement-inline-row",n),e.before(s),s.appendChild(e),s}i(ls,"wrapWithFlexRow");function ps(n,e){let t=e.tag||"div",r=document.createElement(t);return r.setAttribute("swish-placement-container",n),e.classNames&&vn(r,e.classNames),r}i(ps,"createContainer");function ds(n,e){return n.ui.createElement(e.name,{})}i(ds,"createElement");function fs(n,e){for(let[t,r]of Object.entries(e)){let s=t.replace(/([A-Z])/g,"-$1").toLowerCase();r===!1||r===void 0||r===null||(r===!0?n.setAttribute(s,"true"):n.setAttribute(s,String(r)))}}i(fs,"applyProps");function vn(n,e){n.classList.add(...e)}i(vn,"applyClassNames");var xe=class{constructor(){this.eventBus=new EventTarget}static{i(this,"EventBus")}subscribe(e,t,r){return Array.isArray(e)||(e=[e]),e.forEach(s=>{this.eventBus.addEventListener(s,t,r)}),()=>{e.forEach(s=>{this.eventBus.removeEventListener(s,t,r)})}}unsubscribe(e,t,r){this.eventBus.removeEventListener(e,t,r)}publish(e,t){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:t}))}};var Et;function wn(n){return{lang:n?.lang??Et?.lang,message:n?.message,abortEarly:n?.abortEarly??Et?.abortEarly,abortPipeEarly:n?.abortPipeEarly??Et?.abortPipeEarly}}i(wn,"getGlobalConfig");var hs;function ms(n){return hs?.get(n)}i(ms,"getGlobalMessage");var ys;function vs(n){return ys?.get(n)}i(vs,"getSchemaMessage");var gs;function ws(n,e){return gs?.get(n)?.get(e)}i(ws,"getSpecificMessage");function ke(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}i(ke,"_stringify");function K(n,e,t,r,s){let o=s&&"input"in s?s.input:t.value,a=s?.expected??n.expects??null,u=s?.received??ke(o),c={kind:n.kind,type:n.type,input:o,expected:a,received:u,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${u}`,requirement:n.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=n.kind==="schema",p=s?.message??n.message??ws(n.reference,c.lang)??(l?vs(c.lang):null)??r.message??ms(c.lang);p!==void 0&&(c.message=typeof p=="function"?p(c):p),l&&(t.typed=!1),t.issues?t.issues.push(c):t.issues=[c]}i(K,"_addIssue");function Z(n){return{version:1,vendor:"valibot",validate(e){return n["~run"]({value:e},wn())}}}i(Z,"_getStandardProps");function In(n,e){let t=[...new Set(n)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}i(In,"_joinExpects");function he(n,e){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${n}`,requirement:n,message:e,"~run"(t,r){return t.typed&&t.value.length<this.requirement&&K(this,"length",t,r,{received:`${t.value.length}`}),t}}}i(he,"minLength");function X(n,e){return{kind:"validation",type:"min_value",reference:X,async:!1,expects:`>=${n instanceof Date?n.toJSON():ke(n)}`,requirement:n,message:e,"~run"(t,r){return t.typed&&!(t.value>=this.requirement)&&K(this,"value",t,r,{received:t.value instanceof Date?t.value.toJSON():ke(t.value)}),t}}}i(X,"minValue");function T(n){return{kind:"transformation",type:"transform",reference:T,async:!1,operation:n,"~run"(e){return e.value=this.operation(e.value),e}}}i(T,"transform");function Is(n,e,t){return typeof n.fallback=="function"?n.fallback(e,t):n.fallback}i(Is,"getFallback");function bn(n,e,t){return typeof n.default=="function"?n.default(e,t):n.default}i(bn,"getDefault");function oe(n,e){return{kind:"schema",type:"array",reference:oe,expects:"Array",async:!1,item:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s=t.value;if(Array.isArray(s)){t.typed=!0,t.value=[];for(let o=0;o<s.length;o++){let a=s[o],u=this.item["~run"]({value:a},r);if(u.issues){let c={type:"array",origin:"value",input:s,key:o,value:a};for(let l of u.issues)l.path?l.path.unshift(c):l.path=[c],t.issues?.push(l);if(t.issues||(t.issues=u.issues),r.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value.push(u.value)}}else K(this,"type",t,r);return t}}}i(oe,"array");function xt(n){return{kind:"schema",type:"boolean",reference:xt,expects:"boolean",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="boolean"?e.typed=!0:K(this,"type",e,t),e}}}i(xt,"boolean");function E(n){return{kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:K(this,"type",e,t),e}}}i(E,"number");function g(n,e){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s=t.value;if(s&&typeof s=="object"){t.typed=!0,t.value={};for(let o in this.entries){let a=this.entries[o];if(o in s||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let u=o in s?s[o]:bn(a),c=a["~run"]({value:u},r);if(c.issues){let l={type:"object",origin:"value",input:s,key:o,value:u};for(let p of c.issues)p.path?p.path.unshift(l):p.path=[l],t.issues?.push(p);if(t.issues||(t.issues=c.issues),r.abortEarly){t.typed=!1;break}}c.typed||(t.typed=!1),t.value[o]=c.value}else if(a.fallback!==void 0)t.value[o]=Is(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(K(this,"key",t,r,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:s,key:o,value:s[o]}]}),r.abortEarly))break}}else K(this,"type",t,r);return t}}}i(g,"object");function P(n,e){return{kind:"schema",type:"optional",reference:P,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:e,get"~standard"(){return Z(this)},"~run"(t,r){return t.value===void 0&&(this.default!==void 0&&(t.value=bn(this,t,r)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,r)}}}i(P,"optional");function me(n,e){return{kind:"schema",type:"picklist",reference:me,expects:In(n.map(ke),"|"),async:!1,options:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){return this.options.includes(t.value)?t.typed=!0:K(this,"type",t,r),t}}}i(me,"picklist");function v(n){return{kind:"schema",type:"string",reference:v,expects:"string",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:K(this,"type",e,t),e}}}i(v,"string");function gn(n){let e;if(n)for(let t of n)e?e.push(...t.issues):e=t.issues;return e}i(gn,"_subIssues");function $(n,e){return{kind:"schema",type:"union",reference:$,expects:In(n.map(t=>t.expects),"|"),async:!1,options:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s,o,a;for(let u of this.options){let c=u["~run"]({value:t.value},r);if(c.typed)if(c.issues)o?o.push(c):o=[c];else{s=c;break}else a?a.push(c):a=[c]}if(s)return s;if(o){if(o.length===1)return o[0];K(this,"type",t,r,{issues:gn(o)}),t.typed=!0}else{if(a?.length===1)return a[0];K(this,"type",t,r,{issues:gn(a)})}return t}}}i($,"union");function b(...n){return{...n[0],pipe:n,get"~standard"(){return Z(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}}}i(b,"pipe");function S(n,e,t){let r=n["~run"]({value:e},wn(t));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}i(S,"safeParse");var de=b($([b(v(),T(A)),E()]),T(n=>Number(n)),b(E(),X(1)));var m=class{constructor(e,t,r,s){this.swish=e;this.ui=t;this.eventBus=r;this.options=s}static{i(this,"IntentHandler")}};var bs=$([g({variantId:de,quantity:P(b(E(),X(1)),1)}),g({items:b(oe(g({variantId:de,quantity:P(b(E(),X(1)),1)})),he(1))})]),Ce=class extends m{static{i(this,"CreateCartLineHandler")}async invoke(e){let t=S(bs,e);if(!t.success)return{intent:"create:cart-line",code:"error",message:"Invalid intent data",issues:t.issues.map(s=>s.message)};let r=t.output;try{let s="items"in r?r.items.map(a=>({id:a.variantId,quantity:a.quantity})):[{id:r.variantId,quantity:r.quantity}];return{intent:"create:cart-line",code:"ok",data:await this.swish.ajax.addToCart({items:s})}}catch(s){let o=[],a="Failed to add item to cart";return s instanceof Error?(s.message&&(a=s.message,o.push(s.message)),s.stack&&o.push(s.stack)):typeof s=="string"&&s.trim()?(a=s,o.push(s)):s!=null&&o.push(String(s)),{intent:"create:cart-line",code:"error",message:a,issues:o.length?o:["Cart request failed"]}}}};var Ss=g({variantId:de,quantity:P(b(E(),X(1)),1)}),Es=150,xs=$([g({variantId:de,quantity:P(b(E(),X(1)),1)}),g({items:b(oe(Ss),he(1))})]),Re=class extends m{static{i(this,"InitiateCheckoutHandler")}async invoke(e){let t=S(xs,e);if(!t.success)return{intent:"initiate:checkout",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let r=t.output,o=("items"in r?r.items:[{variantId:r.variantId,quantity:r.quantity}]).map(u=>`${u.variantId}:${u.quantity}`).join(","),a=new URL(`/cart/${o}`,this.swish.shopUrl);return a.searchParams.set("checkout","1"),typeof window<"u"&&window.setTimeout(()=>window.location.assign(a.href),Es),{intent:"initiate:checkout",code:"ok",data:{checkoutUrl:a.href}}}};var Ae=class extends m{static{i(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 ks=g({listId:v()}),De=class extends m{static{i(this,"DeleteListHandler")}async invoke(e){let t=S(ks,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 Cs=g({itemId:v()}),Pe=class extends m{static{i(this,"EditItemListsHandler")}async invoke(e){let t=S(Cs,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,s=await this.ui.showListSelect({itemId:r});if(s.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(s.data.action==="submit"){let{item:o,product:a,variant:u}=s.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:o,product:a,variant:u}}}return{intent:"unsave:item",code:"ok",data:{itemId:s.data.data.itemId}}}};var Rs=g({itemId:b(v()),productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()))}),Te=class extends m{static{i(this,"EditItemVariantHandler")}async invoke(e){let t=S(Rs,e);if(!t.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:t.issues.map(y=>y.message)};let{itemId:r,productId:s,variantId:o}=t.output;if(!(!o||this.swish.options.intents.editSavedProduct.promptVariantChange)){let y=await this.swish.api.items.updateById(r,{productId:s,variantId:o});if("error"in y)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[y.error.message]};if(!y.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let h=await this.swish.storefront.loadSaveIntentData({productId:D("Product",s),variantId:o?D("ProductVariant",o):void 0});if(!h.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load save intent data",issues:[h.errors?.message??"No product data returned from API"]};let x=h.data?.product,w="variant"in h.data?h.data.variant:void 0;return{intent:"edit:item-variant",code:"ok",data:{item:y.data,product:x,variant:w}}}let u=await this.ui.showVariantSelect({itemId:r,productId:s,variantId:o});if(u.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:c,product:l,variant:p}=u.data;return{intent:"edit:item-variant",code:"ok",data:{item:c,product:l,variant:p}}}};var As=g({listId:v(),access:me(["public","private"])}),_e=class extends m{static{i(this,"EditListAccessHandler")}async invoke(e){let t=S(As,e);if(!t.success)return{intent:"edit:list-access",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r,access:s}=t.output;if((await this.ui.showConfirmDialog({titleKey:s==="public"?"listMenu.public.title":"listMenu.private.title",descriptionKey:s==="public"?"listMenu.public.description":"listMenu.private.description",confirmLabelKey:s==="public"?"listMenu.public.text":"listMenu.private.text",cancelLabelKey:"listMenu.cancel",danger:!1})).code==="closed")return{intent:"edit:list-access",code:"closed"};let a=await this.swish.api.lists.updateById(r,{access:s});return"error"in a?{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:[a.error.message]}:a.data?{intent:"edit:list-access",code:"ok",data:{list:a.data}}:{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:["API response missing data"]}}};var Ds=g({listId:v()}),Oe=class extends m{static{i(this,"EditListHandler")}async invoke(e){let t=S(Ds,e);if(!t.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{listId:r}=t.output,s=await this.ui.showListEditor({listId:r});if(s.code==="closed")return{intent:"edit:list",code:"closed"};let{list:o}=s.data;return{intent:"edit:list",code:"ok",data:{list:o}}}};var Ps=150,Ts=g({returnTo:v()}),Le=class extends m{static{i(this,"InitiateSignInHandler")}async invoke(e){let t=S(Ts,e);if(!t.success)return{intent:"initiate:sign-in",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let r=t.output.returnTo;return(await this.ui.showConfirmDialog({titleKey:"signIn.title",descriptionKey:"signIn.description",confirmLabelKey:"signIn.continue",danger:!1})).code==="closed"?{intent:"initiate:sign-in",code:"closed"}:(this.scheduleRedirect(r),{intent:"initiate:sign-in",code:"ok",data:void 0})}scheduleRedirect(e){window.setTimeout(()=>this.redirectToSignIn(e),Ps)}redirectToSignIn(e){let t=this.swish.storefrontContext.routes.accountUrl,r=new URL(t,window.location.origin);r.searchParams.set("return_url",e),window.location.assign(r.toString())}};var $e=class extends m{static{i(this,"OpenHomeHandler")}async invoke(e){return{intent:"open:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var _s=g({listId:v()}),Me=class extends m{static{i(this,"OpenListDetailPageMenuHandler")}async invoke(e){let t=S(_s,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 Os=g({listId:v()}),Ve=class extends m{static{i(this,"OpenListHandler")}async invoke(e){let t=S(Os,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 Ls=g({listId:v()}),qe=class extends m{static{i(this,"OpenListMenuHandler")}async invoke(e){let t=S(Ls,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,s=await this.ui.showListMenu({listId:r});if(s.code==="closed")return{intent:"open:list-menu",code:"closed"};if(s.data.action==="edit")return{intent:"edit:list",code:"ok",data:s.data.data};if(s.data.action==="delete")return{intent:"delete:list",code:"ok",data:{listId:r}};if(s.data.action==="edit-access"){let o=s.data.data?.currentListAccess,a=o==="public"?"private":o==="private"?"public":void 0;return a?(await this.swish.intents.invoke("edit:list-access",{listId:r,access:a})).complete:{intent:"open:list-menu",code:"error",message:"Missing list access from UI",issues:["List menu UI did not provide currentListAccess"]}}return s.data.action==="share"?(await this.swish.intents.invoke("initiate:share",{listId:r})).complete:{intent:"open:list-menu",code:"error",message:"Unknown list menu action",issues:["Unknown action returned from list menu UI"]}}};var Ne=class extends m{static{i(this,"OpenListsHandler")}async invoke(e){return{intent:"open:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var Be=class extends m{static{i(this,"OpenNotificationsHandler")}async invoke(e){return{intent:"open:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var $s=g({orderId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E())}),Ue=class extends m{static{i(this,"OpenOrderHandler")}async invoke(e){let t=S($s,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 Ms=g({orderId:v()}),Fe=class extends m{static{i(this,"OpenOrderMenuHandler")}async invoke(e){let t=S(Ms,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 je=class extends m{static{i(this,"OpenOrdersHandler")}async invoke(e){return{intent:"open:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Vs=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E()))}),Ge=class extends m{static{i(this,"OpenProductHandler")}async invoke(e){let t=S(Vs,e);if(!t.success)return{intent:"open:product",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{productId:r,variantId:s}=t.output;return{intent:"open:product",code:(await this.ui.showDrawer({view:"product",productId:r.toString(),variantId:s?.toString()})).code,data:void 0}}};var He=class extends m{static{i(this,"OpenProfileHandler")}async invoke(e){return{intent:"open:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var qs=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E()))}),Qe=class extends m{static{i(this,"OpenQuickBuyHandler")}async invoke(e){let t=S(qs,e);if(!t.success)return{intent:"open:quick-buy",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{productId:r,variantId:s}=t.output,o=await this.ui.showQuickBuy({productId:r,variantId:s});return o.code==="closed"?{intent:"open:quick-buy",code:"closed"}:{intent:"open:quick-buy",code:"ok",data:o.data}}};var ze=class extends m{static{i(this,"OpenSavesHandler")}async invoke(e){return{intent:"open:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var iu=g({returnTo:P(v())}),We=class extends m{static{i(this,"OpenSignInHandler")}async invoke(e){return{intent:"open:sign-in",code:(await this.ui.showSignIn({returnTo:e?.returnTo})).code,data:void 0}}};var Ns=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E())),quantity:P(b(E(),X(1))),tags:P(oe(v()))}),Ke=class extends m{static{i(this,"SaveItemHandler")}async invoke(e){let t=S(Ns,e);if(!t.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:t.issues.map(h=>h.message)};let{productId:r,variantId:s,quantity:o,tags:a}=t.output,u=await this.swish.storefront.loadSaveIntentData({productId:D("Product",r),variantId:s?D("ProductVariant",s):void 0});if(u.errors)return{intent:"save:item",code:"error",message:u.errors.message??"Failed to load save intent data",issues:u.errors.graphQLErrors?.map(h=>h.message)??[]};if(!u.data||!u.data.product)return{intent:"save:item",code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=u.data,l=c.variantsCount?.count&&c.variantsCount.count>1,p=!!s,f=!this.options.saveProduct.promptVariantIfMissing||!this.options.saveProduct.promptVariantIfPresent&&p;if(!l||f){let h=i(()=>!l&&c.selectedOrFirstAvailableVariant?Number(A(c.selectedOrFirstAvailableVariant.id)):s,"variantIdToUse"),x=await this.swish.api.items.create({productId:r,variantId:h(),quantity:o,tags:a});if("error"in x)return{intent:"save:item",code:"error",message:"Failed to create item",issues:[x.error.message]};if(!x.data)return{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let w="variant"in u.data?u.data.variant:void 0;return{intent:"save:item",code:"ok",data:{item:x.data,product:c,variant:l?w:c.selectedOrFirstAvailableVariant}}}let y=await this.ui.showVariantSelect({productId:r,variantId:s});return y.code==="closed"?{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:y.data}}};function ye(n,e){let{storeDomain:t}=n.options.storefrontApi,{rootUrl:r,listDetailPagePath:s}=n.options.storefrontContext.routes,o=new URL(`https://${t}`),a=new URL(`${r==="/"?"":r}${s}`,o);return a.searchParams.set("public-list-id",e.publicListId),a}i(ye,"buildShareListUrl");async function ve(n){return typeof navigator?.clipboard?.writeText!="function"?{ok:!1,issues:["Clipboard API not available"]}:navigator.clipboard.writeText(n).then(()=>({ok:!0})).catch(e=>({ok:!1,issues:[e?.message??"Failed to copy to clipboard"]}))}i(ve,"copyToClipboard");function Sn(){let n=navigator.userAgent.includes("Mac OS")&&navigator.maxTouchPoints>1;return/Android|Mobile/i.test(navigator.userAgent)||n}i(Sn,"isMobileDevice");var Bs=g({listId:v()}),Xe=class extends m{static{i(this,"ShareListHandler")}async invoke(e){let t=S(Bs,e);if(!t.success)return{intent:"initiate:share",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r}=t.output,s=ye(this.swish,{publicListId:r}).toString();if(Sn()&&typeof navigator.share=="function"&&(await navigator.share({title:"Share list",url:s}).then(()=>({ok:!0})).catch(()=>({ok:!1}))).ok)return{intent:"initiate:share",code:"ok",data:{listId:r,url:s,method:"native"}};let a=await ve(s);return a.ok?{intent:"initiate:share",code:"ok",data:{listId:r,url:s,method:"clipboard"}}:{intent:"initiate:share",code:"error",message:"Failed to share list",issues:a.issues}}};var ku=g({title:P(v()),text:v(),image:P(v()),action:P(g({label:v(),url:P(v())})),variant:P(me(["compact","full"])),icon:P(v())}),Ye=class extends m{static{i(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var Us=g({itemId:v(),delete:P(xt())}),Je=class extends m{static{i(this,"UnsaveItemHandler")}async invoke(e){let t=S(Us,e);if(!t.success)return{intent:"unsave:item",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{itemId:r,delete:s}=t.output;if(this.options.unsaveProduct.selectList&&!s){let a=await this.ui.showListSelect({itemId:r});if(a.code==="closed")return{intent:"unsave:item",code:"closed"};if(a.data.action==="submit"){let{item:u,product:c,variant:l}=a.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:u,product:c,variant:l}}}if(a.data.action==="unsave"){let{itemId:u}=a.data.data;return{intent:"unsave:item",code:"ok",data:{itemId:u}}}}if(!this.options.unsaveProduct.confirm){let a=await this.swish.api.items.deleteById(r);return"error"in a?{intent:"unsave:item",code:"error",message:"Failed to delete item",issues:[a.error.message]}:{intent:"unsave:item",code:"ok",data:{itemId:r}}}return(await this.ui.showUnsaveAlert({itemId:r})).code==="closed"?{intent:"unsave:item",code:"closed"}:{intent:"unsave:item",code:"ok",data:{itemId:r}}}};var z=class{constructor(e,t,r){this.swish=e;this.ui=t;this.options=r}static{i(this,"IntentHook")}};var Ze=class extends z{static{i(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.editSavedProduct.showFeedback&&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 et=class extends z{static{i(this,"AfterEditListAccessHook")}async invoke(e){if(e.code!=="ok")return;let t=e.data.list.access==="public"?"List is now public":"List is now private";await(await this.swish.intents.invoke("show:toast",{text:t,variant:"compact",icon:"check"})).complete}};var tt=class extends z{static{i(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 nt=class extends z{static{i(this,"AfterSaveItemHook")}async invoke(e){if(this.options.saveProduct.showFeedback&&e.code==="ok"){let{item:t,product:r,variant:s}=e.data;r&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:r.title,image:s?.image?.url??r.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:t.id})}}};var rt=class extends z{static{i(this,"AfterShareListHook")}async invoke(e){if(e.code!=="ok")return;await(await this.swish.intents.invoke("show:toast",{variant:"compact",text:"Link shared",icon:"check"})).complete}};var st=class{static{i(this,"Intents")}constructor(e,t){this.swish=e,this.ui=t,this.eventBus=new EventTarget,this.options=e.options.intents,this.handlers={"create:cart-line":new Ce(this.swish,this.ui,this.eventBus,this.options),"initiate:checkout":new Re(this.swish,this.ui,this.eventBus,this.options),"save:item":new Ke(this.swish,this.ui,this.eventBus,this.options),"unsave:item":new Je(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Te(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new Pe(this.swish,this.ui,this.eventBus,this.options),"create:list":new Ae(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Oe(this.swish,this.ui,this.eventBus,this.options),"edit:list-access":new _e(this.swish,this.ui,this.eventBus,this.options),"delete:list":new De(this.swish,this.ui,this.eventBus,this.options),"open:home":new $e(this.swish,this.ui,this.eventBus,this.options),"initiate:share":new Xe(this.swish,this.ui,this.eventBus,this.options),"open:list":new Ve(this.swish,this.ui,this.eventBus,this.options),"open:lists":new Ne(this.swish,this.ui,this.eventBus,this.options),"open:orders":new je(this.swish,this.ui,this.eventBus,this.options),"open:order":new Ue(this.swish,this.ui,this.eventBus,this.options),"open:saves":new ze(this.swish,this.ui,this.eventBus,this.options),"open:notifications":new Be(this.swish,this.ui,this.eventBus,this.options),"open:profile":new He(this.swish,this.ui,this.eventBus,this.options),"open:product":new Ge(this.swish,this.ui,this.eventBus,this.options),"open:list-menu":new qe(this.swish,this.ui,this.eventBus,this.options),"open:order-menu":new Fe(this.swish,this.ui,this.eventBus,this.options),"open:list-detail-page-menu":new Me(this.swish,this.ui,this.eventBus,this.options),"initiate:sign-in":new Le(this.swish,this.ui,this.eventBus,this.options),"open:sign-in":new We(this.swish,this.ui,this.eventBus,this.options),"open:quick-buy":new Qe(this.swish,this.ui,this.eventBus,this.options),"show:toast":new Ye(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],s={lifecycle:"before",intent:e,data:r};return this.publishAnalyticsEvent("swish-intent",s),this.publishAnalyticsEvent(`swish-intent=${e}`,s),{intent:e,data:r,complete:this.handleIntent(e,r).then(o=>{let a={lifecycle:"after",intent:e,data:r,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${e}`,a),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:o})),o})}}listen(e,t){let r=i(o=>{"detail"in o&&o.detail?t(o.detail):console.warn("Intent response event without detail",o)},"eventListener"),s=i(()=>{this.eventBus.removeEventListener(e,r)},"unsubscribe");return this.eventBus.addEventListener(e,r),s}parseIntentFromString(e){if(typeof e=="string"){let[t,...r]=e.split(","),s=r.reduce((o,a)=>{let[u,c]=a.split("=");return o[u]=c,o},{});return{intent:t,data:s}}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 nt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new Ze(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("open:home",e=>{new tt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:list-access",e=>{new et(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("initiate:share",e=>{new rt(this.swish,this.ui,this.options).invoke(e.detail)})}initIntentWatcher(){ie({selector:"[swish-intent]",onElementFound:i(e=>{let t=e.getAttribute("swish-intent");t&&e.addEventListener("click",()=>{let{intent:r,data:s}=this.parseIntentFromString(t);Object.keys(s).length>0?this.invoke(r,s):this.invoke(r)})},"onElementFound")}),ie({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:i(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",t=>{if(!t.metaKey&&!t.ctrlKey&&!t.shiftKey&&!t.altKey){let r=new URL(e.href),s=r.hash,o=r.searchParams.get("swish-intent");if(o){let{intent:a,data:u}=this.parseIntentFromString(o);a&&(t.preventDefault(),t.stopPropagation(),Object.keys(u).length>0?this.invoke(a,u):this.invoke(a))}else if(s){let a=this.parseIntentFromHash(s);a&&(t.preventDefault(),t.stopPropagation(),this.invoke(a))}}})},"onElementFound")}),pe({fireOnInit:!0,onLocationChange:i(e=>{let t=new URL(e.href),r=t.hash,s=t.searchParams.get("swish-intent");if(s){let{intent:o,data:a}=this.parseIntentFromString(s);o&&(Object.keys(a).length>0?this.invoke(o,a):this.invoke(o))}else if(r){let o=this.parseIntentFromHash(r);o&&this.invoke(o)}},"onLocationChange")})}};var En=i(n=>({swishApi:{authProxy:n.swishApi?.authProxy??"/apps/wishlist/api",version:n.swishApi?.version??"2026-01"},storefrontApi:{storeDomain:n.storefrontApi?.storeDomain??"",accessToken:n.storefrontApi?.accessToken??""},storefrontContext:{...n.storefrontContext,routes:{...n.storefrontContext.routes,rootUrl:n.storefrontContext.routes?.rootUrl??"/",listDetailPagePath:n.storefrontContext.routes?.listDetailPagePath??"/apps/wishlist"},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)},productOptions:{sortValues:n.productOptions?.sortValues??(({option:e,optionValues:t})=>t)},metafields:{product:n.metafields?.product??[],productVariant:n.metafields?.productVariant??[]},features:{accounts:n?.features?.accounts??!0,lists:n?.features?.lists??!0,orders:n?.features?.orders??!0,notifications:n?.features?.notifications??!0},intents:{saveProduct:{promptVariantIfMissing:n?.intents?.saveProduct?.promptVariantIfMissing??!0,promptVariantIfPresent:n?.intents?.saveProduct?.promptVariantIfPresent??!0,showFeedback:n?.intents?.saveProduct?.showFeedback??!0},unsaveProduct:{selectList:n?.intents?.unsaveProduct?.selectList??!0,confirm:n?.intents?.unsaveProduct?.confirm??!0,showFeedback:n?.intents?.unsaveProduct?.showFeedback??!0},editSavedProduct:{promptVariantChange:n?.intents?.editSavedProduct?.promptVariantChange??!0,showFeedback:n?.intents?.editSavedProduct?.showFeedback??!0}},swishUi:{baseUrl:n.swishUi?.baseUrl??"https://swish.app/cdn",version:n.swishUi?.version??it,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:{enabled:n.swishUi?.components?.drawer?.navigation?.enabled??!0,variant:n.swishUi?.components?.drawer?.navigation?.variant??"floating",items:n.swishUi?.components?.drawer?.navigation?.items??[]},emptyCallout:{enabled:n.swishUi?.components?.drawer?.emptyCallout?.enabled??!1,shoppingCalloutUrl:n.swishUi?.components?.drawer?.emptyCallout?.shoppingCalloutUrl??"/collections/all"},miniMenu:{enabled:n.swishUi?.components?.drawer?.miniMenu?.enabled??!0,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??[],design:n.swishUi?.design??{}}}),"createSwishOptions");var Fs=Symbol.for("preact-signals");function at(){if(ne>1)ne--;else{for(var n,e=!1;ge!==void 0;){var t=ge;for(ge=void 0,kt++;t!==void 0;){var r=t.o;if(t.o=void 0,t.f&=-3,!(8&t.f)&&Cn(t))try{t.c()}catch(s){e||(n=s,e=!0)}t=r}}if(kt=0,ne--,e)throw n}}i(at,"t");function re(n){if(ne>0)return n();ne++;try{return n()}finally{at()}}i(re,"r");var k=void 0;function xn(n){var e=k;k=void 0;try{return n()}finally{k=e}}i(xn,"n");var ge=void 0,ne=0,kt=0,ot=0;function kn(n){if(k!==void 0){var e=n.n;if(e===void 0||e.t!==k)return e={i:0,S:n,p:k.s,n:void 0,t:k,e:void 0,x:void 0,r:e},k.s!==void 0&&(k.s.n=e),k.s=e,n.n=e,32&k.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=k.s,e.n=void 0,k.s.n=e,k.s=e),e}}i(kn,"e");function B(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}i(B,"u");B.prototype.brand=Fs;B.prototype.h=function(){return!0};B.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:xn(function(){var r;(r=e.W)==null||r.call(e)}))};B.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&&xn(function(){var s;(s=e.Z)==null||s.call(e)}))}};B.prototype.subscribe=function(n){var e=this;return Q(function(){var t=e.value,r=k;k=void 0;try{n(t)}finally{k=r}},{name:"sub"})};B.prototype.valueOf=function(){return this.value};B.prototype.toString=function(){return this.value+""};B.prototype.toJSON=function(){return this.value};B.prototype.peek=function(){var n=k;k=void 0;try{return this.value}finally{k=n}};Object.defineProperty(B.prototype,"value",{get:i(function(){var n=kn(this);return n!==void 0&&(n.i=this.i),this.v},"get"),set:i(function(n){if(n!==this.v){if(kt>100)throw new Error("Cycle detected");this.v=n,this.i++,ot++,ne++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{at()}}},"set")});function V(n,e){return new B(n,e)}i(V,"d");function Cn(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}i(Cn,"c");function Rn(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}}}i(Rn,"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}i(An,"l");function ae(n,e){B.call(this,void 0),this.x=n,this.s=void 0,this.g=ot-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(ae,"y");ae.prototype=new B;ae.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ot))return!0;if(this.g=ot,this.f|=1,this.i>0&&!Cn(this))return this.f&=-2,!0;var n=k;try{Rn(this),k=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 k=n,An(this),this.f&=-2,!0};ae.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)}B.prototype.S.call(this,n)};ae.prototype.U=function(n){if(this.t!==void 0&&(B.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)}};ae.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(ae.prototype,"value",{get:i(function(){if(1&this.f)throw new Error("Cycle detected");var n=kn(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 ae(n,e)}i(F,"w");function Dn(n){var e=n.u;if(n.u=void 0,typeof e=="function"){ne++;var t=k;k=void 0;try{e()}catch(r){throw n.f&=-2,n.f|=8,Ct(n),r}finally{k=t,at()}}}i(Dn,"_");function Ct(n){for(var e=n.s;e!==void 0;e=e.n)e.S.U(e);n.x=void 0,n.s=void 0,Dn(n)}i(Ct,"b");function js(n){if(k!==this)throw new Error("Out-of-order effect");An(this),k=n,this.f&=-2,8&this.f&&Ct(this),at()}i(js,"g");function fe(n,e){this.x=n,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}i(fe,"p");fe.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()}};fe.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Dn(this),Rn(this),ne++;var n=k;return k=this,js.bind(this,n)};fe.prototype.N=function(){2&this.f||(this.f|=2,this.o=ge,ge=this)};fe.prototype.d=function(){this.f|=8,1&this.f||Ct(this)};fe.prototype.dispose=function(){this.d()};function Q(n,e){var t=new fe(n,e);try{t.c()}catch(s){throw t.d(),s}var r=t.d.bind(t);return r[Symbol.dispose]=r,r}i(Q,"E");var Gs=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,Rt=i(n=>{let e=n.match(Gs);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),Pn=i(({source:n,onProductUrlChange:e})=>{let t=i(r=>{let s=Rt(r);s?.productHandle&&e(s)},"handleChange");if(n instanceof HTMLAnchorElement)return dn({element:n,onHrefChange:i(r=>t(r),"onHrefChange")});if(n instanceof Location)return pe({onLocationChange:i(r=>t(r.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Tn=i(n=>e=>{let{productHandle:t,productId:r,variantId:s,itemId:o}=e?.dataset??{},c=!!(r||t)||!!o,l=V({loading:!1,productId:r,variantId:s,itemId:o});if(!c){let p=e instanceof HTMLAnchorElement?e:window.location,f=Rt(p.href);f?.productHandle&&f.productHandle!==l.value.productHandle&&(l.value={...l.value,...f,productId:void 0},Pn({source:p,onProductUrlChange:i(y=>{l.value={...l.value,...y,productId:y.productHandle!==l.value.productHandle?void 0:l.value.productId}},"onProductUrlChange")}))}return Q(()=>{l.value.loading||!l.value.productId&&l.value.productHandle&&(l.value={...l.value,loading:!0},n.storefront.loadProductId({productHandle:l.value.productHandle}).then(p=>{p.errors&&console.error("Error loading product id",p.errors),l.value={...l.value,productId:p.data?.product?.id?A(p.data.product.id):void 0,loading:!1}}))}),l},"itemContextSignal");var _n=i(n=>e=>{let t=F(()=>{let{productId:_,variantId:I,loading:q}=e.value;return!_||q?null:I?`variant:${A(I)}`:`product:${A(_)}`}),r=F(()=>e.value.loading||!!e.value.itemId||!e.value.productId),s=F(()=>({limit:1,query:t.value??void 0})),o=V(!r.value),a=V(null),u=V(!1),c=V(!1),{data:l,loading:p,error:f,refetching:y}=n.state.swishQuery(_=>n.api.items.list(_),{refetch:["item-create","item-update","item-delete"],variables:s,skip:r}),h=V(e.value.itemId??null);Q(()=>{re(()=>{if(o.value=p.value,a.value=f.value,!e.value.itemId){let _=l.value?.[0]?.id??null;_!==h.value&&(h.value=_)}})});async function x(){if(!h.value)return;u.value=!0;let I=await(await n.intents.invoke("unsave:item",{itemId:h.value})).complete;I.code==="ok"&&"itemId"in I.data&&(h.value=null),u.value=!1}i(x,"unsave");async function w(){if(!h.value)return;u.value=!0;let I=await(await n.intents.invoke("edit:item-lists",{itemId:h.value})).complete;I.code==="ok"&&"itemId"in I.data&&(h.value=null),u.value=!1}i(w,"update");async function O(){let{productId:_,variantId:I}=e.value;if(!_)return;u.value=!0,c.value=!0;let C=await(await n.intents.invoke("save:item",{productId:_,variantId:I})).complete;if(C.code==="ok"){let te=C.data;h.value=te.item.id,u.value=!1}else C.code==="error"&&console.warn("Failed to create item",C),re(()=>{u.value=!1,c.value=!1})}i(O,"save");let N=F(()=>o.value||u.value||e.value.loading);Q(()=>{c.value&&!u.value&&!y.value&&(c.value=!1)});let L=F(()=>{let _=y.value&&c.value,I=!!h.value,q=!I&&(u.value||_),C=I&&(u.value||_),te=F(()=>q?"saving":C?"unsaving":I?"saved":"unsaved");return{error:a.value,status:te.value,savedItemId:h.value,loading:N.value,submitting:u.value,saved:I,saving:q,unsaving:C}});async function G(){N.value||(L.value.saved&&L.value.savedItemId?x():L.value.saved||await O())}return i(G,"toggle"),Object.assign(L,{save:O,unsave:x,update:w,toggle:G})},"itemStateSignal");var On=i(n=>()=>{let{data:e,loading:t,error:r}=n.state.swishQuery(()=>n.api.items.count(),{refetch:["item-create","item-delete"]}),s=V(0),o=V(!0),a=V(null);return Q(()=>{re(()=>{o.value=t.value,a.value=r.value,s.value=e.value?.count??0})}),F(()=>({count:s.value,loading:o.value,error:a.value}))},"itemCountSignal");var Hs="token-update",Ln=i(n=>(e,t)=>{let r=V(null),s=V(null),o=V(null),a=V(!t?.skip),u=V(!1),c=F(()=>a.value&&u.value);async function l(){if(!t?.skip?.value)try{a.value=!0;let p=await e(t?.variables?.value);re(()=>{o.value="error"in p?p.error:null,r.value="data"in p?p.data:null,s.value="pageInfo"in p?p.pageInfo:null,a.value=!1,u.value=!0})}catch(p){re(()=>{o.value=p,a.value=!1,u.value=!0})}}return i(l,"executeFetch"),Q(()=>{if(l(),t?.refetch?.length){let p=[...t.refetch,Hs];return n.events.subscribe(p,l)}}),{data:r,pageInfo:s,error:o,loading:a,refetching:c}},"swishQuerySignals");var ue="GraphQL Client";var At="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",Dt="Response returned unexpected Content-Type:",Pt="An unknown error has occurred. The API did not return a data object or any errors in its response.",ut={json:"application/json",multipart:"multipart/mixed"},Tt="X-SDK-Variant",_t="X-SDK-Version",Mn="shopify-graphql-client",Vn="1.4.1",ct=1e3,qn=[429,503],Ot=/@(defer)\b/i,$n=`\r
|
|
8
|
-
`,
|
|
7
|
+
`+String(r)));rn(e);for(var s=0;s<e.callbacks.length;s++){var o=r[s];o instanceof Error?e.callbacks[s].reject(o):e.callbacks[s].resolve(o)}}).catch(function(r){nn(n,e,r)})}i(ro,"dispatchBatch");function nn(n,e,t){rn(e);for(var r=0;r<e.keys.length;r++)n.clear(e.keys[r]),e.callbacks[r].reject(t)}i(nn,"failedDispatch");function rn(n){if(n.cacheHits)for(var e=0;e<n.cacheHits.length;e++)n.cacheHits[e]()}i(rn,"resolveCacheHits");function so(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}i(so,"getValidMaxBatchSize");function io(n){var e=n&&n.batchScheduleFn;if(e===void 0)return to;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}i(io,"getValidBatchScheduleFn");function oo(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}i(oo,"getValidCacheKeyFn");function ao(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"],s=r.filter(function(o){return t&&typeof t[o]!="function"});if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return t}i(ao,"getValidCacheMap");function uo(n){return n&&n.name?n.name:null}i(uo,"getValidName");function Or(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))}i(Or,"isArrayLike");Lr.exports=eo});var A=i(n=>n.split("/").pop()??"","shopifyGidToId"),D=i((n,e)=>`gid://shopify/${n}/${e}`,"shopifyIdToGid"),G=i(n=>n.toLowerCase().replace(".myshopify.com",""),"toShopName");var J=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{i(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 s=this.createCacheableResponse(t,r);await(await caches.open(this.cacheName)).put(e,s)}catch(s){console.warn("Cache set error:",s)}}async fetchWithCache(e,t,r){let s=await this.getCacheKey(e,t);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(s))return this.inFlightRequests.get(s).then(a=>a.clone());let o=(async()=>{let a=await this.get(s);if(a)return this.isStaleButRevalidatable(a)&&this.revalidateInBackground(s,e,t,r),a.clone();let u=await fetch(e,t);return u.ok&&await this.set(s,u.clone(),r??this.defaultCacheControl),u})().finally(()=>{this.inFlightRequests.delete(s)});return this.inFlightRequests.set(s,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),s=await r.keys();await Promise.all(s.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 a=await e.match(o);a&&this.isExpired(a)&&(await e.delete(o),r++)}let s=t.length-r;return{removed:r,remaining:s}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,t){let r=this.getInputUrl(e),s=`${this.keyPrefix}${r}/${JSON.stringify(t)}`,a=new TextEncoder().encode(s),u=await crypto.subtle.digest("SHA-256",a);return`/${Array.from(new Uint8Array(u)).map(l=>l.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),s=this.parseStaleWhileRevalidate(t);if(r===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3,p=r+(s??0);return c>p}isStaleButRevalidatable(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let r=this.parseMaxAge(t),s=this.parseStaleWhileRevalidate(t);if(r===null||s===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),c=(Date.now()-a)/1e3;return c>r&&c<=r+s}async revalidateInBackground(e,t,r,s){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let a=await fetch(t,r);a.ok&&await this.set(e,a.clone(),s??this.defaultCacheControl)}catch(a){console.warn("Background revalidation error:",a)}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 be=class{static{i(this,"AjaxApiClient")}constructor(e){this.config=e;let t=G(e.storeDomain);this.cache=new J(`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(...s){let o=e.apply(this,s);if(typeof t=="function"){let a=r(s[0]);o.then(u=>t(u,a))}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}`,s={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(r,{...t,headers:{...s,...t.headers}});if(!o.ok){let a;try{a=await o.json()}catch{a={message:`HTTP ${o.status}: ${o.statusText}`,status:o.status.toString(),description:o.statusText}}throw new Error(a.message||a.description)}return o.json()}async fetchCart(){return this.request("/cart.js")}async addToCart(e){let t={...e,items:e.items.map(r=>{let s=Number(A(String(r.id)));if(!Number.isFinite(s)||s<=0)throw new Error(`Invalid Shopify ID: ${r.id}`);return{...r,id:s}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(t)})}async clearCache(){await this.cache.clear()}};var Se=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{i(this,"AjaxApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.url);if(r){let s=await e.clone().json();this.eventBus.publish(r,s)}}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 Wr(){let n=document.body||document.documentElement;return n?Promise.resolve(n):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(n))})}i(Wr,"waitForDOM");function ie({onElementFound:n,selector:e,observerOptions:t,mustMatch:r}){let s=new WeakSet,o=new MutationObserver(p=>{let l=!1;for(let f of p)if(f.addedNodes.length>0){l=!0;break}l&&a()}),a=i(()=>{document.querySelectorAll(e).forEach(p=>{s.has(p)||(s.add(p),r?.(p)!==!1&&u(p))})},"locateElements"),u=i(p=>{if(!t){n(p);return}let l=new IntersectionObserver(f=>{for(let y of f)y.isIntersecting&&(l.disconnect(),n(p))},t);l.observe(p)},"observeElement");return i(async()=>{let p=await Wr();a(),o.observe(p,{childList:!0,subtree:!0})},"locateAndObserveElements")(),o}i(ie,"createElementLocator");function pe({onLocationChange:n,fireOnInit:e=!1}){let t=i(()=>{n(window.location)},"handleChange");window.addEventListener("popstate",t);let r=history.pushState,s=history.replaceState;return history.pushState=function(...o){r.apply(this,o),t()},history.replaceState=function(...o){s.apply(this,o),t()},e&&t(),()=>{window.removeEventListener("popstate",t),history.pushState=r,history.replaceState=s}}i(pe,"createLocationObserver");function pn({element:n,onHrefChange:e}){let t=i(()=>{e(n.href)},"handleChange"),r=new MutationObserver(()=>{t()});return r.observe(n,{attributes:!0,attributeFilter:["href"]}),()=>{r.disconnect()}}i(pn,"createHrefObserver");function hn(n,e){if(!e.element)throw new Error("Element must be provided");let t=null,r=new Map,s=i(()=>{if(t){console.warn("Placement already mounted. Skipping mount.");return}Xr(e),t=ie({selector:e.target.selector,observerOptions:e.target.observerOptions,mustMatch:e.target.mustMatch,onElementFound:i(p=>o(p),"onElementFound")})},"mount"),o=i(p=>{r.has(p)||p.hasAttribute("swish-ignore")||p.getAttribute("swish-placement-target")===e.id||(p.setAttribute("swish-placement-target",e.id),a(p))},"evaluateAndMount"),a=i(async p=>{let l=[],f=e.mount.mode,y=os(p,e.mount.at);if(!y)return;let h=await(typeof e.element=="function"?e.element(e):ps(n,e.element));if(!h)return;if(h.setAttribute("swish-placement-element",e.id),typeof e.element!="function"){let C=e.element;C.props&&ds(h,C.props),C.classNames&&yn(h,C.classNames)}let x;e.container&&(x=ls(e.id,e.container),x.appendChild(h));let w,O=x??h;if(e.layout?.type==="overlay"){us(y);let C=e.layout.anchor??"bottom-right";O.setAttribute("swish-placement-overlay",e.id),O.setAttribute("swish-placement-anchor",C)}let N=!1,L;if(e.layout?.type==="inline"){let C=e.layout,te=C.rowSelector?y.closest(C.rowSelector):null;te?w=te:(w=cs(e.id,y,C),N=!0),L=w.getAttribute("swish-placement-inline-row"),w.setAttribute("swish-placement-inline-row",e.id)}let H=x??h;if(!as(y,H,f)){try{H.remove()}catch{}return}let I={targetEl:p,renderTargetEl:y,mountEl:h,containerEl:x,rowEl:w,rowWasCreated:N,rowInlineAttrPrevValue:L,cleanupFns:l,ownsNode:!0};r.set(p,I);let V={id:e.id,targetEl:p,renderTargetEl:y,mountEl:I.mountEl,containerEl:x,rowEl:w,cleanup:i(C=>l.push(C),"cleanup")};e.element?.name==="save-button"&&Kr(n,V),e.onMount?.(V)},"mountElement"),u=i(p=>{let l=r.get(p);if(l){if(e.onUnmount?.({id:e.id,targetEl:l.targetEl,renderTargetEl:l.renderTargetEl,mountEl:l.mountEl,containerEl:l.containerEl,rowEl:l.rowEl}),l.cleanupFns.forEach(f=>f()),l.targetEl.getAttribute("swish-placement-target")===e.id&&l.targetEl.removeAttribute("swish-placement-target"),l.ownsNode&&(l.containerEl||l.mountEl).remove(),l.rowEl){if(l.rowWasCreated){let f=l.rowEl.parentElement;f&&l.targetEl.parentElement===l.rowEl?l.rowEl.replaceWith(l.targetEl):f?f.removeChild(l.rowEl):l.rowEl.remove()}else if(l.rowInlineAttrPrevValue!==void 0){let f=l.rowInlineAttrPrevValue;f===null?l.rowEl.removeAttribute("swish-placement-inline-row"):l.rowEl.setAttribute("swish-placement-inline-row",f)}}r.delete(p)}},"unmountElement");return{mount:s,unmount:i(()=>{t&&(t.disconnect(),t=null),r.forEach((p,l)=>u(l)),r.clear()},"unmount")}}i(hn,"createPlacement");var Kr=i((n,{mountEl:e,targetEl:t,cleanup:r})=>{let s=n.state.itemContext(t),o=n.state.effect(()=>{let{loading:a,productId:u,variantId:c}=s.value;a||(e.setAttribute("product-id",u??""),e.setAttribute("variant-id",c??""))});r(()=>o?.())},"saveButtonMount");function Xr(n){let e=Yr(n.id),t=is(n),r=document.getElementById(e);if(r){r.textContent=t;return}let s=document.createElement("style");s.id=e,s.setAttribute("swish-placement-style",n.id),s.textContent=t,document.head.appendChild(s)}i(Xr,"ensurePlacementStylesheet");function Yr(n){return`swish-placement-style-${Jr(n)}`}i(Yr,"getPlacementStyleId");function Jr(n){return n.replace(/[^a-zA-Z0-9\-_]/g,"_")}i(Jr,"cssEscapeId");function dn(n){return`--swish-placement-${Zr(String(n))}`}i(dn,"designKeyToCSSVar");function Zr(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}i(Zr,"toKebabCase");function es(n){return Object.entries(n??{sm:500,lg:700}).map(([r,s])=>({name:r,minWidth:s})).sort((r,s)=>r.minWidth-s.minWidth)}i(es,"getBreakpoints");function mn(n,e){if(n==null)return{};if(typeof n=="object"&&!Array.isArray(n)){if(e&&e.size){let t=Object.keys(n);return"base"in n||t.some(s=>e.has(s))?n:{base:n}}return n}return{base:n}}i(mn,"normalizeResponsiveValue");var ts=new Set(["fontWeight","lineHeight","pressedScale","backgroundAlpha","pressedOpacity","pressedScale"]);function fn(n,e){if(e!=null)return typeof e=="number"&&!ts.has(n)?`${e}px`:String(e)}i(fn,"formatDesignValue");function ns(n,e,t){if(!e)return"";let r=new Set(t.map(c=>c.name)),s=[],o={},a=Object.entries(e).map(([c,p])=>[c,p]);for(let[c,p]of a){let l=mn(p,r),f=fn(String(c),l.base);f!==void 0&&s.push(`${dn(c)}:${f};`);for(let y of t){let h=l[y.name],x=fn(String(c),h);x!==void 0&&(o[y.name]||(o[y.name]=[]),o[y.name].push(`${dn(c)}:${x};`))}}let u=[];s.length&&u.push(`[swish-placement-element="${n}"]{${s.join("")}}`);for(let c of t){let p=o[c.name];p?.length&&u.push(`@media(min-width:${c.minWidth}px){[swish-placement-element="${n}"]{${p.join("")}}}`)}return u.join("")}i(ns,"emitDesignCSS");function Ee(n){return n==null?"0px":typeof n=="number"?`${n}px`:n}i(Ee,"formatOffsetValue");function rs(n){return n==null?"":typeof n=="number"?`${n}`:n}i(rs,"formatZIndexValue");function ss(n,e,t){let r=new Set(t.map(p=>p.name)),s=mn(e,r),o=s.base??{},a=Ee(o.x),u=Ee(o.y),c=[];c.push(`[swish-placement-overlay="${n}"]{--swish-placement-offset-x:${a};--swish-placement-offset-y:${u};}`);for(let p of t){let l=s[p.name];if(!l)continue;let f=Ee(l.x),y=Ee(l.y);c.push(`@media(min-width:${p.minWidth}px){[swish-placement-overlay="${n}"]{--swish-placement-offset-x:${f};--swish-placement-offset-y:${y};}}`)}return c.join("")}i(ss,"emitOverlayOffsetCSS");function is(n){let e=n.id,t=es(n.breakpoints),r=`[swish-placement-inline-row="${e}"]{display:flex;flex-direction:row;align-items:center;gap:var(--swish-placement-inline-gap,8px);width:100%}[swish-placement-inline-row="${e}"]>*:not([swish-placement-element="${e}"]){flex:1;min-width:0}`,s=`[swish-placement-overlay="${e}"]{position:absolute;z-index:var(--swish-placement-overlay-z,10);transform:translate(calc(var(--swish-placement-sign-x,1)*var(--swish-placement-offset-x,0px)),calc(var(--swish-placement-sign-y,1)*var(--swish-placement-offset-y,0px)));}[swish-placement-overlay="${e}"][swish-placement-anchor="top-left"]{top:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="top-right"]{top:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-left"]{bottom:0;left:0;}[swish-placement-overlay="${e}"][swish-placement-anchor="bottom-right"]{bottom:0;right:0;}[swish-placement-overlay="${e}"][swish-placement-anchor$="left"]{--swish-placement-sign-x:1;}[swish-placement-overlay="${e}"][swish-placement-anchor$="right"]{--swish-placement-sign-x:-1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="top"]{--swish-placement-sign-y:1;}[swish-placement-overlay="${e}"][swish-placement-anchor^="bottom"]{--swish-placement-sign-y:-1;}`,o="";if(n.layout?.type==="overlay"){let a=ss(e,n.layout.offset,t),u=n.layout.zIndex?`[swish-placement-overlay="${e}"]{--swish-placement-overlay-z:${rs(n.layout.zIndex)};}`:"";o+=a+u+s}else n.layout?.type==="inline"&&(o+=r);if(n.design){let a=ns(e,n.design,t);a&&(o+=a)}return n.css&&(o+=n.css.trim()),o}i(is,"buildPlacementCSS");function os(n,e){if(!e||e==="target")return n;if("closest"in e)return n.closest(e.closest);if("query"in e)return n.querySelector(e.query);if("withinClosest"in e){let t=n.closest(e.withinClosest.root);return t?t.querySelector(e.withinClosest.selector):null}return n}i(os,"resolveMountTarget");function as(n,e,t){switch(t){case"before":return n.parentElement?(n.before(e),!0):!1;case"after":{let r=n.parentElement;return r?(r.insertBefore(e,n.nextSibling),!0):!1}case"append":return n.appendChild(e),!0;case"prepend":return n.insertBefore(e,n.firstChild),!0;case"replace":return n.parentElement?(n.replaceWith(e),!0):!1}}i(as,"insertIntoDOM");function us(n){let e=n.parentElement;return e?(window.getComputedStyle(e).position==="static"&&(e.style.position="relative"),e):null}i(us,"ensureRelativeParent");function cs(n,e,t){if(!e.parentElement)throw new Error("Cannot inline-wrap: refEl has no parentElement");let s=document.createElement("div");return s.setAttribute("swish-placement-inline-row",n),e.before(s),s.appendChild(e),s}i(cs,"wrapWithFlexRow");function ls(n,e){let t=e.tag||"div",r=document.createElement(t);return r.setAttribute("swish-placement-container",n),e.classNames&&yn(r,e.classNames),r}i(ls,"createContainer");function ps(n,e){return n.ui.createElement(e.name,{})}i(ps,"createElement");function ds(n,e){for(let[t,r]of Object.entries(e)){let s=t.replace(/([A-Z])/g,"-$1").toLowerCase();r===!1||r===void 0||r===null||(r===!0?n.setAttribute(s,"true"):n.setAttribute(s,String(r)))}}i(ds,"applyProps");function yn(n,e){n.classList.add(...e)}i(yn,"applyClassNames");var xe=class{constructor(){this.eventBus=new EventTarget}static{i(this,"EventBus")}subscribe(e,t,r){return Array.isArray(e)||(e=[e]),e.forEach(s=>{this.eventBus.addEventListener(s,t,r)}),()=>{e.forEach(s=>{this.eventBus.removeEventListener(s,t,r)})}}unsubscribe(e,t,r){this.eventBus.removeEventListener(e,t,r)}publish(e,t){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:t}))}};var St;function gn(n){return{lang:n?.lang??St?.lang,message:n?.message,abortEarly:n?.abortEarly??St?.abortEarly,abortPipeEarly:n?.abortPipeEarly??St?.abortPipeEarly}}i(gn,"getGlobalConfig");var fs;function hs(n){return fs?.get(n)}i(hs,"getGlobalMessage");var ms;function ys(n){return ms?.get(n)}i(ys,"getSchemaMessage");var vs;function gs(n,e){return vs?.get(n)?.get(e)}i(gs,"getSpecificMessage");function ke(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}i(ke,"_stringify");function K(n,e,t,r,s){let o=s&&"input"in s?s.input:t.value,a=s?.expected??n.expects??null,u=s?.received??ke(o),c={kind:n.kind,type:n.type,input:o,expected:a,received:u,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${u}`,requirement:n.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},p=n.kind==="schema",l=s?.message??n.message??gs(n.reference,c.lang)??(p?ys(c.lang):null)??r.message??hs(c.lang);l!==void 0&&(c.message=typeof l=="function"?l(c):l),p&&(t.typed=!1),t.issues?t.issues.push(c):t.issues=[c]}i(K,"_addIssue");function Z(n){return{version:1,vendor:"valibot",validate(e){return n["~run"]({value:e},gn())}}}i(Z,"_getStandardProps");function wn(n,e){let t=[...new Set(n)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}i(wn,"_joinExpects");function he(n,e){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${n}`,requirement:n,message:e,"~run"(t,r){return t.typed&&t.value.length<this.requirement&&K(this,"length",t,r,{received:`${t.value.length}`}),t}}}i(he,"minLength");function X(n,e){return{kind:"validation",type:"min_value",reference:X,async:!1,expects:`>=${n instanceof Date?n.toJSON():ke(n)}`,requirement:n,message:e,"~run"(t,r){return t.typed&&!(t.value>=this.requirement)&&K(this,"value",t,r,{received:t.value instanceof Date?t.value.toJSON():ke(t.value)}),t}}}i(X,"minValue");function T(n){return{kind:"transformation",type:"transform",reference:T,async:!1,operation:n,"~run"(e){return e.value=this.operation(e.value),e}}}i(T,"transform");function ws(n,e,t){return typeof n.fallback=="function"?n.fallback(e,t):n.fallback}i(ws,"getFallback");function In(n,e,t){return typeof n.default=="function"?n.default(e,t):n.default}i(In,"getDefault");function oe(n,e){return{kind:"schema",type:"array",reference:oe,expects:"Array",async:!1,item:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s=t.value;if(Array.isArray(s)){t.typed=!0,t.value=[];for(let o=0;o<s.length;o++){let a=s[o],u=this.item["~run"]({value:a},r);if(u.issues){let c={type:"array",origin:"value",input:s,key:o,value:a};for(let p of u.issues)p.path?p.path.unshift(c):p.path=[c],t.issues?.push(p);if(t.issues||(t.issues=u.issues),r.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value.push(u.value)}}else K(this,"type",t,r);return t}}}i(oe,"array");function Et(n){return{kind:"schema",type:"boolean",reference:Et,expects:"boolean",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="boolean"?e.typed=!0:K(this,"type",e,t),e}}}i(Et,"boolean");function E(n){return{kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:K(this,"type",e,t),e}}}i(E,"number");function g(n,e){return{kind:"schema",type:"object",reference:g,expects:"Object",async:!1,entries:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s=t.value;if(s&&typeof s=="object"){t.typed=!0,t.value={};for(let o in this.entries){let a=this.entries[o];if(o in s||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let u=o in s?s[o]:In(a),c=a["~run"]({value:u},r);if(c.issues){let p={type:"object",origin:"value",input:s,key:o,value:u};for(let l of c.issues)l.path?l.path.unshift(p):l.path=[p],t.issues?.push(l);if(t.issues||(t.issues=c.issues),r.abortEarly){t.typed=!1;break}}c.typed||(t.typed=!1),t.value[o]=c.value}else if(a.fallback!==void 0)t.value[o]=ws(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(K(this,"key",t,r,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:s,key:o,value:s[o]}]}),r.abortEarly))break}}else K(this,"type",t,r);return t}}}i(g,"object");function P(n,e){return{kind:"schema",type:"optional",reference:P,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:e,get"~standard"(){return Z(this)},"~run"(t,r){return t.value===void 0&&(this.default!==void 0&&(t.value=In(this,t,r)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,r)}}}i(P,"optional");function me(n,e){return{kind:"schema",type:"picklist",reference:me,expects:wn(n.map(ke),"|"),async:!1,options:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){return this.options.includes(t.value)?t.typed=!0:K(this,"type",t,r),t}}}i(me,"picklist");function v(n){return{kind:"schema",type:"string",reference:v,expects:"string",async:!1,message:n,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:K(this,"type",e,t),e}}}i(v,"string");function vn(n){let e;if(n)for(let t of n)e?e.push(...t.issues):e=t.issues;return e}i(vn,"_subIssues");function $(n,e){return{kind:"schema",type:"union",reference:$,expects:wn(n.map(t=>t.expects),"|"),async:!1,options:n,message:e,get"~standard"(){return Z(this)},"~run"(t,r){let s,o,a;for(let u of this.options){let c=u["~run"]({value:t.value},r);if(c.typed)if(c.issues)o?o.push(c):o=[c];else{s=c;break}else a?a.push(c):a=[c]}if(s)return s;if(o){if(o.length===1)return o[0];K(this,"type",t,r,{issues:vn(o)}),t.typed=!0}else{if(a?.length===1)return a[0];K(this,"type",t,r,{issues:vn(a)})}return t}}}i($,"union");function b(...n){return{...n[0],pipe:n,get"~standard"(){return Z(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}}}i(b,"pipe");function S(n,e,t){let r=n["~run"]({value:e},gn(t));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}i(S,"safeParse");var de=b($([b(v(),T(A)),E()]),T(n=>Number(n)),b(E(),X(1)));var m=class{constructor(e,t,r,s){this.swish=e;this.ui=t;this.eventBus=r;this.options=s}static{i(this,"IntentHandler")}};var Is=$([g({variantId:de,quantity:P(b(E(),X(1)),1)}),g({items:b(oe(g({variantId:de,quantity:P(b(E(),X(1)),1)})),he(1))})]),Ce=class extends m{static{i(this,"CreateCartLineHandler")}async invoke(e){let t=S(Is,e);if(!t.success)return{intent:"create:cart-line",code:"error",message:"Invalid intent data",issues:t.issues.map(s=>s.message)};let r=t.output;try{let s="items"in r?r.items.map(a=>({id:a.variantId,quantity:a.quantity})):[{id:r.variantId,quantity:r.quantity}];return{intent:"create:cart-line",code:"ok",data:await this.swish.ajax.addToCart({items:s})}}catch(s){let o=[],a="Failed to add item to cart";return s instanceof Error?(s.message&&(a=s.message,o.push(s.message)),s.stack&&o.push(s.stack)):typeof s=="string"&&s.trim()?(a=s,o.push(s)):s!=null&&o.push(String(s)),{intent:"create:cart-line",code:"error",message:a,issues:o.length?o:["Cart request failed"]}}}};var bs=g({variantId:de,quantity:P(b(E(),X(1)),1)}),Ss=150,Es=$([g({variantId:de,quantity:P(b(E(),X(1)),1)}),g({items:b(oe(bs),he(1))})]),Re=class extends m{static{i(this,"InitiateCheckoutHandler")}async invoke(e){let t=S(Es,e);if(!t.success)return{intent:"initiate:checkout",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let r=t.output,o=("items"in r?r.items:[{variantId:r.variantId,quantity:r.quantity}]).map(u=>`${u.variantId}:${u.quantity}`).join(","),a=new URL(`/cart/${o}`,this.swish.shopUrl);return a.searchParams.set("checkout","1"),typeof window<"u"&&window.setTimeout(()=>window.location.assign(a.href),Ss),{intent:"initiate:checkout",code:"ok",data:{checkoutUrl:a.href}}}};var Ae=class extends m{static{i(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 xs=g({listId:v()}),De=class extends m{static{i(this,"DeleteListHandler")}async invoke(e){let t=S(xs,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 ks=g({itemId:v()}),Pe=class extends m{static{i(this,"EditItemListsHandler")}async invoke(e){let t=S(ks,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,s=await this.ui.showListSelect({itemId:r});if(s.code==="closed")return{intent:"edit:item-lists",code:"closed"};if(s.data.action==="submit"){let{item:o,product:a,variant:u}=s.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:o,product:a,variant:u}}}return{intent:"unsave:item",code:"ok",data:{itemId:s.data.data.itemId}}}};var Cs=g({itemId:b(v()),productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()))}),Te=class extends m{static{i(this,"EditItemVariantHandler")}async invoke(e){let t=S(Cs,e);if(!t.success)return{intent:"edit:item-variant",code:"error",message:"Invalid intent data",issues:t.issues.map(y=>y.message)};let{itemId:r,productId:s,variantId:o}=t.output;if(!(!o||this.swish.options.intents.editSavedProduct.promptVariantChange)){let y=await this.swish.api.items.updateById(r,{productId:s,variantId:o});if("error"in y)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:[y.error.message]};if(!y.data)return{intent:"edit:item-variant",code:"error",message:"Failed to update variant",issues:["No item returned from API"]};let h=await this.swish.storefront.loadSaveIntentData({productId:D("Product",s),variantId:o?D("ProductVariant",o):void 0});if(!h.data?.product)return{intent:"edit:item-variant",code:"error",message:"Failed to load save intent data",issues:[h.errors?.message??"No product data returned from API"]};let x=h.data?.product,w="variant"in h.data?h.data.variant:void 0;return{intent:"edit:item-variant",code:"ok",data:{item:y.data,product:x,variant:w}}}let u=await this.ui.showVariantSelect({itemId:r,productId:s,variantId:o});if(u.code==="closed")return{intent:"edit:item-variant",code:"closed"};let{item:c,product:p,variant:l}=u.data;return{intent:"edit:item-variant",code:"ok",data:{item:c,product:p,variant:l}}}};var Rs=g({listId:v(),access:me(["public","private"])}),_e=class extends m{static{i(this,"EditListAccessHandler")}async invoke(e){let t=S(Rs,e);if(!t.success)return{intent:"edit:list-access",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r,access:s}=t.output;if((await this.ui.showConfirmDialog({titleKey:s==="public"?"listMenu.public.title":"listMenu.private.title",descriptionKey:s==="public"?"listMenu.public.description":"listMenu.private.description",confirmLabelKey:s==="public"?"listMenu.public.text":"listMenu.private.text",cancelLabelKey:"listMenu.cancel",danger:!1})).code==="closed")return{intent:"edit:list-access",code:"closed"};let a=await this.swish.api.lists.updateById(r,{access:s});return"error"in a?{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:[a.error.message]}:a.data?{intent:"edit:list-access",code:"ok",data:{list:a.data}}:{intent:"edit:list-access",code:"error",message:"Failed to update list access",issues:["API response missing data"]}}};var As=g({listId:v()}),Oe=class extends m{static{i(this,"EditListHandler")}async invoke(e){let t=S(As,e);if(!t.success)return{intent:"edit:list",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{listId:r}=t.output,s=await this.ui.showListEditor({listId:r});if(s.code==="closed")return{intent:"edit:list",code:"closed"};let{list:o}=s.data;return{intent:"edit:list",code:"ok",data:{list:o}}}};var Ds=150,Ps=g({returnTo:v()}),Le=class extends m{static{i(this,"InitiateSignInHandler")}async invoke(e){let t=S(Ps,e);if(!t.success)return{intent:"initiate:sign-in",code:"error",message:"Invalid intent data",issues:t.issues.map(o=>o.message)};let r=t.output.returnTo;return(await this.ui.showConfirmDialog({titleKey:"signIn.title",descriptionKey:"signIn.description",confirmLabelKey:"signIn.continue",danger:!1})).code==="closed"?{intent:"initiate:sign-in",code:"closed"}:(this.scheduleRedirect(r),{intent:"initiate:sign-in",code:"ok",data:void 0})}scheduleRedirect(e){window.setTimeout(()=>this.redirectToSignIn(e),Ds)}redirectToSignIn(e){let t=this.swish.storefrontContext.routes.accountUrl,r=new URL(t,window.location.origin);r.searchParams.set("return_url",e),window.location.assign(r.toString())}};var $e=class extends m{static{i(this,"OpenHomeHandler")}async invoke(e){return{intent:"open:home",code:(await this.ui.showDrawer()).code,data:void 0}}};var Ts=g({listId:v()}),Me=class extends m{static{i(this,"OpenListDetailPageMenuHandler")}async invoke(e){let t=S(Ts,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 _s=g({listId:v()}),qe=class extends m{static{i(this,"OpenListHandler")}async invoke(e){let t=S(_s,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 Os=g({listId:v()}),Ve=class extends m{static{i(this,"OpenListMenuHandler")}async invoke(e){let t=S(Os,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,s=await this.ui.showListMenu({listId:r});if(s.code==="closed")return{intent:"open:list-menu",code:"closed"};if(s.data.action==="edit")return{intent:"edit:list",code:"ok",data:s.data.data};if(s.data.action==="delete")return{intent:"delete:list",code:"ok",data:{listId:r}};if(s.data.action==="edit-access"){let o=s.data.data?.currentListAccess,a=o==="public"?"private":o==="private"?"public":void 0;return a?(await this.swish.intents.invoke("edit:list-access",{listId:r,access:a})).complete:{intent:"open:list-menu",code:"error",message:"Missing list access from UI",issues:["List menu UI did not provide currentListAccess"]}}return s.data.action==="share"?(await this.swish.intents.invoke("initiate:share",{listId:r})).complete:{intent:"open:list-menu",code:"error",message:"Unknown list menu action",issues:["Unknown action returned from list menu UI"]}}};var Ne=class extends m{static{i(this,"OpenListsHandler")}async invoke(e){return{intent:"open:lists",code:(await this.ui.showDrawer({view:"lists"})).code,data:void 0}}};var Ue=class extends m{static{i(this,"OpenNotificationsHandler")}async invoke(e){return{intent:"open:notifications",code:(await this.ui.showDrawer({view:"notifications"})).code,data:void 0}}};var Ls=g({orderId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E())}),Be=class extends m{static{i(this,"OpenOrderHandler")}async invoke(e){let t=S(Ls,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 $s=g({orderId:v()}),Fe=class extends m{static{i(this,"OpenOrderMenuHandler")}async invoke(e){let t=S($s,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 je=class extends m{static{i(this,"OpenOrdersHandler")}async invoke(e){return{intent:"open:orders",code:(await this.ui.showDrawer({view:"orders"})).code,data:void 0}}};var Ms=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E()))}),He=class extends m{static{i(this,"OpenProductHandler")}async invoke(e){let t=S(Ms,e);if(!t.success)return{intent:"open:product",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{productId:r,variantId:s}=t.output;return{intent:"open:product",code:(await this.ui.showDrawer({view:"product",productId:r.toString(),variantId:s?.toString()})).code,data:void 0}}};var Ge=class extends m{static{i(this,"OpenProfileHandler")}async invoke(e){return{intent:"open:profile",code:(await this.ui.showDrawer({view:"profile"})).code,data:void 0}}};var qs=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E()))}),Qe=class extends m{static{i(this,"OpenQuickBuyHandler")}async invoke(e){let t=S(qs,e);if(!t.success)return{intent:"open:quick-buy",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{productId:r,variantId:s}=t.output,o=await this.ui.showQuickBuy({productId:r,variantId:s});return o.code==="closed"?{intent:"open:quick-buy",code:"closed"}:{intent:"open:quick-buy",code:"ok",data:o.data}}};var ze=class extends m{static{i(this,"OpenSavesHandler")}async invoke(e){return{intent:"open:saves",code:(await this.ui.showDrawer({view:"saves"})).code,data:void 0}}};var su=g({returnTo:P(v())}),We=class extends m{static{i(this,"OpenSignInHandler")}async invoke(e){return{intent:"open:sign-in",code:(await this.ui.showSignIn({returnTo:e?.returnTo})).code,data:void 0}}};var Vs=g({productId:b($([b(v(),T(A)),E()]),T(n=>Number(n)),E()),variantId:P(b($([b(v(),T(A)),E()]),T(Number),E())),quantity:P(b(E(),X(1))),tags:P(oe(v()))}),Ke=class extends m{static{i(this,"SaveItemHandler")}async invoke(e){let t=S(Vs,e);if(!t.success)return{intent:"save:item",code:"error",message:"Invalid intent data",issues:t.issues.map(h=>h.message)};let{productId:r,variantId:s,quantity:o,tags:a}=t.output,u=await this.swish.storefront.loadSaveIntentData({productId:D("Product",r),variantId:s?D("ProductVariant",s):void 0});if(u.errors)return{intent:"save:item",code:"error",message:u.errors.message??"Failed to load save intent data",issues:u.errors.graphQLErrors?.map(h=>h.message)??[]};if(!u.data||!u.data.product)return{intent:"save:item",code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=u.data,p=c.variantsCount?.count&&c.variantsCount.count>1,l=!!s,f=!this.options.saveProduct.promptVariantIfMissing||!this.options.saveProduct.promptVariantIfPresent&&l;if(!p||f){let h=i(()=>!p&&c.selectedOrFirstAvailableVariant?Number(A(c.selectedOrFirstAvailableVariant.id)):s,"variantIdToUse"),x=await this.swish.api.items.create({productId:r,variantId:h(),quantity:o,tags:a});if("error"in x)return{intent:"save:item",code:"error",message:"Failed to create item",issues:[x.error.message]};if(!x.data)return{intent:"save:item",code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let w="variant"in u.data?u.data.variant:void 0;return{intent:"save:item",code:"ok",data:{item:x.data,product:c,variant:p?w:c.selectedOrFirstAvailableVariant}}}let y=await this.ui.showVariantSelect({productId:r,variantId:s});return y.code==="closed"?{intent:"save:item",code:"closed"}:{intent:"save:item",code:"ok",data:y.data}}};function ye(n,e){let{storeDomain:t}=n.options.storefrontApi,{rootUrl:r,listDetailPagePath:s}=n.options.storefrontContext.routes,o=new URL(`https://${t}`),a=new URL(`${r==="/"?"":r}${s}`,o);return a.searchParams.set("public-list-id",e.publicListId),a}i(ye,"buildShareListUrl");async function ve(n){return typeof navigator?.clipboard?.writeText!="function"?{ok:!1,issues:["Clipboard API not available"]}:navigator.clipboard.writeText(n).then(()=>({ok:!0})).catch(e=>({ok:!1,issues:[e?.message??"Failed to copy to clipboard"]}))}i(ve,"copyToClipboard");function bn(){let n=navigator.userAgent.includes("Mac OS")&&navigator.maxTouchPoints>1;return/Android|Mobile/i.test(navigator.userAgent)||n}i(bn,"isMobileDevice");var Ns=g({listId:v()}),Xe=class extends m{static{i(this,"ShareListHandler")}async invoke(e){let t=S(Ns,e);if(!t.success)return{intent:"initiate:share",code:"error",message:"Invalid intent data",issues:t.issues.map(u=>u.message)};let{listId:r}=t.output,s=ye(this.swish,{publicListId:r}).toString();if(bn()&&typeof navigator.share=="function"&&(await navigator.share({title:"Share list",url:s}).then(()=>({ok:!0})).catch(()=>({ok:!1}))).ok)return{intent:"initiate:share",code:"ok",data:{listId:r,url:s,method:"native"}};let a=await ve(s);return a.ok?{intent:"initiate:share",code:"ok",data:{listId:r,url:s,method:"clipboard"}}:{intent:"initiate:share",code:"error",message:"Failed to share list",issues:a.issues}}};var xu=g({title:P(v()),text:v(),image:P(v()),action:P(g({label:v(),url:P(v())})),variant:P(me(["compact","full"])),icon:P(v())}),Ye=class extends m{static{i(this,"ShowToastHandler")}async invoke(e){return{intent:"show:toast",code:(await this.ui.showToast(e)).code,data:void 0}}};var Us=g({itemId:v(),delete:P(Et())}),Je=class extends m{static{i(this,"UnsaveItemHandler")}async invoke(e){let t=S(Us,e);if(!t.success)return{intent:"unsave:item",code:"error",message:"Invalid intent data",issues:t.issues.map(a=>a.message)};let{itemId:r,delete:s}=t.output;if(this.options.unsaveProduct.selectList&&!s){let a=await this.ui.showListSelect({itemId:r});if(a.code==="closed")return{intent:"unsave:item",code:"closed"};if(a.data.action==="submit"){let{item:u,product:c,variant:p}=a.data.data;return{intent:"edit:item-lists",code:"ok",data:{item:u,product:c,variant:p}}}if(a.data.action==="unsave"){let{itemId:u}=a.data.data;return{intent:"unsave:item",code:"ok",data:{itemId:u}}}}if(!this.options.unsaveProduct.confirm){let a=await this.swish.api.items.deleteById(r);return"error"in a?{intent:"unsave:item",code:"error",message:"Failed to delete item",issues:[a.error.message]}:{intent:"unsave:item",code:"ok",data:{itemId:r}}}return(await this.ui.showUnsaveAlert({itemId:r})).code==="closed"?{intent:"unsave:item",code:"closed"}:{intent:"unsave:item",code:"ok",data:{itemId:r}}}};var z=class{constructor(e,t,r){this.swish=e;this.ui=t;this.options=r}static{i(this,"IntentHook")}};var Ze=class extends z{static{i(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.editSavedProduct.showFeedback&&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 et=class extends z{static{i(this,"AfterEditListAccessHook")}async invoke(e){if(e.code!=="ok")return;let t=e.data.list.access==="public"?"List is now public":"List is now private";await(await this.swish.intents.invoke("show:toast",{text:t,variant:"compact",icon:"check"})).complete}};var tt=class extends z{static{i(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 nt=class extends z{static{i(this,"AfterSaveItemHook")}async invoke(e){if(this.options.saveProduct.showFeedback&&e.code==="ok"){let{item:t,product:r,variant:s}=e.data;r&&(await(await this.swish.intents.invoke("show:toast",{title:"Saved",text:r.title,image:s?.image?.url??r.featuredImage?.url,action:{label:"Add to List"}})).complete).code==="ok"&&this.swish.intents.invoke("edit:item-lists",{itemId:t.id})}}};var rt=class extends z{static{i(this,"AfterShareListHook")}async invoke(e){if(e.code!=="ok")return;await(await this.swish.intents.invoke("show:toast",{variant:"compact",text:"Link shared",icon:"check"})).complete}};var st=class{static{i(this,"Intents")}constructor(e,t){this.swish=e,this.ui=t,this.eventBus=new EventTarget,this.options=e.options.intents,this.handlers={"create:cart-line":new Ce(this.swish,this.ui,this.eventBus,this.options),"initiate:checkout":new Re(this.swish,this.ui,this.eventBus,this.options),"save:item":new Ke(this.swish,this.ui,this.eventBus,this.options),"unsave:item":new Je(this.swish,this.ui,this.eventBus,this.options),"edit:item-variant":new Te(this.swish,this.ui,this.eventBus,this.options),"edit:item-lists":new Pe(this.swish,this.ui,this.eventBus,this.options),"create:list":new Ae(this.swish,this.ui,this.eventBus,this.options),"edit:list":new Oe(this.swish,this.ui,this.eventBus,this.options),"edit:list-access":new _e(this.swish,this.ui,this.eventBus,this.options),"delete:list":new De(this.swish,this.ui,this.eventBus,this.options),"open:home":new $e(this.swish,this.ui,this.eventBus,this.options),"initiate:share":new Xe(this.swish,this.ui,this.eventBus,this.options),"open:list":new qe(this.swish,this.ui,this.eventBus,this.options),"open:lists":new Ne(this.swish,this.ui,this.eventBus,this.options),"open:orders":new je(this.swish,this.ui,this.eventBus,this.options),"open:order":new Be(this.swish,this.ui,this.eventBus,this.options),"open:saves":new ze(this.swish,this.ui,this.eventBus,this.options),"open:notifications":new Ue(this.swish,this.ui,this.eventBus,this.options),"open:profile":new Ge(this.swish,this.ui,this.eventBus,this.options),"open:product":new He(this.swish,this.ui,this.eventBus,this.options),"open:list-menu":new Ve(this.swish,this.ui,this.eventBus,this.options),"open:order-menu":new Fe(this.swish,this.ui,this.eventBus,this.options),"open:list-detail-page-menu":new Me(this.swish,this.ui,this.eventBus,this.options),"initiate:sign-in":new Le(this.swish,this.ui,this.eventBus,this.options),"open:sign-in":new We(this.swish,this.ui,this.eventBus,this.options),"open:quick-buy":new Qe(this.swish,this.ui,this.eventBus,this.options),"show:toast":new Ye(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],s={lifecycle:"before",intent:e,data:r};return this.publishAnalyticsEvent("swish-intent",s),this.publishAnalyticsEvent(`swish-intent=${e}`,s),{intent:e,data:r,complete:this.handleIntent(e,r).then(o=>{let a={lifecycle:"after",intent:e,data:r,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${e}`,a),this.eventBus.dispatchEvent(new CustomEvent(e,{detail:o})),o})}}listen(e,t){let r=i(o=>{"detail"in o&&o.detail?t(o.detail):console.warn("Intent response event without detail",o)},"eventListener"),s=i(()=>{this.eventBus.removeEventListener(e,r)},"unsubscribe");return this.eventBus.addEventListener(e,r),s}parseIntentFromString(e){if(typeof e=="string"){let[t,...r]=e.split(","),s=r.reduce((o,a)=>{let[u,c]=a.split("=");return o[u]=c,o},{});return{intent:t,data:s}}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 nt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:item-lists",e=>{new Ze(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("open:home",e=>{new tt(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:list-access",e=>{new et(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("initiate:share",e=>{new rt(this.swish,this.ui,this.options).invoke(e.detail)})}initIntentWatcher(){ie({selector:"[swish-intent]",onElementFound:i(e=>{let t=e.getAttribute("swish-intent");t&&e.addEventListener("click",()=>{let{intent:r,data:s}=this.parseIntentFromString(t);Object.keys(s).length>0?this.invoke(r,s):this.invoke(r)})},"onElementFound")}),ie({selector:"a[href*='swish-intent='],a[href*='#swish']",onElementFound:i(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",t=>{if(!t.metaKey&&!t.ctrlKey&&!t.shiftKey&&!t.altKey){let r=new URL(e.href),s=r.hash,o=r.searchParams.get("swish-intent");if(o){let{intent:a,data:u}=this.parseIntentFromString(o);a&&(t.preventDefault(),t.stopPropagation(),Object.keys(u).length>0?this.invoke(a,u):this.invoke(a))}else if(s){let a=this.parseIntentFromHash(s);a&&(t.preventDefault(),t.stopPropagation(),this.invoke(a))}}})},"onElementFound")}),pe({fireOnInit:!0,onLocationChange:i(e=>{let t=new URL(e.href),r=t.hash,s=t.searchParams.get("swish-intent");if(s){let{intent:o,data:a}=this.parseIntentFromString(s);o&&(Object.keys(a).length>0?this.invoke(o,a):this.invoke(o))}else if(r){let o=this.parseIntentFromHash(r);o&&this.invoke(o)}},"onLocationChange")})}};var Sn=i(n=>({swishApi:{authProxy:n.swishApi?.authProxy??"/apps/wishlist/api",version:n.swishApi?.version??"2026-01"},storefrontApi:{storeDomain:n.storefrontApi?.storeDomain??"",accessToken:n.storefrontApi?.accessToken??""},storefrontContext:{...n.storefrontContext,routes:{...n.storefrontContext.routes,rootUrl:n.storefrontContext.routes?.rootUrl??"/",listDetailPagePath:n.storefrontContext.routes?.listDetailPagePath??"/apps/wishlist"},localization:{country:n.storefrontContext.localization.country.toUpperCase(),language:n.storefrontContext.localization.language.toUpperCase(),market:n.storefrontContext.localization.market}},productOptions:{sortValues:n.productOptions?.sortValues??(({option:e,optionValues:t})=>t)},metafields:{product:n.metafields?.product??[],productVariant:n.metafields?.productVariant??[]},features:{accounts:n?.features?.accounts??!0,lists:n?.features?.lists??!0,orders:n?.features?.orders??!0,notifications:n?.features?.notifications??!0},intents:{saveProduct:{promptVariantIfMissing:n?.intents?.saveProduct?.promptVariantIfMissing??!0,promptVariantIfPresent:n?.intents?.saveProduct?.promptVariantIfPresent??!0,showFeedback:n?.intents?.saveProduct?.showFeedback??!0},unsaveProduct:{selectList:n?.intents?.unsaveProduct?.selectList??!0,confirm:n?.intents?.unsaveProduct?.confirm??!0,showFeedback:n?.intents?.unsaveProduct?.showFeedback??!0},editSavedProduct:{promptVariantChange:n?.intents?.editSavedProduct?.promptVariantChange??!0,showFeedback:n?.intents?.editSavedProduct?.showFeedback??!0}},swishUi:{baseUrl:n.swishUi?.baseUrl??"https://swish.app/cdn",version:n.swishUi?.version??it,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:{enabled:n.swishUi?.components?.drawer?.navigation?.enabled??!0,variant:n.swishUi?.components?.drawer?.navigation?.variant??"floating",items:n.swishUi?.components?.drawer?.navigation?.items??[]},emptyCallout:{enabled:n.swishUi?.components?.drawer?.emptyCallout?.enabled??!1,shoppingCalloutUrl:n.swishUi?.components?.drawer?.emptyCallout?.shoppingCalloutUrl??"/collections/all"},miniMenu:{enabled:n.swishUi?.components?.drawer?.miniMenu?.enabled??!0,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??[],design:n.swishUi?.design??{}}}),"createSwishOptions");var Bs=Symbol.for("preact-signals");function at(){if(ne>1)ne--;else{for(var n,e=!1;ge!==void 0;){var t=ge;for(ge=void 0,xt++;t!==void 0;){var r=t.o;if(t.o=void 0,t.f&=-3,!(8&t.f)&&kn(t))try{t.c()}catch(s){e||(n=s,e=!0)}t=r}}if(xt=0,ne--,e)throw n}}i(at,"t");function re(n){if(ne>0)return n();ne++;try{return n()}finally{at()}}i(re,"r");var k=void 0;function En(n){var e=k;k=void 0;try{return n()}finally{k=e}}i(En,"n");var ge=void 0,ne=0,xt=0,ot=0;function xn(n){if(k!==void 0){var e=n.n;if(e===void 0||e.t!==k)return e={i:0,S:n,p:k.s,n:void 0,t:k,e:void 0,x:void 0,r:e},k.s!==void 0&&(k.s.n=e),k.s=e,n.n=e,32&k.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=k.s,e.n=void 0,k.s.n=e,k.s=e),e}}i(xn,"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}i(U,"u");U.prototype.brand=Bs;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:En(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&&En(function(){var s;(s=e.Z)==null||s.call(e)}))}};U.prototype.subscribe=function(n){var e=this;return Q(function(){var t=e.value,r=k;k=void 0;try{n(t)}finally{k=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=k;k=void 0;try{return this.value}finally{k=n}};Object.defineProperty(U.prototype,"value",{get:i(function(){var n=xn(this);return n!==void 0&&(n.i=this.i),this.v},"get"),set:i(function(n){if(n!==this.v){if(xt>100)throw new Error("Cycle detected");this.v=n,this.i++,ot++,ne++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{at()}}},"set")});function q(n,e){return new U(n,e)}i(q,"d");function kn(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}i(kn,"c");function Cn(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}}}i(Cn,"a");function Rn(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}i(Rn,"l");function ae(n,e){U.call(this,void 0),this.x=n,this.s=void 0,this.g=ot-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(ae,"y");ae.prototype=new U;ae.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ot))return!0;if(this.g=ot,this.f|=1,this.i>0&&!kn(this))return this.f&=-2,!0;var n=k;try{Cn(this),k=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 k=n,Rn(this),this.f&=-2,!0};ae.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)};ae.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)}};ae.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(ae.prototype,"value",{get:i(function(){if(1&this.f)throw new Error("Cycle detected");var n=xn(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 ae(n,e)}i(F,"w");function An(n){var e=n.u;if(n.u=void 0,typeof e=="function"){ne++;var t=k;k=void 0;try{e()}catch(r){throw n.f&=-2,n.f|=8,kt(n),r}finally{k=t,at()}}}i(An,"_");function kt(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)}i(kt,"b");function Fs(n){if(k!==this)throw new Error("Out-of-order effect");Rn(this),k=n,this.f&=-2,8&this.f&&kt(this),at()}i(Fs,"g");function fe(n,e){this.x=n,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}i(fe,"p");fe.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()}};fe.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,An(this),Cn(this),ne++;var n=k;return k=this,Fs.bind(this,n)};fe.prototype.N=function(){2&this.f||(this.f|=2,this.o=ge,ge=this)};fe.prototype.d=function(){this.f|=8,1&this.f||kt(this)};fe.prototype.dispose=function(){this.d()};function Q(n,e){var t=new fe(n,e);try{t.c()}catch(s){throw t.d(),s}var r=t.d.bind(t);return r[Symbol.dispose]=r,r}i(Q,"E");var js=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,Ct=i(n=>{let e=n.match(js);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),Dn=i(({source:n,onProductUrlChange:e})=>{let t=i(r=>{let s=Ct(r);s?.productHandle&&e(s)},"handleChange");if(n instanceof HTMLAnchorElement)return pn({element:n,onHrefChange:i(r=>t(r),"onHrefChange")});if(n instanceof Location)return pe({onLocationChange:i(r=>t(r.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Pn=i(n=>e=>{let{productHandle:t,productId:r,variantId:s,itemId:o}=e?.dataset??{},c=!!(r||t)||!!o,p=q({loading:!1,productId:r,variantId:s,itemId:o});if(!c){let l=e instanceof HTMLAnchorElement?e:window.location,f=Ct(l.href);f?.productHandle&&f.productHandle!==p.value.productHandle&&(p.value={...p.value,...f,productId:void 0},Dn({source:l,onProductUrlChange:i(y=>{p.value={...p.value,...y,productId:y.productHandle!==p.value.productHandle?void 0:p.value.productId}},"onProductUrlChange")}))}return Q(()=>{p.value.loading||!p.value.productId&&p.value.productHandle&&(p.value={...p.value,loading:!0},n.storefront.loadProductId({productHandle:p.value.productHandle}).then(l=>{l.errors&&console.error("Error loading product id",l.errors),p.value={...p.value,productId:l.data?.product?.id?A(l.data.product.id):void 0,loading:!1}}))}),p},"itemContextSignal");var Tn=i(n=>e=>{let t=F(()=>{let{productId:_,variantId:I,loading:V}=e.value;return!_||V?null:I?`variant:${A(I)}`:`product:${A(_)}`}),r=F(()=>e.value.loading||!!e.value.itemId||!e.value.productId),s=F(()=>({limit:1,query:t.value??void 0})),o=q(!r.value),a=q(null),u=q(!1),c=q(!1),{data:p,loading:l,error:f,refetching:y}=n.state.swishQuery(_=>n.api.items.list(_),{refetch:["item-create","item-update","item-delete"],variables:s,skip:r}),h=q(e.value.itemId??null);Q(()=>{re(()=>{if(o.value=l.value,a.value=f.value,!e.value.itemId){let _=p.value?.[0]?.id??null;_!==h.value&&(h.value=_)}})});async function x(){if(!h.value)return;u.value=!0;let I=await(await n.intents.invoke("unsave:item",{itemId:h.value})).complete;I.code==="ok"&&"itemId"in I.data&&(h.value=null),u.value=!1}i(x,"unsave");async function w(){if(!h.value)return;u.value=!0;let I=await(await n.intents.invoke("edit:item-lists",{itemId:h.value})).complete;I.code==="ok"&&"itemId"in I.data&&(h.value=null),u.value=!1}i(w,"update");async function O(){let{productId:_,variantId:I}=e.value;if(!_)return;u.value=!0,c.value=!0;let C=await(await n.intents.invoke("save:item",{productId:_,variantId:I})).complete;if(C.code==="ok"){let te=C.data;h.value=te.item.id,u.value=!1}else C.code==="error"&&console.warn("Failed to create item",C),re(()=>{u.value=!1,c.value=!1})}i(O,"save");let N=F(()=>o.value||u.value||e.value.loading);Q(()=>{c.value&&!u.value&&!y.value&&(c.value=!1)});let L=F(()=>{let _=y.value&&c.value,I=!!h.value,V=!I&&(u.value||_),C=I&&(u.value||_),te=F(()=>V?"saving":C?"unsaving":I?"saved":"unsaved");return{error:a.value,status:te.value,savedItemId:h.value,loading:N.value,submitting:u.value,saved:I,saving:V,unsaving:C}});async function H(){N.value||(L.value.saved&&L.value.savedItemId?x():L.value.saved||await O())}return i(H,"toggle"),Object.assign(L,{save:O,unsave:x,update:w,toggle:H})},"itemStateSignal");var _n=i(n=>()=>{let{data:e,loading:t,error:r}=n.state.swishQuery(()=>n.api.items.count(),{refetch:["item-create","item-delete"]}),s=q(0),o=q(!0),a=q(null);return Q(()=>{re(()=>{o.value=t.value,a.value=r.value,s.value=e.value?.count??0})}),F(()=>({count:s.value,loading:o.value,error:a.value}))},"itemCountSignal");var Hs="token-update",On=i(n=>(e,t)=>{let r=q(null),s=q(null),o=q(null),a=q(!t?.skip),u=q(!1),c=F(()=>a.value&&u.value);async function p(){if(!t?.skip?.value)try{a.value=!0;let l=await e(t?.variables?.value);re(()=>{o.value="error"in l?l.error:null,r.value="data"in l?l.data:null,s.value="pageInfo"in l?l.pageInfo:null,a.value=!1,u.value=!0})}catch(l){re(()=>{o.value=l,a.value=!1,u.value=!0})}}return i(p,"executeFetch"),Q(()=>{if(p(),t?.refetch?.length){let l=[...t.refetch,Hs];return n.events.subscribe(l,p)}}),{data:r,pageInfo:s,error:o,loading:a,refetching:c}},"swishQuerySignals");var ue="GraphQL Client";var Rt="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",At="Response returned unexpected Content-Type:",Dt="An unknown error has occurred. The API did not return a data object or any errors in its response.",ut={json:"application/json",multipart:"multipart/mixed"},Pt="X-SDK-Variant",Tt="X-SDK-Version",$n="shopify-graphql-client",Mn="1.4.1",ct=1e3,qn=[429,503],_t=/@(defer)\b/i,Ln=`\r
|
|
8
|
+
`,Vn=/boundary="?([^=";]+)"?/i,Ot=Ln+Ln;function Y(n,e=ue){return n.startsWith(`${e}`)?n:`${e}: ${n}`}i(Y,"formatErrorMessage");function ee(n){return n instanceof Error?n.message:JSON.stringify(n)}i(ee,"getErrorMessage");function Lt(n){return n instanceof Error&&n.cause?n.cause:void 0}i(Lt,"getErrorCause");function $t(n){return n.flatMap(({errors:e})=>e??[])}i($t,"combineErrors");function lt({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}`)}i(lt,"validateRetries");function B(n,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[n]:e}:{}}i(B,"getKeyValueIfValid");function Mt(n,e){if(n.length===0)return e;let r={[n.pop()]:e};return n.length===0?r:Mt(n,r)}i(Mt,"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})}i(Bn,"combineObjects");function qt([n,...e]){return e.reduce(Bn,{...n})}i(qt,"buildCombinedDataObject");function Vt({clientLogger:n,customFetchApi:e=fetch,client:t=ue,defaultRetryWaitTime:r=ct,retriableCodes:s=qn}){let o=i(async(a,u,c)=>{let p=u+1,l=c+1,f;try{if(f=await e(...a),n({type:"HTTP-Response",content:{requestParams:a,response:f}}),!f.ok&&s.includes(f.status)&&p<=l)throw new Error;let y=f?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return y&&n({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:a,deprecationNotice:y}}),f}catch(y){if(p<=l){let h=f?.headers.get("Retry-After");return await Gs(h?parseInt(h,10):r),n({type:"HTTP-Retry",content:{requestParams:a,lastResponse:f,retryAttempt:u,maxRetries:c}}),o(a,p,c)}throw new Error(Y(`${c>0?`Attempted maximum number of ${c} network retries. Last message - `:""}${ee(y)}`,t))}},"httpFetch");return o}i(Vt,"generateHttpFetch");async function Gs(n){return new Promise(e=>setTimeout(e,n))}i(Gs,"sleep");function Nt({headers:n,url:e,customFetchApi:t=fetch,retries:r=0,logger:s}){lt({client:ue,retries:r});let o={headers:n,url:e,retries:r},a=Qs(s),u=Vt({customFetchApi:t,clientLogger:a,defaultRetryWaitTime:ct}),c=zs(u,o),p=Ws(c),l=ti(c);return{config:o,fetch:c,request:p,requestStream:l}}i(Nt,"createGraphQLClient");function Qs(n){return e=>{n&&n(e)}}i(Qs,"generateClientLogger");async function Fn(n){let{errors:e,data:t,extensions:r}=await n.json();return{...B("data",t),...B("extensions",r),headers:n.headers,...e||!t?{errors:{networkStatusCode:n.status,message:Y(e?Rt:Dt),...B("graphQLErrors",e),response:n}}:{}}}i(Fn,"processJSONResponse");function zs(n,{url:e,headers:t,retries:r}){return async(s,o={})=>{let{variables:a,headers:u,url:c,retries:p,keepalive:l,signal:f}=o,y=JSON.stringify({query:s,variables:a});lt({client:ue,retries:p});let h=Object.entries({...t,...u}).reduce((w,[O,N])=>(w[O]=Array.isArray(N)?N.join(", "):N.toString(),w),{});return!h[Pt]&&!h[Tt]&&(h[Pt]=$n,h[Tt]=Mn),n([c??e,{method:"POST",headers:h,body:y,signal:f,keepalive:l}],1,p??r)}}i(zs,"generateFetch");function Ws(n){return async(...e)=>{if(_t.test(e[0]))throw new Error(Y("This operation will result in a streamable response - use requestStream() instead."));let t=null;try{t=await n(...e);let{status:r,statusText:s}=t,o=t.headers.get("content-type")||"";return t.ok?o.includes(ut.json)?await Fn(t):{errors:{networkStatusCode:r,message:Y(`${At} ${o}`),response:t}}:{errors:{networkStatusCode:r,message:Y(s),response:t}}}catch(r){return{errors:{message:ee(r),...t==null?{}:{networkStatusCode:t.status,response:t}}}}}}i(Ws,"generateRequest");async function*Ks(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()}}}i(Ks,"getStreamBodyIterator");function Xs(n,e){return{async*[Symbol.asyncIterator](){try{let t="";for await(let r of n)if(t+=r,t.indexOf(e)>-1){let s=t.lastIndexOf(e),a=t.slice(0,s).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(Ot)+Ot.length).trim());a.length>0&&(yield a),t=t.slice(s+e.length),t.trim()==="--"&&(t="")}}catch(t){throw new Error(`Error occured while processing stream payload - ${ee(t)}`)}}}}i(Xs,"readStreamChunk");function Ys(n){return{async*[Symbol.asyncIterator](){yield{...await Fn(n),hasNext:!1}}}}i(Ys,"createJsonResponseAsyncIterator");function Js(n){return n.map(e=>{try{return JSON.parse(e)}catch(t){throw new Error(`Error in parsing multipart response - ${ee(t)}`)}}).map(e=>{let{data:t,incremental:r,hasNext:s,extensions:o,errors:a}=e;if(!r)return{data:t||{},...B("errors",a),...B("extensions",o),hasNext:s};let u=r.map(({data:c,path:p,errors:l})=>({data:c&&p?Mt(p,c):{},...B("errors",l)}));return{data:u.length===1?u[0].data:qt([...u.map(({data:c})=>c)]),...B("errors",$t(u)),hasNext:s}})}i(Js,"getResponseDataFromChunkBodies");function Zs(n,e){if(n.length>0)throw new Error(Rt,{cause:{graphQLErrors:n}});if(Object.keys(e).length===0)throw new Error(Dt)}i(Zs,"validateResponseData");function ei(n,e){let t=(e??"").match(Vn),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 s=Ks(n),o={},a;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let c of Xs(s,r)){let p=Js(c);a=p.find(f=>f.extensions)?.extensions??a;let l=$t(p);o=qt([o,...p.map(({data:f})=>f)]),u=p.slice(-1)[0].hasNext,Zs(l,o),yield{...B("data",o),...B("extensions",a),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let c=Lt(u);yield{...B("data",o),...B("extensions",a),errors:{message:Y(ee(u)),networkStatusCode:n.status,...B("graphQLErrors",c?.graphQLErrors),response:n},hasNext:!1}}}}}i(ei,"createMultipartResponseAsyncInterator");function ti(n){return async(...e)=>{if(!_t.test(e[0]))throw new Error(Y("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 s=t.headers.get("content-type")||"";switch(!0){case s.includes(ut.json):return Ys(t);case s.includes(ut.multipart):return ei(t,s);default:throw new Error(`${At} ${s}`,{cause:t})}}catch(t){return{async*[Symbol.asyncIterator](){let r=Lt(t);yield{errors:{message:Y(ee(t)),...B("networkStatusCode",r?.status),...B("response",r)},hasNext:!1}}}}}}i(ti,"generateRequestStream");function Ut({client:n,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let t=e.trim(),r=t.match(/^https?:/)?t:`https://${t}`,s=new URL(r);return s.protocol="https",s.origin}catch(t){throw new Error(`${n}: a valid store domain ("${e}") must be provided`,{cause:t})}}i(Ut,"validateDomainAndGetStoreUrl");function pt({client:n,currentSupportedApiVersions:e,apiVersion:t,logger:r}){let s=`${n}: the provided apiVersion ("${t}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!t||typeof t!="string")throw new Error(`${s} is invalid. ${o}`);let a=t.trim();e.includes(a)||(r?r({type:"Unsupported_Api_Version",content:{apiVersion:t,supportedApiVersions:e}}):console.warn(`${s} is likely deprecated or not supported. ${o}`))}i(pt,"validateApiVersion");function dt(n){let e=n*3-2;return e===10?e:`0${e}`}i(dt,"getQuarterMonth");function Bt(n,e,t){let r=e-t;return r<=0?`${n-1}-${dt(r+4)}`:`${n}-${dt(r)}`}i(Bt,"getPrevousVersion");function jn(){let n=new Date,e=n.getUTCMonth(),t=n.getUTCFullYear(),r=Math.floor(e/3+1);return{year:t,quarter:r,version:`${t}-${dt(r)}`}}i(jn,"getCurrentApiVersion");function Ft(){let{year:n,quarter:e,version:t}=jn(),r=e===4?`${n+1}-01`:`${n}-${dt(e+1)}`;return[Bt(n,e,3),Bt(n,e,2),Bt(n,e,1),t,r,"unstable"]}i(Ft,"getCurrentSupportedApiVersions");function jt(n){return e=>({...e??{},...n.headers})}i(jt,"generateGetHeaders");function Ht({getHeaders:n,getApiUrl:e}){return(t,r)=>{let s=[t];if(r&&Object.keys(r).length>0){let{variables:o,apiVersion:a,headers:u,retries:c,signal:p}=r;s.push({...o?{variables:o}:{},...u?{headers:n(u)}:{},...a?{url:e(a)}:{},...c?{retries:c}:{},...p?{signal:p}:{}})}return s}}i(Ht,"generateGetGQLClientParams");var Gt="application/json",Hn="storefront-api-client",Gn="1.0.9",Qn="X-Shopify-Storefront-Access-Token",zn="Shopify-Storefront-Private-Token",Wn="X-SDK-Variant",Kn="X-SDK-Version",Xn="X-SDK-Variant-Source",ce="Storefront API Client";function Yn(n){if(n&&typeof window<"u")throw new Error(`${ce}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}i(Yn,"validatePrivateAccessTokenUsage");function Jn(n,e){if(!n&&!e)throw new Error(`${ce}: a public or private access token must be provided`);if(n&&e)throw new Error(`${ce}: only provide either a public or private access token`)}i(Jn,"validateRequiredAccessTokens");function Qt({storeDomain:n,apiVersion:e,publicAccessToken:t,privateAccessToken:r,clientName:s,retries:o=0,customFetchApi:a,logger:u}){let c=Ft(),p=Ut({client:ce,storeDomain:n}),l={client:ce,currentSupportedApiVersions:c,logger:u};pt({...l,apiVersion:e}),Jn(t,r),Yn(r);let f=ni(p,e,l),y={storeDomain:p,apiVersion:e,...t?{publicAccessToken:t}:{privateAccessToken:r},headers:{"Content-Type":Gt,Accept:Gt,[Wn]:Hn,[Kn]:Gn,...s?{[Xn]:s}:{},...t?{[Qn]:t}:{[zn]:r}},apiUrl:f(),clientName:s},h=Nt({headers:y.headers,url:y.apiUrl,retries:o,customFetchApi:a,logger:u}),x=jt(y),w=ri(y,f),O=Ht({getHeaders:x,getApiUrl:w});return Object.freeze({config:y,getHeaders:x,getApiUrl:w,fetch:i((...L)=>h.fetch(...O(...L)),"fetch"),request:i((...L)=>h.request(...O(...L)),"request"),requestStream:i((...L)=>h.requestStream(...O(...L)),"requestStream")})}i(Qt,"createStorefrontApiClient");function ni(n,e,t){return r=>{r&&pt({...t,apiVersion:r});let s=(r??e).trim();return`${n}/api/${s}/graphql.json`}}i(ni,"generateApiUrlFormatter");function ri(n,e){return t=>t?e(t):n.apiUrl}i(ri,"generateGetApiUrl");var j=`
|
|
9
9
|
fragment productImageFields on Image {
|
|
10
10
|
id
|
|
11
11
|
altText
|
|
12
12
|
url
|
|
13
13
|
thumbhash
|
|
14
14
|
}
|
|
15
|
-
`,
|
|
15
|
+
`,zt=`
|
|
16
16
|
fragment saveIntentProductFields on Product {
|
|
17
17
|
id
|
|
18
18
|
availableForSale
|
|
@@ -90,7 +90,7 @@ Values:
|
|
|
90
90
|
value
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
-
`,
|
|
93
|
+
`,Wt=`
|
|
94
94
|
fragment productVariantDataFields on ProductVariant {
|
|
95
95
|
id
|
|
96
96
|
availableForSale
|
|
@@ -119,7 +119,7 @@ Values:
|
|
|
119
119
|
value
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
|
-
`,
|
|
122
|
+
`,Kt=`
|
|
123
123
|
fragment productOptionsVariantFields on ProductVariant {
|
|
124
124
|
id
|
|
125
125
|
selectedOptions {
|
|
@@ -127,7 +127,7 @@ Values:
|
|
|
127
127
|
value
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
-
`,
|
|
130
|
+
`,Xt=`
|
|
131
131
|
fragment selectedVariantFields on Product {
|
|
132
132
|
id
|
|
133
133
|
availableForSale
|
|
@@ -194,7 +194,7 @@ Values:
|
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
|
-
`,
|
|
197
|
+
`,Yt=`
|
|
198
198
|
fragment productImagesFields on Product {
|
|
199
199
|
images(first: 20) {
|
|
200
200
|
nodes {
|
|
@@ -202,7 +202,7 @@ Values:
|
|
|
202
202
|
}
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
|
-
`;var
|
|
205
|
+
`;var Zn=`
|
|
206
206
|
query GetSaveIntentData(
|
|
207
207
|
$productId: ID!
|
|
208
208
|
$country: CountryCode!
|
|
@@ -212,9 +212,9 @@ Values:
|
|
|
212
212
|
...saveIntentProductFields
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
|
-
${
|
|
215
|
+
${zt}
|
|
216
216
|
${j}
|
|
217
|
-
`,
|
|
217
|
+
`,er=`
|
|
218
218
|
query GetSaveIntentDataWithVariant(
|
|
219
219
|
$productId: ID!
|
|
220
220
|
$variantId: ID!
|
|
@@ -228,9 +228,9 @@ Values:
|
|
|
228
228
|
...saveIntentVariantFields
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
-
${
|
|
231
|
+
${zt}
|
|
232
232
|
${j}
|
|
233
|
-
`,
|
|
233
|
+
`,tr=`
|
|
234
234
|
query GetProductCardData(
|
|
235
235
|
$productId: ID!
|
|
236
236
|
$productMetafields: [HasMetafieldsIdentifier!]!
|
|
@@ -243,7 +243,7 @@ Values:
|
|
|
243
243
|
}
|
|
244
244
|
${we}
|
|
245
245
|
${j}
|
|
246
|
-
`,
|
|
246
|
+
`,nr=`
|
|
247
247
|
query GetProductCardDataWithVariant(
|
|
248
248
|
$productId: ID!
|
|
249
249
|
$variantId: ID!
|
|
@@ -260,9 +260,9 @@ Values:
|
|
|
260
260
|
}
|
|
261
261
|
}
|
|
262
262
|
${we}
|
|
263
|
-
${
|
|
263
|
+
${Wt}
|
|
264
264
|
${j}
|
|
265
|
-
`,
|
|
265
|
+
`,rr=`
|
|
266
266
|
query GetProductOptions(
|
|
267
267
|
$productId: ID!
|
|
268
268
|
$country: CountryCode!
|
|
@@ -274,7 +274,7 @@ Values:
|
|
|
274
274
|
}
|
|
275
275
|
${le}
|
|
276
276
|
${j}
|
|
277
|
-
`,
|
|
277
|
+
`,sr=`
|
|
278
278
|
query GetProductOptionsByHandle(
|
|
279
279
|
$handle: String!
|
|
280
280
|
$country: CountryCode!
|
|
@@ -286,7 +286,7 @@ Values:
|
|
|
286
286
|
}
|
|
287
287
|
${le}
|
|
288
288
|
${j}
|
|
289
|
-
`,
|
|
289
|
+
`,ir=`
|
|
290
290
|
query GetProductOptionsWithVariant(
|
|
291
291
|
$productId: ID!
|
|
292
292
|
$variantId: ID!
|
|
@@ -301,9 +301,9 @@ Values:
|
|
|
301
301
|
}
|
|
302
302
|
}
|
|
303
303
|
${le}
|
|
304
|
-
${
|
|
304
|
+
${Kt}
|
|
305
305
|
${j}
|
|
306
|
-
`,
|
|
306
|
+
`,or=`
|
|
307
307
|
query GetProductOptionsByHandleWithVariant(
|
|
308
308
|
$handle: String!
|
|
309
309
|
$variantId: ID!
|
|
@@ -318,9 +318,9 @@ Values:
|
|
|
318
318
|
}
|
|
319
319
|
}
|
|
320
320
|
${le}
|
|
321
|
-
${
|
|
321
|
+
${Kt}
|
|
322
322
|
${j}
|
|
323
|
-
`,
|
|
323
|
+
`,ar=`
|
|
324
324
|
query GetSelectedVariant(
|
|
325
325
|
$productId: ID!
|
|
326
326
|
$selectedOptions: [SelectedOptionInput!]!
|
|
@@ -331,9 +331,9 @@ Values:
|
|
|
331
331
|
...selectedVariantFields
|
|
332
332
|
}
|
|
333
333
|
}
|
|
334
|
-
${
|
|
334
|
+
${Xt}
|
|
335
335
|
${j}
|
|
336
|
-
`,
|
|
336
|
+
`,ur=`
|
|
337
337
|
query GetSelectedVariantByHandle(
|
|
338
338
|
$handle: String!
|
|
339
339
|
$selectedOptions: [SelectedOptionInput!]!
|
|
@@ -344,9 +344,9 @@ Values:
|
|
|
344
344
|
...selectedVariantFields
|
|
345
345
|
}
|
|
346
346
|
}
|
|
347
|
-
${
|
|
347
|
+
${Xt}
|
|
348
348
|
${j}
|
|
349
|
-
`,
|
|
349
|
+
`,cr=`
|
|
350
350
|
query GetProductDetailData(
|
|
351
351
|
$productId: ID!
|
|
352
352
|
$productMetafields: [HasMetafieldsIdentifier!]!
|
|
@@ -361,9 +361,9 @@ Values:
|
|
|
361
361
|
}
|
|
362
362
|
${we}
|
|
363
363
|
${le}
|
|
364
|
-
${
|
|
364
|
+
${Yt}
|
|
365
365
|
${j}
|
|
366
|
-
`,
|
|
366
|
+
`,lr=`
|
|
367
367
|
query GetProductDetailDataWithVariant(
|
|
368
368
|
$productId: ID!
|
|
369
369
|
$variantId: ID!
|
|
@@ -383,10 +383,10 @@ Values:
|
|
|
383
383
|
}
|
|
384
384
|
${we}
|
|
385
385
|
${le}
|
|
386
|
-
${
|
|
387
|
-
${
|
|
386
|
+
${Wt}
|
|
387
|
+
${Yt}
|
|
388
388
|
${j}
|
|
389
|
-
`,
|
|
389
|
+
`,pr=`
|
|
390
390
|
query GetProductImagesById(
|
|
391
391
|
$ids: [ID!]!
|
|
392
392
|
$country: CountryCode!
|
|
@@ -411,7 +411,7 @@ Values:
|
|
|
411
411
|
}
|
|
412
412
|
}
|
|
413
413
|
${j}
|
|
414
|
-
`,
|
|
414
|
+
`,dr=`
|
|
415
415
|
query GetProductRecommendationsById(
|
|
416
416
|
$productId: ID!
|
|
417
417
|
$intent: ProductRecommendationIntent
|
|
@@ -422,7 +422,7 @@ Values:
|
|
|
422
422
|
id
|
|
423
423
|
}
|
|
424
424
|
}
|
|
425
|
-
`,
|
|
425
|
+
`,fr=`
|
|
426
426
|
query GetProductRecommendationsByHandle(
|
|
427
427
|
$handle: String!
|
|
428
428
|
$intent: ProductRecommendationIntent
|
|
@@ -433,17 +433,17 @@ Values:
|
|
|
433
433
|
id
|
|
434
434
|
}
|
|
435
435
|
}
|
|
436
|
-
`,
|
|
436
|
+
`,hr=`
|
|
437
437
|
query GetProductIdByHandle($handle: String!) {
|
|
438
438
|
product(handle: $handle) {
|
|
439
439
|
id
|
|
440
440
|
}
|
|
441
441
|
}
|
|
442
|
-
`;var
|
|
442
|
+
`;var mr=i(async(n,{productId:e,variantId:t,productMetafields:r=[],variantMetafields:s=[],country:o,language:a})=>{if(!e)throw new Error("A productId must be provided");let u=i(()=>{if(e&&!t)return tr;if(e&&t)return nr},"getProductOptionsQuery"),c=i(()=>{if(e&&!t)return{productId:D("Product",e),productMetafields:r,country:o,language:a};if(e&&t)return{productId:D("Product",e),variantId:D("ProductVariant",t),productMetafields:r,variantMetafields:s,country:o,language:a}},"getVariables"),p=u(),l=c();if(!l||!p)throw new Error("Invalid query arguments");return n.query(p,l)},"loadProductCardData");var yr=i(async(n,{productId:e,variantId:t,productMetafields:r=[],variantMetafields:s=[],country:o,language:a})=>{if(!e)throw new Error("A productId must be provided");let u=i(()=>{if(e&&!t)return cr;if(e&&t)return lr},"getProductDetailDataQuery"),c=i(()=>{if(e&&!t)return{productId:D("Product",e),productMetafields:r,country:o,language:a};if(e&&t)return{productId:D("Product",e),variantId:D("ProductVariant",t),productMetafields:r,variantMetafields:s,country:o,language:a}},"getVariables"),p=u(),l=c();if(!l||!p)throw new Error("Invalid query arguments");return n.query(p,l)},"loadProductDetailData");var vr=i(async(n,{productHandle:e})=>{if(!e)throw new Error("A product handle must be provided");return n.query(hr,{handle:e})},"loadProductId");var gr=i(async(n,{items:e,country:t,language:r})=>{if(!e?.length)throw new Error("A list of items must be provided");let s={ids:e.map(o=>o.variantId?D("ProductVariant",o.variantId.toString()):D("Product",o.productId.toString())),country:t,language:r};try{return{data:(await n.query(pr,s)).data?.nodes.map(u=>u===null?null:"image"in u?u.image:"featuredImage"in u?u.featuredImage:null).filter(u=>u!==null)??[],error:null}}catch(o){return console.error(o),{data:null,error:o}}},"loadProductImages");var wr=i(async(n,{productId:e,productHandle:t,variantId:r,country:s,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let a=i(()=>{if(e&&!r)return rr;if(t&&!r)return sr;if(e&&r)return ir;if(t&&r)return or},"getProductOptionsQuery"),u=i(()=>{if(e&&!r)return{productId:D("Product",e),country:s,language:o};if(t&&!r)return{handle:t,country:s,language:o};if(e&&r)return{productId:D("Product",e),variantId:D("ProductVariant",r),country:s,language:o};if(t&&r)return{handle:t,variantId:D("ProductVariant",r),country:s,language:o}},"getVariables"),c=a(),p=u();if(!p||!c)throw new Error("Invalid query arguments");return n.query(c,p)},"loadProductOptions");var Ir=i(async(n,{productId:e,productHandle:t,intent:r,country:s,language:o})=>{if(!e&&!t)throw new Error("Either productId or productHandle must be provided");if(e){let u={productId:D("Product",e),intent:r,country:s,language:o};return n.query(dr,u)}let a={handle:t,intent:r,country:s,language:o};return n.query(fr,a)},"loadProductRecommendations");var br=i(async(n,{productId:e,variantId:t,country:r,language:s})=>{let o=i(()=>{if(e&&!t)return Zn;if(e&&t)return er},"getProductOptionsQuery"),a=i(()=>{if(e&&!t)return{productId:D("Product",A(e)),country:r,language:s};if(e&&t)return{productId:D("Product",A(e)),variantId:D("ProductVariant",A(t)),country:r,language:s}},"getVariables"),u=o(),c=a();if(!c||!u)throw new Error("Invalid query arguments");return n.query(u,c)},"loadSaveIntentData");var Sr=i(async(n,{productId:e,productHandle:t,selectedOptions:r,country:s,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let a=e?ar:ur,u=e?{productId:`gid://shopify/Product/${e}`,selectedOptions:r,country:s,language:o}:{handle:t,selectedOptions:r,country:s,language:o};return n.query(a,u)},"loadSelectedVariant");var si="2026-01",ii=["GetProductIdByHandle"],ft=class{constructor(e,t,r,s){this.client=null;this.query=i(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=i(async e=>wr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductOptions");this.loadSelectedVariant=i(async e=>Sr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSelectedVariant");this.loadProductCardData=i(async e=>mr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductCardData");this.loadProductDetailData=i(async e=>yr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductDetailData");this.loadProductImages=i(async e=>gr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductImages");this.loadProductRecommendations=i(async e=>Ir(this,{...e,country:this.context.localization.country,language:this.context.localization.language}),"loadProductRecommendations");this.loadProductId=i(async e=>vr(this,e),"loadProductId");this.loadSaveIntentData=i(async e=>br(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSaveIntentData");this.options=e,this.context=t,this.productOptions=r,this.metafields={productMetafields:s?.product.map(a=>({namespace:a.split(".")[0],key:a.split(".")[1]}))??[],variantMetafields:s?.productVariant.map(a=>({namespace:a.split(".")[0],key:a.split(".")[1]}))??[]};let o=G(t.myshopifyDomain);this.shortCache=new J(`storefront-api-short-${o}`,"max-age=60, stale-while-revalidate=3600"),this.longCache=new J(`storefront-api-long-${o}`,"max-age=3600, stale-while-revalidate=86400"),this.shortCache.cleanupExpiredEntries().catch(a=>{console.warn("Storefront API cache initialization cleanup error:",a)}),this.longCache.cleanupExpiredEntries().catch(a=>{console.warn("Storefront API cache initialization cleanup error:",a)}),this.client=Qt({apiVersion:si,customFetchApi:i((a,u)=>u?.method==="OPTIONS"?this.fetch(a,u):ii.some(c=>u?.body?.toString().includes(`query ${c}`))?this.longCache.fetchWithCache(a,u):this.shortCache.fetchWithCache(a,u),"customFetchApi"),publicAccessToken:this.options.accessToken,storeDomain:this.options.storeDomain})}static{i(this,"StorefrontApiClient")}fetch(e,t){return t?.method==="OPTIONS"?fetch(e,t):this.shortCache.fetchWithCache(e,t)}async clearCache(){await this.shortCache.clear()}};var oi=Object.defineProperty,d=i((n,e)=>oi(n,"name",{value:e,configurable:!0}),"n"),ai={bodySerializer:d(n=>JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t),"bodySerializer")},ui={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},Kp=Object.entries(ui),ci=d(({onRequest:n,onSseError:e,onSseEvent:t,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:a,sseMaxRetryDelay:u,sseSleepFn:c,url:p,...l})=>{let f,y=c??(h=>new Promise(x=>setTimeout(x,h)));return{stream:d(async function*(){let h=o??3e3,x=0,w=l.signal??new AbortController().signal;for(;!w.aborted;){x++;let O=l.headers instanceof Headers?l.headers:new Headers(l.headers);f!==void 0&&O.set("Last-Event-ID",f);try{let N={redirect:"follow",...l,body:l.serializedBody,headers:O,signal:w},L=new Request(p,N);n&&(L=await n(p,N));let H=await(l.fetch??globalThis.fetch)(L);if(!H.ok)throw new Error(`SSE failed: ${H.status} ${H.statusText}`);if(!H.body)throw new Error("No body in SSE response");let _=H.body.pipeThrough(new TextDecoderStream).getReader(),I="",V=d(()=>{try{_.cancel()}catch{}},"abortHandler");w.addEventListener("abort",V);try{for(;;){let{done:C,value:te}=await _.read();if(C)break;I+=te;let on=I.split(`
|
|
443
443
|
|
|
444
|
-
`);I=
|
|
445
|
-
`),Ie=[],
|
|
446
|
-
`);try{se=JSON.parse(W),cn=!0}catch{se=W}}cn&&(s&&await s(se),r&&(se=await r(se))),t?.({data:se,event:un,id:f,retry:h}),Ie.length&&(yield se)}}}finally{w.removeEventListener("abort",q),_.releaseLock()}break}catch(N){if(e?.(N),a!==void 0&&x>=a)break;let L=Math.min(h*2**(x-1),u??3e4);await y(L)}}},"createStream")()}},"createSseClient"),pi=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),di=d(n=>{switch(n){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),fi=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),Cr=d(({allowReserved:n,explode:e,name:t,style:r,value:s})=>{if(!e){let u=(n?s:s.map(c=>encodeURIComponent(c))).join(di(r));switch(r){case"label":return`.${u}`;case"matrix":return`;${t}=${u}`;case"simple":return u;default:return`${t}=${u}`}}let o=pi(r),a=s.map(u=>r==="label"||r==="simple"?n?u:encodeURIComponent(u):mt({allowReserved:n,name:t,value:u})).join(o);return r==="label"||r==="matrix"?o+a:a},"serializeArrayParam"),mt=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"),Rr=d(({allowReserved:n,explode:e,name:t,style:r,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${t}=${s.toISOString()}`;if(r!=="deepObject"&&!e){let c=[];Object.entries(s).forEach(([p,f])=>{c=[...c,p,n?f:encodeURIComponent(f)]});let l=c.join(",");switch(r){case"form":return`${t}=${l}`;case"label":return`.${l}`;case"matrix":return`;${t}=${l}`;default:return l}}let a=fi(r),u=Object.entries(s).map(([c,l])=>mt({allowReserved:n,name:r==="deepObject"?`${t}[${c}]`:c,value:l})).join(a);return r==="label"||r==="matrix"?a+u:u},"serializeObjectParam"),hi=/\{[^{}]+\}/g,mi=d(({path:n,url:e})=>{let t=e,r=e.match(hi);if(r)for(let s of r){let o=!1,a=s.substring(1,s.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let c=n[a];if(c==null)continue;if(Array.isArray(c)){t=t.replace(s,Cr({explode:o,name:a,style:u,value:c}));continue}if(typeof c=="object"){t=t.replace(s,Rr({explode:o,name:a,style:u,value:c,valueOnly:!0}));continue}if(u==="matrix"){t=t.replace(s,`;${mt({name:a,value:c})}`);continue}let l=encodeURIComponent(u==="label"?`.${c}`:c);t=t.replace(s,l)}return t},"defaultPathSerializer"),yi=d(({baseUrl:n,path:e,query:t,querySerializer:r,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,a=(n??"")+o;e&&(a=mi({path:e,url:a}));let u=t?r(t):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"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}i(Ar,"K");d(Ar,"getValidRequestBody");var vi=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"),Dr=d(({allowReserved:n,array:e,object:t}={})=>d(r=>{let s=[];if(r&&typeof r=="object")for(let o in r){let a=r[o];if(a!=null)if(Array.isArray(a)){let u=Cr({allowReserved:n,explode:!0,name:o,style:"form",value:a,...e});u&&s.push(u)}else if(typeof a=="object"){let u=Rr({allowReserved:n,explode:!0,name:o,style:"deepObject",value:a,...t});u&&s.push(u)}else{let u=mt({allowReserved:n,name:o,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),gi=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"),wi=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"),Ii=d(async({security:n,...e})=>{for(let t of n){if(wi(e,t.name))continue;let r=await vi(t,e.auth);if(!r)continue;let s=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[s]=r;break;case"cookie":e.headers.append("Cookie",`${s}=${r}`);break;case"header":default:e.headers.set(s,r);break}}},"setAuthParams"),xr=d(n=>yi({baseUrl:n.baseUrl,path:n.path,query:n.query,querySerializer:typeof n.querySerializer=="function"?n.querySerializer:Dr(n.querySerializer),url:n.url}),"buildUrl"),kr=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=Pr(n.headers,e.headers),r},"mergeConfigs"),bi=d(n=>{let e=[];return n.forEach((t,r)=>{e.push([r,t])}),e},"headersEntries"),Pr=d((...n)=>{let e=new Headers;for(let t of n){if(!t)continue;let r=t instanceof Headers?bi(t):Object.entries(t);for(let[s,o]of r)if(o===null)e.delete(s);else if(Array.isArray(o))for(let a of o)e.append(s,a);else o!==void 0&&e.set(s,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),Tr=class{static{i(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(Tr,"Interceptors");var Zt=Tr,Si=d(()=>({error:new Zt,request:new Zt,response:new Zt}),"createInterceptors"),Ei=Dr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xi={"Content-Type":"application/json"},ht=d((n={})=>({...ui,headers:xi,parseAs:"auto",querySerializer:Ei,...n}),"createConfig"),en=d((n={})=>{let e=kr(ht(),n),t=d(()=>({...e}),"getConfig"),r=d(l=>(e=kr(e,l),t()),"setConfig"),s=Si(),o=d(async l=>{let p={...e,...l,fetch:l.fetch??e.fetch??globalThis.fetch,headers:Pr(e.headers,l.headers),serializedBody:void 0};p.security&&await Ii({...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 f=xr(p);return{opts:p,url:f}},"beforeRequest"),a=d(async l=>{let{opts:p,url:f}=await o(l),y={redirect:"follow",...p,body:Ar(p)},h=new Request(f,y);for(let I of s.request.fns)I&&(h=await I(h,p));let x=p.fetch,w=await x(h);for(let I of s.response.fns)I&&(w=await I(w,h,p));let O={request:h,response:w};if(w.ok){let I=(p.parseAs==="auto"?gi(w.headers.get("Content-Type")):p.parseAs)??"json";if(w.status===204||w.headers.get("Content-Length")==="0"){let C;switch(I){case"arrayBuffer":case"blob":case"text":C=await w[I]();break;case"formData":C=new FormData;break;case"stream":C=w.body;break;case"json":default:C={};break}return p.responseStyle==="data"?C:{data:C,...O}}let q;switch(I){case"arrayBuffer":case"blob":case"formData":case"json":case"text":q=await w[I]();break;case"stream":return p.responseStyle==="data"?w.body:{data:w.body,...O}}return I==="json"&&(p.responseValidator&&await p.responseValidator(q),p.responseTransformer&&(q=await p.responseTransformer(q))),p.responseStyle==="data"?q:{data:q,...O}}let N=await w.text(),L;try{L=JSON.parse(N)}catch{}let G=L??N,_=G;for(let I of s.error.fns)I&&(_=await I(G,w,h,p));if(_=_||{},p.throwOnError)throw _;return p.responseStyle==="data"?void 0:{error:_,...O}},"request"),u=d(l=>p=>a({...p,method:l}),"makeMethodFn"),c=d(l=>async p=>{let{opts:f,url:y}=await o(p);return li({...f,body:f.body,headers:f.headers,method:l,onRequest:d(async(h,x)=>{let w=new Request(h,x);for(let O of s.request.fns)O&&(w=await O(w,f));return w},"onRequest"),url:y})},"makeSseFn");return{buildUrl:xr,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:t,head:u("HEAD"),interceptors:s,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:r,sse:{connect:c("CONNECT"),delete:c("DELETE"),get:c("GET"),head:c("HEAD"),options:c("OPTIONS"),patch:c("PATCH"),post:c("POST"),put:c("PUT"),trace:c("TRACE")},trace:u("TRACE")}},"createClient"),R=en(ht({baseUrl:"https://swish.app/api/2026-01"})),ki=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n}),"listControllerFind"),Ci=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerCreate"),Ri=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerDeleteById"),Ai=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerFindById"),Di=d(n=>(n.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerUpdateById"),Pi=d(n=>(n.client??R).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerSetListItemsOrder"),Ti=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerAddItemsToList"),_i=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...n}),"listControllerRemoveItemFromList"),Oi=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerDelete"),Li=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...n}),"itemControllerFind"),$i=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerCreate"),Mi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...n}),"itemControllerCount"),Vi=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerDeleteById"),qi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerFindById"),Ni=d(n=>(n.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerUpdateById"),Bi=d(n=>(n.client??R).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerSetListsById"),Ui=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerIdentify"),Fi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerCreateToken"),ji=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...n}),"profileControllerGetProfile"),Gi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...n}),"analyticsControllerLoadSavedItems"),Hi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...n}),"analyticsControllerLoadSessions"),Qi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...n}),"analyticsControllerLoadNewLists"),zi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/tracking",...n,headers:{"Content-Type":"application/json",...n.headers}}),"trackingControllerTrack"),Wi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...n}),"ordersControllerFind"),Ki=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...n}),"ordersControllerFindOne"),Xi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}/save",...n}),"sharedListsControllerSave"),Yi=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerDeleteById"),Ji=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerFindById"),Zi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...n}),"sharedListsControllerFindAll"),tn="2026-01",_r=d(n=>new eo(n),"createApiClient"),Or=class{static{i(this,"H")}constructor(e){this.version=tn,this.items={list:d(u=>this.handlePaginatedRequest(Li({query:u,client:this.directClient})),"list"),create:d(u=>this.handleRequest($i({body:u,client:this.directClient})),"create"),delete:d(u=>this.handleRequest(Oi({body:{itemIds:u},client:this.directClient})),"delete"),findById:d(u=>this.handleRequest(qi({path:{itemId:u},client:this.directClient})),"findById"),updateById:d((u,c)=>this.handleRequest(Ni({body:c,path:{itemId:u},client:this.directClient})),"updateById"),deleteById:d(u=>this.handleRequest(Vi({path:{itemId:u},client:this.directClient})),"deleteById"),setListsById:d((u,c)=>this.handleRequest(Bi({body:{listIds:c},path:{itemId:u},client:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(Mi({client:this.directClient})),"count")},this.lists={list:d(u=>this.handlePaginatedRequest(ki({query:u,client:this.directClient})),"list"),create:d(u=>this.handleRequest(Ci({body:u,client:this.directClient})),"create"),findById:d(u=>this.handleRequest(Ai({path:{listId:u},client:this.directClient})),"findById"),updateById:d((u,c)=>this.handleRequest(Di({body:c,path:{listId:u},client:this.directClient})),"updateById"),deleteById:d(u=>this.handleRequest(Ri({path:{listId:u},client:this.directClient})),"deleteById"),orderItems:d((u,c)=>this.handleRequest(Pi({body:{itemIds:c},path:{listId:u},client:this.directClient})),"orderItems"),addItemsToList:d((u,c)=>this.handleRequest(Ti({body:{itemIds:c},path:{listId:u},client:this.directClient})),"addItemsToList"),removeItemFromList:d((u,c)=>this.handleRequest(_i({path:{listId:u,itemId:c},client:this.directClient})),"removeItemFromList")},this.profiles={createToken:d((u={})=>this.handleRequest(Fi({body:u,client:this.proxyClient??this.directClient})),"createToken"),identify:d(u=>this.handleRequest(Ui({body:u,client:this.directClient})),"identify"),getProfile:d(()=>this.handleRequest(ji({client:this.directClient})),"getProfile")},this.orders={list:d(u=>this.handlePaginatedRequest(Wi({query:u,client:this.directClient})),"list"),findById:d(u=>this.handleRequest(Ki({path:{orderId:u},client:this.directClient})),"findById")},this.sharedLists={list:d(u=>this.handlePaginatedRequest(Zi({query:u,client:this.directClient})),"list"),save:d(u=>this.handleRequest(Xi({path:{listId:u},client:this.directClient})),"save"),findById:d(u=>this.handleRequest(Ji({path:{listId:u},client:this.directClient})),"findById"),deleteById:d(u=>this.handleRequest(Yi({path:{listId:u},client:this.directClient})),"deleteById")},this.analytics={savedItems:d(u=>this.handleRequest(Gi({query:u,client:this.directClient})),"savedItems"),sessions:d(u=>this.handleRequest(Hi({query:u,client:this.directClient})),"sessions"),newLists:d(u=>this.handleRequest(Qi({query:u,client:this.directClient})),"newLists")},this.tracking={track:d((u,c)=>this.handleRequest(zi({body:u,headers:c,client:this.directClient})),"track")},this.handleRequest=d(async u=>{let{data:c,error:l}=await u;return l!=null&&l.error?{error:l.error}:{data:c?.data}},"handleRequest"),this.handlePaginatedRequest=d(async u=>{var c;let{data:l,error:p}=await u;return p!=null&&p.error?{error:p.error}:{data:l?.data??[],pageInfo:l?.pageInfo??{next:null,previous:null,totalCount:((c=l?.data)==null?void 0:c.length)??0}}},"handlePaginatedRequest");var t,r,s,o,a;(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=en(ht({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),(r=e.config)!=null&&r.authProxy&&(this.proxyClient=en(ht({...e.config,baseUrl:e.config.authProxy}))),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&((s=this.proxyClient)==null||s.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)),(a=this.proxyClient)==null||a.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(Or,"SwishClient");var eo=Or;var Vr=Wr(Mr(),1);var qr=i(n=>new Vr.default(async e=>{let t=[...new Set(e)].sort((s,o)=>s.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(s=>{let o=r.data.find(a=>s===`variant:${a.variantId}`||s===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:i(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var yt=class{constructor(e,t,r){this.tokenHasProfile=!1;this.api=e,this.context=t,this.eventBus=r}static{i(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 s=this.getSessionId();await this.acquireToken(s,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=H(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let t=H(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${t}`,e)}deleteSessionId(){let e=H(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=H(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let t=H(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${t}`,e)}deleteSwishToken(){let e=H(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 vt=class{static{i(this,"SwishApi")}constructor(e,t,r,s){this.config=e,this.storefrontContext=t;let o=H(t.myshopifyDomain);this.cache=new J(`swish-api-${o}`,"max-age=60, stale-while-revalidate=3600",s+(e.version??tn)),this.cache.cleanupExpiredEntries().catch(a=>{console.warn("Swish API cache initialization cleanup error:",a)}),this.auth=new yt(this,t,r),this.apiClient=_r({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=qr(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.initAuth();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(s){console.warn("Failed to set storefront context headers:",s)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,t){let r=t.method!=="GET",s=t.url.includes("/profiles/token");if(r&&!s){let o=this.auth.hasToken(),a=!this.auth.hasProfile(),u=e.ok;await this.cache.clear(),o&&a&&u&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,t),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}async withFallback(e,t){return await this.initAuth(),this.auth.hasProfile()?e():Promise.resolve(t)}get items(){return{...this.apiClient.items,count:i(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:i(async(e,t)=>{let r=i(()=>{if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let s=e.query.split(" ");s.length>1&&console.warn("Batching will only support one query parameter");let o=s[0];if(!o.match(/^product:\d+$/)&&!o.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(o)}return this.apiClient.items.list(e)},"execute");return t?.shared?r():this.withFallback(r,{data:[],pageInfo:{next:null,previous:null,totalCount:0}})},"list"),findById:i(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:i(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:i(async(e,t)=>{let r=i(()=>this.apiClient.lists.findById(e),"execute");return t?.shared?r():this.withFallback(()=>this.apiClient.lists.findById(e),{data:null})},"findById")}}get orders(){return{...this.apiClient.orders,list:i(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:i(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 gt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{i(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.method,e.status,t.url);if(!r)return;let s=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{s=JSON.parse(s).data}catch(o){console.warn(o)}this.eventBus.publish(r,s)}catch(r){console.warn(r)}}getEventName(e,t,r){e=e.toUpperCase();let s=new URL(r).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,c]=a.split(" ");return u!==e?!1:new RegExp(c).test(s)})?.[1]}};var wt=class{constructor(e,t){this.inflightModals=new Map;this.modalsWithScrollLock=new Set;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._templatePromises=new Map;this._importPromises=new Map;this._lockScroll=i(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=i(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{i(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{try{if(typeof e=="string"&&(e=await this.requireUiComponent(e)),!e||e.getAttribute("open")!=="true")return;e.setAttribute("open","false")}finally{e&&typeof e!="string"&&this.modalsWithScrollLock.has(e)&&(this.modalsWithScrollLock.delete(e),this.unlockScroll())}})().finally(()=>{this.inflightModals.delete(e)});return 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")&&(this.lockScroll(),this.modalsWithScrollLock.add(e),e.setAttribute("open","true"))})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,t),t}waitForEvent(e,t){return new Promise(r=>{let s=[],o=i(()=>{s.forEach(({event:a,listener:u})=>{e.removeEventListener(a,u)})},"cleanup");Object.entries(t).forEach(([a,u])=>{let c=i(l=>{let p=u(l);o(),r(p)},"listener");s.push({event:a,listener:c}),e.addEventListener(a,c)})})}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,{submit:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({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:i(s=>s instanceof CustomEvent?{code:"ok",data:s.detail}:(console.warn("Unsave alert submitted without detail",s),{code:"closed"}),"submit"),close:i(()=>({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:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showConfirmDialog(e){await this.hideAllToasts();let t=await this.requireUiComponent("confirm-dialog");e.titleKey?t.setAttribute("title-key",e.titleKey):t.removeAttribute("title-key"),e.descriptionKey?t.setAttribute("description-key",e.descriptionKey):t.removeAttribute("description-key"),e.confirmLabelKey?t.setAttribute("confirm-label-key",e.confirmLabelKey):t.removeAttribute("confirm-label-key"),e.cancelLabelKey?t.setAttribute("cancel-label-key",e.cancelLabelKey):t.removeAttribute("cancel-label-key"),e.danger?t.setAttribute("danger",""):t.removeAttribute("danger"),await this.showModal(t);let r=await this.waitForEvent(t,{submit:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({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:i(()=>({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:i(()=>({code:"closed"}),"close"),edit:i(s=>s instanceof CustomEvent?{code:"ok",data:{action:"edit",data:s.detail}}:(console.warn("List menu edit without detail",s),{code:"closed"}),"edit"),delete:i(()=>({code:"ok",data:{action:"delete"}}),"delete"),share:i(()=>({code:"ok",data:{action:"share"}}),"share"),"edit-access":i(s=>{if(s instanceof CustomEvent){let a=s.detail?.currentListAccess;if(a==="public"||a==="private")return{code:"ok",data:{action:"edit-access",data:{currentListAccess:a}}}}return{code:"ok",data:{action:"edit-access"}}},"edit-access")});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:i(()=>({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:i(()=>({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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:{action:"submit",data:s.detail}}:(console.warn("List select submit without detail",s),{code:"closed"}),"submit"),unsave:i(s=>s instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:s.detail}}:(console.warn("List select unsave without detail",s),{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:i(s=>{s.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:i(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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("Variant select submit without detail",s),{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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("Quick buy submit without detail",s),{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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("List editor submit without detail",s),{code:"closed"}),"submit")});return await this.hideModal(t),r}async createElement(e,t){let[r,{themeVariablesStylesheet:s}]=await Promise.all([this.loadTemplate(e),this.loadCricalResources()]),o=document.createElement("template");o.innerHTML=r.replace(' shadowrootmode="open"',"");let a=o.content.firstElementChild;return a.addEventListener("connected",()=>{a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[s],this.hydrateElement(e,a,t?.onHydrated))},{once:!0}),a}async hydrateElement(e,t,r){if(t.hasAttribute("hydrated")){r?.(t.getComponentRef());return}await Promise.all([this.loadNonCriticalResources(),this.importScript(e)]).then(([{bundleCssStylesheet:s,customCssStylesheets:o},{hydrate:a}])=>{t.shadowRoot&&s&&(t.shadowRoot.adoptedStyleSheets=[...t.shadowRoot.adoptedStyleSheets,...o,s],t.shadowRoot?.querySelector(":host > style")?.remove()),a(t),t.setAttribute("hydrated","")}),r?.(t.getComponentRef())}async requireUiComponent(e,t){this.loadCricalResources();let r=await this.loadTemplate(e),s=this.queryComponent(e)??await this.insertComponent({name:e,template:r,refElement:t?.refElement??document.body,position:"beforeend"});return s.shadowRoot&&!s.hasAttribute("hydrated")?Promise.all([this.loadNonCriticalResources(),this.importScript(e)]).then(([{bundleCssStylesheet:o,customCssStylesheets:a},{hydrate:u}])=>{s.shadowRoot&&o&&(s.shadowRoot.adoptedStyleSheets=[...s.shadowRoot.adoptedStyleSheets,...a,o],s.shadowRoot?.querySelector(":host > style")?.remove()),u(s),s.setAttribute("hydrated",""),t?.onHydrated?.(s.getComponentRef())}):s.hasAttribute("hydrated")&&t?.onHydrated?.(s.getComponentRef()),s}async loadTemplate(e){let t=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`;if(this._templatePromises.has(t))return this._templatePromises.get(t);let r=fetch(t).then(s=>s.text());return this._templatePromises.set(t,r),r}async importScript(e){let t=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;if(this._importPromises.has(t))return this._importPromises.get(t);let r=import(t);return this._importPromises.set(t,r),r}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(o=>o.text()),r=new CSSStyleSheet;r.replaceSync(t);let s=lo(this.swishUiOptions.design);return Object.entries(s).forEach(([o,a])=>{r.cssRules[0].cssRules[0].style.setProperty(o,a)}),{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=i(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[r,...s]=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(a=>a.text())):t(o))]);return{bundleCssStylesheet:r,customCssStylesheets:s}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,template:t,position:r,refElement:s}){let{themeVariablesStylesheet:o}=await this.loadCricalResources();s.insertAdjacentHTML(r,t.replace(' shadowrootmode="open"',""));let a=this.queryComponent(e);if(!a)throw new Error(`Element ${e} not found in DOM`);return a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[o]),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(`
|
|
444
|
+
`);I=on.pop()??"";for(let Vr of on){let Nr=Vr.split(`
|
|
445
|
+
`),Ie=[],an;for(let W of Nr)if(W.startsWith("data:"))Ie.push(W.replace(/^data:\s*/,""));else if(W.startsWith("event:"))an=W.replace(/^event:\s*/,"");else if(W.startsWith("id:"))f=W.replace(/^id:\s*/,"");else if(W.startsWith("retry:")){let cn=Number.parseInt(W.replace(/^retry:\s*/,""),10);Number.isNaN(cn)||(h=cn)}let se,un=!1;if(Ie.length){let W=Ie.join(`
|
|
446
|
+
`);try{se=JSON.parse(W),un=!0}catch{se=W}}un&&(s&&await s(se),r&&(se=await r(se))),t?.({data:se,event:an,id:f,retry:h}),Ie.length&&(yield se)}}}finally{w.removeEventListener("abort",V),_.releaseLock()}break}catch(N){if(e?.(N),a!==void 0&&x>=a)break;let L=Math.min(h*2**(x-1),u??3e4);await y(L)}}},"createStream")()}},"createSseClient"),li=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),pi=d(n=>{switch(n){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),di=d(n=>{switch(n){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),kr=d(({allowReserved:n,explode:e,name:t,style:r,value:s})=>{if(!e){let u=(n?s:s.map(c=>encodeURIComponent(c))).join(pi(r));switch(r){case"label":return`.${u}`;case"matrix":return`;${t}=${u}`;case"simple":return u;default:return`${t}=${u}`}}let o=li(r),a=s.map(u=>r==="label"||r==="simple"?n?u:encodeURIComponent(u):mt({allowReserved:n,name:t,value:u})).join(o);return r==="label"||r==="matrix"?o+a:a},"serializeArrayParam"),mt=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"),Cr=d(({allowReserved:n,explode:e,name:t,style:r,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${t}=${s.toISOString()}`;if(r!=="deepObject"&&!e){let c=[];Object.entries(s).forEach(([l,f])=>{c=[...c,l,n?f:encodeURIComponent(f)]});let p=c.join(",");switch(r){case"form":return`${t}=${p}`;case"label":return`.${p}`;case"matrix":return`;${t}=${p}`;default:return p}}let a=di(r),u=Object.entries(s).map(([c,p])=>mt({allowReserved:n,name:r==="deepObject"?`${t}[${c}]`:c,value:p})).join(a);return r==="label"||r==="matrix"?a+u:u},"serializeObjectParam"),fi=/\{[^{}]+\}/g,hi=d(({path:n,url:e})=>{let t=e,r=e.match(fi);if(r)for(let s of r){let o=!1,a=s.substring(1,s.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let c=n[a];if(c==null)continue;if(Array.isArray(c)){t=t.replace(s,kr({explode:o,name:a,style:u,value:c}));continue}if(typeof c=="object"){t=t.replace(s,Cr({explode:o,name:a,style:u,value:c,valueOnly:!0}));continue}if(u==="matrix"){t=t.replace(s,`;${mt({name:a,value:c})}`);continue}let p=encodeURIComponent(u==="label"?`.${c}`:c);t=t.replace(s,p)}return t},"defaultPathSerializer"),mi=d(({baseUrl:n,path:e,query:t,querySerializer:r,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,a=(n??"")+o;e&&(a=hi({path:e,url:a}));let u=t?r(t):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function Rr(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}i(Rr,"K");d(Rr,"getValidRequestBody");var yi=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 s=[];if(r&&typeof r=="object")for(let o in r){let a=r[o];if(a!=null)if(Array.isArray(a)){let u=kr({allowReserved:n,explode:!0,name:o,style:"form",value:a,...e});u&&s.push(u)}else if(typeof a=="object"){let u=Cr({allowReserved:n,explode:!0,name:o,style:"deepObject",value:a,...t});u&&s.push(u)}else{let u=mt({allowReserved:n,name:o,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),vi=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"),gi=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"),wi=d(async({security:n,...e})=>{for(let t of n){if(gi(e,t.name))continue;let r=await yi(t,e.auth);if(!r)continue;let s=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[s]=r;break;case"cookie":e.headers.append("Cookie",`${s}=${r}`);break;case"header":default:e.headers.set(s,r);break}}},"setAuthParams"),Er=d(n=>mi({baseUrl:n.baseUrl,path:n.path,query:n.query,querySerializer:typeof n.querySerializer=="function"?n.querySerializer:Ar(n.querySerializer),url:n.url}),"buildUrl"),xr=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=Dr(n.headers,e.headers),r},"mergeConfigs"),Ii=d(n=>{let e=[];return n.forEach((t,r)=>{e.push([r,t])}),e},"headersEntries"),Dr=d((...n)=>{let e=new Headers;for(let t of n){if(!t)continue;let r=t instanceof Headers?Ii(t):Object.entries(t);for(let[s,o]of r)if(o===null)e.delete(s);else if(Array.isArray(o))for(let a of o)e.append(s,a);else o!==void 0&&e.set(s,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),Pr=class{static{i(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(Pr,"Interceptors");var Jt=Pr,bi=d(()=>({error:new Jt,request:new Jt,response:new Jt}),"createInterceptors"),Si=Ar({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Ei={"Content-Type":"application/json"},ht=d((n={})=>({...ai,headers:Ei,parseAs:"auto",querySerializer:Si,...n}),"createConfig"),Zt=d((n={})=>{let e=xr(ht(),n),t=d(()=>({...e}),"getConfig"),r=d(p=>(e=xr(e,p),t()),"setConfig"),s=bi(),o=d(async p=>{let l={...e,...p,fetch:p.fetch??e.fetch??globalThis.fetch,headers:Dr(e.headers,p.headers),serializedBody:void 0};l.security&&await wi({...l,security:l.security}),l.requestValidator&&await l.requestValidator(l),l.body!==void 0&&l.bodySerializer&&(l.serializedBody=l.bodySerializer(l.body)),(l.body===void 0||l.serializedBody==="")&&l.headers.delete("Content-Type");let f=Er(l);return{opts:l,url:f}},"beforeRequest"),a=d(async p=>{let{opts:l,url:f}=await o(p),y={redirect:"follow",...l,body:Rr(l)},h=new Request(f,y);for(let I of s.request.fns)I&&(h=await I(h,l));let x=l.fetch,w=await x(h);for(let I of s.response.fns)I&&(w=await I(w,h,l));let O={request:h,response:w};if(w.ok){let I=(l.parseAs==="auto"?vi(w.headers.get("Content-Type")):l.parseAs)??"json";if(w.status===204||w.headers.get("Content-Length")==="0"){let C;switch(I){case"arrayBuffer":case"blob":case"text":C=await w[I]();break;case"formData":C=new FormData;break;case"stream":C=w.body;break;case"json":default:C={};break}return l.responseStyle==="data"?C:{data:C,...O}}let V;switch(I){case"arrayBuffer":case"blob":case"formData":case"json":case"text":V=await w[I]();break;case"stream":return l.responseStyle==="data"?w.body:{data:w.body,...O}}return I==="json"&&(l.responseValidator&&await l.responseValidator(V),l.responseTransformer&&(V=await l.responseTransformer(V))),l.responseStyle==="data"?V:{data:V,...O}}let N=await w.text(),L;try{L=JSON.parse(N)}catch{}let H=L??N,_=H;for(let I of s.error.fns)I&&(_=await I(H,w,h,l));if(_=_||{},l.throwOnError)throw _;return l.responseStyle==="data"?void 0:{error:_,...O}},"request"),u=d(p=>l=>a({...l,method:p}),"makeMethodFn"),c=d(p=>async l=>{let{opts:f,url:y}=await o(l);return ci({...f,body:f.body,headers:f.headers,method:p,onRequest:d(async(h,x)=>{let w=new Request(h,x);for(let O of s.request.fns)O&&(w=await O(w,f));return w},"onRequest"),url:y})},"makeSseFn");return{buildUrl:Er,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:t,head:u("HEAD"),interceptors:s,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:r,sse:{connect:c("CONNECT"),delete:c("DELETE"),get:c("GET"),head:c("HEAD"),options:c("OPTIONS"),patch:c("PATCH"),post:c("POST"),put:c("PUT"),trace:c("TRACE")},trace:u("TRACE")}},"createClient"),R=Zt(ht({baseUrl:"https://swish.app/api/2026-01"})),xi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n}),"listControllerFind"),ki=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerCreate"),Ci=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerDeleteById"),Ri=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n}),"listControllerFindById"),Ai=d(n=>(n.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerUpdateById"),Di=d(n=>(n.client??R).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerSetListItemsOrder"),Pi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"listControllerAddItemsToList"),Ti=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...n}),"listControllerRemoveItemFromList"),_i=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerDelete"),Oi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...n}),"itemControllerFind"),Li=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerCreate"),$i=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...n}),"itemControllerCount"),Mi=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerDeleteById"),qi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n}),"itemControllerFindById"),Vi=d(n=>(n.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerUpdateById"),Ni=d(n=>(n.client??R).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...n,headers:{"Content-Type":"application/json",...n.headers}}),"itemControllerSetListsById"),Ui=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerIdentify"),Bi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...n,headers:{"Content-Type":"application/json",...n.headers}}),"profileControllerCreateToken"),Fi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles",...n}),"profileControllerGetProfile"),ji=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/saved-items",...n}),"analyticsControllerLoadSavedItems"),Hi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/sessions",...n}),"analyticsControllerLoadSessions"),Gi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/analytics/new-lists",...n}),"analyticsControllerLoadNewLists"),Qi=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/tracking",...n,headers:{"Content-Type":"application/json",...n.headers}}),"trackingControllerTrack"),zi=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...n}),"ordersControllerFind"),Wi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...n}),"ordersControllerFindOne"),Ki=d(n=>(n.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}/save",...n}),"sharedListsControllerSave"),Xi=d(n=>(n.client??R).delete({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerDeleteById"),Yi=d(n=>(n.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists/{listId}",...n}),"sharedListsControllerFindById"),Ji=d(n=>(n?.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/shared-lists",...n}),"sharedListsControllerFindAll"),en="2026-01",Tr=d(n=>new Zi(n),"createApiClient"),_r=class{static{i(this,"H")}constructor(e){this.version=en,this.items={list:d(u=>this.handlePaginatedRequest(Oi({query:u,client:this.directClient})),"list"),create:d(u=>this.handleRequest(Li({body:u,client:this.directClient})),"create"),delete:d(u=>this.handleRequest(_i({body:{itemIds:u},client:this.directClient})),"delete"),findById:d(u=>this.handleRequest(qi({path:{itemId:u},client:this.directClient})),"findById"),updateById:d((u,c)=>this.handleRequest(Vi({body:c,path:{itemId:u},client:this.directClient})),"updateById"),deleteById:d(u=>this.handleRequest(Mi({path:{itemId:u},client:this.directClient})),"deleteById"),setListsById:d((u,c)=>this.handleRequest(Ni({body:{listIds:c},path:{itemId:u},client:this.directClient})),"setListsById"),count:d(()=>this.handleRequest($i({client:this.directClient})),"count")},this.lists={list:d(u=>this.handlePaginatedRequest(xi({query:u,client:this.directClient})),"list"),create:d(u=>this.handleRequest(ki({body:u,client:this.directClient})),"create"),findById:d(u=>this.handleRequest(Ri({path:{listId:u},client:this.directClient})),"findById"),updateById:d((u,c)=>this.handleRequest(Ai({body:c,path:{listId:u},client:this.directClient})),"updateById"),deleteById:d(u=>this.handleRequest(Ci({path:{listId:u},client:this.directClient})),"deleteById"),orderItems:d((u,c)=>this.handleRequest(Di({body:{itemIds:c},path:{listId:u},client:this.directClient})),"orderItems"),addItemsToList:d((u,c)=>this.handleRequest(Pi({body:{itemIds:c},path:{listId:u},client:this.directClient})),"addItemsToList"),removeItemFromList:d((u,c)=>this.handleRequest(Ti({path:{listId:u,itemId:c},client:this.directClient})),"removeItemFromList")},this.profiles={createToken:d((u={})=>this.handleRequest(Bi({body:u,client:this.proxyClient??this.directClient})),"createToken"),identify:d(u=>this.handleRequest(Ui({body:u,client:this.directClient})),"identify"),getProfile:d(()=>this.handleRequest(Fi({client:this.directClient})),"getProfile")},this.orders={list:d(u=>this.handlePaginatedRequest(zi({query:u,client:this.directClient})),"list"),findById:d(u=>this.handleRequest(Wi({path:{orderId:u},client:this.directClient})),"findById")},this.sharedLists={list:d(u=>this.handlePaginatedRequest(Ji({query:u,client:this.directClient})),"list"),save:d(u=>this.handleRequest(Ki({path:{listId:u},client:this.directClient})),"save"),findById:d(u=>this.handleRequest(Yi({path:{listId:u},client:this.directClient})),"findById"),deleteById:d(u=>this.handleRequest(Xi({path:{listId:u},client:this.directClient})),"deleteById")},this.analytics={savedItems:d(u=>this.handleRequest(ji({query:u,client:this.directClient})),"savedItems"),sessions:d(u=>this.handleRequest(Hi({query:u,client:this.directClient})),"sessions"),newLists:d(u=>this.handleRequest(Gi({query:u,client:this.directClient})),"newLists")},this.tracking={track:d((u,c)=>this.handleRequest(Qi({body:u,headers:c,client:this.directClient})),"track")},this.handleRequest=d(async u=>{let{data:c,error:p}=await u;return p!=null&&p.error?{error:p.error}:{data:c?.data}},"handleRequest"),this.handlePaginatedRequest=d(async u=>{var c;let{data:p,error:l}=await u;return l!=null&&l.error?{error:l.error}:{data:p?.data??[],pageInfo:p?.pageInfo??{next:null,previous:null,totalCount:((c=p?.data)==null?void 0:c.length)??0}}},"handlePaginatedRequest");var t,r,s,o,a;(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=Zt(ht({baseUrl:`https://swish.app/api/${this.version}`,...e.config})),(r=e.config)!=null&&r.authProxy&&(this.proxyClient=Zt(ht({...e.config,baseUrl:e.config.authProxy}))),e.authToken&&(this.authToken=e.authToken),e.requestInterceptor&&((s=this.proxyClient)==null||s.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)),(a=this.proxyClient)==null||a.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(_r,"SwishClient");var Zi=_r;var Mr=zr($r(),1);var qr=i(n=>new Mr.default(async e=>{let t=[...new Set(e)].sort((s,o)=>s.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(s=>{let o=r.data.find(a=>s===`variant:${a.variantId}`||s===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:i(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var yt=class{constructor(e,t,r){this.tokenHasProfile=!1;this.api=e,this.context=t,this.eventBus=r}static{i(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 s=this.getSessionId();await this.acquireToken(s,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=G(this.context.myshopifyDomain);return localStorage.getItem(`swish-session-${e}`)??void 0}setSessionId(e){let t=G(this.context.myshopifyDomain);localStorage.setItem(`swish-session-${t}`,e)}deleteSessionId(){let e=G(this.context.myshopifyDomain);localStorage.removeItem(`swish-session-${e}`)}getSwishToken(){let e=G(this.context.myshopifyDomain);return sessionStorage.getItem(`swish-token-${e}`)??void 0}setSwishToken(e){let t=G(this.context.myshopifyDomain);sessionStorage.setItem(`swish-token-${t}`,e)}deleteSwishToken(){let e=G(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 vt=class{static{i(this,"SwishApi")}constructor(e,t,r,s){this.config=e,this.storefrontContext=t;let o=G(t.myshopifyDomain);this.cache=new J(`swish-api-${o}`,"max-age=60, stale-while-revalidate=3600",s+(e.version??en)),this.cache.cleanupExpiredEntries().catch(a=>{console.warn("Swish API cache initialization cleanup error:",a)}),this.auth=new yt(this,t,r),this.apiClient=Tr({authToken:this.auth.getSwishToken(),config:{...e,fetch:this.fetchFunction.bind(this)},requestInterceptor:this.requestInterceptor.bind(this),responseInterceptor:this.responseInterceptor.bind(this)}),this.itemsLoader=qr(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.initAuth();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(s){console.warn("Failed to set storefront context headers:",s)}return this.config.requestInterceptor&&(e=await this.config.requestInterceptor(e)),e}async responseInterceptor(e,t){let r=t.method!=="GET",s=t.url.includes("/profiles/token");if(r&&!s){let o=this.auth.hasToken(),a=!this.auth.hasProfile(),u=e.ok;await this.cache.clear(),o&&a&&u&&await this.auth.renewToken()}return await this.config.responseInterceptor?.(e,t),e}setAuthToken(e){this.apiClient.setAuthToken(e)}initAuth(){return this.auth.init()}async withFallback(e,t){return await this.initAuth(),this.auth.hasProfile()?e():Promise.resolve(t)}get items(){return{...this.apiClient.items,count:i(async()=>this.withFallback(()=>this.apiClient.items.count(),{data:{count:0}}),"count"),list:i(async(e,t)=>{let r=i(()=>{if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let s=e.query.split(" ");s.length>1&&console.warn("Batching will only support one query parameter");let o=s[0];if(!o.match(/^product:\d+$/)&&!o.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(o)}return this.apiClient.items.list(e)},"execute");return t?.shared?r():this.withFallback(r,{data:[],pageInfo:{next:null,previous:null,totalCount:0}})},"list"),findById:i(async e=>this.withFallback(()=>this.apiClient.items.findById(e),{data:null}),"findById")}}get lists(){return{...this.apiClient.lists,list:i(async e=>this.withFallback(()=>this.apiClient.lists.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:i(async(e,t)=>{let r=i(()=>this.apiClient.lists.findById(e),"execute");return t?.shared?r():this.withFallback(()=>this.apiClient.lists.findById(e),{data:null})},"findById")}}get orders(){return{...this.apiClient.orders,list:i(async e=>this.withFallback(()=>this.apiClient.orders.list(e),{data:[],pageInfo:{next:null,previous:null,totalCount:0}}),"list"),findById:i(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 gt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{i(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let r=this.getEventName(t.method,e.status,t.url);if(!r)return;let s=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{s=JSON.parse(s).data}catch(o){console.warn(o)}this.eventBus.publish(r,s)}catch(r){console.warn(r)}}getEventName(e,t,r){e=e.toUpperCase();let s=new URL(r).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,c]=a.split(" ");return u!==e?!1:new RegExp(c).test(s)})?.[1]}};var wt=class{constructor(e,t){this.inflightModals=new Map;this.modalsWithScrollLock=new Set;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._templatePromises=new Map;this._importPromises=new Map;this._lockScroll=i(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=i(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{i(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{try{if(typeof e=="string"&&(e=await this.requireUiComponent(e)),!e||e.getAttribute("open")!=="true")return;e.setAttribute("open","false")}finally{e&&typeof e!="string"&&this.modalsWithScrollLock.has(e)&&(this.modalsWithScrollLock.delete(e),this.unlockScroll())}})().finally(()=>{this.inflightModals.delete(e)});return 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")&&(this.lockScroll(),this.modalsWithScrollLock.add(e),e.setAttribute("open","true"))})().finally(()=>{this.inflightModals.delete(e)});return this.inflightModals.set(e,t),t}waitForEvent(e,t){return new Promise(r=>{let s=[],o=i(()=>{s.forEach(({event:a,listener:u})=>{e.removeEventListener(a,u)})},"cleanup");Object.entries(t).forEach(([a,u])=>{let c=i(p=>{let l=u(p);o(),r(l)},"listener");s.push({event:a,listener:c}),e.addEventListener(a,c)})})}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,{submit:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({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:i(s=>s instanceof CustomEvent?{code:"ok",data:s.detail}:(console.warn("Unsave alert submitted without detail",s),{code:"closed"}),"submit"),close:i(()=>({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:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({code:"closed"}),"close")});return await this.hideModal(t),r}async showConfirmDialog(e){await this.hideAllToasts();let t=await this.requireUiComponent("confirm-dialog");e.titleKey?t.setAttribute("title-key",e.titleKey):t.removeAttribute("title-key"),e.descriptionKey?t.setAttribute("description-key",e.descriptionKey):t.removeAttribute("description-key"),e.confirmLabelKey?t.setAttribute("confirm-label-key",e.confirmLabelKey):t.removeAttribute("confirm-label-key"),e.cancelLabelKey?t.setAttribute("cancel-label-key",e.cancelLabelKey):t.removeAttribute("cancel-label-key"),e.danger?t.setAttribute("danger",""):t.removeAttribute("danger"),await this.showModal(t);let r=await this.waitForEvent(t,{submit:i(()=>({code:"ok",data:void 0}),"submit"),close:i(()=>({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:i(()=>({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:i(()=>({code:"closed"}),"close"),edit:i(s=>s instanceof CustomEvent?{code:"ok",data:{action:"edit",data:s.detail}}:(console.warn("List menu edit without detail",s),{code:"closed"}),"edit"),delete:i(()=>({code:"ok",data:{action:"delete"}}),"delete"),share:i(()=>({code:"ok",data:{action:"share"}}),"share"),"edit-access":i(s=>{if(s instanceof CustomEvent){let a=s.detail?.currentListAccess;if(a==="public"||a==="private")return{code:"ok",data:{action:"edit-access",data:{currentListAccess:a}}}}return{code:"ok",data:{action:"edit-access"}}},"edit-access")});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:i(()=>({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:i(()=>({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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:{action:"submit",data:s.detail}}:(console.warn("List select submit without detail",s),{code:"closed"}),"submit"),unsave:i(s=>s instanceof CustomEvent?{code:"ok",data:{action:"unsave",data:s.detail}}:(console.warn("List select unsave without detail",s),{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:i(s=>{s.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:i(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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("Variant select submit without detail",s),{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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("Quick buy submit without detail",s),{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:i(()=>({code:"closed"}),"close"),submit:i(s=>"detail"in s&&s.detail?{code:"ok",data:s.detail}:(console.warn("List editor submit without detail",s),{code:"closed"}),"submit")});return await this.hideModal(t),r}async createElement(e,t){let[r,{themeVariablesStylesheet:s}]=await Promise.all([this.loadTemplate(e),this.loadCricalResources()]),o=document.createElement("template");o.innerHTML=r.replace(' shadowrootmode="open"',"");let a=o.content.firstElementChild;return a.addEventListener("connected",()=>{a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[s],this.hydrateElement(e,a,t?.onHydrated))},{once:!0}),a}async hydrateElement(e,t,r){if(t.hasAttribute("hydrated")){r?.(t.getComponentRef());return}await Promise.all([this.loadNonCriticalResources(),this.importScript(e)]).then(([{bundleCssStylesheet:s,customCssStylesheets:o},{hydrate:a}])=>{t.shadowRoot&&s&&(t.shadowRoot.adoptedStyleSheets=[...t.shadowRoot.adoptedStyleSheets,...o,s],t.shadowRoot?.querySelector(":host > style")?.remove()),a(t),t.setAttribute("hydrated","")}),r?.(t.getComponentRef())}async requireUiComponent(e,t){this.loadCricalResources();let r=await this.loadTemplate(e),s=this.queryComponent(e)??await this.insertComponent({name:e,template:r,refElement:t?.refElement??document.body,position:"beforeend"});return s.shadowRoot&&!s.hasAttribute("hydrated")?Promise.all([this.loadNonCriticalResources(),this.importScript(e)]).then(([{bundleCssStylesheet:o,customCssStylesheets:a},{hydrate:u}])=>{s.shadowRoot&&o&&(s.shadowRoot.adoptedStyleSheets=[...s.shadowRoot.adoptedStyleSheets,...a,o],s.shadowRoot?.querySelector(":host > style")?.remove()),u(s),s.setAttribute("hydrated",""),t?.onHydrated?.(s.getComponentRef())}):s.hasAttribute("hydrated")&&t?.onHydrated?.(s.getComponentRef()),s}async loadTemplate(e){let t=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`;if(this._templatePromises.has(t))return this._templatePromises.get(t);let r=fetch(t).then(s=>s.text());return this._templatePromises.set(t,r),r}async importScript(e){let t=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;if(this._importPromises.has(t))return this._importPromises.get(t);let r=import(t);return this._importPromises.set(t,r),r}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(o=>o.text()),r=new CSSStyleSheet;r.replaceSync(t);let s=co(this.swishUiOptions.design);return Object.entries(s).forEach(([o,a])=>{r.cssRules[0].cssRules[0].style.setProperty(o,a)}),{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=i(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[r,...s]=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(a=>a.text())):t(o))]);return{bundleCssStylesheet:r,customCssStylesheets:s}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,template:t,position:r,refElement:s}){let{themeVariablesStylesheet:o}=await this.loadCricalResources();s.insertAdjacentHTML(r,t.replace(' shadowrootmode="open"',""));let a=this.queryComponent(e);if(!a)throw new Error(`Element ${e} not found in DOM`);return a.shadowRoot&&(a.shadowRoot.adoptedStyleSheets=[o]),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(`
|
|
447
447
|
html[swish-locked] body {
|
|
448
448
|
overflow: hidden;
|
|
449
449
|
position: fixed;
|
|
@@ -451,4 +451,4 @@ Values:
|
|
|
451
451
|
left: 0px;
|
|
452
452
|
right: 0px;
|
|
453
453
|
}
|
|
454
|
-
`),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"))}};function
|
|
454
|
+
`),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"))}};function co(n){if(!n)return{};let e={},t=i(r=>{Object.entries(r).forEach(([s,o])=>{if(o!=null){if(typeof o=="object"&&!Array.isArray(o)){t(o);return}if(typeof o=="string"||typeof o=="number"){let a=s.startsWith("--")?s:`--swish-theme-${lo(s)}`;e[a]=po(s,o)}}})},"walk");return t(n),e}i(co,"flattenDesignTokens");function lo(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase()}i(lo,"toKebabCase");function po(n,e){return typeof e=="number"&&!fo(n)?`${e}px`:String(e)}i(po,"formatDesignValue");function fo(n){let e=n.toLowerCase();return e.includes("fontweight")||e.includes("scale")||e.includes("letterspacing")||e.includes("lineheight")}i(fo,"isNonPxValue");var ho=typeof HTMLElement<"u"?HTMLElement:class{},It=class extends ho{constructor(){super();this.getComponentRef=i(()=>this.componentRef,"getComponentRef");this.setComponentRef=i(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{i(this,"SwishUiElement")}connectedCallback(){this.dispatchEvent(new CustomEvent("connected"))}};var it="0.111.0",Xd=`https://swish.app/cdn/sdk@${it}/swish.js`,Yd=i(async n=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;let e=Sn(n),t=new sn(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"),sn=class{constructor(e){this.dom={createElementLocator:ie,createLocationObserver:pe,createPlacement:i(e=>hn(this,e),"createPlacement")};this.ui={createElement:i((e,t)=>this.swishUi.createElement(e,t),"createElement")};this.utils={copyToClipboard:ve,createShareUrl:i(e=>ye(this,e),"createShareUrl")};this.state={itemContext:Pn(this),itemState:Tn(this),itemCount:_n(this),swishQuery:On(this),effect:Q,signal:q,computed:F};this.swishOptions=e,this.events=new xe,this.swishApiPublisher=new gt(this.events);let t=[it,e.swishUi?.version].join("-");this.swishApi=new vt({...this.swishOptions.swishApi,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,this.events,t),this.ajaxApiPublisher=new Se(this.events),this.ajaxApi=new be({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new ft(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishOptions.productOptions,this.swishOptions.metafields),this.swishUi=new wt(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 st(this,this.swishUi)}static{i(this,"SwishApp")}get options(){return this.swishOptions}get storefrontContext(){return this.swishOptions.storefrontContext}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}};export{it as VERSION,ye as buildShareListUrl,ve as copyToClipboard,Yd as createSwish,Xd as swishSdkUrl};
|
package/package.json
CHANGED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { GetProductCardDataQuery, GetProductCardDataWithVariantQuery } from "../swish";
|
|
2
|
-
export type GetBadgesFunction = (args: GetBadgesArgs) => GetBadgesResult;
|
|
3
|
-
export type GetBadgesArgs = {
|
|
4
|
-
product: GetProductCardDataQuery["product"];
|
|
5
|
-
variant?: GetProductCardDataWithVariantQuery["variant"];
|
|
6
|
-
defaultBadges: string[];
|
|
7
|
-
};
|
|
8
|
-
export type GetBadgesResult = (string | Badge)[];
|
|
9
|
-
export interface Badge {
|
|
10
|
-
id: string;
|
|
11
|
-
label: string;
|
|
12
|
-
style?: Record<string, string>;
|
|
13
|
-
}
|
|
14
|
-
export declare class ShopifyBadgesUtils {
|
|
15
|
-
#private;
|
|
16
|
-
constructor({ getBadges }: {
|
|
17
|
-
getBadges?: GetBadgesFunction;
|
|
18
|
-
});
|
|
19
|
-
getBadges({ product, variant }: Omit<GetBadgesArgs, "defaultBadges">): Badge[];
|
|
20
|
-
getDefaultBadges({ product, variant }: Omit<GetBadgesArgs, "defaultBadges">): string[];
|
|
21
|
-
mapBadges(badges: (string | Badge)[]): Badge[];
|
|
22
|
-
}
|