@swishapp/sdk 0.61.0 → 0.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/intents/handlers/open-quick-buy-handler.d.ts +1 -1
- package/dist/intents/intent-handler.d.ts +3 -1
- package/dist/intents/intent-hook.d.ts +6 -4
- package/dist/intents/intents.d.ts +15 -5
- package/dist/options/swish-options.d.ts +14 -0
- package/dist/options/types.d.ts +118 -0
- package/dist/state/index.d.ts +1 -0
- package/dist/storefront-api/load-product-card-data.d.ts +4 -2
- package/dist/storefront-api/load-product-detail-data.d.ts +4 -2
- package/dist/storefront-api/load-product-images.d.ts +4 -1
- package/dist/storefront-api/load-product-options.d.ts +4 -1
- package/dist/storefront-api/load-product-recommendations.d.ts +4 -2
- package/dist/storefront-api/load-save-intent-data.d.ts +8 -7
- package/dist/storefront-api/load-selected-variant.d.ts +4 -2
- package/dist/storefront-api/storefront-api-client.d.ts +120 -10
- package/dist/storefront-api/types/storefront.types.d.ts +107 -1
- package/dist/swish-api/swish-api-client.d.ts +4 -8
- package/dist/swish-ui/swish-ui-element.d.ts +3 -1
- package/dist/swish-ui/swish-ui.d.ts +54 -0
- package/dist/swish-ui/{swish-ui-utils.d.ts → types.d.ts} +4 -37
- package/dist/swish.d.ts +28 -20
- package/dist/swish.js +78 -78
- package/dist/types.d.ts +2 -45
- package/dist/utils/shop-bridge.d.ts +4 -2
- package/dist/utils/shopify-badge-utils.d.ts +22 -0
- package/package.json +9 -9
- package/dist/index.d.ts +0 -9
package/dist/swish.js
CHANGED
|
@@ -1,29 +1,18 @@
|
|
|
1
|
-
var
|
|
1
|
+
var pn=Object.create;var Qe=Object.defineProperty;var dn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var s=(r,e)=>Qe(r,"name",{value:e,configurable:!0});var mn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var vn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fn(e))!yn.call(r,i)&&i!==t&&Qe(r,i,{get:()=>e[i],enumerable:!(n=dn(e,i))||n.enumerable});return r};var gn=(r,e,t)=>(t=r!=null?pn(hn(r)):{},vn(e||!r||!r.__esModule?Qe(t,"default",{value:r,enumerable:!0}):t,r));var sn=mn((Wu,nn)=>{"use strict";var Ni=(function(){function r(t,n){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=Fi(n),this._batchScheduleFn=Hi(n),this._cacheKeyFn=Qi(n),this._cacheMap=zi(n),this._batch=null,this.name=Wi(n)}s(r,"DataLoader");var e=r.prototype;return e.load=s(function(n){if(n==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(n)+"."));var i=Gi(this),o=this._cacheMap,a;if(o){a=this._cacheKeyFn(n);var u=o.get(a);if(u){var l=i.cacheHits||(i.cacheHits=[]);return new Promise(function(p){l.push(function(){p(u)})})}}i.keys.push(n);var c=new Promise(function(p,f){i.callbacks.push({resolve:p,reject:f})});return o&&o.set(a,c),c},"load"),e.loadMany=s(function(n){if(!rn(n))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+n+"."));for(var i=[],o=0;o<n.length;o++)i.push(this.load(n[o]).catch(function(a){return a}));return Promise.all(i)},"loadMany"),e.clear=s(function(n){var i=this._cacheMap;if(i){var o=this._cacheKeyFn(n);i.delete(o)}return this},"clear"),e.clearAll=s(function(){var n=this._cacheMap;return n&&n.clear(),this},"clearAll"),e.prime=s(function(n,i){var o=this._cacheMap;if(o){var a=this._cacheKeyFn(n);if(o.get(a)===void 0){var u;i instanceof Error?(u=Promise.reject(i),u.catch(function(){})):u=Promise.resolve(i),o.set(a,u)}}return this},"prime"),r})(),Mi=typeof process=="object"&&typeof process.nextTick=="function"?function(r){Dt||(Dt=Promise.resolve()),Dt.then(function(){process.nextTick(r)})}:typeof setImmediate=="function"?function(r){setImmediate(r)}:function(r){setTimeout(r)},Dt;function Gi(r){var e=r._batch;if(e!==null&&!e.hasDispatched&&e.keys.length<r._maxBatchSize)return e;var t={hasDispatched:!1,keys:[],callbacks:[]};return r._batch=t,r._batchScheduleFn(function(){ji(r,t)}),t}s(Gi,"getCurrentBatch");function ji(r,e){if(e.hasDispatched=!0,e.keys.length===0){Pt(e);return}var t;try{t=r._batchLoadFn(e.keys)}catch(n){return Rt(r,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(n)+".")))}if(!t||typeof t.then!="function")return Rt(r,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(n){if(!rn(n))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(n)+"."));if(n.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(n)));Ft(e);for(var s=0;s<e.callbacks.length;s++){var o=n[s];o instanceof Error?e.callbacks[s].reject(o):e.callbacks[s].resolve(o)}}).catch(function(n){Mt(t,e,n)})}i(Cs,"dispatchBatch");function Mt(t,e,r){Ft(e);for(var n=0;n<e.keys.length;n++)t.clear(e.keys[n]),e.callbacks[n].reject(r)}i(Mt,"failedDispatch");function Ft(t){if(t.cacheHits)for(var e=0;e<t.cacheHits.length;e++)t.cacheHits[e]()}i(Ft,"resolveCacheHits");function xs(t){var e=!t||t.batch!==!1;if(!e)return 1;var r=t&&t.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError("maxBatchSize must be a positive number: "+r);return r}i(xs,"getValidMaxBatchSize");function Ss(t){var e=t&&t.batchScheduleFn;if(e===void 0)return ws;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}i(Ss,"getValidBatchScheduleFn");function As(t){var e=t&&t.cacheKeyFn;if(e===void 0)return function(r){return r};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}i(As,"getValidCacheKeyFn");function Ds(t){var e=!t||t.cache!==!1;if(!e)return null;var r=t&&t.cacheMap;if(r===void 0)return new Map;if(r!==null){var n=["get","set","delete","clear"],s=n.filter(function(o){return r&&typeof r[o]!="function"});if(s.length!==0)throw new TypeError("Custom cacheMap missing methods: "+s.join(", "))}return r}i(Ds,"getValidCacheMap");function ks(t){return t&&t.name?t.name:null}i(ks,"getValidName");function Pn(t){return typeof t=="object"&&t!==null&&typeof t.length=="number"&&(t.length===0||t.length>0&&Object.prototype.hasOwnProperty.call(t,t.length-1))}i(Pn,"isArrayLike");Tn.exports=bs});var P=i(t=>t.split("/").pop()??"","shopifyGidToId"),E=i((t,e)=>`gid://shopify/${t}/${e}`,"shopifyIdToGid");var K=class{constructor(e,r,n=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=r,this.keyPrefix=n}static{i(this,"FetchCache")}async get(e){try{let r=await caches.open(this.cacheName),n=await r.match(e);if(n&&this.isExpired(n)){await r.delete(e);return}return n}catch(r){console.warn("Cache get error:",r);return}}async set(e,r,n){try{if(n?.includes("no-cache"))return;let s=this.createCacheableResponse(r,n);await(await caches.open(this.cacheName)).put(e,s)}catch(s){console.warn("Cache set error:",s)}}async fetchWithCache(e,r,n){let s=await this.getCacheKey(e,r);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,r,n),a.clone();let u=await fetch(e,r);return u.ok&&await this.set(s,u.clone(),n??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(r){return console.warn("Cache delete error:",r),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,r)=>{try{let n=await caches.open(this.cacheName),s=await n.keys();await Promise.all(s.map(o=>n.delete(o))),e()}catch(n){console.warn("Cache clear error:",n),r(n)}}),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(n=>n.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let r=await caches.open(this.cacheName),n=await r.match(e);return n&&this.isExpired(n)?(await r.delete(e),!1):n!==void 0}catch(r){return console.warn("Cache has error:",r),!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),r=await e.keys(),n=0;for(let o of r){let a=await e.match(o);a&&this.isExpired(a)&&(await e.delete(o),n++)}let s=r.length-n;return{removed:n,remaining:s}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,r){let n=this.getInputUrl(e),s=`${this.keyPrefix}${n}/${JSON.stringify(r)}`,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 r=e.headers.get("Cache-Control");if(!r)return!1;let n=this.parseMaxAge(r),s=this.parseStaleWhileRevalidate(r);if(n===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),l=(Date.now()-a)/1e3,c=n+(s??0);return l>c}isStaleButRevalidatable(e){let r=e.headers.get("Cache-Control");if(!r)return!1;let n=this.parseMaxAge(r),s=this.parseStaleWhileRevalidate(r);if(n===null||s===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),l=(Date.now()-a)/1e3;return l>n&&l<=n+s}async revalidateInBackground(e,r,n,s){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let a=await fetch(r,n);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 r=new RegExp(/max-age=(\d+)/).exec(e);return r?parseInt(r[1],10):null}parseStaleWhileRevalidate(e){let r=new RegExp(/stale-while-revalidate=(\d+)/).exec(e);return r?parseInt(r[1],10):null}createCacheableResponse(e,r){let n=new Headers(e.headers);return n.set("Cache-Control",r),n.has("Date")||n.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}};var Ce=class{static{i(this,"AjaxApiClient")}constructor(e){this.config=e,this.cache=new K("ajax-api","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,r=this.config.responseInterceptor,n=this.getFetchRequest.bind(this);window.fetch=function(...s){let o=e.apply(this,s);if(typeof r=="function"){let a=n(s[0]);o.then(u=>r(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,r){return(e instanceof Request?e.method:r?.method??"GET")==="GET"?this.cache.fetchWithCache(e,r):fetch(e,r)}async request(e,r={}){let n=`${this.getBaseUrl()}${e}`,s={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(n,{...r,headers:{...s,...r.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 r={...e,items:e.items.map(n=>{let s=P(n.id);if(!s)throw new Error(`Invalid Shopify GID format: ${n.id}`);let o=parseInt(s,10);if(isNaN(o))throw new Error(`Invalid numeric ID extracted from GID: ${n.id}`);return{...n,id:o}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(r)})}async clearCache(){await this.cache.clear()}};var xe=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,r){try{let n=this.getEventName(r.url);if(n){let s=await e.clone().json();this.eventBus.publish(n,s)}}catch(n){console.warn(n)}}getEventName(e){for(let[r,n]of Object.entries(this.eventMap))if(e.includes(r))return n;return null}};function Hn(){let t=document.body||document.documentElement;return t?Promise.resolve(t):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(t))})}i(Hn,"waitForDOM");function ge({onElementFound:t,selector:e,observerOptions:r}){let n=new WeakSet,s=new MutationObserver(l=>{let c=!1;for(let p of l)if(p.addedNodes.length>0){c=!0;break}c&&o()}),o=i(()=>{document.querySelectorAll(e).forEach(l=>{n.has(l)||(a(l),n.add(l))})},"locateElements"),a=i(l=>{if(!r){t(l);return}let c=new IntersectionObserver(p=>{for(let h of p)h.isIntersecting&&(c.disconnect(),t(l))},r);c.observe(l)},"observeElement");return i(async()=>{let l=await Hn();o(),s.observe(l,{childList:!0,subtree:!0})},"locateAndObserveElements")(),s}i(ge,"createElementLocator");function de({onLocationChange:t,fireOnInit:e=!1}){let r=i(()=>{t(window.location)},"handleChange");window.addEventListener("popstate",r);let n=history.pushState,s=history.replaceState;return history.pushState=function(...o){n.apply(this,o),r()},history.replaceState=function(...o){s.apply(this,o),r()},e&&r(),()=>{window.removeEventListener("popstate",r),history.pushState=n,history.replaceState=s}}i(de,"createLocationObserver");function Yt({element:t,onHrefChange:e}){let r=i(()=>{e(t.href)},"handleChange"),n=new MutationObserver(()=>{r()});return n.observe(t,{attributes:!0,attributeFilter:["href"]}),()=>{n.disconnect()}}i(Yt,"createHrefObserver");var Se=class{constructor(){this.eventBus=new EventTarget}static{i(this,"EventBus")}subscribe(e,r,n){return Array.isArray(e)||(e=[e]),e.forEach(s=>{this.eventBus.addEventListener(s,r,n)}),()=>{e.forEach(s=>{this.eventBus.removeEventListener(s,r,n)})}}unsubscribe(e,r,n){this.eventBus.removeEventListener(e,r,n)}publish(e,r){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:r}))}};var it;function ot(t){return{lang:t?.lang??it?.lang,message:t?.message,abortEarly:t?.abortEarly??it?.abortEarly,abortPipeEarly:t?.abortPipeEarly??it?.abortPipeEarly}}i(ot,"getGlobalConfig");var Qn;function zn(t){return Qn?.get(t)}i(zn,"getGlobalMessage");var Wn;function Xn(t){return Wn?.get(t)}i(Xn,"getSchemaMessage");var Kn;function Yn(t,e){return Kn?.get(t)?.get(e)}i(Yn,"getSpecificMessage");function st(t){let e=typeof t;return e==="string"?`"${t}"`:e==="number"||e==="bigint"||e==="boolean"?`${t}`:e==="object"||e==="function"?(t&&Object.getPrototypeOf(t)?.constructor?.name)??"null":e}i(st,"_stringify");function J(t,e,r,n,s){let o=s&&"input"in s?s.input:r.value,a=s?.expected??t.expects??null,u=s?.received??st(o),l={kind:t.kind,type:t.type,input:o,expected:a,received:u,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${u}`,requirement:t.requirement,path:s?.path,issues:s?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},c=t.kind==="schema",p=s?.message??t.message??Yn(t.reference,l.lang)??(c?Xn(l.lang):null)??n.message??zn(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),c&&(r.typed=!1),r.issues?r.issues.push(l):r.issues=[l]}i(J,"_addIssue");function ne(t){return{version:1,vendor:"valibot",validate(e){return t["~run"]({value:e},ot())}}}i(ne,"_getStandardProps");function Jn(t,e){let r=[...new Set(t)];return r.length>1?`(${r.join(` ${e} `)})`:r[0]??"never"}i(Jn,"_joinExpects");var Zn=class extends Error{static{i(this,"ValiError")}constructor(t){super(t[0].message),this.name="ValiError",this.issues=t}};function at(t,e){return{kind:"validation",type:"min_value",reference:at,async:!1,expects:`>=${t instanceof Date?t.toJSON():st(t)}`,requirement:t,message:e,"~run"(r,n){return r.typed&&!(r.value>=this.requirement)&&J(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():st(r.value)}),r}}}i(at,"minValue");function N(t){return{kind:"transformation",type:"transform",reference:N,async:!1,operation:t,"~run"(e){return e.value=this.operation(e.value),e}}}i(N,"transform");function ei(t,e,r){return typeof t.fallback=="function"?t.fallback(e,r):t.fallback}i(ei,"getFallback");function Zt(t,e,r){return typeof t.default=="function"?t.default(e,r):t.default}i(Zt,"getDefault");function ut(t,e){return{kind:"schema",type:"array",reference:ut,expects:"Array",async:!1,item:t,message:e,get"~standard"(){return ne(this)},"~run"(r,n){let s=r.value;if(Array.isArray(s)){r.typed=!0,r.value=[];for(let o=0;o<s.length;o++){let a=s[o],u=this.item["~run"]({value:a},n);if(u.issues){let l={type:"array",origin:"value",input:s,key:o,value:a};for(let c of u.issues)c.path?c.path.unshift(l):c.path=[l],r.issues?.push(c);if(r.issues||(r.issues=u.issues),n.abortEarly){r.typed=!1;break}}u.typed||(r.typed=!1),r.value.push(u.value)}}else J(this,"type",r,n);return r}}}i(ut,"array");function F(t){return{kind:"schema",type:"number",reference:F,expects:"number",async:!1,message:t,get"~standard"(){return ne(this)},"~run"(e,r){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:J(this,"type",e,r),e}}}i(F,"number");function x(t,e){return{kind:"schema",type:"object",reference:x,expects:"Object",async:!1,entries:t,message:e,get"~standard"(){return ne(this)},"~run"(r,n){let s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.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]:Zt(a),l=a["~run"]({value:u},n);if(l.issues){let c={type:"object",origin:"value",input:s,key:o,value:u};for(let p of l.issues)p.path?p.path.unshift(c):p.path=[c],r.issues?.push(p);if(r.issues||(r.issues=l.issues),n.abortEarly){r.typed=!1;break}}l.typed||(r.typed=!1),r.value[o]=l.value}else if(a.fallback!==void 0)r.value[o]=ei(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(J(this,"key",r,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:s,key:o,value:s[o]}]}),n.abortEarly))break}}else J(this,"type",r,n);return r}}}i(x,"object");function G(t,e){return{kind:"schema",type:"optional",reference:G,expects:`(${t.expects} | undefined)`,async:!1,wrapped:t,default:e,get"~standard"(){return ne(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Zt(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}i(G,"optional");function b(t){return{kind:"schema",type:"string",reference:b,expects:"string",async:!1,message:t,get"~standard"(){return ne(this)},"~run"(e,r){return typeof e.value=="string"?e.typed=!0:J(this,"type",e,r),e}}}i(b,"string");function Jt(t){let e;if(t)for(let r of t)e?e.push(...r.issues):e=r.issues;return e}i(Jt,"_subIssues");function ie(t,e){return{kind:"schema",type:"union",reference:ie,expects:Jn(t.map(r=>r.expects),"|"),async:!1,options:t,message:e,get"~standard"(){return ne(this)},"~run"(r,n){let s,o,a;for(let u of this.options){let l=u["~run"]({value:r.value},n);if(l.typed)if(l.issues)o?o.push(l):o=[l];else{s=l;break}else a?a.push(l):a=[l]}if(s)return s;if(o){if(o.length===1)return o[0];J(this,"type",r,n,{issues:Jt(o)}),r.typed=!0}else{if(a?.length===1)return a[0];J(this,"type",r,n,{issues:Jt(a)})}return r}}}i(ie,"union");function er(t,e,r){let n=t["~run"]({value:e},ot(r));if(n.issues)throw new Zn(n.issues);return n.value}i(er,"parse");function V(...t){return{...t[0],pipe:t,get"~standard"(){return ne(this)},"~run"(e,r){for(let n of t)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!r.abortEarly&&!r.abortPipeEarly)&&(e=n["~run"](e,r))}return e}}}i(V,"pipe");function O(t,e,r){let n=t["~run"]({value:e},ot(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}i(O,"safeParse");var C=class{constructor(e,r,n){this.swish=e;this.eventBus=r;this.options=n}static{i(this,"IntentHandler")}};var ti=".swish-shop-bridge{position:absolute!important;top:0!important;left:0!important;padding:0!important;border:0!important;margin:0!important;pointer-events:none!important}.swish-shop-bridge input{appearance:none!important;border:none!important;width:1px!important;height:1px!important;padding:0!important;margin:0!important;background:rgba(0,0,0,0)!important}",ri=`<form class=swish-shop-bridge data-login-with-shop-sign-in=true id=customer_login><input name=customer[email] id=customer_login_email> <input name=return_url type=hidden value=${window.location.pathname}></form>`,lt=class extends HTMLElement{constructor(){super();this.swish=window.swish;this.emailInput=this.querySelector('form[data-login-with-shop-sign-in] input[type="email"],form[data-login-with-shop-sign-in] input[name="customer[email]"'),this.emailInput||(this.innerHTML=`
|
|
8
|
-
|
|
9
|
-
${ri}
|
|
10
|
-
`,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(r=>{r.forEach(n=>{n.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}static{i(this,"ShopBridge")}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&(await Promise.all(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.map(n=>import(`/cdn/shopifycloud/shop-js/${n}`))??[]),window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1}))}catch(r){console.warn("Failed to initialize Shop JS",r)}}update(r){if(r.email&&(this.emailInput.value=r.email,this.emailInput.dispatchEvent(new Event("input"))),r.returnTo){let n=this.querySelector("input[name='return_url']");n&&(n.value=r.returnTo)}}};customElements.define("swish-shop-bridge",lt);var se={baseUrl:"/apps/wishlist",version:"0.0.0"},Ae,De,ke,rr=i(t=>{se=t},"setConfig"),Z=new Map,nr=i(async t=>{if(Z.has(t))return Z.get(t);let e=(async()=>{typeof t=="string"&&(t=await j(t)),!(!t||t.getAttribute("open")!=="true")&&t.setAttribute("open","false")})().finally(()=>{Z.delete(t)});return oi(),Z.set(t,e),e},"hideModal"),Q=i(async t=>{if(Z.has(t))return Z.get(t);let e=(async()=>{typeof t=="string"&&(t=await j(t)),!(!t||t.getAttribute("open")==="true")&&t.setAttribute("open","true")})().finally(()=>{Z.delete(t)});return si(),Z.set(t,e),e},"showModal"),ir=i(async t=>{let e=await j("sign-in",{listeners:{close:i(()=>{t?.onClose?.()},"close")}});e.setAttribute("return-to",t?.returnTo??window.location.pathname),await Q(e)},"showSignIn"),sr=i(async t=>{if(!t.itemId)throw new Error("An itemId is required to show the unsave alert");oe();let e=await j("unsave-alert",{listeners:{submit:i(r=>{r instanceof CustomEvent?t.onSubmit?.(r.detail):console.warn("Unsave alert submitted without detail",r)},"submit"),close:i(()=>{t.onClose?.()},"close")}});e.setAttribute("item-id",t.itemId),await Q(e)},"showUnsaveAlert"),or=i(async t=>{if(!t.listId)throw new Error("A listId is required to show the delete list alert");oe();let e=await j("delete-list-alert",{listeners:{submit:i(()=>{t.onSubmit?.()},"submit"),close:i(()=>{t.onClose?.()},"close")}});e.setAttribute("list-id",t.listId),await Q(e)},"showDeleteListAlert"),ar=i(async t=>{oe();let e=await j("drawer",{listeners:{close:i(()=>{t?.onClose?.()},"close")}});e.setAttribute("account-url",f.routes.accountUrl),f.customer.id&&e.setAttribute("customer-id",f.customer.id),await Q(e)},"showDrawer"),ur=i(async t=>{if(!t.listId)throw new Error("listId is required");oe();let e=await j("list-menu",{listeners:{close:i(r=>{t.onClose?.()},"close"),edit:i(r=>{r instanceof CustomEvent?t.onEdit?.(r.detail):console.warn("List menu submitted without detail",r)},"edit"),delete:i(r=>{r instanceof CustomEvent?t.onDelete?.():console.warn("List menu deleted without detail",r)},"delete")}});e.setAttribute("list-id",t.listId),await Q(e)},"showListMenu"),lr=i(async t=>{if(!t.itemId)throw new Error("itemId is required");oe();let e=await j("list-select",{listeners:{submit:i(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("List select form submitted without detail",r)},"submit"),close:i(()=>{t.onClose?.()},"close"),unsave:i(r=>{r instanceof CustomEvent?t.onUnsave?.(r.detail):console.warn("List select unsave without detail",r)},"unsave")}});e.setAttribute("item-id",t.itemId),await Q(e)},"showListSelect"),cr=i(async(t,e)=>{let r=await j("list-detail-page",{refElement:e});t.listId&&r.setAttribute("list-id",t.listId)},"initListDetailPage"),pr=i(async t=>{await j("toast-manager",{onHydrated:i(e=>{e.current.show(t)},"onHydrated")})},"showToast"),oe=i(async()=>{ct("toast-manager")&&await j("toast-manager",{onHydrated:i(t=>{t.current.clear()},"onHydrated")})},"hideAllToasts"),dr=i(async t=>{oe();let e=await j("variant-select",{listeners:{submit:i(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("Variant select form submitted without detail",r)},"submit"),close:i(()=>{t?.onClose?.()},"close")}});if(t?.productId)e.setAttribute("product-id",t.productId);else if(t?.productHandle)e.setAttribute("product-handle",t.productHandle);else throw new Error("Either productId or productHandle must be provided");t?.variantId&&e.setAttribute("variant-id",t.variantId),t?.displayType&&e.setAttribute("display-type",t.displayType),await Q(e)},"showVariantSelect"),fr=i(async t=>{oe();let e=await j("quick-buy",{listeners:{submit:i(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("Quick buy form submitted without detail",r)},"submit"),close:i(()=>{t?.onClose?.()},"close")}});if(t?.productId)e.setAttribute("product-id",t.productId);else throw new Error("ProductId must be provided");t?.variantId&&e.setAttribute("variant-id",t.variantId),await Q(e)},"showQuickBuy"),Pe=i(async t=>{let e=await j("list-editor",{listeners:{submit:i(async r=>{"detail"in r&&r.detail?t?.onSubmit?.(r.detail):console.warn("List editor form submitted without detail",r)},"submit"),close:i(()=>{t?.onClose?.()},"close")}});t?.listId&&e.setAttribute("list-id",t.listId),await Q(e)},"showListEditor"),hr=i(async({onShopModalOpen:t})=>{let e=document.querySelector("swish-shop-bridge");if(e||(document.body.insertAdjacentHTML("beforeend","<swish-shop-bridge></swish-shop-bridge>"),e=document.querySelector("swish-shop-bridge")),!e)throw new Error("Failed to initialize Shop Bridge");return e.addEventListener("shop-modal-open",()=>t(),{once:!0}),await e.load(),e},"initShopBridge"),be=i(async()=>ke||(ke=fetch(`${se?.baseUrl??""}/ui@${se.version}/manifest.json`).then(t=>t.json()),ke),"loadManifest"),tr=new Map,j=i(async(t,e)=>{let r=await be(),n=r.prerender[t],s=`${se?.baseUrl??""}/ui@${se?.version}/${r.scripts[t]}`,o=e?.instance,a=e?.listeners,u=ct(t,o)??await ii({name:t,template:n,refElement:e?.refElement??document.body,position:"beforeend",instance:o});u.shadowRoot&&!u.hasAttribute("hydrated")?Promise.all([ni(),import(s)]).then(([l,{hydrate:c}])=>{u.shadowRoot&&l&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,l]),c(u),u.setAttribute("hydrated",""),e?.onHydrated?.(u.getComponentRef())}):u.hasAttribute("hydrated")&&e?.onHydrated?.(u.getComponentRef());for(let{event:l,listener:c}of tr.values())u.removeEventListener(l,c);for(let[l,c]of Object.entries(a??{}))tr.set(`${t}-${o}-${l}`,{event:l,listener:c}),u.addEventListener(l,c);return u},"requireUiComponent");async function ni(){return De||(De=new Promise((t,e)=>be().then(r=>r.stylesheets.nonCritical?fetch(`${se?.baseUrl??""}/ui@${se?.version}/${r.stylesheets.nonCritical}`):new Response("")).then(r=>r.text()).then(r=>{let n=new CSSStyleSheet;n.replaceSync(r),t(n)}).catch(e)),De)}i(ni,"loadNonCriticalStylesheet");var ii=i(async({name:t,instance:e,template:r,position:n,refElement:s})=>{s.insertAdjacentHTML(n,r.replace(' shadowrootmode="open"',""));let o=ct(t,e);if(!o)throw new Error(`Element ${t} not found in DOM`);if(!Ae){let a=await be();Ae=new CSSStyleSheet,Ae.replaceSync(a.css.critical)}return o.shadowRoot&&(o.shadowRoot.adoptedStyleSheets=[Ae]),o},"insertComponent"),ct=i((t,e)=>{let r=`swish-ui[ref="${t}${e?`-${e}`:""}"]`;return document.querySelector(r)},"queryComponent"),fe,Ie=0,Re=0,si=i(()=>{Ie++,Ie===1&&(Re=window.scrollY,fe||(fe=new CSSStyleSheet,document.adoptedStyleSheets=[...document.adoptedStyleSheets,fe]),fe.replaceSync(`
|
|
11
|
-
html[locked] body {
|
|
12
|
-
overflow: hidden;
|
|
13
|
-
position: fixed;
|
|
14
|
-
top: -${Re}px;
|
|
15
|
-
left: 0px;
|
|
16
|
-
right: 0px;
|
|
17
|
-
}
|
|
18
|
-
`),document.documentElement.setAttribute("locked",""))},"lockScroll"),oi=i(()=>{Ie>0&&Ie--,Ie===0&&(fe&&fe.replaceSync(""),window.scrollTo({top:Re,behavior:"instant"}),Re=0,document.documentElement.removeAttribute("locked"))},"unlockScroll");typeof requestIdleCallback=="function"?requestIdleCallback(()=>{be()}):setTimeout(()=>{be()},1e3);var ai=x({itemId:G(V(b())),productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()))}),he=class extends C{static{i(this,"EditItemVariantHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(ai,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(c=>c.message)});return}let{itemId:a,productId:u,variantId:l}=o.output;dr({productId:u.toString(),variantId:l?.toString(),onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async c=>{let{item:p,product:h,variant:v}=c,y={code:"ok",data:{item:p,product:h,variant:v}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemVariant",{detail:y})),n(y)},"onSubmit")})})}};var ui=x({productId:V(ie([V(b(),N(P)),F()]),N(t=>Number(t)),F()),variantId:G(V(ie([V(b(),N(P)),F()]),N(Number),F())),quantity:G(V(F(),at(1))),tags:G(ut(b()))}),Te=class extends C{static{i(this,"CreateItemHandler")}async invoke(e){let r=e.data,n=O(ui,r);if(!n.success)return{code:"error",message:"Invalid intent data",issues:n.issues.map(v=>v.message)};let{productId:s,variantId:o,quantity:a,tags:u}=n.output,l=await this.swish.storefront.loadSaveIntentData({productId:E("Product",s),variantId:o?E("ProductVariant",o):void 0});if(l.errors)return{code:"error",message:l.errors.message??"Failed to load save intent data",issues:l.errors.graphQLErrors?.map(v=>v.message)??[]};if(!l.data||!l.data.product)return{code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=l.data,p=c.variantsCount?.count&&c.variantsCount.count>1;if(!p||this.options.allowSaveWithoutVariant){let v=i(()=>!p&&c.selectedOrFirstAvailableVariant?Number(P(c.selectedOrFirstAvailableVariant.id)):o,"variantIdToUse"),y=await this.swish.api.items.create({productId:s,variantId:v(),quantity:a,tags:u});if("error"in y)return{code:"error",message:"Failed to create item",issues:[y.error.message]};if(!y.data)return{code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let R="variant"in l.data?l.data.variant:void 0,m={code:"ok",data:{item:y.data,product:c,variant:p?R:c.selectedOrFirstAvailableVariant}};return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:m})),m}let h=await new he(this.swish,this.eventBus,this.options).invoke({action:"edit",type:"swish/ItemVariant",data:{productId:s,variantId:o}});return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:h})),h}};var _e=class extends C{static{i(this,"CreateListHandler")}async invoke(e){return new Promise(r=>{Pe({onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async n=>{let{list:s}=n;r({code:"ok",data:{list:s}})},"onSubmit")})})}};var li=x({itemId:b()}),Oe=class extends C{static{i(this,"DeleteItemHandler")}async invoke(e){return new Promise(r=>{let n=O(li,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)});return}let{itemId:s}=n.output;sr({itemId:s,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(()=>{r({code:"ok",data:{itemId:s}})},"onSubmit")})})}};var ci=x({listId:b()}),Le=class extends C{static{i(this,"DeleteListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(ci,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;or({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async()=>{r({code:"ok",data:{listId:o}})},"onSubmit")})})}};var pi=x({itemId:b()}),$e=class extends C{static{i(this,"EditItemListsHandler")}async invoke(e,r=!1){return new Promise(n=>{let s=e.data,o=O(pi,s);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(u=>u.message)});return}let{itemId:a}=o.output;lr({itemId:a,onClose:i(()=>{n({code:"closed"})},"onClose"),onSubmit:i(async u=>{let{item:l,product:c,variant:p}=u,h={code:"ok",data:{item:l,product:c,variant:p}};r||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemLists",{detail:h})),n(h)},"onSubmit"),onUnsave(u){let l={code:"ok",data:{itemId:u.itemId}};n(l)}})})}};var di=x({listId:b()}),Ve=class extends C{static{i(this,"EditListHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(di,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;Pe({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(async a=>{let{list:u}=a;r({code:"ok",data:{list:u}})},"onSubmit")})})}};var qe=class extends C{static{i(this,"OpenHomeHandler")}async invoke(e){return new Promise(r=>{ar({onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var fi=x({listId:b()}),Be=class extends C{static{i(this,"OpenListMenuHandler")}async invoke(e){return new Promise(r=>{let n=e.data,s=O(fi,n);if(!s.success){r({code:"error",message:"Invalid intent data",issues:s.issues.map(a=>a.message)});return}let{listId:o}=s.output;ur({listId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onEdit:i(a=>{r({code:"ok",data:a})},"onEdit"),onDelete:i(()=>{r({code:"ok",data:{listId:o}})},"onDelete")})})}};var Mo=x({returnTo:G(b())}),Ne=class extends C{static{i(this,"OpenSignInHandler")}async invoke(e){return new Promise(r=>{ir({returnTo:e.data?.returnTo,onClose:i(()=>{r({code:"closed"})},"onClose")})})}};var hi=x({productId:b(),variantId:G(b())}),Ge=class extends C{static{i(this,"OpenQuickBuyHandler")}async invoke(e){return new Promise(r=>{let n=O(hi,e.data);if(!n.success){r({code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)});return}let{productId:s,variantId:o}=n.output;fr({productId:s,variantId:o,onClose:i(()=>{r({code:"closed"})},"onClose"),onSubmit:i(a=>{r({code:"ok",data:a})},"onSubmit")})})}};var ye=class{constructor(e,r){this.swish=e;this.options=r}static{i(this,"IntentHook")}};var je=class extends ye{static{i(this,"AfterCreateItemHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){let{item:r,product:n,variant:s}=e.data;n&&this.swish.ui.showToast({title:"Saved",text:n.title,image:s?.image?.url??n.featuredImage?.url,action:{label:"Add to List",onClick:i(()=>{this.swish.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:r.id}})},"onClick")}})}}};var Ue=class extends ye{static{i(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.showToastAfterSave&&e.code==="ok"){if("itemId"in e.data)return;let{product:r,variant:n}=e.data;r&&this.swish.ui.showToast({title:"Saved",text:r.title,image:n?.image?.url??r.featuredImage?.url,action:{label:"View",onClick:i(()=>{this.swish.intents.invoke({action:"open",type:"swish/Home"})},"onClick")}})}}};var Me=class{static{i(this,"Intents")}constructor(e,r){this.swish=e,this.eventBus=new EventTarget,this.options=r,this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,r){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,r)}async invoke(e){let r=this.parseIntent(e),n=this.getIntentQuery(r),s={lifecycle:"before",intent:r};return this.publishAnalyticsEvent("swish-intent",s),this.publishAnalyticsEvent(`swish-intent=${n}`,s),{intent:r,complete:this.handleIntent(r).then(o=>{let a={lifecycle:"after",intent:r,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${n}`,a),o})}}listen(e,r){let n=this.getIntentQuery(e),s=i(a=>{"detail"in a&&a.detail?r(a.detail):console.warn("Intent response event without detail",a)},"eventListener"),o=i(()=>{this.eventBus.removeEventListener(n,s)},"unsubscribe");return this.eventBus.addEventListener(n,s),o}getIntentQuery(e){return`${e.action}:${e.type}`}parseIntent(e){if(typeof e=="string"){let[r,...n]=e.split(","),[s,o]=r.split(":"),a=n.reduce((u,l)=>{let[c,p]=l.split("=");return u[c]=p,u},{});return{action:s,type:o,data:a}}return e}async handleIntent(e){return e.action==="create"&&e.type==="swish/Item"?new Te(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/Item"?new Oe(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemVariant"?new he(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemLists"?new $e(this.swish,this.eventBus,this.options).invoke(e):e.action==="create"&&e.type==="swish/List"?new _e(this.swish,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/List"?new Ve(this.swish,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/List"?new Le(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/Home"?new qe(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/ListMenu"?new Be(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/SignIn"?new Ne(this.swish,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/QuickBuy"?new Ge(this.swish,this.eventBus,this.options).invoke(e):{code:"error",message:"Invalid intent",issues:["Invalid intent"]}}initIntentHooks(){this.eventBus.addEventListener("create:swish/Item",e=>{new je(this.swish,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:swish/ItemLists",e=>{new Ue(this.swish,this.options).invoke(e.detail)})}initIntentWatcher(){ge({selector:"[swish-intent]",onElementFound:i(e=>{let r=this.parseIntent(e.getAttribute("swish-intent"));r&&e.addEventListener("click",()=>{this.invoke(r)})},"onElementFound")}),ge({selector:"a[href*='swish-intent=']",onElementFound:i(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",r=>{if(!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&!r.altKey){let s=new URL(e.href).searchParams.get("swish-intent");if(s){let o=this.parseIntent(s);o&&(r.preventDefault(),r.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),de({fireOnInit:!0,onLocationChange:i(e=>{let r=new URLSearchParams(window.location.search).get("swish-intent");if(r){let n=this.parseIntent(r);if(n){this.invoke(n);let s=new URL(window.location.href);s.searchParams.delete("swish-intent"),window.history.replaceState({},document.title,s.toString())}}},"onLocationChange")})}};var yi=Symbol.for("preact-signals");function He(){if(ee>1)ee--;else{for(var t,e=!1;we!==void 0;){var r=we;for(we=void 0,pt++;r!==void 0;){var n=r.o;if(r.o=void 0,r.f&=-3,!(8&r.f)&&vr(r))try{r.c()}catch(s){e||(t=s,e=!0)}r=n}}if(pt=0,ee--,e)throw t}}i(He,"t");function te(t){if(ee>0)return t();ee++;try{return t()}finally{He()}}i(te,"r");var I=void 0;function yr(t){var e=I;I=void 0;try{return t()}finally{I=e}}i(yr,"n");var we=void 0,ee=0,pt=0,Fe=0;function mr(t){if(I!==void 0){var e=t.n;if(e===void 0||e.t!==I)return e={i:0,S:t,p:I.s,n:void 0,t:I,e:void 0,x:void 0,r:e},I.s!==void 0&&(I.s.n=e),I.s=e,t.n=e,32&I.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=I.s,e.n=void 0,I.s.n=e,I.s=e),e}}i(mr,"e");function q(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(q,"u");q.prototype.brand=yi;q.prototype.h=function(){return!0};q.prototype.S=function(t){var e=this,r=this.t;r!==t&&t.e===void 0&&(t.x=r,this.t=t,r!==void 0?r.e=t:yr(function(){var n;(n=e.W)==null||n.call(e)}))};q.prototype.U=function(t){var e=this;if(this.t!==void 0){var r=t.e,n=t.x;r!==void 0&&(r.x=n,t.e=void 0),n!==void 0&&(n.e=r,t.x=void 0),t===this.t&&(this.t=n,n===void 0&&yr(function(){var s;(s=e.Z)==null||s.call(e)}))}};q.prototype.subscribe=function(t){var e=this;return M(function(){var r=e.value,n=I;I=void 0;try{t(r)}finally{I=n}},{name:"sub"})};q.prototype.valueOf=function(){return this.value};q.prototype.toString=function(){return this.value+""};q.prototype.toJSON=function(){return this.value};q.prototype.peek=function(){var t=I;I=void 0;try{return this.value}finally{I=t}};Object.defineProperty(q.prototype,"value",{get:i(function(){var t=mr(this);return t!==void 0&&(t.i=this.i),this.v},"get"),set:i(function(t){if(t!==this.v){if(pt>100)throw new Error("Cycle detected");this.v=t,this.i++,Fe++,ee++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{He()}}},"set")});function S(t,e){return new q(t,e)}i(S,"d");function vr(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}i(vr,"c");function gr(t){for(var e=t.s;e!==void 0;e=e.n){var r=e.S.n;if(r!==void 0&&(e.r=r),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}i(gr,"a");function Ir(t){for(var e=t.s,r=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):r=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}t.s=r}i(Ir,"l");function ae(t,e){q.call(this,void 0),this.x=t,this.s=void 0,this.g=Fe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}i(ae,"y");ae.prototype=new q;ae.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Fe))return!0;if(this.g=Fe,this.f|=1,this.i>0&&!vr(this))return this.f&=-2,!0;var t=I;try{gr(this),I=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(r){this.v=r,this.f|=16,this.i++}return I=t,Ir(this),this.f&=-2,!0};ae.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}q.prototype.S.call(this,t)};ae.prototype.U=function(t){if(this.t!==void 0&&(q.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ae.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ae.prototype,"value",{get:i(function(){if(1&this.f)throw new Error("Cycle detected");var t=mr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v},"get")});function U(t,e){return new ae(t,e)}i(U,"w");function br(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ee++;var r=I;I=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,dt(t),n}finally{I=r,He()}}}i(br,"_");function dt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,br(t)}i(dt,"b");function mi(t){if(I!==this)throw new Error("Out-of-order effect");Ir(this),I=t,this.f&=-2,8&this.f&&dt(this),He()}i(mi,"g");function me(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}i(me,"p");me.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};me.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,br(this),gr(this),ee++;var t=I;return I=this,mi.bind(this,t)};me.prototype.N=function(){2&this.f||(this.f|=2,this.o=we,we=this)};me.prototype.d=function(){this.f|=8,1&this.f||dt(this)};me.prototype.dispose=function(){this.d()};function M(t,e){var r=new me(t,e);try{r.c()}catch(s){throw r.d(),s}var n=r.d.bind(r);return n[Symbol.dispose]=n,n}i(M,"E");var vi=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,ft=i(t=>{let e=t.match(vi);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),wr=i(({source:t,onProductUrlChange:e})=>{let r=i(n=>{let s=ft(n);s?.productHandle&&e(s)},"handleChange");if(t instanceof HTMLAnchorElement)return Yt({element:t,onHrefChange:i(n=>r(n),"onHrefChange")});if(t instanceof Location)return de({onLocationChange:i(n=>r(n.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Er=i(t=>e=>{let{productHandle:r,productId:n,variantId:s,itemId:o}=e?.dataset??{},l=!!(n||r)||!!o,c=S({loading:!1,productId:n,variantId:s,itemId:o});if(!l){let p=e instanceof HTMLAnchorElement?e:window.location,h=ft(p.href);h?.productHandle&&h.productHandle!==c.value.productHandle&&(c.value={...c.value,...h,productId:void 0},wr({source:p,onProductUrlChange:i(v=>{c.value={...c.value,...v,productId:v.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return M(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},t.storefront.loadProductId({productHandle:c.value.productHandle}).then(p=>{p.errors&&console.error("Error loading product id",p.errors),c.value={...c.value,productId:p.data?.product?.id?P(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var Cr=i(t=>e=>{let r=U(()=>{let{productId:w,variantId:g,loading:T}=e.value;return!w||T?null:g?`variant:${P(g)}`:`product:${P(w)}`}),n=U(()=>e.value.loading||!!e.value.itemId||!e.value.productId),s=U(()=>({limit:1,query:r.value??void 0})),o=S(!n.value),a=S(null),u=S(!1),l=S(!1),{data:c,loading:p,error:h,refetching:v}=t.state.swishQuery(w=>t.api.items.list(w),{refetch:["item-create","item-update","item-delete"],variables:s,skip:n}),y=S(e.value.itemId??null);M(()=>{te(()=>{if(o.value=p.value,a.value=h.value,!e.value.itemId){let w=c.value?.[0]?.id??null;w!==y.value&&(y.value=w)}})});async function R(){if(!y.value)return;u.value=!0,(await(await t.intents.invoke({action:"delete",type:"swish/Item",data:{itemId:y.value}})).complete).code==="ok"&&(y.value=null),u.value=!1}i(R,"unsave");async function m(){if(!y.value)return;u.value=!0;let g=await(await t.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:y.value}})).complete;g.code==="ok"&&"itemId"in g.data&&(y.value=null),u.value=!1}i(m,"update");async function D(){let{productId:w,variantId:g}=e.value;if(!w)return;u.value=!0,l.value=!0;let _=await(await t.intents.invoke({action:"create",type:"swish/Item",data:{productId:w,variantId:g}})).complete;if(_.code==="ok"){let ve=_.data;y.value=ve.item.id,u.value=!1}else _.code==="error"&&console.warn("Failed to create item",_),te(()=>{u.value=!1,l.value=!1})}i(D,"save");let $=U(()=>o.value||u.value||e.value.loading);M(()=>{l.value&&!u.value&&!v.value&&(l.value=!1)});let k=U(()=>{let w=v.value&&l.value,g=!!y.value,T=!g&&(u.value||w),_=g&&(u.value||w),ve=U(()=>T?"saving":_?"unsaving":g?"saved":"unsaved");return{error:a.value,status:ve.value,savedItemId:y.value,loading:$.value,submitting:u.value,saved:g,saving:T,unsaving:_}});async function z(){$.value||(k.value.saved&&k.value.savedItemId?m():k.value.saved||await D())}return i(z,"toggle"),Object.assign(k,{save:D,unsave:R,update:m,toggle:z})},"itemStateSignal");var xr=i(t=>()=>{let{data:e,loading:r,error:n}=t.state.swishQuery(()=>t.api.items.count(),{refetch:["item-create","item-delete"]}),s=S(0),o=S(!0),a=S(null);return M(()=>{te(()=>{o.value=r.value,a.value=n.value,s.value=e.value?.count??0})}),U(()=>({count:s.value,loading:o.value,error:a.value}))},"itemCountSignal");var Sr=i(t=>(e,r)=>{let n=S(null),s=S(null),o=S(null),a=S(!r?.skip),u=S(!1),l=U(()=>a.value&&u.value);async function c(){if(!r?.skip?.value)try{a.value=!0;let p=await e(r?.variables?.value);te(()=>{o.value="error"in p?p.error:null,n.value="data"in p?p.data:null,s.value="pageInfo"in p?p.pageInfo:null,a.value=!1,u.value=!0})}catch(p){te(()=>{o.value=p,a.value=!1,u.value=!0})}}return i(c,"executeFetch"),M(()=>{if(c(),r?.refetch?.length)return t.events.subscribe(r.refetch,c)}),{data:n,pageInfo:s,error:o,loading:a,refetching:l}},"swishQuerySignals");var ue="GraphQL Client";var ht="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",yt="Response returned unexpected Content-Type:",mt="An unknown error has occurred. The API did not return a data object or any errors in its response.",Qe={json:"application/json",multipart:"multipart/mixed"},vt="X-SDK-Variant",gt="X-SDK-Version",Dr="shopify-graphql-client",kr="1.4.1",ze=1e3,Rr=[429,503],It=/@(defer)\b/i,Ar=`\r
|
|
19
|
-
`,Pr=/boundary="?([^=";]+)"?/i,bt=Ar+Ar;function X(t,e=ue){return t.startsWith(`${e}`)?t:`${e}: ${t}`}i(X,"formatErrorMessage");function Y(t){return t instanceof Error?t.message:JSON.stringify(t)}i(Y,"getErrorMessage");function wt(t){return t instanceof Error&&t.cause?t.cause:void 0}i(wt,"getErrorCause");function Et(t){return t.flatMap(({errors:e})=>e??[])}i(Et,"combineErrors");function We({client:t,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${t}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}i(We,"validateRetries");function B(t,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[t]:e}:{}}i(B,"getKeyValueIfValid");function Ct(t,e){if(t.length===0)return e;let n={[t.pop()]:e};return t.length===0?n:Ct(t,n)}i(Ct,"buildDataObjectByPath");function Or(t,e){return Object.keys(e||{}).reduce((r,n)=>(typeof e[n]=="object"||Array.isArray(e[n]))&&t[n]?(r[n]=Or(t[n],e[n]),r):(r[n]=e[n],r),Array.isArray(t)?[...t]:{...t})}i(Or,"combineObjects");function xt([t,...e]){return e.reduce(Or,{...t})}i(xt,"buildCombinedDataObject");function St({clientLogger:t,customFetchApi:e=fetch,client:r=ue,defaultRetryWaitTime:n=ze,retriableCodes:s=Rr}){let o=i(async(a,u,l)=>{let c=u+1,p=l+1,h;try{if(h=await e(...a),t({type:"HTTP-Response",content:{requestParams:a,response:h}}),!h.ok&&s.includes(h.status)&&c<=p)throw new Error;let v=h?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return v&&t({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:a,deprecationNotice:v}}),h}catch(v){if(c<=p){let y=h?.headers.get("Retry-After");return await gi(y?parseInt(y,10):n),t({type:"HTTP-Retry",content:{requestParams:a,lastResponse:h,retryAttempt:u,maxRetries:l}}),o(a,c,l)}throw new Error(X(`${l>0?`Attempted maximum number of ${l} network retries. Last message - `:""}${Y(v)}`,r))}},"httpFetch");return o}i(St,"generateHttpFetch");async function gi(t){return new Promise(e=>setTimeout(e,t))}i(gi,"sleep");function At({headers:t,url:e,customFetchApi:r=fetch,retries:n=0,logger:s}){We({client:ue,retries:n});let o={headers:t,url:e,retries:n},a=Ii(s),u=St({customFetchApi:r,clientLogger:a,defaultRetryWaitTime:ze}),l=bi(u,o),c=wi(l),p=ki(l);return{config:o,fetch:l,request:c,requestStream:p}}i(At,"createGraphQLClient");function Ii(t){return e=>{t&&t(e)}}i(Ii,"generateClientLogger");async function Lr(t){let{errors:e,data:r,extensions:n}=await t.json();return{...B("data",r),...B("extensions",n),headers:t.headers,...e||!r?{errors:{networkStatusCode:t.status,message:X(e?ht:mt),...B("graphQLErrors",e),response:t}}:{}}}i(Lr,"processJSONResponse");function bi(t,{url:e,headers:r,retries:n}){return async(s,o={})=>{let{variables:a,headers:u,url:l,retries:c,keepalive:p,signal:h}=o,v=JSON.stringify({query:s,variables:a});We({client:ue,retries:c});let y=Object.entries({...r,...u}).reduce((m,[D,$])=>(m[D]=Array.isArray($)?$.join(", "):$.toString(),m),{});return!y[vt]&&!y[gt]&&(y[vt]=Dr,y[gt]=kr),t([l??e,{method:"POST",headers:y,body:v,signal:h,keepalive:p}],1,c??n)}}i(bi,"generateFetch");function wi(t){return async(...e)=>{if(It.test(e[0]))throw new Error(X("This operation will result in a streamable response - use requestStream() instead."));let r=null;try{r=await t(...e);let{status:n,statusText:s}=r,o=r.headers.get("content-type")||"";return r.ok?o.includes(Qe.json)?await Lr(r):{errors:{networkStatusCode:n,message:X(`${yt} ${o}`),response:r}}:{errors:{networkStatusCode:n,message:X(s),response:r}}}catch(n){return{errors:{message:Y(n),...r==null?{}:{networkStatusCode:r.status,response:r}}}}}}i(wi,"generateRequest");async function*Ei(t){let e=new TextDecoder;if(t.body[Symbol.asyncIterator])for await(let r of t.body)yield e.decode(r);else{let r=t.body.getReader(),n;try{for(;!(n=await r.read()).done;)yield e.decode(n.value)}finally{r.cancel()}}}i(Ei,"getStreamBodyIterator");function Ci(t,e){return{async*[Symbol.asyncIterator](){try{let r="";for await(let n of t)if(r+=n,r.indexOf(e)>-1){let s=r.lastIndexOf(e),a=r.slice(0,s).split(e).filter(u=>u.trim().length>0).map(u=>u.slice(u.indexOf(bt)+bt.length).trim());a.length>0&&(yield a),r=r.slice(s+e.length),r.trim()==="--"&&(r="")}}catch(r){throw new Error(`Error occured while processing stream payload - ${Y(r)}`)}}}}i(Ci,"readStreamChunk");function xi(t){return{async*[Symbol.asyncIterator](){yield{...await Lr(t),hasNext:!1}}}}i(xi,"createJsonResponseAsyncIterator");function Si(t){return t.map(e=>{try{return JSON.parse(e)}catch(r){throw new Error(`Error in parsing multipart response - ${Y(r)}`)}}).map(e=>{let{data:r,incremental:n,hasNext:s,extensions:o,errors:a}=e;if(!n)return{data:r||{},...B("errors",a),...B("extensions",o),hasNext:s};let u=n.map(({data:l,path:c,errors:p})=>({data:l&&c?Ct(c,l):{},...B("errors",p)}));return{data:u.length===1?u[0].data:xt([...u.map(({data:l})=>l)]),...B("errors",Et(u)),hasNext:s}})}i(Si,"getResponseDataFromChunkBodies");function Ai(t,e){if(t.length>0)throw new Error(ht,{cause:{graphQLErrors:t}});if(Object.keys(e).length===0)throw new Error(mt)}i(Ai,"validateResponseData");function Di(t,e){let r=(e??"").match(Pr),n=`--${r?r[1]:"-"}`;if(!t.body?.getReader&&!t.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:t});let s=Ei(t),o={},a;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let l of Ci(s,n)){let c=Si(l);a=c.find(h=>h.extensions)?.extensions??a;let p=Et(c);o=xt([o,...c.map(({data:h})=>h)]),u=c.slice(-1)[0].hasNext,Ai(p,o),yield{...B("data",o),...B("extensions",a),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let l=wt(u);yield{...B("data",o),...B("extensions",a),errors:{message:X(Y(u)),networkStatusCode:t.status,...B("graphQLErrors",l?.graphQLErrors),response:t},hasNext:!1}}}}}i(Di,"createMultipartResponseAsyncInterator");function ki(t){return async(...e)=>{if(!It.test(e[0]))throw new Error(X("This operation does not result in a streamable response - use request() instead."));try{let r=await t(...e),{statusText:n}=r;if(!r.ok)throw new Error(n,{cause:r});let s=r.headers.get("content-type")||"";switch(!0){case s.includes(Qe.json):return xi(r);case s.includes(Qe.multipart):return Di(r,s);default:throw new Error(`${yt} ${s}`,{cause:r})}}catch(r){return{async*[Symbol.asyncIterator](){let n=wt(r);yield{errors:{message:X(Y(r)),...B("networkStatusCode",n?.status),...B("response",n)},hasNext:!1}}}}}}i(ki,"generateRequestStream");function Dt({client:t,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let r=e.trim(),n=r.match(/^https?:/)?r:`https://${r}`,s=new URL(n);return s.protocol="https",s.origin}catch(r){throw new Error(`${t}: a valid store domain ("${e}") must be provided`,{cause:r})}}i(Dt,"validateDomainAndGetStoreUrl");function Xe({client:t,currentSupportedApiVersions:e,apiVersion:r,logger:n}){let s=`${t}: the provided apiVersion ("${r}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!r||typeof r!="string")throw new Error(`${s} is invalid. ${o}`);let a=r.trim();e.includes(a)||(n?n({type:"Unsupported_Api_Version",content:{apiVersion:r,supportedApiVersions:e}}):console.warn(`${s} is likely deprecated or not supported. ${o}`))}i(Xe,"validateApiVersion");function Ke(t){let e=t*3-2;return e===10?e:`0${e}`}i(Ke,"getQuarterMonth");function kt(t,e,r){let n=e-r;return n<=0?`${t-1}-${Ke(n+4)}`:`${t}-${Ke(n)}`}i(kt,"getPrevousVersion");function $r(){let t=new Date,e=t.getUTCMonth(),r=t.getUTCFullYear(),n=Math.floor(e/3+1);return{year:r,quarter:n,version:`${r}-${Ke(n)}`}}i($r,"getCurrentApiVersion");function Rt(){let{year:t,quarter:e,version:r}=$r(),n=e===4?`${t+1}-01`:`${t}-${Ke(e+1)}`;return[kt(t,e,3),kt(t,e,2),kt(t,e,1),r,n,"unstable"]}i(Rt,"getCurrentSupportedApiVersions");function Pt(t){return e=>({...e??{},...t.headers})}i(Pt,"generateGetHeaders");function Tt({getHeaders:t,getApiUrl:e}){return(r,n)=>{let s=[r];if(n&&Object.keys(n).length>0){let{variables:o,apiVersion:a,headers:u,retries:l,signal:c}=n;s.push({...o?{variables:o}:{},...u?{headers:t(u)}:{},...a?{url:e(a)}:{},...l?{retries:l}:{},...c?{signal:c}:{}})}return s}}i(Tt,"generateGetGQLClientParams");var _t="application/json",Vr="storefront-api-client",qr="1.0.9",Br="X-Shopify-Storefront-Access-Token",Nr="Shopify-Storefront-Private-Token",Gr="X-SDK-Variant",jr="X-SDK-Version",Ur="X-SDK-Variant-Source",le="Storefront API Client";function Mr(t){if(t&&typeof window<"u")throw new Error(`${le}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}i(Mr,"validatePrivateAccessTokenUsage");function Fr(t,e){if(!t&&!e)throw new Error(`${le}: a public or private access token must be provided`);if(t&&e)throw new Error(`${le}: only provide either a public or private access token`)}i(Fr,"validateRequiredAccessTokens");function Ot({storeDomain:t,apiVersion:e,publicAccessToken:r,privateAccessToken:n,clientName:s,retries:o=0,customFetchApi:a,logger:u}){let l=Rt(),c=Dt({client:le,storeDomain:t}),p={client:le,currentSupportedApiVersions:l,logger:u};Xe({...p,apiVersion:e}),Fr(r,n),Mr(n);let h=Ri(c,e,p),v={storeDomain:c,apiVersion:e,...r?{publicAccessToken:r}:{privateAccessToken:n},headers:{"Content-Type":_t,Accept:_t,[Gr]:Vr,[jr]:qr,...s?{[Ur]:s}:{},...r?{[Br]:r}:{[Nr]:n}},apiUrl:h(),clientName:s},y=At({headers:v.headers,url:v.apiUrl,retries:o,customFetchApi:a,logger:u}),R=Pt(v),m=Pi(v,h),D=Tt({getHeaders:R,getApiUrl:m});return Object.freeze({config:v,getHeaders:R,getApiUrl:m,fetch:i((...k)=>y.fetch(...D(...k)),"fetch"),request:i((...k)=>y.request(...D(...k)),"request"),requestStream:i((...k)=>y.requestStream(...D(...k)),"requestStream")})}i(Ot,"createStorefrontApiClient");function Ri(t,e,r){return n=>{n&&Xe({...r,apiVersion:n});let s=(n??e).trim();return`${t}/api/${s}/graphql.json`}}i(Ri,"generateApiUrlFormatter");function Pi(t,e){return r=>r?e(r):t.apiUrl}i(Pi,"generateGetApiUrl");var L=`
|
|
7
|
+
`+String(n)));Pt(e);for(var i=0;i<e.callbacks.length;i++){var o=n[i];o instanceof Error?e.callbacks[i].reject(o):e.callbacks[i].resolve(o)}}).catch(function(n){Rt(r,e,n)})}s(ji,"dispatchBatch");function Rt(r,e,t){Pt(e);for(var n=0;n<e.keys.length;n++)r.clear(e.keys[n]),e.callbacks[n].reject(t)}s(Rt,"failedDispatch");function Pt(r){if(r.cacheHits)for(var e=0;e<r.cacheHits.length;e++)r.cacheHits[e]()}s(Pt,"resolveCacheHits");function Fi(r){var e=!r||r.batch!==!1;if(!e)return 1;var t=r&&r.maxBatchSize;if(t===void 0)return 1/0;if(typeof t!="number"||t<1)throw new TypeError("maxBatchSize must be a positive number: "+t);return t}s(Fi,"getValidMaxBatchSize");function Hi(r){var e=r&&r.batchScheduleFn;if(e===void 0)return Mi;if(typeof e!="function")throw new TypeError("batchScheduleFn must be a function: "+e);return e}s(Hi,"getValidBatchScheduleFn");function Qi(r){var e=r&&r.cacheKeyFn;if(e===void 0)return function(t){return t};if(typeof e!="function")throw new TypeError("cacheKeyFn must be a function: "+e);return e}s(Qi,"getValidCacheKeyFn");function zi(r){var e=!r||r.cache!==!1;if(!e)return null;var t=r&&r.cacheMap;if(t===void 0)return new Map;if(t!==null){var n=["get","set","delete","clear"],i=n.filter(function(o){return t&&typeof t[o]!="function"});if(i.length!==0)throw new TypeError("Custom cacheMap missing methods: "+i.join(", "))}return t}s(zi,"getValidCacheMap");function Wi(r){return r&&r.name?r.name:null}s(Wi,"getValidName");function rn(r){return typeof r=="object"&&r!==null&&typeof r.length=="number"&&(r.length===0||r.length>0&&Object.prototype.hasOwnProperty.call(r,r.length-1))}s(rn,"isArrayLike");nn.exports=Ni});var D=s(r=>r.split("/").pop()??"","shopifyGidToId"),w=s((r,e)=>`gid://shopify/${r}/${e}`,"shopifyIdToGid");var Q=class{constructor(e,t,n=""){this.revalidationPromises=new Map;this.inFlightRequests=new Map;this.clearCachePromise=null;this.cacheName=e,this.defaultCacheControl=t,this.keyPrefix=n}static{s(this,"FetchCache")}async get(e){try{let t=await caches.open(this.cacheName),n=await t.match(e);if(n&&this.isExpired(n)){await t.delete(e);return}return n}catch(t){console.warn("Cache get error:",t);return}}async set(e,t,n){try{if(n?.includes("no-cache"))return;let i=this.createCacheableResponse(t,n);await(await caches.open(this.cacheName)).put(e,i)}catch(i){console.warn("Cache set error:",i)}}async fetchWithCache(e,t,n){let i=await this.getCacheKey(e,t);if(this.clearCachePromise&&await this.clearCachePromise,this.inFlightRequests.has(i))return this.inFlightRequests.get(i).then(a=>a.clone());let o=(async()=>{let a=await this.get(i);if(a)return this.isStaleButRevalidatable(a)&&this.revalidateInBackground(i,e,t,n),a.clone();let u=await fetch(e,t);return u.ok&&await this.set(i,u.clone(),n??this.defaultCacheControl),u})().finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,o),o}async delete(e){try{return await(await caches.open(this.cacheName)).delete(e)}catch(t){return console.warn("Cache delete error:",t),!1}}async clear(){return this.clearCachePromise?this.clearCachePromise:(this.clearCachePromise=new Promise(async(e,t)=>{try{let n=await caches.open(this.cacheName),i=await n.keys();await Promise.all(i.map(o=>n.delete(o))),e()}catch(n){console.warn("Cache clear error:",n),t(n)}}),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(n=>n.url)}catch(e){return console.warn("Cache keys error:",e),[]}}async has(e){try{let t=await caches.open(this.cacheName),n=await t.match(e);return n&&this.isExpired(n)?(await t.delete(e),!1):n!==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(),n=0;for(let o of t){let a=await e.match(o);a&&this.isExpired(a)&&(await e.delete(o),n++)}let i=t.length-n;return{removed:n,remaining:i}}catch(e){return console.warn("Cache cleanup error:",e),{removed:0,remaining:0}}}async getCacheKey(e,t){let n=this.getInputUrl(e),i=`${this.keyPrefix}${n}/${JSON.stringify(t)}`,a=new TextEncoder().encode(i),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 n=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(n===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),l=(Date.now()-a)/1e3,c=n+(i??0);return l>c}isStaleButRevalidatable(e){let t=e.headers.get("Cache-Control");if(!t)return!1;let n=this.parseMaxAge(t),i=this.parseStaleWhileRevalidate(t);if(n===null||i===null)return!1;let o=e.headers.get("Date");if(!o)return!1;let a=new Date(o).getTime(),l=(Date.now()-a)/1e3;return l>n&&l<=n+i}async revalidateInBackground(e,t,n,i){if(this.revalidationPromises.has(e))return;let o=(async()=>{try{let a=await fetch(t,n);a.ok&&await this.set(e,a.clone(),i??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 n=new Headers(e.headers);return n.set("Cache-Control",t),n.has("Date")||n.set("Date",new Date().toUTCString()),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}};var ye=class{static{s(this,"AjaxApiClient")}constructor(e){this.config=e,this.cache=new Q("ajax-api","max-age=60, stale-while-revalidate=3600"),this.cache.cleanupExpiredEntries().catch(t=>{console.warn("Ajax API cache initialization cleanup error:",t)})}patchFetch(){if(!window.fetch||typeof window.fetch!="function")return;let e=window.fetch,t=this.config.responseInterceptor,n=this.getFetchRequest.bind(this);window.fetch=function(...i){let o=e.apply(this,i);if(typeof t=="function"){let a=n(i[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 n=`${this.getBaseUrl()}${e}`,i={"Content-Type":"application/json",Accept:"application/json"},o=await this.fetch(n,{...t,headers:{...i,...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(n=>{let i=D(n.id);if(!i)throw new Error(`Invalid Shopify GID format: ${n.id}`);let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid numeric ID extracted from GID: ${n.id}`);return{...n,id:o}})};return this.request("/cart/add.js",{method:"POST",body:JSON.stringify(t)})}async clearCache(){await this.cache.clear()}};var me=class{constructor(e){this.eventMap={"/cart/add":"cart-add","/cart/update":"cart-update","/cart/change":"cart-change","/cart/clear":"cart-clear"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{s(this,"AjaxApiPublisher")}async processFetchResponse(e,t){try{let n=this.getEventName(t.url);if(n){let i=await e.clone().json();this.eventBus.publish(n,i)}}catch(n){console.warn(n)}}getEventName(e){for(let[t,n]of Object.entries(this.eventMap))if(e.includes(t))return n;return null}};function In(){let r=document.body||document.documentElement;return r?Promise.resolve(r):new Promise(e=>{window.addEventListener("DOMContentLoaded",()=>e(r))})}s(In,"waitForDOM");function de({onElementFound:r,selector:e,observerOptions:t}){let n=new WeakSet,i=new MutationObserver(l=>{let c=!1;for(let p of l)if(p.addedNodes.length>0){c=!0;break}c&&o()}),o=s(()=>{document.querySelectorAll(e).forEach(l=>{n.has(l)||(a(l),n.add(l))})},"locateElements"),a=s(l=>{if(!t){r(l);return}let c=new IntersectionObserver(p=>{for(let f of p)f.isIntersecting&&(c.disconnect(),r(l))},t);c.observe(l)},"observeElement");return s(async()=>{let l=await In();o(),i.observe(l,{childList:!0,subtree:!0})},"locateAndObserveElements")(),i}s(de,"createElementLocator");function ae({onLocationChange:r,fireOnInit:e=!1}){let t=s(()=>{r(window.location)},"handleChange");window.addEventListener("popstate",t);let n=history.pushState,i=history.replaceState;return history.pushState=function(...o){n.apply(this,o),t()},history.replaceState=function(...o){i.apply(this,o),t()},e&&t(),()=>{window.removeEventListener("popstate",t),history.pushState=n,history.replaceState=i}}s(ae,"createLocationObserver");function Vt({element:r,onHrefChange:e}){let t=s(()=>{e(r.href)},"handleChange"),n=new MutationObserver(()=>{t()});return n.observe(r,{attributes:!0,attributeFilter:["href"]}),()=>{n.disconnect()}}s(Vt,"createHrefObserver");var ve=class{constructor(){this.eventBus=new EventTarget}static{s(this,"EventBus")}subscribe(e,t,n){return Array.isArray(e)||(e=[e]),e.forEach(i=>{this.eventBus.addEventListener(i,t,n)}),()=>{e.forEach(i=>{this.eventBus.removeEventListener(i,t,n)})}}unsubscribe(e,t,n){this.eventBus.removeEventListener(e,t,n)}publish(e,t){this.eventBus.dispatchEvent(new CustomEvent(e,{detail:t}))}};var ze;function Nt(r){return{lang:r?.lang??ze?.lang,message:r?.message,abortEarly:r?.abortEarly??ze?.abortEarly,abortPipeEarly:r?.abortPipeEarly??ze?.abortPipeEarly}}s(Nt,"getGlobalConfig");var wn;function bn(r){return wn?.get(r)}s(bn,"getGlobalMessage");var En;function Cn(r){return En?.get(r)}s(Cn,"getSchemaMessage");var xn;function Sn(r,e){return xn?.get(r)?.get(e)}s(Sn,"getSpecificMessage");function We(r){let e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&Object.getPrototypeOf(r)?.constructor?.name)??"null":e}s(We,"_stringify");function X(r,e,t,n,i){let o=i&&"input"in i?i.input:t.value,a=i?.expected??r.expects??null,u=i?.received??We(o),l={kind:r.kind,type:r.type,input:o,expected:a,received:u,message:`Invalid ${e}: ${a?`Expected ${a} but r`:"R"}eceived ${u}`,requirement:r.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},c=r.kind==="schema",p=i?.message??r.message??Sn(r.reference,l.lang)??(c?Cn(l.lang):null)??n.message??bn(l.lang);p!==void 0&&(l.message=typeof p=="function"?p(l):p),c&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}s(X,"_addIssue");function Z(r){return{version:1,vendor:"valibot",validate(e){return r["~run"]({value:e},Nt())}}}s(Z,"_getStandardProps");function An(r,e){let t=[...new Set(r)];return t.length>1?`(${t.join(` ${e} `)})`:t[0]??"never"}s(An,"_joinExpects");function Xe(r,e){return{kind:"validation",type:"min_value",reference:Xe,async:!1,expects:`>=${r instanceof Date?r.toJSON():We(r)}`,requirement:r,message:e,"~run"(t,n){return t.typed&&!(t.value>=this.requirement)&&X(this,"value",t,n,{received:t.value instanceof Date?t.value.toJSON():We(t.value)}),t}}}s(Xe,"minValue");function j(r){return{kind:"transformation",type:"transform",reference:j,async:!1,operation:r,"~run"(e){return e.value=this.operation(e.value),e}}}s(j,"transform");function kn(r,e,t){return typeof r.fallback=="function"?r.fallback(e,t):r.fallback}s(kn,"getFallback");function Mt(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}s(Mt,"getDefault");function Ke(r,e){return{kind:"schema",type:"array",reference:Ke,expects:"Array",async:!1,item:r,message:e,get"~standard"(){return Z(this)},"~run"(t,n){let i=t.value;if(Array.isArray(i)){t.typed=!0,t.value=[];for(let o=0;o<i.length;o++){let a=i[o],u=this.item["~run"]({value:a},n);if(u.issues){let l={type:"array",origin:"value",input:i,key:o,value:a};for(let c of u.issues)c.path?c.path.unshift(l):c.path=[l],t.issues?.push(c);if(t.issues||(t.issues=u.issues),n.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value.push(u.value)}}else X(this,"type",t,n);return t}}}s(Ke,"array");function U(r){return{kind:"schema",type:"number",reference:U,expects:"number",async:!1,message:r,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:X(this,"type",e,t),e}}}s(U,"number");function A(r,e){return{kind:"schema",type:"object",reference:A,expects:"Object",async:!1,entries:r,message:e,get"~standard"(){return Z(this)},"~run"(t,n){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let o in this.entries){let a=this.entries[o];if(o in i||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){let u=o in i?i[o]:Mt(a),l=a["~run"]({value:u},n);if(l.issues){let c={type:"object",origin:"value",input:i,key:o,value:u};for(let p of l.issues)p.path?p.path.unshift(c):p.path=[c],t.issues?.push(p);if(t.issues||(t.issues=l.issues),n.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[o]=l.value}else if(a.fallback!==void 0)t.value[o]=kn(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(X(this,"key",t,n,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:i,key:o,value:i[o]}]}),n.abortEarly))break}}else X(this,"type",t,n);return t}}}s(A,"object");function N(r,e){return{kind:"schema",type:"optional",reference:N,expects:`(${r.expects} | undefined)`,async:!1,wrapped:r,default:e,get"~standard"(){return Z(this)},"~run"(t,n){return t.value===void 0&&(this.default!==void 0&&(t.value=Mt(this,t,n)),t.value===void 0)?(t.typed=!0,t):this.wrapped["~run"](t,n)}}}s(N,"optional");function b(r){return{kind:"schema",type:"string",reference:b,expects:"string",async:!1,message:r,get"~standard"(){return Z(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:X(this,"type",e,t),e}}}s(b,"string");function Ut(r){let e;if(r)for(let t of r)e?e.push(...t.issues):e=t.issues;return e}s(Ut,"_subIssues");function ee(r,e){return{kind:"schema",type:"union",reference:ee,expects:An(r.map(t=>t.expects),"|"),async:!1,options:r,message:e,get"~standard"(){return Z(this)},"~run"(t,n){let i,o,a;for(let u of this.options){let l=u["~run"]({value:t.value},n);if(l.typed)if(l.issues)o?o.push(l):o=[l];else{i=l;break}else a?a.push(l):a=[l]}if(i)return i;if(o){if(o.length===1)return o[0];X(this,"type",t,n,{issues:Ut(o)}),t.typed=!0}else{if(a?.length===1)return a[0];X(this,"type",t,n,{issues:Ut(a)})}return t}}}s(ee,"union");function M(...r){return{...r[0],pipe:r,get"~standard"(){return Z(this)},"~run"(e,t){for(let n of r)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}s(M,"pipe");function _(r,e,t){let n=r["~run"]({value:e},Nt(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}s(_,"safeParse");var E=class{constructor(e,t,n,i){this.swish=e;this.ui=t;this.eventBus=n;this.options=i}static{s(this,"IntentHandler")}};var Dn=A({itemId:N(M(b())),productId:M(ee([M(b(),j(D)),U()]),j(r=>Number(r)),U()),variantId:N(M(ee([M(b(),j(D)),U()]),j(r=>Number(r)),U()))}),ue=class extends E{static{s(this,"EditItemVariantHandler")}async invoke(e,t=!1){return new Promise(n=>{let i=e.data,o=_(Dn,i);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(c=>c.message)});return}let{itemId:a,productId:u,variantId:l}=o.output;this.ui.showVariantSelect({productId:u.toString(),variantId:l?.toString(),onClose:s(()=>{n({code:"closed"})},"onClose"),onSubmit:s(async c=>{let{item:p,product:f,variant:m}=c,h={code:"ok",data:{item:p,product:f,variant:m}};t||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemVariant",{detail:h})),n(h)},"onSubmit")})})}};var Rn=A({productId:M(ee([M(b(),j(D)),U()]),j(r=>Number(r)),U()),variantId:N(M(ee([M(b(),j(D)),U()]),j(Number),U())),quantity:N(M(U(),Xe(1))),tags:N(Ke(b()))}),ge=class extends E{static{s(this,"CreateItemHandler")}async invoke(e){let t=e.data,n=_(Rn,t);if(!n.success)return{code:"error",message:"Invalid intent data",issues:n.issues.map(m=>m.message)};let{productId:i,variantId:o,quantity:a,tags:u}=n.output,l=await this.swish.storefront.loadSaveIntentData({productId:w("Product",i),variantId:o?w("ProductVariant",o):void 0});if(l.errors)return{code:"error",message:l.errors.message??"Failed to load save intent data",issues:l.errors.graphQLErrors?.map(m=>m.message)??[]};if(!l.data||!l.data.product)return{code:"error",message:"Failed to load save intent data",issues:["API response missing data"]};let{product:c}=l.data,p=c.variantsCount?.count&&c.variantsCount.count>1;if(!p||!this.options.save.requireVariant){let m=s(()=>!p&&c.selectedOrFirstAvailableVariant?Number(D(c.selectedOrFirstAvailableVariant.id)):o,"variantIdToUse"),h=await this.swish.api.items.create({productId:i,variantId:m(),quantity:a,tags:u});if("error"in h)return{code:"error",message:"Failed to create item",issues:[h.error.message]};if(!h.data)return{code:"error",message:"Could not complete item creation",issues:["API response missing data"]};let R="variant"in l.data?l.data.variant:void 0,y={code:"ok",data:{item:h.data,product:c,variant:p?R:c.selectedOrFirstAvailableVariant}};return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:y})),y}let f=await new ue(this.swish,this.ui,this.eventBus,this.options).invoke({action:"edit",type:"swish/ItemVariant",data:{productId:i,variantId:o}});return this.eventBus.dispatchEvent(new CustomEvent("create:swish/Item",{detail:f})),f}};var Ie=class extends E{static{s(this,"CreateListHandler")}async invoke(e){return new Promise(t=>{this.ui.showListEditor({onClose:s(()=>{t({code:"closed"})},"onClose"),onSubmit:s(async n=>{let{list:i}=n;t({code:"ok",data:{list:i}})},"onSubmit")})})}};var Pn=A({itemId:b()}),we=class extends E{static{s(this,"DeleteItemHandler")}async invoke(e){return new Promise(async t=>{let n=_(Pn,e.data);if(!n.success){t({code:"error",message:"Invalid intent data",issues:n.issues.map(o=>o.message)});return}let{itemId:i}=n.output;if(!this.options.unsave.requireConfirmation){let o=await this.swish.api.items.deleteById(i);if("error"in o){t({code:"error",message:"Failed to delete item",issues:[o.error.message]});return}t({code:"ok",data:{itemId:i}});return}this.ui.showUnsaveAlert({itemId:i,onClose:s(()=>{t({code:"closed"})},"onClose"),onSubmit:s(()=>{t({code:"ok",data:{itemId:i}})},"onSubmit")})})}};var Tn=A({listId:b()}),be=class extends E{static{s(this,"DeleteListHandler")}async invoke(e){return new Promise(t=>{let n=e.data,i=_(Tn,n);if(!i.success){t({code:"error",message:"Invalid intent data",issues:i.issues.map(a=>a.message)});return}let{listId:o}=i.output;this.ui.showDeleteListAlert({listId:o,onClose:s(()=>{t({code:"closed"})},"onClose"),onSubmit:s(async()=>{t({code:"ok",data:{listId:o}})},"onSubmit")})})}};var _n=A({itemId:b()}),Ee=class extends E{static{s(this,"EditItemListsHandler")}async invoke(e,t=!1){return new Promise(n=>{let i=e.data,o=_(_n,i);if(!o.success){n({code:"error",message:"Invalid intent data",issues:o.issues.map(u=>u.message)});return}let{itemId:a}=o.output;this.ui.showListSelect({itemId:a,onClose:s(()=>{n({code:"closed"})},"onClose"),onSubmit:s(async u=>{let{item:l,product:c,variant:p}=u,f={code:"ok",data:{item:l,product:c,variant:p}};t||this.eventBus.dispatchEvent(new CustomEvent("edit:swish/ItemLists",{detail:f})),n(f)},"onSubmit"),onUnsave(u){let l={code:"ok",data:{itemId:u.itemId}};n(l)}})})}};var On=A({listId:b()}),Ce=class extends E{static{s(this,"EditListHandler")}async invoke(e){return new Promise(t=>{let n=e.data,i=_(On,n);if(!i.success){t({code:"error",message:"Invalid intent data",issues:i.issues.map(a=>a.message)});return}let{listId:o}=i.output;this.ui.showListEditor({listId:o,onClose:s(()=>{t({code:"closed"})},"onClose"),onSubmit:s(async a=>{let{list:u}=a;t({code:"ok",data:{list:u}})},"onSubmit")})})}};var xe=class extends E{static{s(this,"OpenHomeHandler")}async invoke(e){return new Promise(t=>{this.ui.showDrawer({onClose:s(()=>{t({code:"closed"})},"onClose")})})}};var Ln=A({listId:b()}),Se=class extends E{static{s(this,"OpenListMenuHandler")}async invoke(e){return new Promise(t=>{let n=e.data,i=_(Ln,n);if(!i.success){t({code:"error",message:"Invalid intent data",issues:i.issues.map(a=>a.message)});return}let{listId:o}=i.output;this.ui.showListMenu({listId:o,onClose:s(()=>{t({code:"closed"})},"onClose"),onEdit:s(a=>{t({code:"ok",data:a})},"onEdit"),onDelete:s(()=>{t({code:"ok",data:{listId:o}})},"onDelete")})})}};var Xs=A({returnTo:N(b())}),Ae=class extends E{static{s(this,"OpenSignInHandler")}async invoke(e){return new Promise(t=>{this.ui.showSignIn({returnTo:e.data?.returnTo,onClose:s(()=>{t({code:"closed"})},"onClose")})})}};var $n=A({productId:b(),variantId:N(b())}),ke=class extends E{static{s(this,"OpenQuickBuyHandler")}async invoke(e){return new Promise(t=>{let n=_($n,e.data);if(!n.success){t({code:"error",message:"Invalid intent data",issues:n.issues.map(a=>a.message)});return}let{productId:i,variantId:o}=n.output;this.ui.showQuickBuy({productId:i,variantId:o,onClose:s(()=>{t({code:"closed"})},"onClose"),onSubmit:s(a=>{t({code:"ok",data:a})},"onSubmit")})})}};var le=class{constructor(e,t,n){this.swish=e;this.ui=t;this.options=n}static{s(this,"IntentHook")}};var De=class extends le{static{s(this,"AfterCreateItemHook")}async invoke(e){if(this.options.save.showToast&&e.code==="ok"){let{item:t,product:n,variant:i}=e.data;n&&this.ui.showToast({title:"Saved",text:n.title,image:i?.image?.url??n.featuredImage?.url,action:{label:"Add to List",onClick:s(()=>{this.swish.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:t.id}})},"onClick")}})}}};var Re=class extends le{static{s(this,"AfterEditItemListsHook")}async invoke(e){if(this.options.edit.showToast&&e.code==="ok"){if("itemId"in e.data)return;let{product:t,variant:n}=e.data;t&&this.ui.showToast({title:"Saved",text:t.title,image:n?.image?.url??t.featuredImage?.url,action:{label:"View",onClick:s(()=>{this.swish.intents.invoke({action:"open",type:"swish/Home"})},"onClick")}})}}};var Pe=class{static{s(this,"Intents")}constructor(e,t){this.swish=e,this.ui=t,this.eventBus=new EventTarget,this.options=e.options.swishUi.intents,this.initIntentHooks(),this.initIntentWatcher()}publishAnalyticsEvent(e,t){typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish(e,t)}async invoke(e){let t=this.parseIntent(e),n=this.getIntentQuery(t),i={lifecycle:"before",intent:t};return this.publishAnalyticsEvent("swish-intent",i),this.publishAnalyticsEvent(`swish-intent=${n}`,i),{intent:t,complete:this.handleIntent(t).then(o=>{let a={lifecycle:"after",intent:t,response:o};return this.publishAnalyticsEvent("swish-intent",a),this.publishAnalyticsEvent(`swish-intent=${n}`,a),o})}}listen(e,t){let n=this.getIntentQuery(e),i=s(a=>{"detail"in a&&a.detail?t(a.detail):console.warn("Intent response event without detail",a)},"eventListener"),o=s(()=>{this.eventBus.removeEventListener(n,i)},"unsubscribe");return this.eventBus.addEventListener(n,i),o}getIntentQuery(e){return`${e.action}:${e.type}`}parseIntent(e){if(typeof e=="string"){let[t,...n]=e.split(","),[i,o]=t.split(":"),a=n.reduce((u,l)=>{let[c,p]=l.split("=");return u[c]=p,u},{});return{action:i,type:o,data:a}}return e}async handleIntent(e){return e.action==="create"&&e.type==="swish/Item"?new ge(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/Item"?new we(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemVariant"?new ue(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/ItemLists"?new Ee(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="create"&&e.type==="swish/List"?new Ie(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="edit"&&e.type==="swish/List"?new Ce(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="delete"&&e.type==="swish/List"?new be(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/Home"?new xe(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/ListMenu"?new Se(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/SignIn"?new Ae(this.swish,this.ui,this.eventBus,this.options).invoke(e):e.action==="open"&&e.type==="swish/QuickBuy"?new ke(this.swish,this.ui,this.eventBus,this.options).invoke(e):{code:"error",message:"Invalid intent",issues:["Invalid intent"]}}initIntentHooks(){this.eventBus.addEventListener("create:swish/Item",e=>{new De(this.swish,this.ui,this.options).invoke(e.detail)}),this.eventBus.addEventListener("edit:swish/ItemLists",e=>{new Re(this.swish,this.ui,this.options).invoke(e.detail)})}initIntentWatcher(){de({selector:"[swish-intent]",onElementFound:s(e=>{let t=this.parseIntent(e.getAttribute("swish-intent"));t&&e.addEventListener("click",()=>{this.invoke(t)})},"onElementFound")}),de({selector:"a[href*='swish-intent=']",onElementFound:s(e=>{e instanceof HTMLAnchorElement&&e.addEventListener("click",t=>{if(!t.metaKey&&!t.ctrlKey&&!t.shiftKey&&!t.altKey){let i=new URL(e.href).searchParams.get("swish-intent");if(i){let o=this.parseIntent(i);o&&(t.preventDefault(),t.stopPropagation(),this.invoke(o))}}})},"onElementFound")}),ae({fireOnInit:!0,onLocationChange:s(e=>{let t=new URLSearchParams(window.location.search).get("swish-intent");if(t){let n=this.parseIntent(t);if(n){this.invoke(n);let i=new URL(window.location.href);i.searchParams.delete("swish-intent"),window.history.replaceState({},document.title,i.toString())}}},"onLocationChange")})}};var Bn=Symbol.for("preact-signals");function _e(){if(K>1)K--;else{for(var r,e=!1;fe!==void 0;){var t=fe;for(fe=void 0,Ye++;t!==void 0;){var n=t.o;if(t.o=void 0,t.f&=-3,!(8&t.f)&&Ft(t))try{t.c()}catch(i){e||(r=i,e=!0)}t=n}}if(Ye=0,K--,e)throw r}}s(_e,"t");function Y(r){if(K>0)return r();K++;try{return r()}finally{_e()}}s(Y,"r");var g=void 0;function Gt(r){var e=g;g=void 0;try{return r()}finally{g=e}}s(Gt,"n");var fe=void 0,K=0,Ye=0,Te=0;function jt(r){if(g!==void 0){var e=r.n;if(e===void 0||e.t!==g)return e={i:0,S:r,p:g.s,n:void 0,t:g,e:void 0,x:void 0,r:e},g.s!==void 0&&(g.s.n=e),g.s=e,r.n=e,32&g.f&&r.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=g.s,e.n=void 0,g.s.n=e,g.s=e),e}}s(jt,"e");function $(r,e){this.v=r,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s($,"u");$.prototype.brand=Bn;$.prototype.h=function(){return!0};$.prototype.S=function(r){var e=this,t=this.t;t!==r&&r.e===void 0&&(r.x=t,this.t=r,t!==void 0?t.e=r:Gt(function(){var n;(n=e.W)==null||n.call(e)}))};$.prototype.U=function(r){var e=this;if(this.t!==void 0){var t=r.e,n=r.x;t!==void 0&&(t.x=n,r.e=void 0),n!==void 0&&(n.e=t,r.x=void 0),r===this.t&&(this.t=n,n===void 0&&Gt(function(){var i;(i=e.Z)==null||i.call(e)}))}};$.prototype.subscribe=function(r){var e=this;return V(function(){var t=e.value,n=g;g=void 0;try{r(t)}finally{g=n}},{name:"sub"})};$.prototype.valueOf=function(){return this.value};$.prototype.toString=function(){return this.value+""};$.prototype.toJSON=function(){return this.value};$.prototype.peek=function(){var r=g;g=void 0;try{return this.value}finally{g=r}};Object.defineProperty($.prototype,"value",{get:s(function(){var r=jt(this);return r!==void 0&&(r.i=this.i),this.v},"get"),set:s(function(r){if(r!==this.v){if(Ye>100)throw new Error("Cycle detected");this.v=r,this.i++,Te++,K++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{_e()}}},"set")});function C(r,e){return new $(r,e)}s(C,"d");function Ft(r){for(var e=r.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}s(Ft,"c");function Ht(r){for(var e=r.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){r.s=e;break}}}s(Ht,"a");function Qt(r){for(var e=r.s,t=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):t=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}r.s=t}s(Qt,"l");function te(r,e){$.call(this,void 0),this.x=r,this.s=void 0,this.g=Te-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}s(te,"y");te.prototype=new $;te.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Te))return!0;if(this.g=Te,this.f|=1,this.i>0&&!Ft(this))return this.f&=-2,!0;var r=g;try{Ht(this),g=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 g=r,Qt(this),this.f&=-2,!0};te.prototype.S=function(r){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}$.prototype.S.call(this,r)};te.prototype.U=function(r){if(this.t!==void 0&&($.prototype.U.call(this,r),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};te.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var r=this.t;r!==void 0;r=r.x)r.t.N()}};Object.defineProperty(te.prototype,"value",{get:s(function(){if(1&this.f)throw new Error("Cycle detected");var r=jt(this);if(this.h(),r!==void 0&&(r.i=this.i),16&this.f)throw this.v;return this.v},"get")});function q(r,e){return new te(r,e)}s(q,"w");function zt(r){var e=r.u;if(r.u=void 0,typeof e=="function"){K++;var t=g;g=void 0;try{e()}catch(n){throw r.f&=-2,r.f|=8,Je(r),n}finally{g=t,_e()}}}s(zt,"_");function Je(r){for(var e=r.s;e!==void 0;e=e.n)e.S.U(e);r.x=void 0,r.s=void 0,zt(r)}s(Je,"b");function qn(r){if(g!==this)throw new Error("Out-of-order effect");Qt(this),g=r,this.f&=-2,8&this.f&&Je(this),_e()}s(qn,"g");function ce(r,e){this.x=r,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}s(ce,"p");ce.prototype.c=function(){var r=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{r()}};ce.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,zt(this),Ht(this),K++;var r=g;return g=this,qn.bind(this,r)};ce.prototype.N=function(){2&this.f||(this.f|=2,this.o=fe,fe=this)};ce.prototype.d=function(){this.f|=8,1&this.f||Je(this)};ce.prototype.dispose=function(){this.d()};function V(r,e){var t=new ce(r,e);try{t.c()}catch(i){throw t.d(),i}var n=t.d.bind(t);return n[Symbol.dispose]=n,n}s(V,"E");var Vn=/\/products\/([^/?#]+)(?:\?(?:[^#]*?&)?variant=(\d+))?/,Ze=s(r=>{let e=r.match(Vn);return e?{productHandle:e[1],variantId:e[2]}:null},"parseProductUrl"),Wt=s(({source:r,onProductUrlChange:e})=>{let t=s(n=>{let i=Ze(n);i?.productHandle&&e(i)},"handleChange");if(r instanceof HTMLAnchorElement)return Vt({element:r,onHrefChange:s(n=>t(n),"onHrefChange")});if(r instanceof Location)return ae({onLocationChange:s(n=>t(n.href),"onLocationChange")});throw new Error("Invalid source for observing product url")},"observeProductUrl");var Xt=s(r=>e=>{let{productHandle:t,productId:n,variantId:i,itemId:o}=e?.dataset??{},l=!!(n||t)||!!o,c=C({loading:!1,productId:n,variantId:i,itemId:o});if(!l){let p=e instanceof HTMLAnchorElement?e:window.location,f=Ze(p.href);f?.productHandle&&f.productHandle!==c.value.productHandle&&(c.value={...c.value,...f,productId:void 0},Wt({source:p,onProductUrlChange:s(m=>{c.value={...c.value,...m,productId:m.productHandle!==c.value.productHandle?void 0:c.value.productId}},"onProductUrlChange")}))}return V(()=>{c.value.loading||!c.value.productId&&c.value.productHandle&&(c.value={...c.value,loading:!0},r.storefront.loadProductId({productHandle:c.value.productHandle}).then(p=>{p.errors&&console.error("Error loading product id",p.errors),c.value={...c.value,productId:p.data?.product?.id?D(p.data.product.id):void 0,loading:!1}}))}),c},"itemContextSignal");var Kt=s(r=>e=>{let t=q(()=>{let{productId:I,variantId:v,loading:P}=e.value;return!I||P?null:v?`variant:${D(v)}`:`product:${D(I)}`}),n=q(()=>e.value.loading||!!e.value.itemId||!e.value.productId),i=q(()=>({limit:1,query:t.value??void 0})),o=C(!n.value),a=C(null),u=C(!1),l=C(!1),{data:c,loading:p,error:f,refetching:m}=r.state.swishQuery(I=>r.api.items.list(I),{refetch:["item-create","item-update","item-delete"],variables:i,skip:n}),h=C(e.value.itemId??null);V(()=>{Y(()=>{if(o.value=p.value,a.value=f.value,!e.value.itemId){let I=c.value?.[0]?.id??null;I!==h.value&&(h.value=I)}})});async function R(){if(!h.value)return;u.value=!0,(await(await r.intents.invoke({action:"delete",type:"swish/Item",data:{itemId:h.value}})).complete).code==="ok"&&(h.value=null),u.value=!1}s(R,"unsave");async function y(){if(!h.value)return;u.value=!0;let v=await(await r.intents.invoke({action:"edit",type:"swish/ItemLists",data:{itemId:h.value}})).complete;v.code==="ok"&&"itemId"in v.data&&(h.value=null),u.value=!1}s(y,"update");async function S(){let{productId:I,variantId:v}=e.value;if(!I)return;u.value=!0,l.value=!0;let T=await(await r.intents.invoke({action:"create",type:"swish/Item",data:{productId:I,variantId:v}})).complete;if(T.code==="ok"){let pe=T.data;h.value=pe.item.id,u.value=!1}else T.code==="error"&&console.warn("Failed to create item",T),Y(()=>{u.value=!1,l.value=!1})}s(S,"save");let L=q(()=>o.value||u.value||e.value.loading);V(()=>{l.value&&!u.value&&!m.value&&(l.value=!1)});let k=q(()=>{let I=m.value&&l.value,v=!!h.value,P=!v&&(u.value||I),T=v&&(u.value||I),pe=q(()=>P?"saving":T?"unsaving":v?"saved":"unsaved");return{error:a.value,status:pe.value,savedItemId:h.value,loading:L.value,submitting:u.value,saved:v,saving:P,unsaving:T}});async function F(){L.value||(k.value.saved&&k.value.savedItemId?y():k.value.saved||await S())}return s(F,"toggle"),Object.assign(k,{save:S,unsave:R,update:y,toggle:F})},"itemStateSignal");var Yt=s(r=>()=>{let{data:e,loading:t,error:n}=r.state.swishQuery(()=>r.api.items.count(),{refetch:["item-create","item-delete"]}),i=C(0),o=C(!0),a=C(null);return V(()=>{Y(()=>{o.value=t.value,a.value=n.value,i.value=e.value?.count??0})}),q(()=>({count:i.value,loading:o.value,error:a.value}))},"itemCountSignal");var Jt=s(r=>(e,t)=>{let n=C(null),i=C(null),o=C(null),a=C(!t?.skip),u=C(!1),l=q(()=>a.value&&u.value);async function c(){if(!t?.skip?.value)try{a.value=!0;let p=await e(t?.variables?.value);Y(()=>{o.value="error"in p?p.error:null,n.value="data"in p?p.data:null,i.value="pageInfo"in p?p.pageInfo:null,a.value=!1,u.value=!0})}catch(p){Y(()=>{o.value=p,a.value=!1,u.value=!0})}}return s(c,"executeFetch"),V(()=>{if(c(),t?.refetch?.length)return r.events.subscribe(t.refetch,c)}),{data:n,pageInfo:i,error:o,loading:a,refetching:l}},"swishQuerySignals");var re="GraphQL Client";var et="An error occurred while fetching from the API. Review 'graphQLErrors' for details.",tt="Response returned unexpected Content-Type:",rt="An unknown error has occurred. The API did not return a data object or any errors in its response.",Oe={json:"application/json",multipart:"multipart/mixed"},nt="X-SDK-Variant",it="X-SDK-Version",er="shopify-graphql-client",tr="1.4.1",Le=1e3,rr=[429,503],st=/@(defer)\b/i,Zt=`\r
|
|
8
|
+
`,nr=/boundary="?([^=";]+)"?/i,ot=Zt+Zt;function H(r,e=re){return r.startsWith(`${e}`)?r:`${e}: ${r}`}s(H,"formatErrorMessage");function W(r){return r instanceof Error?r.message:JSON.stringify(r)}s(W,"getErrorMessage");function at(r){return r instanceof Error&&r.cause?r.cause:void 0}s(at,"getErrorCause");function ut(r){return r.flatMap(({errors:e})=>e??[])}s(ut,"combineErrors");function $e({client:r,retries:e}){if(e!==void 0&&(typeof e!="number"||e<0||e>3))throw new Error(`${r}: The provided "retries" value (${e}) is invalid - it cannot be less than ${0} or greater than ${3}`)}s($e,"validateRetries");function B(r,e){return e&&(typeof e!="object"||Array.isArray(e)||typeof e=="object"&&Object.keys(e).length>0)?{[r]:e}:{}}s(B,"getKeyValueIfValid");function lt(r,e){if(r.length===0)return e;let n={[r.pop()]:e};return r.length===0?n:lt(r,n)}s(lt,"buildDataObjectByPath");function or(r,e){return Object.keys(e||{}).reduce((t,n)=>(typeof e[n]=="object"||Array.isArray(e[n]))&&r[n]?(t[n]=or(r[n],e[n]),t):(t[n]=e[n],t),Array.isArray(r)?[...r]:{...r})}s(or,"combineObjects");function ct([r,...e]){return e.reduce(or,{...r})}s(ct,"buildCombinedDataObject");function pt({clientLogger:r,customFetchApi:e=fetch,client:t=re,defaultRetryWaitTime:n=Le,retriableCodes:i=rr}){let o=s(async(a,u,l)=>{let c=u+1,p=l+1,f;try{if(f=await e(...a),r({type:"HTTP-Response",content:{requestParams:a,response:f}}),!f.ok&&i.includes(f.status)&&c<=p)throw new Error;let m=f?.headers.get("X-Shopify-API-Deprecated-Reason")||"";return m&&r({type:"HTTP-Response-GraphQL-Deprecation-Notice",content:{requestParams:a,deprecationNotice:m}}),f}catch(m){if(c<=p){let h=f?.headers.get("Retry-After");return await Un(h?parseInt(h,10):n),r({type:"HTTP-Retry",content:{requestParams:a,lastResponse:f,retryAttempt:u,maxRetries:l}}),o(a,c,l)}throw new Error(H(`${l>0?`Attempted maximum number of ${l} network retries. Last message - `:""}${W(m)}`,t))}},"httpFetch");return o}s(pt,"generateHttpFetch");async function Un(r){return new Promise(e=>setTimeout(e,r))}s(Un,"sleep");function dt({headers:r,url:e,customFetchApi:t=fetch,retries:n=0,logger:i}){$e({client:re,retries:n});let o={headers:r,url:e,retries:n},a=Nn(i),u=pt({customFetchApi:t,clientLogger:a,defaultRetryWaitTime:Le}),l=Mn(u,o),c=Gn(l),p=Xn(l);return{config:o,fetch:l,request:c,requestStream:p}}s(dt,"createGraphQLClient");function Nn(r){return e=>{r&&r(e)}}s(Nn,"generateClientLogger");async function ar(r){let{errors:e,data:t,extensions:n}=await r.json();return{...B("data",t),...B("extensions",n),headers:r.headers,...e||!t?{errors:{networkStatusCode:r.status,message:H(e?et:rt),...B("graphQLErrors",e),response:r}}:{}}}s(ar,"processJSONResponse");function Mn(r,{url:e,headers:t,retries:n}){return async(i,o={})=>{let{variables:a,headers:u,url:l,retries:c,keepalive:p,signal:f}=o,m=JSON.stringify({query:i,variables:a});$e({client:re,retries:c});let h=Object.entries({...t,...u}).reduce((y,[S,L])=>(y[S]=Array.isArray(L)?L.join(", "):L.toString(),y),{});return!h[nt]&&!h[it]&&(h[nt]=er,h[it]=tr),r([l??e,{method:"POST",headers:h,body:m,signal:f,keepalive:p}],1,c??n)}}s(Mn,"generateFetch");function Gn(r){return async(...e)=>{if(st.test(e[0]))throw new Error(H("This operation will result in a streamable response - use requestStream() instead."));let t=null;try{t=await r(...e);let{status:n,statusText:i}=t,o=t.headers.get("content-type")||"";return t.ok?o.includes(Oe.json)?await ar(t):{errors:{networkStatusCode:n,message:H(`${tt} ${o}`),response:t}}:{errors:{networkStatusCode:n,message:H(i),response:t}}}catch(n){return{errors:{message:W(n),...t==null?{}:{networkStatusCode:t.status,response:t}}}}}}s(Gn,"generateRequest");async function*jn(r){let e=new TextDecoder;if(r.body[Symbol.asyncIterator])for await(let t of r.body)yield e.decode(t);else{let t=r.body.getReader(),n;try{for(;!(n=await t.read()).done;)yield e.decode(n.value)}finally{t.cancel()}}}s(jn,"getStreamBodyIterator");function Fn(r,e){return{async*[Symbol.asyncIterator](){try{let t="";for await(let n of r)if(t+=n,t.indexOf(e)>-1){let i=t.lastIndexOf(e),a=t.slice(0,i).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(i+e.length),t.trim()==="--"&&(t="")}}catch(t){throw new Error(`Error occured while processing stream payload - ${W(t)}`)}}}}s(Fn,"readStreamChunk");function Hn(r){return{async*[Symbol.asyncIterator](){yield{...await ar(r),hasNext:!1}}}}s(Hn,"createJsonResponseAsyncIterator");function Qn(r){return r.map(e=>{try{return JSON.parse(e)}catch(t){throw new Error(`Error in parsing multipart response - ${W(t)}`)}}).map(e=>{let{data:t,incremental:n,hasNext:i,extensions:o,errors:a}=e;if(!n)return{data:t||{},...B("errors",a),...B("extensions",o),hasNext:i};let u=n.map(({data:l,path:c,errors:p})=>({data:l&&c?lt(c,l):{},...B("errors",p)}));return{data:u.length===1?u[0].data:ct([...u.map(({data:l})=>l)]),...B("errors",ut(u)),hasNext:i}})}s(Qn,"getResponseDataFromChunkBodies");function zn(r,e){if(r.length>0)throw new Error(et,{cause:{graphQLErrors:r}});if(Object.keys(e).length===0)throw new Error(rt)}s(zn,"validateResponseData");function Wn(r,e){let t=(e??"").match(nr),n=`--${t?t[1]:"-"}`;if(!r.body?.getReader&&!r.body?.[Symbol.asyncIterator])throw new Error("API multipart response did not return an iterable body",{cause:r});let i=jn(r),o={},a;return{async*[Symbol.asyncIterator](){try{let u=!0;for await(let l of Fn(i,n)){let c=Qn(l);a=c.find(f=>f.extensions)?.extensions??a;let p=ut(c);o=ct([o,...c.map(({data:f})=>f)]),u=c.slice(-1)[0].hasNext,zn(p,o),yield{...B("data",o),...B("extensions",a),hasNext:u}}if(u)throw new Error("Response stream terminated unexpectedly")}catch(u){let l=at(u);yield{...B("data",o),...B("extensions",a),errors:{message:H(W(u)),networkStatusCode:r.status,...B("graphQLErrors",l?.graphQLErrors),response:r},hasNext:!1}}}}}s(Wn,"createMultipartResponseAsyncInterator");function Xn(r){return async(...e)=>{if(!st.test(e[0]))throw new Error(H("This operation does not result in a streamable response - use request() instead."));try{let t=await r(...e),{statusText:n}=t;if(!t.ok)throw new Error(n,{cause:t});let i=t.headers.get("content-type")||"";switch(!0){case i.includes(Oe.json):return Hn(t);case i.includes(Oe.multipart):return Wn(t,i);default:throw new Error(`${tt} ${i}`,{cause:t})}}catch(t){return{async*[Symbol.asyncIterator](){let n=at(t);yield{errors:{message:H(W(t)),...B("networkStatusCode",n?.status),...B("response",n)},hasNext:!1}}}}}}s(Xn,"generateRequestStream");function ft({client:r,storeDomain:e}){try{if(!e||typeof e!="string")throw new Error;let t=e.trim(),n=t.match(/^https?:/)?t:`https://${t}`,i=new URL(n);return i.protocol="https",i.origin}catch(t){throw new Error(`${r}: a valid store domain ("${e}") must be provided`,{cause:t})}}s(ft,"validateDomainAndGetStoreUrl");function Be({client:r,currentSupportedApiVersions:e,apiVersion:t,logger:n}){let i=`${r}: the provided apiVersion ("${t}")`,o=`Currently supported API versions: ${e.join(", ")}`;if(!t||typeof t!="string")throw new Error(`${i} is invalid. ${o}`);let a=t.trim();e.includes(a)||(n?n({type:"Unsupported_Api_Version",content:{apiVersion:t,supportedApiVersions:e}}):console.warn(`${i} is likely deprecated or not supported. ${o}`))}s(Be,"validateApiVersion");function qe(r){let e=r*3-2;return e===10?e:`0${e}`}s(qe,"getQuarterMonth");function ht(r,e,t){let n=e-t;return n<=0?`${r-1}-${qe(n+4)}`:`${r}-${qe(n)}`}s(ht,"getPrevousVersion");function ur(){let r=new Date,e=r.getUTCMonth(),t=r.getUTCFullYear(),n=Math.floor(e/3+1);return{year:t,quarter:n,version:`${t}-${qe(n)}`}}s(ur,"getCurrentApiVersion");function yt(){let{year:r,quarter:e,version:t}=ur(),n=e===4?`${r+1}-01`:`${r}-${qe(e+1)}`;return[ht(r,e,3),ht(r,e,2),ht(r,e,1),t,n,"unstable"]}s(yt,"getCurrentSupportedApiVersions");function mt(r){return e=>({...e??{},...r.headers})}s(mt,"generateGetHeaders");function vt({getHeaders:r,getApiUrl:e}){return(t,n)=>{let i=[t];if(n&&Object.keys(n).length>0){let{variables:o,apiVersion:a,headers:u,retries:l,signal:c}=n;i.push({...o?{variables:o}:{},...u?{headers:r(u)}:{},...a?{url:e(a)}:{},...l?{retries:l}:{},...c?{signal:c}:{}})}return i}}s(vt,"generateGetGQLClientParams");var gt="application/json",lr="storefront-api-client",cr="1.0.9",pr="X-Shopify-Storefront-Access-Token",dr="Shopify-Storefront-Private-Token",fr="X-SDK-Variant",hr="X-SDK-Version",yr="X-SDK-Variant-Source",ne="Storefront API Client";function mr(r){if(r&&typeof window<"u")throw new Error(`${ne}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`)}s(mr,"validatePrivateAccessTokenUsage");function vr(r,e){if(!r&&!e)throw new Error(`${ne}: a public or private access token must be provided`);if(r&&e)throw new Error(`${ne}: only provide either a public or private access token`)}s(vr,"validateRequiredAccessTokens");function It({storeDomain:r,apiVersion:e,publicAccessToken:t,privateAccessToken:n,clientName:i,retries:o=0,customFetchApi:a,logger:u}){let l=yt(),c=ft({client:ne,storeDomain:r}),p={client:ne,currentSupportedApiVersions:l,logger:u};Be({...p,apiVersion:e}),vr(t,n),mr(n);let f=Kn(c,e,p),m={storeDomain:c,apiVersion:e,...t?{publicAccessToken:t}:{privateAccessToken:n},headers:{"Content-Type":gt,Accept:gt,[fr]:lr,[hr]:cr,...i?{[yr]:i}:{},...t?{[pr]:t}:{[dr]:n}},apiUrl:f(),clientName:i},h=dt({headers:m.headers,url:m.apiUrl,retries:o,customFetchApi:a,logger:u}),R=mt(m),y=Yn(m,f),S=vt({getHeaders:R,getApiUrl:y});return Object.freeze({config:m,getHeaders:R,getApiUrl:y,fetch:s((...k)=>h.fetch(...S(...k)),"fetch"),request:s((...k)=>h.request(...S(...k)),"request"),requestStream:s((...k)=>h.requestStream(...S(...k)),"requestStream")})}s(It,"createStorefrontApiClient");function Kn(r,e,t){return n=>{n&&Be({...t,apiVersion:n});let i=(n??e).trim();return`${r}/api/${i}/graphql.json`}}s(Kn,"generateApiUrlFormatter");function Yn(r,e){return t=>t?e(t):r.apiUrl}s(Yn,"generateGetApiUrl");var O=`
|
|
20
9
|
fragment productImageFields on Image {
|
|
21
10
|
id
|
|
22
11
|
altText
|
|
23
12
|
url
|
|
24
13
|
thumbhash
|
|
25
14
|
}
|
|
26
|
-
`,
|
|
15
|
+
`,wt=`
|
|
27
16
|
fragment saveIntentProductFields on Product {
|
|
28
17
|
id
|
|
29
18
|
availableForSale
|
|
@@ -48,7 +37,7 @@ Values:
|
|
|
48
37
|
}
|
|
49
38
|
title
|
|
50
39
|
}
|
|
51
|
-
`,
|
|
40
|
+
`,ie=`
|
|
52
41
|
fragment productCardDataFields on Product {
|
|
53
42
|
id
|
|
54
43
|
availableForSale
|
|
@@ -97,7 +86,7 @@ Values:
|
|
|
97
86
|
value
|
|
98
87
|
}
|
|
99
88
|
}
|
|
100
|
-
|
|
89
|
+
`,bt=`
|
|
101
90
|
fragment productVariantDataFields on ProductVariant {
|
|
102
91
|
id
|
|
103
92
|
availableForSale
|
|
@@ -126,7 +115,7 @@ Values:
|
|
|
126
115
|
value
|
|
127
116
|
}
|
|
128
117
|
}
|
|
129
|
-
`,
|
|
118
|
+
`,Et=`
|
|
130
119
|
fragment productOptionsVariantFields on ProductVariant {
|
|
131
120
|
id
|
|
132
121
|
selectedOptions {
|
|
@@ -134,7 +123,7 @@ Values:
|
|
|
134
123
|
value
|
|
135
124
|
}
|
|
136
125
|
}
|
|
137
|
-
`,
|
|
126
|
+
`,Ct=`
|
|
138
127
|
fragment selectedVariantFields on Product {
|
|
139
128
|
id
|
|
140
129
|
availableForSale
|
|
@@ -165,7 +154,7 @@ Values:
|
|
|
165
154
|
}
|
|
166
155
|
}
|
|
167
156
|
}
|
|
168
|
-
`,
|
|
157
|
+
`,se=`
|
|
169
158
|
fragment productOptionsFields on Product {
|
|
170
159
|
id
|
|
171
160
|
availableForSale
|
|
@@ -201,7 +190,7 @@ Values:
|
|
|
201
190
|
}
|
|
202
191
|
}
|
|
203
192
|
}
|
|
204
|
-
`,
|
|
193
|
+
`,xt=`
|
|
205
194
|
fragment productImagesFields on Product {
|
|
206
195
|
images(first: 20) {
|
|
207
196
|
nodes {
|
|
@@ -209,7 +198,7 @@ Values:
|
|
|
209
198
|
}
|
|
210
199
|
}
|
|
211
200
|
}
|
|
212
|
-
`;var
|
|
201
|
+
`;var gr=`
|
|
213
202
|
query GetSaveIntentData(
|
|
214
203
|
$productId: ID!
|
|
215
204
|
$country: CountryCode!
|
|
@@ -219,9 +208,9 @@ Values:
|
|
|
219
208
|
...saveIntentProductFields
|
|
220
209
|
}
|
|
221
210
|
}
|
|
222
|
-
${
|
|
223
|
-
${
|
|
224
|
-
`,
|
|
211
|
+
${wt}
|
|
212
|
+
${O}
|
|
213
|
+
`,Ir=`
|
|
225
214
|
query GetSaveIntentDataWithVariant(
|
|
226
215
|
$productId: ID!
|
|
227
216
|
$variantId: ID!
|
|
@@ -235,9 +224,9 @@ Values:
|
|
|
235
224
|
...saveIntentVariantFields
|
|
236
225
|
}
|
|
237
226
|
}
|
|
238
|
-
${
|
|
239
|
-
${
|
|
240
|
-
`,
|
|
227
|
+
${wt}
|
|
228
|
+
${O}
|
|
229
|
+
`,wr=`
|
|
241
230
|
query GetProductCardData(
|
|
242
231
|
$productId: ID!
|
|
243
232
|
$productMetafields: [HasMetafieldsIdentifier!]!
|
|
@@ -248,9 +237,9 @@ Values:
|
|
|
248
237
|
...productCardDataFields
|
|
249
238
|
}
|
|
250
239
|
}
|
|
251
|
-
${
|
|
252
|
-
${
|
|
253
|
-
`,
|
|
240
|
+
${ie}
|
|
241
|
+
${O}
|
|
242
|
+
`,br=`
|
|
254
243
|
query GetProductCardDataWithVariant(
|
|
255
244
|
$productId: ID!
|
|
256
245
|
$variantId: ID!
|
|
@@ -266,10 +255,10 @@ Values:
|
|
|
266
255
|
...productVariantDataFields
|
|
267
256
|
}
|
|
268
257
|
}
|
|
269
|
-
${
|
|
270
|
-
${
|
|
271
|
-
${
|
|
272
|
-
`,
|
|
258
|
+
${ie}
|
|
259
|
+
${bt}
|
|
260
|
+
${O}
|
|
261
|
+
`,Er=`
|
|
273
262
|
query GetProductOptions(
|
|
274
263
|
$productId: ID!
|
|
275
264
|
$country: CountryCode!
|
|
@@ -279,9 +268,9 @@ Values:
|
|
|
279
268
|
...productOptionsFields
|
|
280
269
|
}
|
|
281
270
|
}
|
|
282
|
-
${
|
|
283
|
-
${
|
|
284
|
-
`,
|
|
271
|
+
${se}
|
|
272
|
+
${O}
|
|
273
|
+
`,Cr=`
|
|
285
274
|
query GetProductOptionsByHandle(
|
|
286
275
|
$handle: String!
|
|
287
276
|
$country: CountryCode!
|
|
@@ -291,9 +280,9 @@ Values:
|
|
|
291
280
|
...productOptionsFields
|
|
292
281
|
}
|
|
293
282
|
}
|
|
294
|
-
${
|
|
295
|
-
${
|
|
296
|
-
`,
|
|
283
|
+
${se}
|
|
284
|
+
${O}
|
|
285
|
+
`,xr=`
|
|
297
286
|
query GetProductOptionsWithVariant(
|
|
298
287
|
$productId: ID!
|
|
299
288
|
$variantId: ID!
|
|
@@ -307,10 +296,10 @@ Values:
|
|
|
307
296
|
...productOptionsVariantFields
|
|
308
297
|
}
|
|
309
298
|
}
|
|
310
|
-
${
|
|
311
|
-
${
|
|
312
|
-
${
|
|
313
|
-
`,
|
|
299
|
+
${se}
|
|
300
|
+
${Et}
|
|
301
|
+
${O}
|
|
302
|
+
`,Sr=`
|
|
314
303
|
query GetProductOptionsByHandleWithVariant(
|
|
315
304
|
$handle: String!
|
|
316
305
|
$variantId: ID!
|
|
@@ -324,10 +313,10 @@ Values:
|
|
|
324
313
|
...productOptionsVariantFields
|
|
325
314
|
}
|
|
326
315
|
}
|
|
327
|
-
${
|
|
328
|
-
${
|
|
329
|
-
${
|
|
330
|
-
`,
|
|
316
|
+
${se}
|
|
317
|
+
${Et}
|
|
318
|
+
${O}
|
|
319
|
+
`,Ar=`
|
|
331
320
|
query GetSelectedVariant(
|
|
332
321
|
$productId: ID!
|
|
333
322
|
$selectedOptions: [SelectedOptionInput!]!
|
|
@@ -338,9 +327,9 @@ Values:
|
|
|
338
327
|
...selectedVariantFields
|
|
339
328
|
}
|
|
340
329
|
}
|
|
341
|
-
${
|
|
342
|
-
${
|
|
343
|
-
`,
|
|
330
|
+
${Ct}
|
|
331
|
+
${O}
|
|
332
|
+
`,kr=`
|
|
344
333
|
query GetSelectedVariantByHandle(
|
|
345
334
|
$handle: String!
|
|
346
335
|
$selectedOptions: [SelectedOptionInput!]!
|
|
@@ -351,9 +340,9 @@ Values:
|
|
|
351
340
|
...selectedVariantFields
|
|
352
341
|
}
|
|
353
342
|
}
|
|
354
|
-
${
|
|
355
|
-
${
|
|
356
|
-
`,
|
|
343
|
+
${Ct}
|
|
344
|
+
${O}
|
|
345
|
+
`,Dr=`
|
|
357
346
|
query GetProductDetailData(
|
|
358
347
|
$productId: ID!
|
|
359
348
|
$productMetafields: [HasMetafieldsIdentifier!]!
|
|
@@ -366,11 +355,11 @@ Values:
|
|
|
366
355
|
...productImagesFields
|
|
367
356
|
}
|
|
368
357
|
}
|
|
369
|
-
${
|
|
370
|
-
${
|
|
371
|
-
${
|
|
372
|
-
${
|
|
373
|
-
`,
|
|
358
|
+
${ie}
|
|
359
|
+
${se}
|
|
360
|
+
${xt}
|
|
361
|
+
${O}
|
|
362
|
+
`,Rr=`
|
|
374
363
|
query GetProductDetailDataWithVariant(
|
|
375
364
|
$productId: ID!
|
|
376
365
|
$variantId: ID!
|
|
@@ -388,12 +377,12 @@ Values:
|
|
|
388
377
|
...productVariantDataFields
|
|
389
378
|
}
|
|
390
379
|
}
|
|
391
|
-
${
|
|
392
|
-
${
|
|
393
|
-
${
|
|
394
|
-
${
|
|
395
|
-
${
|
|
396
|
-
`,
|
|
380
|
+
${ie}
|
|
381
|
+
${se}
|
|
382
|
+
${bt}
|
|
383
|
+
${xt}
|
|
384
|
+
${O}
|
|
385
|
+
`,Pr=`
|
|
397
386
|
query GetProductImagesById(
|
|
398
387
|
$ids: [ID!]!
|
|
399
388
|
$country: CountryCode!
|
|
@@ -417,8 +406,8 @@ Values:
|
|
|
417
406
|
}
|
|
418
407
|
}
|
|
419
408
|
}
|
|
420
|
-
${
|
|
421
|
-
`,
|
|
409
|
+
${O}
|
|
410
|
+
`,Tr=`
|
|
422
411
|
query GetProductRecommendationsById(
|
|
423
412
|
$productId: ID!
|
|
424
413
|
$intent: ProductRecommendationIntent
|
|
@@ -430,9 +419,9 @@ Values:
|
|
|
430
419
|
...productCardDataFields
|
|
431
420
|
}
|
|
432
421
|
}
|
|
433
|
-
${
|
|
434
|
-
${
|
|
435
|
-
`,
|
|
422
|
+
${ie}
|
|
423
|
+
${O}
|
|
424
|
+
`,_r=`
|
|
436
425
|
query GetProductRecommendationsByHandle(
|
|
437
426
|
$handle: String!
|
|
438
427
|
$intent: ProductRecommendationIntent
|
|
@@ -444,16 +433,27 @@ Values:
|
|
|
444
433
|
...productCardDataFields
|
|
445
434
|
}
|
|
446
435
|
}
|
|
447
|
-
${
|
|
448
|
-
${
|
|
449
|
-
`,
|
|
436
|
+
${ie}
|
|
437
|
+
${O}
|
|
438
|
+
`,Or=`
|
|
450
439
|
query GetProductIdByHandle($handle: String!) {
|
|
451
440
|
product(handle: $handle) {
|
|
452
441
|
id
|
|
453
442
|
}
|
|
454
443
|
}
|
|
455
|
-
`;var
|
|
444
|
+
`;var Lr=s(async(r,{productId:e,variantId:t,productMetafields:n=[],variantMetafields:i=[],country:o,language:a})=>{if(!e)throw new Error("A productId must be provided");let u=s(()=>{if(e&&!t)return wr;if(e&&t)return br},"getProductOptionsQuery"),l=s(()=>{if(e&&!t)return{productId:w("Product",e),productMetafields:n,country:o,language:a};if(e&&t)return{productId:w("Product",e),variantId:w("ProductVariant",t),productMetafields:n,variantMetafields:i,country:o,language:a}},"getVariables"),c=u(),p=l();if(!p||!c)throw new Error("Invalid query arguments");return r.query(c,p)},"loadProductCardData");var $r=s(async(r,{productId:e,variantId:t,productMetafields:n=[],variantMetafields:i=[],country:o,language:a})=>{if(!e)throw new Error("A productId must be provided");let u=s(()=>{if(e&&!t)return Dr;if(e&&t)return Rr},"getProductOptionsQuery"),l=s(()=>{if(e&&!t)return{productId:w("Product",e),productMetafields:n,country:o,language:a};if(e&&t)return{productId:w("Product",e),variantId:w("ProductVariant",t),productMetafields:n,variantMetafields:i,country:o,language:a}},"getVariables"),c=u(),p=l();if(!p||!c)throw new Error("Invalid query arguments");return r.query(c,p)},"loadProductDetailData");var Br=s(async(r,{productHandle:e})=>{if(!e)throw new Error("A product handle must be provided");return r.query(Or,{handle:e})},"loadProductId");var qr=s(async(r,{items:e,country:t,language:n})=>{if(!e?.length)throw new Error("A list of items must be provided");let i={ids:e.map(o=>o.variantId?w("ProductVariant",o.variantId.toString()):w("Product",o.productId.toString())),country:t,language:n};try{return{data:(await r.query(Pr,i)).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 Vr=s(async(r,{productId:e,productHandle:t,variantId:n,country:i,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let a=s(()=>{if(e&&!n)return Er;if(t&&!n)return Cr;if(e&&n)return xr;if(t&&n)return Sr},"getProductOptionsQuery"),u=s(()=>{if(e&&!n)return{productId:w("Product",e),country:i,language:o};if(t&&!n)return{handle:t,country:i,language:o};if(e&&n)return{productId:w("Product",e),variantId:w("ProductVariant",n),country:i,language:o};if(t&&n)return{handle:t,variantId:w("ProductVariant",n),country:i,language:o}},"getVariables"),l=a(),c=u();if(!c||!l)throw new Error("Invalid query arguments");return r.query(l,c)},"loadProductOptions");var Ur=s(async(r,{productId:e,productHandle:t,intent:n,productMetafields:i=[],country:o,language:a})=>{if(!e&&!t)throw new Error("Either productId or productHandle must be provided");if(e){let l={productId:w("Product",e),intent:n,productMetafields:i,country:o,language:a};return r.query(Tr,l)}let u={handle:t,intent:n,productMetafields:i,country:o,language:a};return r.query(_r,u)},"loadProductRecommendations");var Nr=s(async(r,{productId:e,variantId:t,country:n,language:i})=>{let o=s(()=>{if(e&&!t)return gr;if(e&&t)return Ir},"getProductOptionsQuery"),a=s(()=>{if(e&&!t)return{productId:w("Product",D(e)),country:n,language:i};if(e&&t)return{productId:w("Product",D(e)),variantId:w("ProductVariant",D(t)),country:n,language:i}},"getVariables"),u=o(),l=a();if(!l||!u)throw new Error("Invalid query arguments");return r.query(u,l)},"loadSaveIntentData");var Mr=s(async(r,{productId:e,productHandle:t,selectedOptions:n,country:i,language:o})=>{if(!e&&!t)throw new Error("Either productId or handle must be provided");let a=e?Ar:kr,u=e?{productId:`gid://shopify/Product/${e}`,selectedOptions:n,country:i,language:o}:{handle:t,selectedOptions:n,country:i,language:o};return r.query(a,u)},"loadSelectedVariant");var Jn="2025-10",Zn=["GetProductIdByHandle"],Ve=class{constructor(e,t,n,i){this.client=null;this.query=s(async(e,t)=>{if(!this.client)throw new Error("Storefront API client not initialized");let n=await this.client.request(e,{variables:t});return{data:n.data,errors:n.errors??null}},"query");this.loadProductOptions=s(async e=>Vr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductOptions");this.loadSelectedVariant=s(async e=>Mr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSelectedVariant");this.loadProductCardData=s(async e=>Lr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}).then(t=>t.data?"variant"in t.data?{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product,variant:t.data.variant})}}:{...t,data:{...t.data,badges:this.badges.getBadges({product:t.data.product})}}:t),"loadProductCardData");this.loadProductDetailData=s(async e=>$r(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}).then(t=>{if(!t.data?.product)return t;let n=t.data.product,i="variant"in t.data?t.data.variant:null,o=this.badges.getBadges({product:n,variant:i});return{...t,data:{product:n,variant:i,badges:o}}}),"loadProductDetailData");this.loadProductImages=s(async e=>qr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadProductImages");this.loadProductRecommendations=s(async e=>Ur(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}).then(t=>{if(!t.data?.productRecommendations)return t;let n=t.data.productRecommendations.map(i=>{let o=this.badges.getBadges({product:i});return{product:i,badges:o}});return{...t,data:{productRecommendations:n}}}),"loadProductRecommendations");this.loadProductId=s(async e=>Br(this,e),"loadProductId");this.loadSaveIntentData=s(async e=>Nr(this,{...e,...this.metafields,country:this.context.localization.country,language:this.context.localization.language}),"loadSaveIntentData");this.options=e,this.context=t,this.badges=n,this.metafields={productMetafields:i?.product.map(o=>({namespace:o.split(".")[0],key:o.split(".")[1]}))??[],variantMetafields:i?.productVariant.map(o=>({namespace:o.split(".")[0],key:o.split(".")[1]}))??[]},this.shortCache=new Q("storefront-api-short","max-age=60, stale-while-revalidate=3600"),this.longCache=new Q("storefront-api-long","max-age=3600, stale-while-revalidate=86400"),this.shortCache.cleanupExpiredEntries().catch(o=>{console.warn("Storefront API cache initialization cleanup error:",o)}),this.longCache.cleanupExpiredEntries().catch(o=>{console.warn("Storefront API cache initialization cleanup error:",o)}),this.client=It({apiVersion:Jn,customFetchApi:s((o,a)=>a?.method==="OPTIONS"?this.fetch(o,a):Zn.some(u=>a?.body?.toString().includes(`query ${u}`))?this.longCache.fetchWithCache(o,a):this.shortCache.fetchWithCache(o,a),"customFetchApi"),publicAccessToken:this.options.accessToken,storeDomain:this.options.storeDomain})}static{s(this,"StorefrontApiClient")}fetch(e,t){return t?.method==="OPTIONS"?fetch(e,t):this.shortCache.fetchWithCache(e,t)}async clearCache(){await this.shortCache.clear()}};var ei=Object.defineProperty,d=s((r,e)=>ei(r,"name",{value:e,configurable:!0}),"n"),ti={bodySerializer:d(r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString():t),"bodySerializer")},ri={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},Mu=Object.entries(ri),ni=d(({onRequest:r,onSseError:e,onSseEvent:t,responseTransformer:n,responseValidator:i,sseDefaultRetryDelay:o,sseMaxRetryAttempts:a,sseMaxRetryDelay:u,sseSleepFn:l,url:c,...p})=>{let f,m=l??(h=>new Promise(R=>setTimeout(R,h)));return{stream:d(async function*(){let h=o??3e3,R=0,y=p.signal??new AbortController().signal;for(;!y.aborted;){R++;let S=p.headers instanceof Headers?p.headers:new Headers(p.headers);f!==void 0&&S.set("Last-Event-ID",f);try{let L={redirect:"follow",...p,body:p.serializedBody,headers:S,signal:y},k=new Request(c,L);r&&(k=await r(c,L));let F=await(p.fetch??globalThis.fetch)(k);if(!F.ok)throw new Error(`SSE failed: ${F.status} ${F.statusText}`);if(!F.body)throw new Error("No body in SSE response");let I=F.body.pipeThrough(new TextDecoderStream).getReader(),v="",P=d(()=>{try{I.cancel()}catch{}},"abortHandler");y.addEventListener("abort",P);try{for(;;){let{done:T,value:pe}=await I.read();if(T)break;v+=pe;let Ot=v.split(`
|
|
456
445
|
|
|
457
|
-
`);
|
|
458
|
-
`),
|
|
459
|
-
`);try{re=JSON.parse(H),Wt=!0}catch{re=H}}Wt&&(s&&await s(re),n&&(re=await n(re))),r?.({data:re,event:zt,id:h,retry:y}),Ee.length&&(yield re)}}}finally{m.removeEventListener("abort",T),w.releaseLock()}break}catch($){if(e?.($),a!==void 0&&R>=a)break;let k=Math.min(y*2**(R-1),u??3e4);await v(k)}}},"createStream")()}},"createSseClient"),Bi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),Ni=d(t=>{switch(t){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),Gi=d(t=>{switch(t){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),In=d(({allowReserved:t,explode:e,name:r,style:n,value:s})=>{if(!e){let u=(t?s:s.map(l=>encodeURIComponent(l))).join(Ni(n));switch(n){case"label":return`.${u}`;case"matrix":return`;${r}=${u}`;case"simple":return u;default:return`${r}=${u}`}}let o=Bi(n),a=s.map(u=>n==="label"||n==="simple"?t?u:encodeURIComponent(u):Ze({allowReserved:t,name:r,value:u})).join(o);return n==="label"||n==="matrix"?o+a:a},"serializeArrayParam"),Ze=d(({allowReserved:t,name:e,value:r})=>{if(r==null)return"";if(typeof r=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${t?r:encodeURIComponent(r)}`},"serializePrimitiveParam"),bn=d(({allowReserved:t,explode:e,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(s).forEach(([p,h])=>{l=[...l,p,t?h:encodeURIComponent(h)]});let c=l.join(",");switch(n){case"form":return`${r}=${c}`;case"label":return`.${c}`;case"matrix":return`;${r}=${c}`;default:return c}}let a=Gi(n),u=Object.entries(s).map(([l,c])=>Ze({allowReserved:t,name:n==="deepObject"?`${r}[${l}]`:l,value:c})).join(a);return n==="label"||n==="matrix"?a+u:u},"serializeObjectParam"),ji=/\{[^{}]+\}/g,Ui=d(({path:t,url:e})=>{let r=e,n=e.match(ji);if(n)for(let s of n){let o=!1,a=s.substring(1,s.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let l=t[a];if(l==null)continue;if(Array.isArray(l)){r=r.replace(s,In({explode:o,name:a,style:u,value:l}));continue}if(typeof l=="object"){r=r.replace(s,bn({explode:o,name:a,style:u,value:l,valueOnly:!0}));continue}if(u==="matrix"){r=r.replace(s,`;${Ze({name:a,value:l})}`);continue}let c=encodeURIComponent(u==="label"?`.${l}`:l);r=r.replace(s,c)}return r},"defaultPathSerializer"),Mi=d(({baseUrl:t,path:e,query:r,querySerializer:n,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,a=(t??"")+o;e&&(a=Ui({path:e,url:a}));let u=r?n(r):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function wn(t){let e=t.body!==void 0;if(e&&t.bodySerializer)return"serializedBody"in t?t.serializedBody!==void 0&&t.serializedBody!==""?t.serializedBody:null:t.body!==""?t.body:null;if(e)return t.body}i(wn,"G");d(wn,"getValidRequestBody");var Fi=d(async(t,e)=>{let r=typeof e=="function"?await e(t):e;if(r)return t.scheme==="bearer"?`Bearer ${r}`:t.scheme==="basic"?`Basic ${btoa(r)}`:r},"getAuthToken"),En=d(({allowReserved:t,array:e,object:r}={})=>d(n=>{let s=[];if(n&&typeof n=="object")for(let o in n){let a=n[o];if(a!=null)if(Array.isArray(a)){let u=In({allowReserved:t,explode:!0,name:o,style:"form",value:a,...e});u&&s.push(u)}else if(typeof a=="object"){let u=bn({allowReserved:t,explode:!0,name:o,style:"deepObject",value:a,...r});u&&s.push(u)}else{let u=Ze({allowReserved:t,name:o,value:a});u&&s.push(u)}}return s.join("&")},"querySerializer"),"createQuerySerializer"),Hi=d(t=>{var e;if(!t)return"stream";let r=(e=t.split(";")[0])==null?void 0:e.trim();if(r){if(r.startsWith("application/json")||r.endsWith("+json"))return"json";if(r==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>r.startsWith(n)))return"blob";if(r.startsWith("text/"))return"text"}},"getParseAs"),Qi=d((t,e)=>{var r,n;return e?!!(t.headers.has(e)||(r=t.query)!=null&&r[e]||(n=t.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),zi=d(async({security:t,...e})=>{for(let r of t){if(Qi(e,r.name))continue;let n=await Fi(r,e.auth);if(!n)continue;let s=r.name??"Authorization";switch(r.in){case"query":e.query||(e.query={}),e.query[s]=n;break;case"cookie":e.headers.append("Cookie",`${s}=${n}`);break;case"header":default:e.headers.set(s,n);break}}},"setAuthParams"),mn=d(t=>Mi({baseUrl:t.baseUrl,path:t.path,query:t.query,querySerializer:typeof t.querySerializer=="function"?t.querySerializer:En(t.querySerializer),url:t.url}),"buildUrl"),vn=d((t,e)=>{var r;let n={...t,...e};return(r=n.baseUrl)!=null&&r.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Cn(t.headers,e.headers),n},"mergeConfigs"),Wi=d(t=>{let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e},"headersEntries"),Cn=d((...t)=>{let e=new Headers;for(let r of t){if(!r)continue;let n=r instanceof Headers?Wi(r):Object.entries(r);for(let[s,o]of n)if(o===null)e.delete(s);else if(Array.isArray(o))for(let a of o)e.append(s,a);else o!==void 0&&e.set(s,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),xn=class{static{i(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let r=this.getInterceptorIndex(e);this.fns[r]&&(this.fns[r]=null)}exists(e){let r=this.getInterceptorIndex(e);return!!this.fns[r]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,r){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=r,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(xn,"Interceptors");var Nt=xn,Xi=d(()=>({error:new Nt,request:new Nt,response:new Nt}),"createInterceptors"),Ki=En({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Yi={"Content-Type":"application/json"},Je=d((t={})=>({...$i,headers:Yi,parseAs:"auto",querySerializer:Ki,...t}),"createConfig"),Gt=d((t={})=>{let e=vn(Je(),t),r=d(()=>({...e}),"getConfig"),n=d(c=>(e=vn(e,c),r()),"setConfig"),s=Xi(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:Cn(e.headers,c.headers),serializedBody:void 0};p.security&&await zi({...p,security:p.security}),p.requestValidator&&await p.requestValidator(p),p.body!==void 0&&p.bodySerializer&&(p.serializedBody=p.bodySerializer(p.body)),(p.body===void 0||p.serializedBody==="")&&p.headers.delete("Content-Type");let h=mn(p);return{opts:p,url:h}},"beforeRequest"),a=d(async c=>{let{opts:p,url:h}=await o(c),v={redirect:"follow",...p,body:wn(p)},y=new Request(h,v);for(let g of s.request.fns)g&&(y=await g(y,p));let R=p.fetch,m=await R(y);for(let g of s.response.fns)g&&(m=await g(m,y,p));let D={request:y,response:m};if(m.ok){let g=(p.parseAs==="auto"?Hi(m.headers.get("Content-Type")):p.parseAs)??"json";if(m.status===204||m.headers.get("Content-Length")==="0"){let _;switch(g){case"arrayBuffer":case"blob":case"text":_=await m[g]();break;case"formData":_=new FormData;break;case"stream":_=m.body;break;case"json":default:_={};break}return p.responseStyle==="data"?_:{data:_,...D}}let T;switch(g){case"arrayBuffer":case"blob":case"formData":case"json":case"text":T=await m[g]();break;case"stream":return p.responseStyle==="data"?m.body:{data:m.body,...D}}return g==="json"&&(p.responseValidator&&await p.responseValidator(T),p.responseTransformer&&(T=await p.responseTransformer(T))),p.responseStyle==="data"?T:{data:T,...D}}let $=await m.text(),k;try{k=JSON.parse($)}catch{}let z=k??$,w=z;for(let g of s.error.fns)g&&(w=await g(z,m,y,p));if(w=w||{},p.throwOnError)throw w;return p.responseStyle==="data"?void 0:{error:w,...D}},"request"),u=d(c=>p=>a({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:h,url:v}=await o(p);return qi({...h,body:h.body,headers:h.headers,method:c,onRequest:d(async(y,R)=>{let m=new Request(y,R);for(let D of s.request.fns)D&&(m=await D(m,h));return m},"onRequest"),url:v})},"makeSseFn");return{buildUrl:mn,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:r,head:u("HEAD"),interceptors:s,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:n,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:u("TRACE")}},"createClient"),A=Gt(Je({baseUrl:"https://swish.app/api/2026-01"})),Ji=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t}),"listControllerFind"),Zi=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerCreate"),es=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerDeleteById"),ts=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t}),"listControllerFindById"),rs=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerUpdateById"),ns=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerSetListItemsOrder"),is=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"listControllerAddItemsToList"),ss=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...t}),"listControllerRemoveItemFromList"),os=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerDelete"),as=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...t}),"itemControllerFind"),us=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerCreate"),ls=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...t}),"itemControllerCount"),cs=d(t=>(t.client??A).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerDeleteById"),ps=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t}),"itemControllerFindById"),ds=d(t=>(t.client??A).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerUpdateById"),fs=d(t=>(t.client??A).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...t,headers:{"Content-Type":"application/json",...t.headers}}),"itemControllerSetListsById"),hs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...t}),"profileControllerCustomerAccountsVersion"),ys=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerIdentify"),ms=d(t=>(t.client??A).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...t,headers:{"Content-Type":"application/json",...t.headers}}),"profileControllerCreateToken"),vs=d(t=>(t?.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...t}),"ordersControllerFind"),gs=d(t=>(t.client??A).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...t}),"ordersControllerFindOne"),jt="2026-01",gn="/apps/wishlist/api",Sn=d(t=>new Is(t),"createApiClient"),An=class{static{i(this,"H")}constructor(e){this.useProxy=!1,this.version=jt,this.items={list:d(n=>this.handlePaginatedRequest(as({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(us({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),delete:d(n=>this.handleRequest(os({body:{itemIds:n},client:this.useProxy?this.proxyClient:this.directClient})),"delete"),findById:d(n=>this.handleRequest(ps({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(ds({body:s,path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(cs({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),setListsById:d((n,s)=>this.handleRequest(fs({body:{listIds:s},path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(ls({client:this.useProxy?this.proxyClient:this.directClient})),"count")},this.lists={list:d(n=>this.handlePaginatedRequest(Ji({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(Zi({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),findById:d(n=>this.handleRequest(ts({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,s)=>this.handleRequest(rs({body:s,path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(es({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),orderItems:d((n,s)=>this.handleRequest(ns({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"orderItems"),addItemsToList:d((n,s)=>this.handleRequest(is({body:{itemIds:s},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"addItemsToList"),removeItemFromList:d((n,s)=>this.handleRequest(ss({path:{listId:n,itemId:s},client:this.useProxy?this.proxyClient:this.directClient})),"removeItemFromList")},this.profiles={customerAccountsVersion:d(()=>this.handleRequest(hs({client:this.useProxy?this.proxyClient:this.directClient})),"customerAccountsVersion"),createToken:d((n={},s)=>this.handleRequest(ms({body:n,client:this.useProxy||s!=null&&s.useProxy?this.proxyClient:this.directClient})),"createToken"),identify:d(n=>this.handleRequest(ys({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"identify")},this.orders={list:d(n=>this.handlePaginatedRequest(vs({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),findById:d(n=>this.handleRequest(gs({path:{orderId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById")},this.handleRequest=d(async n=>{let{data:s,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:s?.data}},"handleRequest"),this.handlePaginatedRequest=d(async n=>{var s;let{data:o,error:a}=await n;return a!=null&&a.error?{error:a.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((s=o?.data)==null?void 0:s.length)??0}}},"handlePaginatedRequest");var r;this.profile=e.profile,(r=e.config)!=null&&r.version&&(this.version=e.config.version),this.directClient=Gt(Je({baseUrl:`https://swish.app/api/${this.version}`})),this.proxyClient=Gt(Je({baseUrl:gn})),e.authToken&&(this.authToken=e.authToken),e.config&&this.setConfig(e.config),e.requestInterceptor&&(this.proxyClient.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&(this.proxyClient.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),this.proxyClient.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig({proxyBaseUrl:e=gn,baseUrl:r,useProxy:n=!1,...s}){this.useProxy=n,this.proxyClient.setConfig({...s,baseUrl:e}),this.directClient.setConfig({...s})}proxyRequestInterceptor(e){return this.profile&&(e.headers.set("Profile",this.profile),e.headers.set("Swish-Api-Version",this.version)),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(An,"SwishClient");var Is=An;var Dn=i(t=>t?JSON.parse(atob(t.split(".")[1])):null,"getTokenData"),kn=i((t,e=60)=>{let r=Dn(t);return r?r.exp&&r.exp<Date.now()/1e3+e:!1},"isTokenExpired"),Rn=i(t=>{let e=Dn(t);return e?e.sub.startsWith("gid://shopify/Customer/"):!1},"isCustomerToken");var On=Fn(_n(),1);var Ln=i(t=>new On.default(async e=>{let r=[...new Set(e)].sort((s,o)=>s.localeCompare(o)),n=await t.items.list({query:r.join(" "),limit:200});return"error"in n?(console.error("Failed to load items",n.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(s=>{let o=n.data.find(a=>s===`variant:${a.variantId}`||s===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:i(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var et=class{static{i(this,"SwishApi")}constructor(e,r){this.config=e,this.cache=new K("swish-api","max-age=60, stale-while-revalidate=3600",r+(e.version??jt)),this.cache.cleanupExpiredEntries().catch(o=>{console.warn("Swish API cache initialization cleanup error:",o)});let n=this.config.loadProfile?.(),s=this.config.loadAuthToken?.();this.apiClient=Sn({profile:n,authToken:s,proxyMode:this.config.proxyMode,config:{...e,fetch:i((o,a)=>(o instanceof Request?o.method:a?.method??"GET")==="GET"?this.cache.fetchWithCache(o,a):fetch(o,a),"fetch")},requestInterceptor:i(async o=>{let a=new URL(o.url,window.location.origin),u=this.config.proxyBaseUrl??"/apps/wishlist/api",l=a.pathname==="/profiles/token";return!a.pathname.startsWith(u)&&!l&&await this.bootstrapAuth(),o},"requestInterceptor"),responseInterceptor:i(async(o,a)=>(this.processProfileHeader(o),a.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(o,a),o),"responseInterceptor")}),this.itemsLoader=Ln(this)}async bootstrapAuth(){if(this._bootstrapAuthPromise)return this._bootstrapAuthPromise;this._bootstrapAuthPromise=(async()=>{let e=this.config.loadAuthToken?.();if(e)try{if(kn(e,60))throw new Error("TOKEN_EXPIRED")}catch(o){(!(o instanceof Error)||o.message!=="TOKEN_EXPIRED")&&console.error("Failed to decode cached auth token",{cause:o}),this.config.deleteAuthToken?.(),e=void 0}if(e){this.apiClient.setAuthToken(e);return}let r=this.apiClient.getProfile(),n=this.config.customerId,s=await this.apiClient.profiles.createToken({customer:n,session:r},{useProxy:!0});if("error"in s){console.error("Failed to bootstrap auth with error",s.error);return}if(!s.data?.token){console.error("Failed to bootstrap auth with no token");return}await this.config.storeAuthToken?.(s.data.token),this.apiClient.setAuthToken(s.data.token)})();try{return await this._bootstrapAuthPromise}finally{this._bootstrapAuthPromise=void 0}}processProfileHeader(e){let r=e.headers.get("Set-Profile");r?(this.apiClient.setProfile(r),this.config.storeProfile?.(r)):r===""&&this.config.deleteProfile?.()}get items(){return{...this.apiClient.items,list:i(async(e,r)=>{if(!f.customer.id&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(r?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let n=e.query.split(" ");n.length>1&&console.warn("Batching will only support one query parameter");let s=n[0];if(!s.match(/^product:\d+$/)&&!s.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(s)}return this.apiClient.items.list(e)},"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get orders(){return{...this.apiClient.orders,list:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.orders.list(e),"list"),findById:i(async e=>!f.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.orders.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var tt=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{i(this,"SwishApiPublisher")}async processFetchResponse(e,r){try{let n=this.getEventName(r.method,e.status,r.url);if(!n)return;let s=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{s=JSON.parse(s).data}catch(o){console.warn(o)}this.eventBus.publish(n,s)}catch(n){console.warn(n)}}getEventName(e,r,n){e=e.toUpperCase();let s=new URL(n).pathname;return e==="GET"||r<200||r>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,l]=a.split(" ");return u!==e?!1:new RegExp(l).test(s)})?.[1]}};var rt=class extends HTMLElement{constructor(){super();this.getComponentRef=i(()=>this.componentRef,"getComponentRef");this.setComponentRef=i(r=>{this.componentRef=r},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let r=this.querySelector("template");r&&this.shadowRoot&&(this.shadowRoot.appendChild(r.content),r.remove())}static{i(this,"SwishUiElement")}};var Rs="0.61.0",f={customer:{id:null,email:null,firstName:null,lastName:null,b2b:null},localization:{country:"",language:"",market:0},routes:{accountUrl:"/account",accountLoginUrl:"/account/login",rootUrl:"/"}},Lc=i(async t=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}try{let n=document.getElementById("swishEmbedData");if(!n)throw new Error("Swish embed data not found");Object.assign(f,JSON.parse(n.innerText))}catch(n){console.warn("Could not read Swish embed data.",{cause:n})}let e=t.proxy?.baseUrl??"/apps/wishlist",r=new Ht({loadProfile:i(()=>localStorage.getItem("swish-profile")??void 0,"loadProfile"),storeProfile:i(n=>localStorage.setItem("swish-profile",n),"storeProfile"),deleteProfile:i(()=>localStorage.removeItem("swish-profile"),"deleteProfile"),loadAuthToken:i(()=>sessionStorage.getItem("swish-token")??void 0,"loadAuthToken"),storeAuthToken:i(n=>sessionStorage.setItem("swish-token",n),"storeAuthToken"),deleteAuthToken:i(()=>sessionStorage.removeItem("swish-token"),"deleteAuthToken"),proxy:{baseUrl:e},ui:t.ui,storefront:t.storefront,swishApi:t.swishApi});try{let n=localStorage.getItem("swish-token"),s=n&&Rn(n),o=!!f.customer.id;o!==s&&localStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await r.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=r,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e,market:f.localization.market,country:f.localization.country,rootUrl:f.routes.rootUrl}),r},"swishApp"),Ht=class{constructor(e){this.ui={hideModal:nr,showModal:Q,initShopBridge:hr,showToast:pr,initListDetailPage:cr};this.dom={createElementLocator:ge,createQueryParamsObserver:de};this.state={itemContext:Er(this),itemState:Cr(this),itemCount:xr(this),swishQuery:Sr(this),effect:M,signal:S,computed:U};this.options=e,this.events=new Se;let r={proxyBaseUrl:`${this.options.proxy.baseUrl}/api`,...this.options.swishApi??{}};this.swishApiPublisher=new tt(this.events);let n=[Rs,e.ui?.version].join("-");this.swishApi=new et({...r,version:r.version,customerId:f.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse,loadProfile:e.loadProfile,storeProfile:e.storeProfile,deleteProfile:e.deleteProfile,loadAuthToken:e.loadAuthToken,storeAuthToken:e.storeAuthToken,deleteAuthToken:e.deleteAuthToken},n),this.ajaxApiPublisher=new xe(this.events),this.ajaxApi=new Ce({storeDomain:this.options.storefront.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ye(this.options.storefront),this.options.ui&&rr(this.options.ui),this.events.subscribe(["cart-add","cart-update","cart-change","cart-clear"],()=>{this.ajaxApi.clearCache()}),customElements.get("swish-ui")||customElements.define("swish-ui",rt),this.intents=new Me(this,{allowSaveWithoutVariant:!1,deleteSavedItemsWithoutEdit:!1,showToastAfterSave:!0,showToastAfterDelete:!0})}static{i(this,"SwishApp")}get customer(){return f.customer}get localization(){return f.localization}get shopifyRoutes(){return f.routes}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.options.storefront.storeDomain}`}};export{Ht as SwishApp,Rs as VERSION,Lc as swishApp,f as swishEmbedData};
|
|
446
|
+
`);v=Ot.pop()??"";for(let ln of Ot){let cn=ln.split(`
|
|
447
|
+
`),he=[],Lt;for(let G of cn)if(G.startsWith("data:"))he.push(G.replace(/^data:\s*/,""));else if(G.startsWith("event:"))Lt=G.replace(/^event:\s*/,"");else if(G.startsWith("id:"))f=G.replace(/^id:\s*/,"");else if(G.startsWith("retry:")){let Bt=Number.parseInt(G.replace(/^retry:\s*/,""),10);Number.isNaN(Bt)||(h=Bt)}let J,$t=!1;if(he.length){let G=he.join(`
|
|
448
|
+
`);try{J=JSON.parse(G),$t=!0}catch{J=G}}$t&&(i&&await i(J),n&&(J=await n(J))),t?.({data:J,event:Lt,id:f,retry:h}),he.length&&(yield J)}}}finally{y.removeEventListener("abort",P),I.releaseLock()}break}catch(L){if(e?.(L),a!==void 0&&R>=a)break;let k=Math.min(h*2**(R-1),u??3e4);await m(k)}}},"createStream")()}},"createSseClient"),ii=d(r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorArrayExplode"),si=d(r=>{switch(r){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},"separatorArrayNoExplode"),oi=d(r=>{switch(r){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},"separatorObjectExplode"),Hr=d(({allowReserved:r,explode:e,name:t,style:n,value:i})=>{if(!e){let u=(r?i:i.map(l=>encodeURIComponent(l))).join(si(n));switch(n){case"label":return`.${u}`;case"matrix":return`;${t}=${u}`;case"simple":return u;default:return`${t}=${u}`}}let o=ii(n),a=i.map(u=>n==="label"||n==="simple"?r?u:encodeURIComponent(u):Ne({allowReserved:r,name:t,value:u})).join(o);return n==="label"||n==="matrix"?o+a:a},"serializeArrayParam"),Ne=d(({allowReserved:r,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}=${r?t:encodeURIComponent(t)}`},"serializePrimitiveParam"),Qr=d(({allowReserved:r,explode:e,name:t,style:n,value:i,valueOnly:o})=>{if(i instanceof Date)return o?i.toISOString():`${t}=${i.toISOString()}`;if(n!=="deepObject"&&!e){let l=[];Object.entries(i).forEach(([p,f])=>{l=[...l,p,r?f:encodeURIComponent(f)]});let c=l.join(",");switch(n){case"form":return`${t}=${c}`;case"label":return`.${c}`;case"matrix":return`;${t}=${c}`;default:return c}}let a=oi(n),u=Object.entries(i).map(([l,c])=>Ne({allowReserved:r,name:n==="deepObject"?`${t}[${l}]`:l,value:c})).join(a);return n==="label"||n==="matrix"?a+u:u},"serializeObjectParam"),ai=/\{[^{}]+\}/g,ui=d(({path:r,url:e})=>{let t=e,n=e.match(ai);if(n)for(let i of n){let o=!1,a=i.substring(1,i.length-1),u="simple";a.endsWith("*")&&(o=!0,a=a.substring(0,a.length-1)),a.startsWith(".")?(a=a.substring(1),u="label"):a.startsWith(";")&&(a=a.substring(1),u="matrix");let l=r[a];if(l==null)continue;if(Array.isArray(l)){t=t.replace(i,Hr({explode:o,name:a,style:u,value:l}));continue}if(typeof l=="object"){t=t.replace(i,Qr({explode:o,name:a,style:u,value:l,valueOnly:!0}));continue}if(u==="matrix"){t=t.replace(i,`;${Ne({name:a,value:l})}`);continue}let c=encodeURIComponent(u==="label"?`.${l}`:l);t=t.replace(i,c)}return t},"defaultPathSerializer"),li=d(({baseUrl:r,path:e,query:t,querySerializer:n,url:i})=>{let o=i.startsWith("/")?i:`/${i}`,a=(r??"")+o;e&&(a=ui({path:e,url:a}));let u=t?n(t):"";return u.startsWith("?")&&(u=u.substring(1)),u&&(a+=`?${u}`),a},"getUrl");function zr(r){let e=r.body!==void 0;if(e&&r.bodySerializer)return"serializedBody"in r?r.serializedBody!==void 0&&r.serializedBody!==""?r.serializedBody:null:r.body!==""?r.body:null;if(e)return r.body}s(zr,"G");d(zr,"getValidRequestBody");var ci=d(async(r,e)=>{let t=typeof e=="function"?await e(r):e;if(t)return r.scheme==="bearer"?`Bearer ${t}`:r.scheme==="basic"?`Basic ${btoa(t)}`:t},"getAuthToken"),Wr=d(({allowReserved:r,array:e,object:t}={})=>d(n=>{let i=[];if(n&&typeof n=="object")for(let o in n){let a=n[o];if(a!=null)if(Array.isArray(a)){let u=Hr({allowReserved:r,explode:!0,name:o,style:"form",value:a,...e});u&&i.push(u)}else if(typeof a=="object"){let u=Qr({allowReserved:r,explode:!0,name:o,style:"deepObject",value:a,...t});u&&i.push(u)}else{let u=Ne({allowReserved:r,name:o,value:a});u&&i.push(u)}}return i.join("&")},"querySerializer"),"createQuerySerializer"),pi=d(r=>{var e;if(!r)return"stream";let t=(e=r.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(n=>t.startsWith(n)))return"blob";if(t.startsWith("text/"))return"text"}},"getParseAs"),di=d((r,e)=>{var t,n;return e?!!(r.headers.has(e)||(t=r.query)!=null&&t[e]||(n=r.headers.get("Cookie"))!=null&&n.includes(`${e}=`)):!1},"checkForExistence"),fi=d(async({security:r,...e})=>{for(let t of r){if(di(e,t.name))continue;let n=await ci(t,e.auth);if(!n)continue;let i=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[i]=n;break;case"cookie":e.headers.append("Cookie",`${i}=${n}`);break;case"header":default:e.headers.set(i,n);break}}},"setAuthParams"),Gr=d(r=>li({baseUrl:r.baseUrl,path:r.path,query:r.query,querySerializer:typeof r.querySerializer=="function"?r.querySerializer:Wr(r.querySerializer),url:r.url}),"buildUrl"),jr=d((r,e)=>{var t;let n={...r,...e};return(t=n.baseUrl)!=null&&t.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Xr(r.headers,e.headers),n},"mergeConfigs"),hi=d(r=>{let e=[];return r.forEach((t,n)=>{e.push([n,t])}),e},"headersEntries"),Xr=d((...r)=>{let e=new Headers;for(let t of r){if(!t)continue;let n=t instanceof Headers?hi(t):Object.entries(t);for(let[i,o]of n)if(o===null)e.delete(i);else if(Array.isArray(o))for(let a of o)e.append(i,a);else o!==void 0&&e.set(i,typeof o=="object"?JSON.stringify(o):o)}return e},"mergeHeaders"),Kr=class{static{s(this,"$")}constructor(){this.fns=[]}clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){let t=this.getInterceptorIndex(e);return!!this.fns[t]}getInterceptorIndex(e){return typeof e=="number"?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){let n=this.getInterceptorIndex(e);return this.fns[n]?(this.fns[n]=t,e):!1}use(e){return this.fns.push(e),this.fns.length-1}};d(Kr,"Interceptors");var St=Kr,yi=d(()=>({error:new St,request:new St,response:new St}),"createInterceptors"),mi=Wr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),vi={"Content-Type":"application/json"},Ue=d((r={})=>({...ti,headers:vi,parseAs:"auto",querySerializer:mi,...r}),"createConfig"),At=d((r={})=>{let e=jr(Ue(),r),t=d(()=>({...e}),"getConfig"),n=d(c=>(e=jr(e,c),t()),"setConfig"),i=yi(),o=d(async c=>{let p={...e,...c,fetch:c.fetch??e.fetch??globalThis.fetch,headers:Xr(e.headers,c.headers),serializedBody:void 0};p.security&&await fi({...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=Gr(p);return{opts:p,url:f}},"beforeRequest"),a=d(async c=>{let{opts:p,url:f}=await o(c),m={redirect:"follow",...p,body:zr(p)},h=new Request(f,m);for(let v of i.request.fns)v&&(h=await v(h,p));let R=p.fetch,y=await R(h);for(let v of i.response.fns)v&&(y=await v(y,h,p));let S={request:h,response:y};if(y.ok){let v=(p.parseAs==="auto"?pi(y.headers.get("Content-Type")):p.parseAs)??"json";if(y.status===204||y.headers.get("Content-Length")==="0"){let T;switch(v){case"arrayBuffer":case"blob":case"text":T=await y[v]();break;case"formData":T=new FormData;break;case"stream":T=y.body;break;case"json":default:T={};break}return p.responseStyle==="data"?T:{data:T,...S}}let P;switch(v){case"arrayBuffer":case"blob":case"formData":case"json":case"text":P=await y[v]();break;case"stream":return p.responseStyle==="data"?y.body:{data:y.body,...S}}return v==="json"&&(p.responseValidator&&await p.responseValidator(P),p.responseTransformer&&(P=await p.responseTransformer(P))),p.responseStyle==="data"?P:{data:P,...S}}let L=await y.text(),k;try{k=JSON.parse(L)}catch{}let F=k??L,I=F;for(let v of i.error.fns)v&&(I=await v(F,y,h,p));if(I=I||{},p.throwOnError)throw I;return p.responseStyle==="data"?void 0:{error:I,...S}},"request"),u=d(c=>p=>a({...p,method:c}),"makeMethodFn"),l=d(c=>async p=>{let{opts:f,url:m}=await o(p);return ni({...f,body:f.body,headers:f.headers,method:c,onRequest:d(async(h,R)=>{let y=new Request(h,R);for(let S of i.request.fns)S&&(y=await S(y,f));return y},"onRequest"),url:m})},"makeSseFn");return{buildUrl:Gr,connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),getConfig:t,head:u("HEAD"),interceptors:i,options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),request:a,setConfig:n,sse:{connect:l("CONNECT"),delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT"),trace:l("TRACE")},trace:u("TRACE")}},"createClient"),x=At(Ue({baseUrl:"https://swish.app/api/2026-01"})),gi=d(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/lists",...r}),"listControllerFind"),Ii=d(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/lists",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerCreate"),wi=d(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r}),"listControllerDeleteById"),bi=d(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r}),"listControllerFindById"),Ei=d(r=>(r.client??x).patch({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerUpdateById"),Ci=d(r=>(r.client??x).put({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/order",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerSetListItemsOrder"),xi=d(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"listControllerAddItemsToList"),Si=d(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/lists/{listId}/items/{itemId}",...r}),"listControllerRemoveItemFromList"),Ai=d(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerDelete"),ki=d(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items",...r}),"itemControllerFind"),Di=d(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/items",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerCreate"),Ri=d(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items/count",...r}),"itemControllerCount"),Pi=d(r=>(r.client??x).delete({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r}),"itemControllerDeleteById"),Ti=d(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r}),"itemControllerFindById"),_i=d(r=>(r.client??x).patch({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerUpdateById"),Oi=d(r=>(r.client??x).put({security:[{scheme:"bearer",type:"http"}],url:"/items/{itemId}/lists",...r,headers:{"Content-Type":"application/json",...r.headers}}),"itemControllerSetListsById"),Li=d(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/profiles/accounts-version",...r}),"profileControllerCustomerAccountsVersion"),$i=d(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/identify",...r,headers:{"Content-Type":"application/json",...r.headers}}),"profileControllerIdentify"),Bi=d(r=>(r.client??x).post({security:[{scheme:"bearer",type:"http"}],url:"/profiles/token",...r,headers:{"Content-Type":"application/json",...r.headers}}),"profileControllerCreateToken"),qi=d(r=>(r?.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/orders",...r}),"ordersControllerFind"),Vi=d(r=>(r.client??x).get({security:[{scheme:"bearer",type:"http"}],url:"/orders/{orderId}",...r}),"ordersControllerFindOne"),kt="2026-01",Fr="/apps/wishlist/api",Yr=d(r=>new Ui(r),"createApiClient"),Jr=class{static{s(this,"H")}constructor(e){this.useProxy=!1,this.version=kt,this.items={list:d(n=>this.handlePaginatedRequest(ki({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(Di({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),delete:d(n=>this.handleRequest(Ai({body:{itemIds:n},client:this.useProxy?this.proxyClient:this.directClient})),"delete"),findById:d(n=>this.handleRequest(Ti({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,i)=>this.handleRequest(_i({body:i,path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(Pi({path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),setListsById:d((n,i)=>this.handleRequest(Oi({body:{listIds:i},path:{itemId:n},client:this.useProxy?this.proxyClient:this.directClient})),"setListsById"),count:d(()=>this.handleRequest(Ri({client:this.useProxy?this.proxyClient:this.directClient})),"count")},this.lists={list:d(n=>this.handlePaginatedRequest(gi({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),create:d(n=>this.handleRequest(Ii({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"create"),findById:d(n=>this.handleRequest(bi({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById"),updateById:d((n,i)=>this.handleRequest(Ei({body:i,path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"updateById"),deleteById:d(n=>this.handleRequest(wi({path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"deleteById"),orderItems:d((n,i)=>this.handleRequest(Ci({body:{itemIds:i},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"orderItems"),addItemsToList:d((n,i)=>this.handleRequest(xi({body:{itemIds:i},path:{listId:n},client:this.useProxy?this.proxyClient:this.directClient})),"addItemsToList"),removeItemFromList:d((n,i)=>this.handleRequest(Si({path:{listId:n,itemId:i},client:this.useProxy?this.proxyClient:this.directClient})),"removeItemFromList")},this.profiles={customerAccountsVersion:d(()=>this.handleRequest(Li({client:this.useProxy?this.proxyClient:this.directClient})),"customerAccountsVersion"),createToken:d((n={},i)=>this.handleRequest(Bi({body:n,client:this.useProxy||i!=null&&i.useProxy?this.proxyClient:this.directClient})),"createToken"),identify:d(n=>this.handleRequest($i({body:n,client:this.useProxy?this.proxyClient:this.directClient})),"identify")},this.orders={list:d(n=>this.handlePaginatedRequest(qi({query:n,client:this.useProxy?this.proxyClient:this.directClient})),"list"),findById:d(n=>this.handleRequest(Vi({path:{orderId:n},client:this.useProxy?this.proxyClient:this.directClient})),"findById")},this.handleRequest=d(async n=>{let{data:i,error:o}=await n;return o!=null&&o.error?{error:o.error}:{data:i?.data}},"handleRequest"),this.handlePaginatedRequest=d(async n=>{var i;let{data:o,error:a}=await n;return a!=null&&a.error?{error:a.error}:{data:o?.data??[],pageInfo:o?.pageInfo??{next:null,previous:null,totalCount:((i=o?.data)==null?void 0:i.length)??0}}},"handlePaginatedRequest");var t;this.profile=e.profile,(t=e.config)!=null&&t.version&&(this.version=e.config.version),this.directClient=At(Ue({baseUrl:`https://swish.app/api/${this.version}`})),this.proxyClient=At(Ue({baseUrl:Fr})),e.authToken&&(this.authToken=e.authToken),e.config&&this.setConfig(e.config),e.requestInterceptor&&(this.proxyClient.interceptors.request.use(e.requestInterceptor),this.directClient.interceptors.request.use(e.requestInterceptor)),e.responseInterceptor&&(this.proxyClient.interceptors.response.use(e.responseInterceptor),this.directClient.interceptors.response.use(e.responseInterceptor)),this.proxyClient.interceptors.request.use(this.proxyRequestInterceptor.bind(this)),this.directClient.interceptors.request.use(this.directRequestInterceptor.bind(this))}setProfile(e){this.profile=e}getProfile(){return this.profile}setAuthToken(e){this.authToken=e}setConfig({proxyBaseUrl:e=Fr,baseUrl:t,useProxy:n=!1,...i}){this.useProxy=n,this.proxyClient.setConfig({...i,baseUrl:e}),this.directClient.setConfig({...i})}proxyRequestInterceptor(e){return this.profile&&(e.headers.set("Profile",this.profile),e.headers.set("Swish-Api-Version",this.version)),e}directRequestInterceptor(e){return this.authToken&&e.headers.set("Authorization",`Bearer ${this.authToken}`),e}};d(Jr,"SwishClient");var Ui=Jr;var Zr=s(r=>r?JSON.parse(atob(r.split(".")[1])):null,"getTokenData"),en=s((r,e=60)=>{let t=Zr(r);return t?t.exp&&t.exp<Date.now()/1e3+e:!1},"isTokenExpired"),tn=s(r=>{let e=Zr(r);return e?e.sub.startsWith("gid://shopify/Customer/"):!1},"isCustomerToken");var on=gn(sn(),1);var an=s(r=>new on.default(async e=>{let t=[...new Set(e)].sort((i,o)=>i.localeCompare(o)),n=await r.items.list({query:t.join(" "),limit:200});return"error"in n?(console.error("Failed to load items",n.error),e.map(()=>({data:[],pageInfo:{next:null,previous:null,totalCount:0}}))):e.map(i=>{let o=n.data.find(a=>i===`variant:${a.variantId}`||i===`product:${a.productId}`);return{data:o?[o]:[],pageInfo:{next:null,previous:null,totalCount:o?1:0}}})},{batchScheduleFn:s(e=>setTimeout(e,50),"batchScheduleFn"),cache:!1,maxBatchSize:200}),"createItemsBatchLoader");var oe={profile:{get:s(()=>localStorage.getItem("swish-profile")??void 0,"get"),set:s(r=>localStorage.setItem("swish-profile",r),"set"),delete:s(()=>localStorage.removeItem("swish-profile"),"delete")},authToken:{get:s(()=>sessionStorage.getItem("swish-token")??void 0,"get"),set:s(r=>sessionStorage.setItem("swish-token",r),"set"),delete:s(()=>sessionStorage.removeItem("swish-token"),"delete")}},Me=class{static{s(this,"SwishApi")}constructor(e,t,n){this.config=e,this.context=t,this.cache=new Q("swish-api","max-age=60, stale-while-revalidate=3600",n+(e.version??kt)),this.cache.cleanupExpiredEntries().catch(a=>{console.warn("Swish API cache initialization cleanup error:",a)});let i=oe.profile.get(),o=oe.authToken.get();this.apiClient=Yr({profile:i,authToken:o,proxyMode:this.config.proxyMode,config:{...e,fetch:s((a,u)=>(a instanceof Request?a.method:u?.method??"GET")==="GET"?this.cache.fetchWithCache(a,u):fetch(a,u),"fetch")},requestInterceptor:s(async a=>{let u=new URL(a.url,window.location.origin),l=this.config.proxyBaseUrl??"/apps/wishlist/api",c=u.pathname==="/profiles/token";return!u.pathname.startsWith(l)&&!c&&await this.bootstrapAuth(),a},"requestInterceptor"),responseInterceptor:s(async(a,u)=>(this.processProfileHeader(a),u.method!=="GET"&&await this.cache.clear(),await this.config.responseInterceptor?.(a,u),a),"responseInterceptor")}),this.itemsLoader=an(this)}async bootstrapAuth(){if(this._bootstrapAuthPromise)return this._bootstrapAuthPromise;this._bootstrapAuthPromise=(async()=>{let e=oe.authToken.get();if(e)try{if(en(e,60))throw new Error("TOKEN_EXPIRED")}catch(o){(!(o instanceof Error)||o.message!=="TOKEN_EXPIRED")&&console.error("Failed to decode cached auth token",{cause:o}),oe.authToken.delete(),e=void 0}if(e){this.apiClient.setAuthToken(e);return}let t=this.apiClient.getProfile(),n=this.config.customerId,i=await this.apiClient.profiles.createToken({customer:n,session:t},{useProxy:!0});if("error"in i){console.error("Failed to bootstrap auth with error",i.error);return}if(!i.data?.token){console.error("Failed to bootstrap auth with no token");return}oe.authToken.set(i.data.token),this.apiClient.setAuthToken(i.data.token)})();try{return await this._bootstrapAuthPromise}finally{this._bootstrapAuthPromise=void 0}}processProfileHeader(e){let t=e.headers.get("Set-Profile");t?(this.apiClient.setProfile(t),oe.profile.set(t)):t===""&&oe.profile.delete()}get items(){return{...this.apiClient.items,list:s(async(e,t)=>{if(!this.config.customerId&&!this.apiClient.getProfile())return{data:[],pageInfo:{next:null,previous:null,totalCount:0}};if(t?.batch&&e?.query){e.limit!==1&&console.warn("Batching will always limit to 1 item");let n=e.query.split(" ");n.length>1&&console.warn("Batching will only support one query parameter");let i=n[0];if(!i.match(/^product:\d+$/)&&!i.match(/^variant:\d+$/))console.warn("Batching will only support product:<id> or variant:<id>");else return this.itemsLoader?.load(i)}return this.apiClient.items.list(e)},"list"),findById:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:null}:this.apiClient.items.findById(e),"findById")}}get lists(){return{...this.apiClient.lists,list:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.lists.list(e),"list"),findById:s(async e=>!this.config.customerId&&!this.apiClient.getProfile()?{data:null}:this.apiClient.lists.findById(e),"findById")}}get orders(){return{...this.apiClient.orders,list:s(async e=>!this.context.customer.id&&!this.apiClient.getProfile()?{data:[],pageInfo:{next:null,previous:null,totalCount:0}}:this.apiClient.orders.list(e),"list"),findById:s(async e=>!this.context.customer.id&&!this.apiClient.getProfile()?{data:null}:this.apiClient.orders.findById(e),"findById")}}get profiles(){return this.apiClient.profiles}async clearCache(){await this.cache.clear()}};var Ge=class{constructor(e){this.eventMap={"POST /items\\/?$":"item-create","DELETE /items\\/?$":"item-delete","PATCH /items\\/([^/]+)\\/?$":"item-update","DELETE /items\\/([^/]+)\\/?$":"item-delete","PUT /items\\/([^/]+)\\/lists\\/?$":"item-lists-update","POST /lists\\/?$":"list-create","DELETE /lists\\/?$":"list-delete","PATCH /lists\\/([^/]+)\\/?$":"list-update","DELETE /lists\\/([^/]+)\\/?$":"list-delete"};this.eventBus=e,this.processFetchResponse=this.processFetchResponse.bind(this)}static{s(this,"SwishApiPublisher")}async processFetchResponse(e,t){try{let n=this.getEventName(t.method,e.status,t.url);if(!n)return;let i=await e.clone().text();if(e.headers.get("Content-Type")?.includes("application/json"))try{i=JSON.parse(i).data}catch(o){console.warn(o)}this.eventBus.publish(n,i)}catch(n){console.warn(n)}}getEventName(e,t,n){e=e.toUpperCase();let i=new URL(n).pathname;return e==="GET"||t<200||t>=300?void 0:Object.entries(this.eventMap).find(([a])=>{let[u,l]=a.split(" ");return u!==e?!1:new RegExp(l).test(i)})?.[1]}};var Xi=typeof HTMLElement<"u"?HTMLElement:class{},je=class extends Xi{constructor(){super();this.getComponentRef=s(()=>this.componentRef,"getComponentRef");this.setComponentRef=s(t=>{this.componentRef=t},"setComponentRef");this.shadowRoot||this.attachShadow({mode:"open"});let t=this.querySelector("template");t&&this.shadowRoot&&(this.shadowRoot.appendChild(t.content),t.remove())}static{s(this,"SwishUiElement")}};var Fe=class{static{s(this,"ShopifyBadgesUtils")}#e;constructor({getBadges:e}){this.#e=e?.bind(this)}getBadges({product:e,variant:t}){try{let n=this.getDefaultBadges({product:e,variant:t});return this.#e?this.mapBadges(this.#e({product:e,variant:t,defaultBadges:n})??[]):this.mapBadges(n)}catch(n){return console.error("Error getting badges",n),[]}}getDefaultBadges({product:e,variant:t}){let n=[];if(e?.availableForSale===!1||t?.availableForSale===!1)return n.push("Sold out"),n;let i=t?t.price.amount:e?.priceRange?.minVariantPrice.amount,o=t?t.compareAtPrice?.amount:e?.compareAtPriceRange?.minVariantPrice.amount;return o&&parseFloat(o)>parseFloat(i)&&n.push("Sale"),n}mapBadges(e){return e.map(t=>typeof t=="string"?{id:t.toLowerCase().replace(/[^a-z0-9]/g,"_"),label:t}:t)}};var un=s(r=>{let e=r.proxy?.baseUrl??"/apps/wishlist";return{proxy:{baseUrl:e},storefrontApi:{storeDomain:r.storefrontApi?.storeDomain??"",accessToken:r.storefrontApi?.accessToken??""},storefrontContext:{...r.storefrontContext,localization:{country:r.storefrontContext.localization.country.toUpperCase(),language:r.storefrontContext.localization.language.toUpperCase(),market:r.storefrontContext.localization.market}},badges:{getBadges:r.badges?.getBadges??(({defaultBadges:t})=>t)},metafields:{product:r.metafields?.product??[],productVariant:r.metafields?.productVariant??[]},swishApi:{version:r.swishApi?.version??"2026-01"},swishUi:{baseUrl:r.swishUi?.baseUrl??`${e}/assets`,components:{productRow:{showVariantTitle:r.swishUi?.components?.productRow?.showVariantTitle??!1},productDetail:{descriptionMaxLines:r.swishUi?.components?.productDetail?.descriptionMaxLines??4},variantSelect:{displayType:r.swishUi?.components?.variantSelect?.displayType??"pills"},imageSlider:{flush:r.swishUi?.components?.imageSlider?.flush??!1,loop:r.swishUi?.components?.imageSlider?.loop??!1},images:{baseTint:r.swishUi?.components?.images?.baseTint??!1},buyButtons:{shopPay:r.swishUi?.components?.buyButtons?.shopPay??!1},listDetailPage:{desktopColumns:r.swishUi?.components?.listDetailPage?.desktopColumns??4,showBuyButton:r.swishUi?.components?.listDetailPage?.showBuyButton??!0},drawer:{title:r.swishUi?.components?.drawer?.title??"",logo:{url:r.swishUi?.components?.drawer?.logo?.url??"",altText:r.swishUi?.components?.drawer?.logo?.altText??""},navigation:{variant:r.swishUi?.components?.drawer?.navigation?.variant??"floating",items:r.swishUi?.components?.drawer?.navigation?.items??[{id:"home",enabled:!0,href:"/"},{id:"items",enabled:!0,href:"/items"},{id:"lists",enabled:!0,href:"/lists"},{id:"chat",enabled:!1,href:"/chat"},{id:"orders",enabled:!0,href:"/orders"},{id:"profile",enabled:!0,href:"/profile"}]},miniMenu:{items:r.swishUi?.components?.drawer?.miniMenu?.items??[]}}},css:r.swishUi?.css??[],intents:{save:{requireVariant:r.swishUi?.intents?.save?.requireVariant??!1,showToast:r.swishUi?.intents?.save?.showToast??!1},edit:{showToast:r.swishUi?.intents?.edit?.showToast??!1},unsave:{requireConfirmation:r.swishUi?.intents?.unsave?.requireConfirmation??!1,openEditor:r.swishUi?.intents?.unsave?.openEditor??!1,showToast:r.swishUi?.intents?.unsave?.showToast??!1}},theme:r.swishUi?.theme??{},version:r.swishUi?.version??"0.40.0"}}},"createSwishOptions");var Ki=".swish-shop-bridge{position:absolute!important;top:0!important;left:0!important;padding:0!important;border:0!important;margin:0!important;pointer-events:none!important}.swish-shop-bridge input{appearance:none!important;border:none!important;width:1px!important;height:1px!important;padding:0!important;margin:0!important;background:rgba(0,0,0,0)!important}",Yi=s(()=>{let r="/";return typeof window<"u"&&(r=window.location.pathname),`<form class=swish-shop-bridge data-login-with-shop-sign-in=true id=customer_login><input name=customer[email] id=customer_login_email> <input name=return_url type=hidden value=${r}></form>`},"getHtml"),Ji=typeof HTMLElement<"u"?HTMLElement:class{},Tt=class extends Ji{static{s(this,"ShopBridge")}get swish(){return typeof window<"u"?window.swish:void 0}constructor(){super(),this.emailInput=this.querySelector('form[data-login-with-shop-sign-in] input[type="email"],form[data-login-with-shop-sign-in] input[name="customer[email]"'),this.emailInput||(this.innerHTML=`
|
|
449
|
+
<style>${Ki}</style>
|
|
450
|
+
${Yi()}
|
|
451
|
+
`,this.emailInput=this.querySelector("#customer_login_email")),this.shopModalObserver=new MutationObserver(e=>{e.forEach(t=>{t.attributeName==="style"&&document.documentElement.style.overflow==="hidden"&&this.dispatchEvent(new CustomEvent("shop-modal-open"))})}),this.shopModalObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style"]})}disconnectedCallback(){this.shopModalObserver?.disconnect()}async load(){try{(window.Shopify?.featureAssets?.["shop-js"]?.["init-customer-accounts"]?.[0]??"").includes("init-customer-accounts")&&window.Shopify?.SignInWithShop?.initCustomerAccounts?.(!0,{fedCMEnabled:!0,windoidEnabled:!1})}catch(e){console.warn("Failed to initialize Shop JS",e)}}update(e){if(e.email&&(this.emailInput.value=e.email,this.emailInput.dispatchEvent(new Event("input"))),e.returnTo){let t=this.querySelector("input[name='return_url']");t&&(t.value=e.returnTo)}}};typeof customElements<"u"&&customElements.define("swish-shop-bridge",Tt);var He=class{constructor(e,t){this.inflightModals=new Map;this.eventListeners=new Map;this.scrollLockRefCount=0;this.scrollPositionBeforeLock=0;this._lockScroll=s(()=>this.lockScroll(),"_lockScroll");this._unlockScroll=s(()=>this.unlockScroll(),"_unlockScroll");this.swishUiOptions=e,this.storefrontContext=t}static{s(this,"SwishUi")}async hideModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")!=="true")&&e.setAttribute("open","false")})().finally(()=>{this.inflightModals.delete(e)});return this.unlockScroll(),this.inflightModals.set(e,t),t}async showModal(e){if(this.inflightModals.has(e))return this.inflightModals.get(e);let t=(async()=>{typeof e=="string"&&(e=await this.requireUiComponent(e)),!(!e||e.getAttribute("open")==="true")&&e.setAttribute("open","true")})().finally(()=>{this.inflightModals.delete(e)});return this.lockScroll(),this.inflightModals.set(e,t),t}async showSignIn(e){let t=await this.requireUiComponent("sign-in",{listeners:{close:s(()=>e?.onClose?.(),"close")}});t.setAttribute("return-to",e?.returnTo??window.location.pathname),await this.showModal(t)}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",{listeners:{submit:s(n=>{n instanceof CustomEvent?e.onSubmit?.(n.detail):console.warn("Unsave alert submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}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",{listeners:{submit:s(()=>{e.onSubmit?.()},"submit"),close:s(()=>{e.onClose?.()},"close")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showDrawer(e){await this.hideAllToasts();let t=await this.requireUiComponent("drawer",{listeners:{close:s(()=>{e?.onClose?.()},"close")}});t.setAttribute("account-url",this.storefrontContext.routes.accountUrl),this.storefrontContext.customer.id&&t.setAttribute("customer-id",this.storefrontContext.customer.id),await this.showModal(t)}async showListMenu(e){if(!e.listId)throw new Error("listId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-menu",{listeners:{close:s(n=>{e.onClose?.()},"close"),edit:s(n=>{n instanceof CustomEvent?e.onEdit?.(n.detail):console.warn("List menu submitted without detail",n)},"edit"),delete:s(n=>{n instanceof CustomEvent?e.onDelete?.():console.warn("List menu deleted without detail",n)},"delete")}});t.setAttribute("list-id",e.listId),await this.showModal(t)}async showListSelect(e){if(!e.itemId)throw new Error("itemId is required");await this.hideAllToasts();let t=await this.requireUiComponent("list-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List select form submitted without detail",n)},"submit"),close:s(()=>{e.onClose?.()},"close"),unsave:s(n=>{n instanceof CustomEvent?e.onUnsave?.(n.detail):console.warn("List select unsave without detail",n)},"unsave")}});t.setAttribute("item-id",e.itemId),await this.showModal(t)}async initListDetailPage(e,t){let n=await this.requireUiComponent("list-detail-page",{refElement:t});e.listId&&n.setAttribute("list-id",e.listId)}async showToast(e){await this.requireUiComponent("toast-manager",{onHydrated:s(t=>{t.current.show(e)},"onHydrated")})}async hideAllToasts(){this.queryComponent("toast-manager")&&await this.requireUiComponent("toast-manager",{onHydrated:s(e=>{e.current.clear()},"onHydrated")})}async showVariantSelect(e){await this.hideAllToasts();let t=await this.requireUiComponent("variant-select",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Variant select form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);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),e?.displayType&&t.setAttribute("display-type",e.displayType),await this.showModal(t)}async showQuickBuy(e){await this.hideAllToasts();let t=await this.requireUiComponent("quick-buy",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("Quick buy form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});if(e?.productId)t.setAttribute("product-id",e.productId);else throw new Error("ProductId must be provided");e?.variantId&&t.setAttribute("variant-id",e.variantId),await this.showModal(t)}async showListEditor(e){let t=await this.requireUiComponent("list-editor",{listeners:{submit:s(async n=>{"detail"in n&&n.detail?e?.onSubmit?.(n.detail):console.warn("List editor form submitted without detail",n)},"submit"),close:s(()=>{e?.onClose?.()},"close")}});e?.listId&&t.setAttribute("list-id",e.listId),await this.showModal(t)}async initShopBridge({onShopModalOpen:e}){let t=document.querySelector("swish-shop-bridge");if(t||(document.body.insertAdjacentHTML("beforeend","<swish-shop-bridge></swish-shop-bridge>"),t=document.querySelector("swish-shop-bridge")),!t)throw new Error("Failed to initialize Shop Bridge");return t.addEventListener("shop-modal-open",()=>e(),{once:!0}),await t.load(),t}async requireUiComponent(e,t){this.loadCricalResources();let n=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.html`,i=await fetch(n).then(l=>l.text()),o=t?.instance,a=t?.listeners,u=this.queryComponent(e,o)??await this.insertComponent({name:e,template:i,refElement:t?.refElement??document.body,position:"beforeend",instance:o});if(u.shadowRoot&&!u.hasAttribute("hydrated")){let l=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/${e}.js`;Promise.all([this.loadNonCriticalResources(),import(l)]).then(([{bundleCssStylesheet:c,customCssStylesheets:p},{hydrate:f}])=>{u.shadowRoot&&c&&(u.shadowRoot.adoptedStyleSheets=[...u.shadowRoot.adoptedStyleSheets,...p,c],u.shadowRoot?.querySelector(":host > style")?.remove()),f(u),u.setAttribute("hydrated",""),t?.onHydrated?.(u.getComponentRef())})}else u.hasAttribute("hydrated")&&t?.onHydrated?.(u.getComponentRef());for(let{event:l,listener:c}of this.eventListeners.values())u.removeEventListener(l,c);for(let[l,c]of Object.entries(a??{}))this.eventListeners.set(`${e}-${o}-${l}`,{event:l,listener:c}),u.addEventListener(l,c);return u}async loadCricalResources(){return this._loadCricalResourcesPromise?this._loadCricalResourcesPromise:(this._loadCricalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/theme.css`,t=await fetch(e).then(i=>i.text()),n=new CSSStyleSheet;return n.replaceSync(t),{themeVariablesStylesheet:n}})(),this._loadCricalResourcesPromise)}async loadNonCriticalResources(){return this._loadNonCriticalResourcesPromise?this._loadNonCriticalResourcesPromise:(this._loadNonCriticalResourcesPromise=(async()=>{let e=`${this.swishUiOptions.baseUrl}/ui@${this.swishUiOptions.version}/bundle.css`,t=s(o=>{let a=new CSSStyleSheet;return a.replaceSync(o),a},"createCssStylesheet"),[n,...i]=await Promise.all([fetch(e).then(o=>o.text()).then(t),...this.swishUiOptions.css.map(async o=>o instanceof URL?t(await fetch(o).then(a=>a.text())):t(o))]);return{bundleCssStylesheet:n,customCssStylesheets:i}})(),this._loadNonCriticalResourcesPromise)}async insertComponent({name:e,instance:t,template:n,position:i,refElement:o}){let{themeVariablesStylesheet:a}=await this.loadCricalResources();o.insertAdjacentHTML(i,n.replace(' shadowrootmode="open"',""));let u=this.queryComponent(e,t);if(!u)throw new Error(`Element ${e} not found in DOM`);return u.shadowRoot&&(u.shadowRoot.adoptedStyleSheets=[a]),u}queryComponent(e,t){let n=`swish-ui[ref="${e}${t?`-${t}`:""}"]`;return document.querySelector(n)}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(`
|
|
452
|
+
html[swish-locked] body {
|
|
453
|
+
overflow: hidden;
|
|
454
|
+
position: fixed;
|
|
455
|
+
top: -${this.scrollPositionBeforeLock}px;
|
|
456
|
+
left: 0px;
|
|
457
|
+
right: 0px;
|
|
458
|
+
}
|
|
459
|
+
`),document.documentElement.setAttribute("swish-locked",""))}unlockScroll(){this.scrollLockRefCount>0&&this.scrollLockRefCount--,this.scrollLockRefCount===0&&(this.scrollLockStyleSheet&&this.scrollLockStyleSheet.replaceSync(""),window.scrollTo({top:this.scrollPositionBeforeLock,behavior:"instant"}),this.scrollPositionBeforeLock=0,document.documentElement.removeAttribute("swish-locked"))}};var Zi="0.71.0",Hl=s(async r=>{if(typeof window>"u")throw new Error("Swish is not supported in this environment");if(window.swish)return window.swish;try{let n=localStorage.getItem("wk_session_id");n&&(localStorage.setItem("swish-profile",`gid://swish/Session/${n}`),localStorage.removeItem("wk_session_id"))}catch(n){console.warn("Failed to migrate legacy session id to Swish profile",{cause:n})}let e=un(r),t=new _t(e);try{let n=sessionStorage.getItem("swish-token"),i=n&&tn(n),o=!!e.storefrontContext.customer.id;o!==i&&sessionStorage.removeItem("swish-token");let u=!!localStorage.getItem("swish-profile");o===u&&await t.api.clearCache()}catch(n){console.warn("Could not check if customer logged out.",{cause:n})}return window.swish=t,document.dispatchEvent(new Event("swish-ready")),typeof window.Shopify?.analytics?.publish=="function"&&window.Shopify.analytics.publish("swish-ready",{proxyUrl:e.proxy.baseUrl,market:e.storefrontContext.localization.market,country:e.storefrontContext.localization.country,language:e.storefrontContext.localization.language,rootUrl:e.storefrontContext.routes.rootUrl}),t},"createSwish"),_t=class{constructor(e){this.dom={createElementLocator:de,createQueryParamsObserver:ae};this.state={itemContext:Xt(this),itemState:Kt(this),itemCount:Yt(this),swishQuery:Jt(this),effect:V,signal:C,computed:q};this.swishOptions=e,this.events=new ve,this.swishBadges=new Fe({getBadges:this.swishOptions.badges?.getBadges});let t={proxyBaseUrl:`${this.swishOptions.proxy.baseUrl}/api`,...this.swishOptions.swishApi??{}};this.swishApiPublisher=new Ge(this.events);let n=[Zi,e.swishUi?.version].join("-");this.swishApi=new Me({...t,customerId:e.storefrontContext.customer.id??void 0,responseInterceptor:this.swishApiPublisher.processFetchResponse},this.swishOptions.storefrontContext,n),this.ajaxApiPublisher=new me(this.events),this.ajaxApi=new ye({storeDomain:this.swishOptions.storefrontApi.storeDomain,responseInterceptor:this.ajaxApiPublisher.processFetchResponse}),this.ajaxApi.patchFetch(),this.storefrontApi=new Ve(this.swishOptions.storefrontApi,this.swishOptions.storefrontContext,this.swishBadges,this.swishOptions.metafields),this.swishUi=new He(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",je),this.intents=new Pe(this,this.swishUi)}static{s(this,"SwishApp")}get options(){return this.swishOptions}get customer(){return this.swishOptions.storefrontContext.customer}get localization(){return this.swishOptions.storefrontContext.localization}get routes(){return this.swishOptions.storefrontContext.routes}get badges(){return this.swishBadges}get api(){return this.swishApi}get storefront(){return this.storefrontApi}get ajax(){return this.ajaxApi}get shopUrl(){return`https://${this.swishOptions.storefrontApi.storeDomain}`}get ui(){return this.swishUi}};export{_t as SwishApp,Zi as VERSION,Hl as createSwish};
|