@liquidcommerce/elements-sdk
Version:
LiquidCommerce Elements SDK
1 lines • 536 kB
JavaScript
(function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):(t="undefined"!=typeof globalThis?globalThis:t||self,e(t.LiquidCommerceElements={}))})(this,function(exports){"use strict";function polyfillReplaceChildren(){"undefined"!=typeof Element&&"replaceChildren"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.replaceChildren=function(...t){for(;this.firstChild;)this.removeChild(this.firstChild);for(const e of t)"string"==typeof e?this.appendChild(document.createTextNode(e)):this.appendChild(e)})}function polyfillPrepend(){"undefined"!=typeof Element&&"prepend"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.prepend=function(...t){const e=document.createDocumentFragment();for(const n of t)"string"==typeof n?e.appendChild(document.createTextNode(n)):e.appendChild(n);this.insertBefore(e,this.firstChild)})}function polyfillRemove(){"undefined"!=typeof Element&&"remove"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}function polyfillReplaceWith(){"undefined"!=typeof Element&&"replaceWith"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.replaceWith=function(...t){const e=this.parentNode;if(!e)return;const n=document.createDocumentFragment();for(const i of t)"string"==typeof i?n.appendChild(document.createTextNode(i)):n.appendChild(i);e.replaceChild(n,this)})}function polyfillBefore(){"undefined"!=typeof Element&&"before"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.before=function(...t){const e=this.parentNode;if(!e)return;const n=document.createDocumentFragment();for(const i of t)"string"==typeof i?n.appendChild(document.createTextNode(i)):n.appendChild(i);e.insertBefore(n,this)})}function polyfillAfter(){"undefined"!=typeof Element&&"after"in Element.prototype||"undefined"!=typeof Element&&(Element.prototype.after=function(...t){const e=this.parentNode;if(!e)return;const n=document.createDocumentFragment();for(const i of t)"string"==typeof i?n.appendChild(document.createTextNode(i)):n.appendChild(i);e.insertBefore(n,this.nextSibling)})}function polyfillObjectFromEntries(){"undefined"!=typeof Object&&"fromEntries"in Object||"undefined"!=typeof Object&&(Object.fromEntries=t=>{const e={};for(const[n,i]of t)e[n]=i;return e})}function safeScrollIntoView(t,e){try{e&&"function"==typeof t.scrollIntoView?t.scrollIntoView(e):t.scrollIntoView()}catch(n){try{t.scrollIntoView()}catch(i){console.warn("scrollIntoView failed:",i)}}}function initializeDOMPolyfills(){try{polyfillReplaceChildren(),polyfillPrepend(),polyfillRemove(),polyfillReplaceWith(),polyfillBefore(),polyfillAfter(),polyfillObjectFromEntries()}catch(_){console.warn("DOM polyfills initialization failed:",_)}}function safeReplaceChildren(t,...e){try{if("replaceChildren"in t&&"function"==typeof t.replaceChildren)t.replaceChildren(...e);else{for(;t.firstChild;)t.removeChild(t.firstChild);for(const n of e)"string"==typeof n?t.appendChild(document.createTextNode(n)):t.appendChild(n)}}catch(n){console.error("replaceChildren operation failed:",n),1===e.length&&"string"==typeof e[0]&&(t.innerHTML=e[0])}}const t={LOCAL:"local",DEVELOPMENT:"development",STAGING:"staging",PRODUCTION:"production"},e={CLIENT_READY:"client_ready",PRODUCT_LOADED:"product_loaded",PRODUCT_QUANTITY_INCREASE:"product_quantity_increase",PRODUCT_QUANTITY_DECREASE:"product_quantity_decrease",PRODUCT_ADD_TO_CART:"product_add_to_cart",PRODUCT_SIZE_CHANGED:"product_size_changed",PRODUCT_FULFILLMENT_TYPE_CHANGED:"product_fulfillment_type_changed",PRODUCT_FULFILLMENT_CHANGED:"product_fulfillment_changed",PRODUCT_ENGRAVING_UPDATED:"product_engraving_updated",CART_LOADED:"cart_loaded",CART_CLOSED:"cart_closed",CART_OPENED:"cart_opened",CART_UPDATED:"cart_updated",CART_FAILED:"cart_failed",CART_RESET:"cart_reset",CART_ITEM_ADDED:"cart_item_added",CART_ITEM_REMOVED:"cart_item_removed",CART_ITEM_QUANTITY_INCREASE:"cart_item_quantity_increase",CART_ITEM_QUANTITY_DECREASE:"cart_item_quantity_decrease",CART_ITEM_ENGRAVING_UPDATED:"cart_item_engraving_updated",CART_PROMO_CODE_APPLIED:"cart_promo_code_applied",CART_PROMO_CODE_REMOVED:"cart_promo_code_removed",CART_PROMO_CODE_FAILED:"cart_promo_code_failed",CART_PRODUCT_ADD_SUCCESS:"cart_product_add_success",CART_PRODUCT_ADD_FAILED:"cart_product_add_failed",ADDRESS_UPDATED:"address_updated",ADDRESS_CLEARED:"address_cleared",ADDRESS_FAILED:"address_failed",CHECKOUT_LOADED:"checkout_loaded",CHECKOUT_OPENED:"checkout_opened",CHECKOUT_CLOSED:"checkout_closed",CHECKOUT_FAILED:"checkout_failed",CHECKOUT_IS_GIFT_TOGGLED:"checkout_is_gift_toggled",CHECKOUT_BILLING_SAME_AS_SHIPPING_TOGGLED:"checkout_billing_same_as_shipping_toggled",CHECKOUT_MARKETING_PREFERENCES_TOGGLED:"checkout_marketing_preferences_toggled",CHECKOUT_CUSTOMER_INFORMATION_UPDATED:"checkout_customer_information_updated",CHECKOUT_BILLING_INFORMATION_UPDATED:"checkout_billing_information_updated",CHECKOUT_GIFT_INFORMATION_UPDATED:"checkout_gift_information_updated",CHECKOUT_ITEM_REMOVED:"checkout_item_removed",CHECKOUT_ITEM_QUANTITY_INCREASE:"checkout_item_quantity_increase",CHECKOUT_ITEM_QUANTITY_DECREASE:"checkout_item_quantity_decrease",CHECKOUT_ITEM_ENGRAVING_UPDATED:"checkout_item_engraving_updated",CHECKOUT_TIP_UPDATED:"checkout_tip_updated",CHECKOUT_SUBMIT_STARTED:"checkout_submit_started",CHECKOUT_SUBMIT_COMPLETED:"checkout_submit_completed",CHECKOUT_SUBMIT_FAILED:"checkout_submit_failed",CHECKOUT_PROMO_CODE_APPLIED:"checkout_promo_code_applied",CHECKOUT_PROMO_CODE_REMOVED:"checkout_promo_code_removed",CHECKOUT_PROMO_CODE_FAILED:"checkout_promo_code_failed",CHECKOUT_GIFT_CARD_APPLIED:"checkout_gift_card_applied",CHECKOUT_GIFT_CARD_REMOVED:"checkout_gift_card_removed",CHECKOUT_GIFT_CARD_FAILED:"checkout_gift_card_failed",CHECKOUT_PRODUCT_ADD_SUCCESS:"checkout_product_add_success",CHECKOUT_PRODUCT_ADD_FAILED:"checkout_product_add_failed"},n={CUSTOMER:"customer",GIFT:"gift",BILLING:"billing"},i={DRAWER:"drawer",INPUT:"input",BIRTHDATE_INPUT:"birthdate-input",ENGRAVING_FORM:"engraving-form",ENGRAVING_VIEW:"engraving-view",BUTTONS_CART_OPEN:"buttons-cart-open",POWERED_BY:"powered-by",LCE_ELEMENT:"lce-element",PURCHASE_MIN_ALERT:"purchase-min-alert",ALERT:"alert",PROMO_CODE_TICKER:"promo-code-ticker",ADDRESS:"address",ADDRESS_INPUT:"address-input",ADDRESS_DISPLAY:"address-display",PRODUCT:"product",PRODUCT_IMAGE_CAROUSEL:"product-image-carousel",PRODUCT_OPTIONS:"product-options",PRODUCT_INTERACTIONS:"product-interactions",PRODUCT_DESCRIPTION:"product-description",PRODUCT_RETAILERS:"product-retailers",PRODUCT_RETAILERS_CAROUSEL:"product-retailers-carousel",PRODUCT_RETAILERS_POPUP:"product-retailers-popup",PRODUCT_RETAILERS_POPUP_LIST:"product-retailers-popup-list",PRODUCT_PRICE:"product-price",PRODUCT_ADD_TO_CART_SECTION:"product-add-to-cart-section",PRODUCT_DRAWER:"product-drawer",PRODUCT_LOADING:"product-loading",CART:"cart",CART_RETAILER:"cart-retailer",CART_ITEM:"cart-item",CART_FOOTER:"cart-footer",CART_ITEM_QUANTITY_PRICE:"cart-item-quantity-price",CART_RETAILER_SUBTOTAL:"cart-retailer-subtotal",CART_PROMO_CODE:"cart-promo-code",CART_HEADER:"cart-header",CART_BODY:"cart-body",CART_FULFILLMENT:"cart-fulfillment",CHECKOUT:"checkout",CHECKOUT_INFORMATION_SECTION:"checkout-information-section",CHECKOUT_STRIPE_FORM:"checkout-stripe-form",CHECKOUT_PAYMENT_FORM:"checkout-payment-form",CHECKOUT_BILLING_FORM:"checkout-billing-form",CHECKOUT_SUMMARY_SECTION:"checkout-summary-section",CHECKOUT_PROMO_CODE:"checkout-promo-code",CHECKOUT_GIFT_CARDS:"checkout-gift-cards",CHECKOUT_AMOUNTS:"checkout-amounts",CHECKOUT_ITEMS:"checkout-items",CHECKOUT_COMPLETED:"checkout-completed",CHECKOUT_DELIVERY_INFORMATION_FORM:"checkout-delivery-information-form",CHECKOUT_BUYER_INFORMATION_FORM:"checkout-buyer-information-form",CHECKOUT_TIPS:"checkout-tips",CHECKOUT_PC_GC:"checkout-pc-gc",CHECKOUT_ITEM:"checkout-item",CHECKOUT_ITEM_QUANTITY:"checkout-item-quantity",CHECKOUT_PLACE_ORDER_BUTTON:"checkout-place-order-button",CHECKOUT_HEADER:"checkout-header",CHECKOUT_PRESALE_COUNTDOWN:"checkout-presale-countdown",CHECKOUT_PRESALE_EXPIRED:"checkout-presale-expired"},r={ON_DEMAND:"onDemand",SHIPPING:"shipping"},s={[t.LOCAL]:"http://0.0.0.0:8080",[t.DEVELOPMENT]:"https://dev-elements.liquidcommerce.us",[t.STAGING]:"https://staging-elements.liquidcommerce.us",[t.PRODUCTION]:"https://elements.liquidcommerce.us"},a={DRAWER_WRAPPER:2147483640,DRAWER_CONTENT:5952,DRAWER_BACKDROP:5951,ADDRESS_SUGGESTIONS:5850,PRODUCT_DRAWER:5840,CART_LOADING:5750,LOADING_INDICATOR:5730,ERROR_MESSAGE:5650,CAROUSEL_CONTROLS:5580,PROGRESS_BAR:5560,CHECKOUT_HEADER:5920,INDEPENDENT_BUTTON:5910,CART_HEADER:5920,TOGGLE_SLIDER:5150,FORM_CONTROLS:5130,ADDRESS_ACTIONS:5050,SKELETON_WAVE:5040};class SingletonManager{static getInstances(){return SingletonManager.instances||(SingletonManager.instances=new Map),SingletonManager.instances}constructor(){}static setClientConstructor(t){SingletonManager.clientConstructor=t}static getClientConstructor(){return SingletonManager.clientConstructor}static getClassInstance(t,e){const n=SingletonManager.getInstances();n.has(t)||n.set(t,e());const i=n.get(t);if(!i)throw new Error("ElementsSdk: Instance for class "+t+" could not be created.");return i}static async getClient(t){const e=[t.apiKey,t.env,t.isBuilder,t.enableDebugging].join("_"),n="LiquidCommerceElementsClient_"+e,i=SingletonManager.getInstances();if(i.has(n))return i.get(n);if(!SingletonManager.clientConstructor)throw new Error("LiquidCommerce Elements: Client constructor is not set.");const r=new SingletonManager.clientConstructor(t);return await r.prepare(),i.set(n,r),r}}SingletonManager.instances=null,SingletonManager.clientConstructor=null;class ClientConfigService{constructor(){this.config=null}static getInstance(){return SingletonManager.getClassInstance("ClientConfigService",()=>new ClientConfigService)}initialize(t,e={}){this.validateInputs(t,e),this.config=Object.freeze(this.buildConfiguration(t,e))}getConfigs(){return{...this.config}}get(t){return this.config[t]}set(t,e){if(!this.config)throw new Error("ClientConfigService is not initialized. Please call initialize() first.");this.config=Object.freeze({...this.config,[t]:e})}isDevelopment(){return this.get("env")===t.DEVELOPMENT}isStaging(){return this.get("env")===t.STAGING}isProduction(){return this.get("env")===t.PRODUCTION}isBuilder(){return this.get("isBuilder")}isDebuggingEnabled(){return this.get("enableDebugging")}debuggingDisabled(){return!this.get("enableDebugging")}hasCustomTheme(){return null!==this.get("customTheme")}isMobile(){return"mobile"===this.get("deviceType")}isLocalStorageAvailable(){return Boolean(this.get("isLocalStorageAvailable"))}getProxyConfig(){return this.get("proxy")}validateInputs(e,n){if(!(null==e?void 0:e.trim()))throw new Error("API key is required");if(n.env&&!Object.values(t).includes(n.env))throw new Error('Invalid environment "'+n.env+'"');if(void 0!==n.isBuilder&&"boolean"!=typeof n.isBuilder)throw new Error("isBuilder must be a boolean");if(void 0!==n.enableDebugging&&"boolean"!=typeof n.enableDebugging)throw new Error("enableDebugging must be a boolean");if(n.promoTicker&&"object"!=typeof n.promoTicker)throw new Error("promoTicker must be an object");if(n.promoTicker){if(!Array.isArray(n.promoTicker))throw new Error("promoTicker must be an array");for(const t of n.promoTicker){if("string"!=typeof t.promoCode||!t.promoCode.trim())throw new Error("promoTicker.promoCode is required and must be a non-empty string");if(!Array.isArray(t.text)||0===t.text.length||!t.text.every(t=>"string"==typeof t&&t.trim()))throw new Error("promoTicker.text is required and must be a non-empty array of strings");if("string"!=typeof t.separator||!t.separator.trim())throw new Error("promoTicker.separator is required and must be a non-empty string");if(!t.activeFrom)throw new Error("promoTicker.activeFrom is required");const e="string"==typeof t.activeFrom?new Date(t.activeFrom):t.activeFrom;if(!(e instanceof Date)||Number.isNaN(e.getTime()))throw new Error("promoTicker.activeFrom must be a valid Date object or ISO date string");if(!t.activeUntil)throw new Error("promoTicker.activeUntil is required");const n="string"==typeof t.activeUntil?new Date(t.activeUntil):t.activeUntil;if(!(n instanceof Date)||Number.isNaN(n.getTime()))throw new Error("promoTicker.activeUntil must be a valid Date object or ISO date string");if(e>=n)throw new Error("promoTicker.activeFrom must be earlier than promoTicker.activeUntil")}}if(n.proxy){if("object"!=typeof n.proxy)throw new Error("proxy must be an object");if(!n.proxy.baseUrl||"string"!=typeof n.proxy.baseUrl)throw new Error("proxy.baseUrl is required and must be a string");if(n.proxy.headers&&"object"!=typeof n.proxy.headers)throw new Error("proxy.headers must be an object")}}buildConfiguration(e,n){var i,r;const a=n.env||t.STAGING,c=s[a];return{apiKey:e.trim(),env:a,isBuilder:null!==(i=n.isBuilder)&&void 0!==i?i:![],enableDebugging:null!==(r=n.enableDebugging)&&void 0!==r?r:![],baseUrl:c,customTheme:n.customTheme||null,proxy:n.proxy||null,deviceType:this.detectDeviceType(),userDeviceId:void 0,isLocalStorageAvailable:void 0,version:void 0,clientPrepared:![],promoTicker:n.promoTicker||null}}detectDeviceType(){var t,e;if("undefined"==typeof navigator)return"desktop";const n=navigator.userAgent.toLowerCase(),i="ontouchstart"in window||navigator.maxTouchPoints>0,r=(null===(t=window.screen)||void 0===t?void 0:t.width)||0,s=(null===(e=window.screen)||void 0===e?void 0:e.height)||0,a=Math.max(r,s),c=[/ipad/,/android(?!.*mobile)/,/tablet/,/kindle/,/playbook/,/silk/,/gt-p\d{4}/,/nexus (7|9|10)/,/xoom/,/sch-i800/,/galaxy tab/,/surface/,/googletv/,/appletv/,/hbbtv/,/roku/,/smarttv/,/webtv/],l=[/android.*mobile/,/iphone/,/ipod/,/blackberry/,/opera mini/,/opera mobi/,/iemobile/,/mobile/,/webos/,/palm/,/symbian/,/nokia/,/fennec/,/maemo/,/windows phone/,/windows ce/,/htc/,/samsung.*mobile/,/lg.*mobile/,/motorola/,/sony.*mobile/,/watch/,/applewatch/,/wearos/,/tizen/];return c.some(t=>t.test(n))?"tablet":l.some(t=>t.test(n))||i&&a<768?"mobile":i&&a>=768&&a<=1200||i&&/macintosh/i.test(n)&&navigator.maxTouchPoints>1||/android/i.test(n)&&i&&a>=768||/windows nt/i.test(n)&&i&&a>=768?"tablet":(/automotive|carplay|android auto|car browser/i.test(n),"desktop")}}class LoggerService{constructor(t){this.prefix="LiquidCommerce Elements",this.colors={debug:"#9CA3AF",log:"#60A5FA",info:"#22D3EE",warn:"#FB923C",error:"#F87171",prefix:"#C084FC"},this.enableLogging=![],this.context=t}static getInstance(t){return SingletonManager.getClassInstance("LoggerService_"+t,()=>new LoggerService(t))}setEnableLogging(t){this.enableLogging=t}getPrefix(t){if(!this.enableLogging)return[];const e=(new Date).toISOString().slice(11,23);return["%c["+e+"%c "+this.prefix+"%c "+this.context+"%c]","color: "+this.colors[t],"color: "+this.colors.prefix+"; font-weight: bold","color: "+this.colors[t],"color: "+this.colors[t]]}debug(...t){if(!this.enableLogging)return;const[e,...n]=this.getPrefix("debug");console.debug(e,...n,...t)}log(...t){if(!this.enableLogging)return;const[e,...n]=this.getPrefix("log");console.log(e,...n,...t)}info(...t){if(!this.enableLogging)return;const[e,...n]=this.getPrefix("info");console.info(e,...n,...t)}warn(...t){if(!this.enableLogging)return;const[e,...n]=this.getPrefix("warn");console.warn(e,...n,...t)}error(...t){if(!this.enableLogging)return;const[e,...n]=this.getPrefix("error");console.error(e,...n,...t)}group(t,e=![]){if(!this.enableLogging)return;const[n,...i]=this.getPrefix("log");e?console.groupCollapsed(n,...i,t):console.group(n,...i,t)}groupEnd(){this.enableLogging&&console.groupEnd()}}class LoggerFactory{static getInstances(){return LoggerFactory.instances||(LoggerFactory.instances=new Map),LoggerFactory.instances}static get(t){const e=this.getInstances();if(!e.has(t)){const n=LoggerService.getInstance(t);n.setEnableLogging(this.enableLoggingGlobally),e.set(t,n)}return e.get(t)}static setEnableLogging(t){this.enableLoggingGlobally=t;const e=this.getInstances();for(const[,n]of e)n.setEnableLogging(t)}}function fetchAdapter(t){return async(e,n)=>{var i;const r=await t(e,n);let s;if("function"==typeof(null===(i=r.headers)||void 0===i?void 0:i.entries))s=Object.fromEntries(r.headers.entries());else{s={};for(const[t,e]of r.headers)s[t]=e}return{ok:r.ok,status:r.status,statusText:r.statusText,headers:s,json:()=>r.json(),text:()=>r.text()}}}LoggerFactory.instances=null,LoggerFactory.enableLoggingGlobally=![];const xhrFetch=(t,e)=>new Promise((n,i)=>{const r=new XMLHttpRequest;r.open(e.method||"GET",t);for(const[t,s]of objectEntries(e.headers))r.setRequestHeader(t,s);r.onload=()=>{n({ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,headers:r.getAllResponseHeaders().split("\r\n").reduce((t,e)=>{const[n,i]=e.split(": ");return n&&i&&(t[n]=i),t},{}),json:()=>Promise.resolve(JSON.parse(r.responseText)),text:()=>Promise.resolve(r.responseText)})},r.onerror=()=>{i(new TypeError("Network request failed"))},r.send(e.body)});function getFetchImplementation(){return"undefined"!=typeof fetch?fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?fetchAdapter(global.fetch):window.fetch?fetchAdapter(window.fetch):xhrFetch}function objectValues(t){const e=[];for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.push(t[n]);return e}function objectEntries(t){const e=[];for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.push([n,t[n]]);return e}class AuthService{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=![],this.apiKey=t.apiKey,this.baseUrl=t.baseUrl,this.env=t.env,this.httpClient=getFetchImplementation(),this.logger=LoggerFactory.get("Auth"),this.clientConfig=ClientConfigService.getInstance()}static getInstance(t){return SingletonManager.getClassInstance("AuthService",()=>new AuthService(t))}async authenticate(){var t,e;if(this.isAuthenticating)return await new Promise(t=>{const o=()=>{this.isAuthenticating?setTimeout(o,100):t(void 0)};o()}),!!this.accessToken;this.isAuthenticating=!![];try{const n=await this.requestWithoutAuth("/auth",{method:"GET"});return this.accessToken=null===(t=null==n?void 0:n.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==n?void 0:n.data)||void 0===e?void 0:e.exp),!![]}catch(n){return this.logger.error("Authentication failed:",(null==n?void 0:n.message)||n),![]}finally{this.isAuthenticating=![]}}async requestWithoutAuth(t,e){const n=this.buildUrl(t),i={"Content-Type":"application/json","X-Liquid-Api-Key":this.apiKey,"X-Liquid-Api-Env":this.env,"X-Liquid-Api-Sdk":window.location.href,"X-Liquid-Sdk-Version":this.clientConfig.get("version")||"unknown","X-Liquid-Timestamp":Date.now(),...this.getProxyHeaders(),...e.headers};this.clientConfig.isBuilder()&&(i["X-Liquid-Api-Builder"]=!![]);const r={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(n,r);if(!s.ok)throw new Error("HTTP error status: "+s.status);return s.json()}isTokenExpired(){return this.tokenExpiration?Date.now()>=this.tokenExpiration:!![]}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const n=this.buildUrl(t),i={"Content-Type":"application/json",Authorization:"Bearer "+this.accessToken,"X-Liquid-Api-Env":this.env,"X-Liquid-Api-Sdk":window.location.href,"X-Liquid-Sdk-Version":this.clientConfig.get("version")||"unknown","X-Liquid-Timestamp":Date.now(),...this.getProxyHeaders(),...e.headers};this.clientConfig.isBuilder()&&(i["X-Liquid-Api-Builder"]=!![]);const r={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(n,r);let a;try{a=await s.json()}catch(c){const t=await s.text().catch(()=>"HTTP error status: "+s.status);a={message:t||c}}if(!s.ok)throw{...a,status:s.status,message:(null==a?void 0:a.message)||"HTTP error status: "+s.status};return a}buildUrl(t){const e=this.clientConfig.getProxyConfig();return new URL("api"+t,e?e.baseUrl:this.baseUrl).toString()}getProxyHeaders(){const t=this.clientConfig.getProxyConfig();return t?{"X-Liquid-Proxy":"true","X-Liquid-Proxy-Target":this.baseUrl,...t.headers}:{}}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,n){return this.request(t,{method:"POST",body:e,headers:n})}async put(t,e,n){return this.request(t,{method:"PUT",body:e,headers:n})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}const c="@liquidcommerce/elements-sdk",l="LiquidCommerce Elements SDK",d="UNLICENSED",h="LiquidCommerce Team",u="2.2.2",p="https://docs.liquidcommerce.co/elements-sdk",m={type:"git",url:"git+https://github.com/liquidcommerce/elements-sdk.git"},g={url:"https://github.com/liquidcommerce/elements-sdk/issues"},v="./dist/index.esm.js",y="./umd/elements.js",b="./dist/types/index.d.ts",x="pnpm@10.0.0",w={".":{types:"./dist/types/index.d.ts",import:"./dist/index.esm.js",browser:"./umd/elements.js",default:"./dist/index.esm.js"},"./package.json":"./package.json"},C=["dist","umd","README.md"],k={access:"public",registry:"https://registry.npmjs.org/"},S="module",I=["dist/index.esm.js","umd/elements.js","src/index.ts","src/index.umd.ts"],T={build:"rollup -c","build:dev":"rollup -c --environment NODE_ENV:development",dev:"rollup -c -w","type-check":"tsc --noEmit",lint:"pnpm biome lint --write",format:"biome format --write",check:"pnpm biome check --write",fl:"pnpm check && pnpm build:dev",changelog:"conventional-changelog -p angular -i CHANGELOG.md -s",clean:"rm -rf dist umd","clean:hard":"rm -rf dist umd node_modules && pnpm install && pnpm build",prepublishOnly:"pnpm run build","deprecate:old":'npm deprecate @liquidcommerceteam/elements-sdk@"*" "Package moved to @liquidcommerce/elements-sdk"'},P=["liquidcommerce","alcohol","beverage","alcohol tech","elements","custom web components","embeddable components","embeddable web components","embeddable commerce"],F={"@biomejs/biome":"2.2.2","@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@rollup/plugin-alias":"^5.1.1","@rollup/plugin-commonjs":"^28.0.6","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^15.3.1","@rollup/plugin-replace":"^6.0.2","@rollup/plugin-terser":"^0.4.4","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/git":"^10.0.1","@semantic-release/github":"^11.0.6","@semantic-release/npm":"^12.0.2","@semantic-release/release-notes-generator":"^14.1.0","@types/core-js":"^2.5.8","@types/node":"^24.5.2","conventional-changelog-cli":"^5.0.0",husky:"^9.1.7",process:"^0.11.10",rollup:"^4.52.2","rollup-obfuscator":"^4.1.1","rollup-plugin-typescript2":"^0.36.0","semantic-release":"^24.2.9","ts-node":"^10.9.2",typescript:"^5.9.2"},D={node:">=20"},A={peerDependencyRules:{ignoreMissing:[]},onlyBuiltDependencies:["@biomejs/biome","javascript-obfuscator"],overrides:{"@conventional-changelog/git-client@<2.0.0":">=2.0.0"}},_={name:c,description:l,license:d,author:h,version:u,homepage:p,repository:m,bugs:g,module:v,browser:y,types:b,packageManager:x,exports:w,files:C,publishConfig:k,type:S,sideEffects:I,scripts:T,keywords:P,devDependencies:F,engines:D,pnpm:A};class GoogleTagManagerService{constructor(){this.partnerEnableGaTracking=![],this.liquidCommerceEnableGaTracking=![],this.isInitialized=![],this.isInitializing=![],this.currency="USD",this.eventQueue=[],this.logger=LoggerFactory.get("GoogleTagManager"),this.clientConfigService=ClientConfigService.getInstance()}static getInstance(){return SingletonManager.getClassInstance("GoogleTagManagerService",()=>new GoogleTagManagerService)}waitForDOMReady(){return new Promise(t=>{if("loading"!==document.readyState)return t(),void 0;document.addEventListener("DOMContentLoaded",()=>t())})}isGTMAlreadyLoaded(){if("function"==="object".gtag)return!![];const t=Array.from(document.querySelectorAll('script[src*="googletagmanager.com/gtm.js"]'));return t.length>0}isContainerLoaded(t){const e=Array.from(document.querySelectorAll('script[src*="googletagmanager.com/gtm.js"]'));return e.some(e=>{const n=e.src;return n.includes("id="+t)})}initializeGtag(){window.dataLayer||(window.dataLayer=[]),window.gtag?this.logger.info("GTM already initialized, using existing gtag function"):(window.gtag=(...t)=>window.dataLayer.push(t),window.dataLayer.push({"gtm.start":Date.now(),event:"gtm.js"}),this.logger.info("Initialized gtag function and dataLayer"))}loadGTMScript(t){return new Promise((e,n)=>{if(this.isContainerLoaded(t))return this.logger.info("GTM container "+t+" already loaded, skipping script injection"),e(),void 0;this.logger.info("Loading GTM container "+t);const i=document.createElement("script");i.src="https://www.googletagmanager.com/gtm.js?id="+t,i.async=!![];const r=setTimeout(()=>n(new Error("GTM script timeout: "+t)),5e3);i.onload=()=>{clearTimeout(r),this.logger.info("GTM container "+t+" loaded successfully"),e()},i.onerror=()=>{clearTimeout(r),n(new Error("GTM script failed: "+t))},document.head.appendChild(i)})}processEventQueue(){const t=Date.now(),e=this.eventQueue.filter(e=>t-e.timestamp<3e4);for(const i of e)try{const t={event:i.eventName,...i.eventData};window.dataLayer.push(t),"function"==="object".gtag&&window.gtag("event",i.eventName,i.eventData),this.logger.debug("Processed queued GTM event: "+i.eventName,{data:i.eventData})}catch(n){this.logger.error("Error processing queued event "+i.methodName+":",n)}this.eventQueue=[],e.length>0&&this.logger.info("Processed "+e.length+" queued GTM events")}getSendToTargets(){const t=[];return this.liquidCommerceEnableGaTracking&&this.liquidCommerceGtmId&&(!this.isContainerLoaded(this.liquidCommerceGtmId)&&this.isGTMAlreadyLoaded()||t.push(this.liquidCommerceGtmId)),this.partnerEnableGaTracking&&this.partnerGtmId&&(this.isGTMAlreadyLoaded()||this.isContainerLoaded(this.partnerGtmId))&&t.push(this.partnerGtmId),0===t.length&&this.isGTMAlreadyLoaded()&&this.logger.debug("No specific targets configured, letting GTM route events naturally"),t}async initialize(t){if(this.isInitialized||this.isInitializing)return this.initializationPromise;if(!this.clientConfigService.isBuilder()){this.isInitializing=!![],this.initializationPromise=this.doInitialize(t);try{await this.initializationPromise}catch(e){this.isInitializing=![],this.initializationPromise=void 0,this.logger.error("GTM initialization failed:",e)}}}async doInitialize(t){if(!(null==t?void 0:t.partnerName)||!(null==t?void 0:t.liquidCommerceGtmId))throw new Error("GTM config missing required fields");if(!t.liquidCommerceEnableGaTracking&&!t.partnerEnableGaTracking)return this.logger.warn("GTM initialization skipped: No tracking enabled"),this.isInitialized=!![],this.isInitializing=![],void 0;await this.waitForDOMReady(),this.partnerName=t.partnerName,this.partnerGtmId=t.partnerGtmId,this.liquidCommerceGtmId=t.liquidCommerceGtmId,this.partnerEnableGaTracking=t.partnerEnableGaTracking,this.liquidCommerceEnableGaTracking=t.liquidCommerceEnableGaTracking;const e=this.isGTMAlreadyLoaded();e&&this.logger.info("Partner GTM detected, integrating with existing setup"),this.initializeGtag();let n=![],i="";if(t.liquidCommerceEnableGaTracking)try{await this.loadGTMScript(t.liquidCommerceGtmId),n=!![],i=e?"GTM integrated with existing setup (Partner GTM detected, LC container: "+t.liquidCommerceGtmId+")":"GTM initialized with container "+t.liquidCommerceGtmId}catch(r){this.logger.warn("Failed to load LiquidCommerce GTM container: "+r+". Checking if partner GTM is available.")}if(n||(e&&window.dataLayer?(n=!![],i="GTM integrated with existing partner setup"):window.dataLayer&&Array.isArray(window.dataLayer)&&(n=!![],i="GTM initialized with dataLayer (basic functionality available)")),!n)throw this.isInitializing=![],new Error("GTM initialization failed: No working GTM configuration available");this.isInitialized=!![],this.isInitializing=![],this.logger.info(i),this.processEventQueue()}executeEvent(t,e,n){try{if(this.clientConfigService.isBuilder())return;const i=this.getSendToTargets(),r={...n,...i.length>0&&{send_to:i},tenant_source:_.description+" v"+_.version,tenant_name:this.partnerName};if(!this.isInitialized)return this.eventQueue.length>=100&&this.eventQueue.shift(),this.eventQueue.push({methodName:t,eventName:e,eventData:r,timestamp:Date.now()}),this.logger.debug("Queued GTM event: "+e+" (initialization pending)",{data:r}),void 0;if(!window.dataLayer||!Array.isArray(window.dataLayer))return this.logger.warn("GTM event "+e+" skipped: dataLayer not available"),void 0;const s={event:e,...r};window.dataLayer.push(s),"function"==="object".gtag&&window.gtag("event",e,r),this.logger.debug("Sent GTM event: "+e,{method:"function"==="object".gtag?"dataLayer + gtag":"dataLayer only",targets:i.length>0?i:"no targeting",data:r})}catch(i){this.logger.error("GTM "+t+" error:",i)}}calculateValue(t){return t.reduce((t,e)=>t+(e.price||0)*(e.quantity||1),0)}viewItem(t){this.executeEvent("viewItem","view_item",{currency:this.currency,value:this.calculateValue([t]),items:[t]})}viewItemList(t,e,n){this.executeEvent("viewItemList","view_item_list",{currency:this.currency,item_list_id:e,item_list_name:n,items:t})}selectItem(t,e,n){this.executeEvent("selectItem","select_item",{item_list_id:e,item_list_name:n,items:[t]})}addToCart(t){this.executeEvent("addToCart","add_to_cart",{currency:this.currency,value:this.calculateValue([t]),quantity:t.quantity||1,items:[t]})}viewCart(t){this.executeEvent("viewCart","view_cart",{currency:this.currency,value:this.calculateValue(t),items:t})}removeFromCart(t){this.executeEvent("removeFromCart","remove_from_cart",{currency:this.currency,value:this.calculateValue([t]),items:[t]})}beginCheckout(t,e){this.executeEvent("beginCheckout","begin_checkout",{currency:this.currency,value:this.calculateValue(t),coupon:e,items:t})}addShippingInfo(t,e){this.executeEvent("addShippingInfo","add_shipping_info",{currency:this.currency,value:this.calculateValue(t),coupon:e,items:t})}addShippingInfoWithCustomerData(t,e,n){this.executeEvent("addShippingInfo","add_shipping_info",{currency:this.currency,value:t,coupon:e,phone:null==n?void 0:n.phone,email:null==n?void 0:n.email,birth_date:null==n?void 0:n.birth_date,customer_id:null==n?void 0:n.customer_id})}addPaymentInfo(t,e,n){this.executeEvent("addPaymentInfo","add_payment_info",{currency:this.currency,value:this.calculateValue(t),payment_type:e,coupon:n,items:t})}addPaymentInfoWithoutItems(t,e,n){this.executeEvent("addPaymentInfo","add_payment_info",{currency:this.currency,value:t,payment_type:e,coupon:n})}purchase(t){this.executeEvent("purchase","purchase",{transaction_id:t.transaction_id,value:t.value,currency:this.currency,tax:t.tax,shipping:t.shipping,coupon:t.coupon,items:t.items})}increaseQuantity(t){this.executeEvent("increaseQuantity","add_to_cart",{currency:this.currency,value:this.calculateValue([t]),items:[t]})}decreaseQuantity(t){this.executeEvent("decreaseQuantity","remove_from_cart",{currency:this.currency,value:this.calculateValue([t]),items:[t]})}}class PubSubService{constructor(){this.eventPrefix="lce",this.logger=LoggerFactory.get("PubSub")}static getInstance(){return SingletonManager.getClassInstance("PubSubService",()=>new PubSubService)}publishAction(t,e){this.publishSpecific("actions."+t,e)}publishForm(t,e){this.publishSpecific("forms."+t,e)}publishSpecific(t,e){const[n,i]=t.includes(".")?t.split(".",2):["actions",t];let r=i.split("_")[0];["product","cart","address","checkout"].includes(r)||(r="other");const s=Date.now(),a={eventId:this.generateEventId(s),namespace:n,event:i,originalEvent:t,actionNamespace:"actions"===n?r:void 0,timestamp:s},c={data:e,metadata:a};this.dispatchNativeEvents(t,c)}dispatchNativeEvents(t,e){const[n]=t.split(".",2);try{const i=new CustomEvent(this.eventPrefix+":"+t,{detail:e,bubbles:!![],cancelable:!![]});window.dispatchEvent(i);const r=new CustomEvent(this.eventPrefix+":"+n,{detail:e,bubbles:!![],cancelable:!![]});window.dispatchEvent(r)}catch(i){this.logger.error("Error dispatching native events for "+t+":",i)}}generateEventId(t){return"evt_"+t+"_"+Math.random().toString(36).slice(2,9)}}const O="liquid_elements",N={identifier:"",id:"",brand:"",category:"",catPath:"",classification:"",type:"",subType:"",salsifyGrouping:"",name:"",description:"",htmlDescription:"",images:[],sizes:{},productHasAvailability:![],fulfillmentHasAvailability:![],quantity:1,selectedFulfillmentType:r.SHIPPING,selectedSizeId:null,selectedFulfillmentId:null,selectedFulfillment:null,loading:![],updating:![],error:null,engravingLines:[],drawer:{isOpen:![],contentConfig:null},rerender:![],mainImage:null},z={id:null,loading:![],error:null,items:{},retailers:{},totals:{subtotal:0,total:0,shippingFee:0,platformFee:0,engravingFee:0,deliveryFee:0,discounts:0,quantity:0},promoCode:null,fulfillments:{},rerender:![],shouldReset:![],updatedAt:"",createdAt:"",events:[]},R={token:"",cartId:"",loading:![],updating:![],error:null,warning:[],isPresaleLocked:![],presaleExpiresAt:null,acceptedAccountCreation:![],deliveryTips:[],hasAgeVerify:![],hasSubstitutionPolicy:![],isGift:![],billingSameAsShipping:!![],marketingPreferences:{canEmail:![],canSms:![]},giftRecipient:{firstName:"",lastName:"",email:"",phone:"",birthDate:"",addressTwo:null,company:null,message:null},customer:{firstName:"",lastName:"",email:"",phone:"",birthDate:"",addressTwo:"",company:""},payment:{key:"",secret:"",paymentMethodId:null,sendSubmitSignal:![]},billing:null,promoCode:null,giftCards:[],orderNumber:null,items:{},readyForSubmit:{customer:![],gift:![],billing:![],payment:![],prepared:![]},amounts:{total:0,subtotal:0,shipping:0,discounts:0,delivery:0,platform:0,tax:0,engraving:0,giftCards:0,service:0,tip:0,details:{taxes:{bag:0,bottleDeposits:0,retailDelivery:0,products:0,delivery:0,shipping:0},discounts:{products:0,delivery:0,shipping:0,service:0,engraving:0}}},rerender:![],isFormValid:![],invalidFields:[],focusField:null,onDemandFulfillmentTipInfo:{},tipSelection:10,stripeFormStatus:{isComplete:![],hasError:![],isProcessing:![],errorMessage:null},deliveryInstructions:null,card:{brand:null,country:null,expMonth:null,expYear:null,last4:null,funding:null},giftCardError:null,promoCodeError:null,events:[]},B={drawer:{isOpen:![],contentConfig:null}},L={id:"",formattedAddress:"",address:{one:"",two:"",city:"",state:"",zip:"",country:""},coordinates:{lat:0,long:0}},j={products:{},cart:z,address:L,checkout:R,ui:B};class ApiClientService{constructor(){this.client=null,this.logger=LoggerFactory.get("ApiClient")}static getInstance(){return SingletonManager.getClassInstance("ApiClientService",()=>new ApiClientService)}async setClient(t){this.client=t}async getAllConfigs(){var t;try{this.ensureClientInitialized();const t=await this.client.get("/configs");if(!this.validResponseData(t))throw this.logger.error(t),new Error("Failed to fetch all configs: Invalid response data");return t.data}catch(e){throw this.logger.error("Error fetching configs:",null!==(t=null==e?void 0:e.message)&&void 0!==t?t:e),e}}async setPersistedStore(t,e){var n;try{this.ensureClientInitialized();const n=await this.client.post("/configs/store/"+t,e);200!==n.statusCode&&this.logger.error("Failed to set persisted store:",n)}catch(i){this.logger.error("Error setting persisted store:",null!==(n=null==i?void 0:i.message)&&void 0!==n?n:i)}}async getPersistedStore(t){var e;try{this.ensureClientInitialized();const e=await this.client.get("/configs/store/"+t);return 200!==e.statusCode?(this.logger.error("Failed to fetch persisted store:",e),null):e.data}catch(n){return this.logger.error("Error fetching persisted store:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),null}}async getProductsData(t,e){var n;try{this.ensureClientInitialized();const n={upcs:t,ids:t,grouping:t,shouldShowOffHours:!![],isLegacy:!![],loc:e},i=await this.client.post("/cloud/catalog/availability",n);return 200===i.statusCode&&i.products&&0!==i.products.length?{products:i.products,retailers:i.retailers}:(this.logger.error(i),null)}catch(i){return this.logger.error("Error fetching product data:",null!==(n=null==i?void 0:i.message)&&void 0!==n?n:i),null}}async getCartData(t){var e;try{this.ensureClientInitialized();const e=await this.client.get("/cloud/cart"+(t?"?id="+t:""));if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to fetch cart data: "+e.message);return e.cart}catch(n){throw this.logger.error("Error fetching cart data:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async updateCart(t){var e;try{this.ensureClientInitialized();const e=await this.client.put("/cloud/cart",t);if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to update cart: "+e.message);return e.cart}catch(n){throw this.logger.error("Error updating cart:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async getAddressSuggestions(t){var e;try{this.ensureClientInitialized();const e=await this.client.get("/cloud/address/autocomplete?input="+t);if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to fetch address suggestions: "+e.message);return e.data}catch(n){throw this.logger.error("Error fetching address suggestions:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async getAddressDetails(t){var e;try{this.ensureClientInitialized();const e=await this.client.get("/cloud/address/details/"+t);if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to fetch address details: "+e.message);return e.data}catch(n){throw this.logger.error("Error fetching address details:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async prepareCheckout(t){var e;try{this.ensureClientInitialized();const e=await this.client.post("/cloud/checkout/prepare",t);if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to fetch prepare checkout data: "+e.message);return e.checkout}catch(n){throw this.logger.error("Error fetching prepare checkout data:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async getPaymentSession(t){var e;try{this.ensureClientInitialized();const e=await this.client.post("/cloud/payment/session",t);if(201!==e.statusCode)throw this.logger.error(e),new Error("Failed to get payment session: "+e.message);return e.data}catch(n){throw this.logger.error("Error fetching payment session:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),n}}async confirmPaymentSession(t,e){var n;try{this.ensureClientInitialized();const n=await this.client.post("/cloud/payment/confirm",{confirmationTokenId:t,setupIntentId:e});if(200!==n.statusCode)throw this.logger.error(n),new Error("Failed to confirm payment session: "+n.message);return n.data}catch(i){throw this.logger.error("Error confirming payment session:",null!==(n=null==i?void 0:i.message)&&void 0!==n?n:i),i}}async checkoutComplete(t){var e;try{this.ensureClientInitialized();const e=await this.client.post("/cloud/checkout/complete",t);if(200!==e.statusCode)throw this.logger.error(e),new Error("Failed to complete checkout: "+e.message);return e.order}catch(n){if(this.logger.error("Error completing checkout:",null!==(e=null==n?void 0:n.message)&&void 0!==e?e:n),null==n?void 0:n.error)throw new Error(n.error);throw n}}validResponseData(t){return t.data&&"object"==typeof t.data&&Object.keys(t.data).length>0}ensureClientInitialized(){if(!this.client)throw new Error("API client is not initialized")}}class StoreService{constructor(){this.middleware=[],this.isLocalStorageAvailable=![],this.loggingMiddleware=({action:t,payload:e,next:n})=>{const i=performance.now();this.logger.group("🏪 Store "+t+" ---------------------------------"),this.logger.debug("Payload:",e);try{const t=n(),e=performance.now()-i;return this.logger.debug("Completed in "+e.toFixed(3)+"ms"),t}catch(r){throw this.logger.error("Error:",r),r}finally{this.logger.groupEnd()}},this.performanceMiddleware=({action:t,next:e})=>{const n=performance.now(),i=e(),r=performance.now()-n;return r>16&&this.logger.warn('⚠️ Slow store operation "'+t+'": '+r.toFixed(2)+"ms"),i},this.state=j,this.listeners=new Map,this.logger=LoggerFactory.get("Store"),this.clientConfig=ClientConfigService.getInstance(),this.api=ApiClientService.getInstance(),this.setupMiddleware()}static getInstance(){return SingletonManager.getClassInstance("StoreService",()=>new StoreService)}async initialize({userDeviceId:t,isLocalStorageAvailable:e,persistedStore:n}){this.localStorageKey=O+"_"+t,this.isLocalStorageAvailable=e,e?await this.loadPersistedState():n&&await this.loadFromDBPersistence(n),this.addBeforeUnloadHandler(),this.logger.info("Store service initialized successfully",{userDeviceId:t,isLocalStorageAvailable:e,hasPersistedState:null!==n,localStorageKey:this.localStorageKey})}get(t){if(!t)return{...this.state};const e=t.split(".");let n=this.state;for(const i of e){if(null==n)return;n=n[i]}return void 0!==n?Array.isArray(n)?[...n]:"object"==typeof n&&null!==n?{...n}:n:void 0}set(t,e){return this.runWithMiddleware("set",{path:t,value:e},()=>{const n=this.get(t);return this.state=this.immutableSet(this.state,t,e),this.notifyListeners(t,e,n),this.isLocalStorageAvailable&&this.debouncedSave(),!![]})}update(t,e){const n=this.get(t),i=e(n);return this.set(t,i)}remove(t){return this.runWithMiddleware("remove",{path:t},()=>{const e=this.get(t);if(void 0===e)return this.logger.warn('No value found at path "'+t+'" to remove.'),![];const n=t.split(".");let i=this.state;const r=n.pop();for(const s of n){if(void 0===i[s])return this.logger.warn('Path "'+t+'" does not exist in the state.'),![];i=i[s]}if(Array.isArray(i))i=i.filter((t,e)=>e!==Number.parseInt(r,10));else{if("object"!=typeof i||null===i)return this.logger.warn('Cannot remove property "'+r+'" from non-object type at path "'+t+'".'),![];{const{[r]:t,...e}=i;i=e}}return this.state=this.immutableSet(this.state,n.join("."),i),this.notifyListeners(t,void 0,e),this.isLocalStorageAvailable&&this.debouncedSave(),!![]})}batch(t){return this.runWithMiddleware("batch",{updates:t},()=>{const e=[];if("function"==typeof t){const n=t(this.state);for(const[t,i]of Object.entries(n)){const n=this.get(t);e.push({path:t,oldValue:n,newValue:i,timestamp:Date.now()}),this.state=this.immutableSet(this.state,t,i)}}else for(const[n,i]of Object.entries(t)){const t=this.get(n);e.push({path:n,oldValue:t,newValue:i,timestamp:Date.now()}),this.state=this.immutableSet(this.state,n,i)}for(const{path:t,oldValue:n,newValue:i}of e)this.notifyListeners(t,i,n);return this.isLocalStorageAvailable&&this.debouncedSave(),!![]})}watch(t,e){const n=t;return this.listeners.has(n)||this.listeners.set(n,new Set),this.listeners.get(n).add(e),()=>{var t;null===(t=this.listeners.get(n))||void 0===t?void 0:t.delete(e)}}watchMany(t,e){const n=[];let i;const r=t.map(t=>this.watch(t,(r,s)=>{n.push({path:t,value:r,oldValue:s}),clearTimeout(i),i=setTimeout(()=>{n.length>0&&(e([...n]),n.length=0)},0)}));return()=>{for(const t of r)t()}}createProductInstance(t){const e="products."+t,n=this.get(e);return n?!![]:this.set(e,N)}removeProductInstance(t){const e=this.get("products"),{[t]:n,...i}=e;return this.set("products",i)}getProductInstances(){return this.get("products")}getState(){return{...this.state}}setupMiddleware(){this.middleware.push(this.loggingMiddleware),this.middleware.push(this.performanceMiddleware)}runWithMiddleware(t,e,n){let i=0;const E=()=>{if(i>=this.middleware.length)return n();const r=this.middleware[i++];return r({action:t,payload:e,state:this.getState(),next:E})};return E()}immutableSet(t,e,n){const i=e.split(".");if(1===i.length){if(Array.isArray(t)){const e=[...t];return e[i[0]]=n,e}return{...t,[i[0]]:n}}const[r,...s]=i,a=t[r],c=Array.isArray(a)?[]:{};if(Array.isArray(t)){const e=[...t];return e[r]=this.immutableSet(a||c,s.join("."),n),e}return{...t,[r]:this.immutableSet(a||c,s.join("."),n)}}notifyListeners(t,e,n){const i=this.listeners.get(t);if(i)for(const c of i)try{c(e,n)}catch(s){this.logger.error('Error in store listener for path "'+t+'":',s)}const r=t.split(".");for(let c=r.length-1;c>0;c--){const t=r.slice(0,c).join("."),e=this.listeners.get(t);if(e){const i=this.get(t),s=r.slice(c).join("."),l=this.immutableSet(i,s,n);for(const n of e)try{n(i,l)}catch(a){this.logger.error('Error in store listener for parent path "'+t+'":',a)}}}}debouncedSave(){this.saveTimeout&&clearTimeout(this.saveTimeout),this.saveTimeout=setTimeout(()=>this.saveStore(),50)}forceSave(){this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveTimeout=void 0),this.saveStore()}saveStore(){if(this.isLocalStorageAvailable&&this.localStorageKey)try{let t="";if(this.clientConfig.debuggingDisabled()){const e=this.get("address.id")||"",n=this.get("cart.id")||"";t=e+"_"+n}else t=this.getState();t&&localStorage.setItem(this.localStorageKey,"string"!=typeof t?JSON.stringify(t):t)}catch(t){this.logger.warn("Failed to persist store state:",t)}}async loadPersistedState(){if(this.isLocalStorageAvailable&&this.localStorageKey)try{const e=localStorage.getItem(this.localStorageKey);if(!e)return;try{const t=JSON.parse(e);for(const[e,n]of Object.entries(t))this.set(e,n);return}catch(t){if(e.includes("_")){const[t,n]=e.split("_");if(void 0!==t){const e=await this.getAddressDataFromId(t);this.set("address",e)}return void 0!==n&&this.set("cart.id",n||null),void 0}this.logger.warn("Unrecognized localStorage format, skipping load",{saved:e})}}catch(e){this.logger.warn("Failed to load persisted state:",e),localStorage.removeItem(this.localStorageKey)}}async loadFromDBPersistence(t){try{t.p&&(this.state.address=await this.getAddressDataFromId(t.p)),t.c&&(this.state.cart.id=t.c),this.logger.info("Session data loaded from DB persistence",{addressId:t.p,cartId:t.c})}catch(e){this.logger.error("Failed to load session data from DB persistence",e)}}addBeforeUnloadHandler(){window.addEventListener("beforeunload",()=>{this.isLocalStorageAvailable&&this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveStore())}),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.isLocalStorageAvailable&&this.saveTimeout&&(clearTimeout(this.saveTimeout),this.saveStore())})}async getAddressDataFromId(t){if(!t||""===t.trim())return L;try{const e=await this.api.getAddressDetails(t);return e&&0!==Object.keys(e).length?{id:t,formattedAddress:e.formattedAddress,address:{one:e.address.one,two:e.address.two,city:e.address.city,state:e.address.state,zip:e.address.zip,country:e.address.country||""},coordinates:{lat:e.coords.lat,long:e.coords.long}}:{...L,id:t}}catch(e){return{...L,id:t}}}}class BaseCommand{constructor(){this.store=StoreService.getInstance(),this.api=ApiClientService.getInstance(),this.logger=LoggerFactory.get("BaseCommand"),this.pubSub=PubSubService.getInstance(),this.googleTagManager=GoogleTagManagerService.getInstance(),this.clientConfig=ClientConfigService.getInstance()}getLocation(){const t=this.store.get("address");if(t.address.one&&t.coordinates.long&&t.coordinates.lat)return{coords:t.coordinates,address:t.address}}}const includeCartEvents=(t,e)=>t.filter(t=>e.includes(t.type)),excludeCartEvents=(t,e)=>t.filter(t=>!e.includes(t.type)),eventsForCart=t=>excludeCartEvents(t,["NewCart","ItemsRemoved","CartError","NoId","InvalidId","NoItemsInCart","RemovedExistingCartItems","PartnerProductConfigs","RetailerMinNotMet"]),hasCartAnyPromoCodeEvents=t=>{const e=["CouponProcessingError","CouponNotFound","CouponExpired","NoApplicableDiscount","CouponNotStarted","MinimumOrderValueNotMet","MinimumOrderUnitsNotMet","MinimumDistinctItemsNotMet","QuotaExceeded","UserLimitExceeded","NotFirstPurchase","InvalidCoupon","InvalidMembership","InvalidDomain","InvalidRequirements","InvalidOrganization","ProductNotEligible","NotEnoughPreviousOrders","RetailerDoesNotAllowPromos","RetailersDoNotAllowPromos"],n=includeCartEvents(t,e);return n.length>0},includeCheckoutEvents=(t,e)=>t.filter(t=>e.includes(t.type)),eventsForCheckout=t=>includeCheckoutEvents(t,["RetailerOnDemandHoursNotAvailable","ItemQuantityChange","MaxQuantityPerOrderExceeded"]),promoCodeCheckoutEvents=t=>includeCheckoutEvents(t,["RetailerDoesNotAllowPromos","RetailersDoNotAllowPromos"]),giftCardCheckoutEvents=t=>includeCheckoutEvents(t,["ErrorProcessingGiftCards","InvalidGiftCardCodes","InvalidGiftCardPartner","InactiveGiftCard","GiftCardAlreadyInUse","GiftCardExpired","GiftCardBalanceDepleted","RetailerDoesNotAllowGiftCards","RetailersDoNotAllowGiftCards"]),hasAnyRetailerGiftCardRestriction=t=>{const e=["RetailerDoesNotAllowGiftCards","RetailersDoNotAllowGiftCards"];return t.some(t=>e.includes(t.type))},q={OutOfStock:"error",ItemsNotAdded:"warning",ItemsRequestedNotAdded:"warning",ItemEngravingError:"error",AddressChange:"warning",LocationAvailability:"warning",PartnerProductConfigs:"warning",RemovedExistingCartItems:"warning",RetailerMinNotMet:"warning",NoItemsInCart:"warning",InvalidId:"warning",NoId:"warning",CartCheckoutProcessed:"success",NewCart:"warning",CartError:"error",ItemQuantityChange:"warning",ItemIdNotFound:"error",ItemsRemoved:"warning",CouponProcessingError:"error",CouponNotFound:"error",CouponExpired:"error",NoApplicableDiscount:"warning",CouponNotStarted:"error",MinimumOrderValueNotMet:"warning",MinimumOrderUnitsNotMet:"warning",MinimumDistinctItemsNotMet:"warning",QuotaExceeded:"error",UserLimitExceeded:"error",NotFirstPurchase:"warning",InvalidCoupon:"error",InvalidMembership:"error",InvalidDomain:"error",InvalidRequirements:"error",InvalidOrganization:"error",ProductNotEligible:"warning",NotEnoughPreviousOrders:"warning",PresaleItemsNotAllowed:"error",PresaleLimitExceeded:"error",PresaleNotStarted:"error",PresaleExpired:"error",PresaleMixedCart:"error",RetailerDoesNotAllowPromos:"warning",RetailersDoNotAllowPromos:"warning"},G={ErrorProcessingGiftCards:"error",InvalidGiftCardCodes:"error",InvalidGiftCardPartner:"error",InactiveGiftCard:"error",GiftCardAlreadyInUse:"error",GiftCardExpired:"error",GiftCardBalanceDepleted:"error",RetailerOnDemandHoursNotAvailable:"warning",It