ui.shipaid.com 0.3.128 → 0.3.129
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/widget.es.js +4 -3
- package/dist/widget.iife.js +1 -1
- package/dist/widget.umd.js +1 -1
- package/package.json +1 -1
package/dist/widget.es.js
CHANGED
|
@@ -5715,7 +5715,7 @@ class ShipAidCheckoutPlus extends s$1 {
|
|
|
5715
5715
|
const [first, ...rest] = matches;
|
|
5716
5716
|
if (first) {
|
|
5717
5717
|
this._originalCheckoutButton = first;
|
|
5718
|
-
this._applyButtonStylesFrom(first);
|
|
5718
|
+
this._applyButtonStylesFrom(first, customStyles || {});
|
|
5719
5719
|
first.setAttribute("data-shipaid-replaced", "true");
|
|
5720
5720
|
if (!first.hasAttribute("shipaid-hidden")) first.setAttribute("shipaid-hidden", "");
|
|
5721
5721
|
if (this.previousElementSibling !== first && this.nextElementSibling !== first) {
|
|
@@ -5760,9 +5760,10 @@ class ShipAidCheckoutPlus extends s$1 {
|
|
|
5760
5760
|
}
|
|
5761
5761
|
}
|
|
5762
5762
|
this._remountTimer = window.setTimeout(() => {
|
|
5763
|
-
var _a2, _b, _c;
|
|
5763
|
+
var _a2, _b, _c, _d, _e;
|
|
5764
5764
|
const hasOriginal = !!(this._originalCheckoutButton && document.contains(this._originalCheckoutButton));
|
|
5765
5765
|
const dbSelector = ((_c = (_b = (_a2 = this._store) == null ? void 0 : _a2.checkoutPlus) == null ? void 0 : _b.selectors) == null ? void 0 : _c.join(",")) || "";
|
|
5766
|
+
const customStyles = ((_e = (_d = this._store) == null ? void 0 : _d.checkoutPlus) == null ? void 0 : _e.styles) || {};
|
|
5766
5767
|
const provided = (dbSelector || this.dataSelector || "").trim();
|
|
5767
5768
|
const selectors = provided ? provided.split(",").map((s3) => s3.trim()).filter(Boolean) : DEFAULT_CHECKOUT_SELECTORS;
|
|
5768
5769
|
const nodeList = document.querySelectorAll(selectors.join(", "));
|
|
@@ -5774,7 +5775,7 @@ class ShipAidCheckoutPlus extends s$1 {
|
|
|
5774
5775
|
el.setAttribute("shipaid-hidden", "");
|
|
5775
5776
|
});
|
|
5776
5777
|
if (!this._originalCheckoutButton && firstEl) {
|
|
5777
|
-
this._applyButtonStylesFrom(firstEl);
|
|
5778
|
+
this._applyButtonStylesFrom(firstEl, customStyles || {});
|
|
5778
5779
|
}
|
|
5779
5780
|
const anyMatch = nodeList.length > 0;
|
|
5780
5781
|
if (!hasOriginal || anyMatch) {
|
package/dist/widget.iife.js
CHANGED
|
@@ -1564,7 +1564,7 @@ function Lt(t,e,i){return t?e():null==i?void 0:i()}const Gt=nt`
|
|
|
1564
1564
|
<div class="shipaid">
|
|
1565
1565
|
${Lt(this._hasFinishedSetup,(()=>{var t,e,i,o,n;const r=null==(o=null==(i=null==(e=null==(t=this._store)?void 0:t.widgetConfigurations)?void 0:e.widget)?void 0:i.theme_checkout)?void 0:o.checkoutButtonSelector,a=sessionStorage.getItem("shipaidWidgetTheme");!a&&r&&sessionStorage.setItem("shipaidWidgetTheme",r),!this.useShipAidCheckout&&r||sessionStorage.removeItem("shipaidWidgetTheme");return this._shouldShowWidget&&this.planActive&&(null==(n=this._store)?void 0:n.widgetShowCart)?a?this.contactlessCheckoutButtonTemplate():this.promptTemplate():(this.useShipAidCheckout||document.querySelectorAll('[id*="shipaid-checkout-container"]').forEach((t=>t.remove())),this.getElementsBySelector(sessionStorage.getItem("shipaidWidgetTheme")||this.dataSelector).forEach((t=>t.removeAttribute("shipaid-hidden"))),R)}),(()=>sessionStorage.getItem("shipaidWidgetTheme")?this.contactlessCheckoutButtonTemplate():this.promptTemplate()))}
|
|
1566
1566
|
</div>
|
|
1567
|
-
`}};Ne.styles=Xt;let Ve=Ne;Ye([a({type:String,attribute:!0})],Ve.prototype,"env"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"useCustomStoreFront"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeDomain"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeAccessToken"),Ye([a({type:String,attribute:!0})],Ve.prototype,"cartId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disablePolling"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableActions"),Ye([a({type:Number,attribute:!0})],Ve.prototype,"pollingInterval"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableRefresh"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"refreshCart"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"persistPopup"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"defaultToggleButton"),Ye([a({type:String,attribute:!0})],Ve.prototype,"lang"),Ye([a({type:String,attribute:!0})],Ve.prototype,"currency"),Ye([a({type:String,attribute:!0})],Ve.prototype,"customerId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"supportSubscriptions"),Ye([a({type:String,attribute:"data-selector"})],Ve.prototype,"dataSelector"),Ye([a({type:String,attribute:"button-id"})],Ve.prototype,"buttonId"),Ye([a({type:String,attribute:"button-title"})],Ve.prototype,"buttonTitle"),Ye([a({type:String,attribute:"widget-title"})],Ve.prototype,"widgetTitle"),Ye([a({type:String,attribute:"button-classes"})],Ve.prototype,"buttonClasses"),Ye([a({type:String,attribute:"shadow-root-selector"})],Ve.prototype,"shadowRootSelector"),Ye([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ve.prototype,"useShipAidCheckout"),Ye([a({type:Boolean,attribute:"preview-green-shipaid"})],Ve.prototype,"previewGreenShipAid"),Ye([s()],Ve.prototype,"_storeDomain"),Ye([s()],Ve.prototype,"_store"),Ye([s()],Ve.prototype,"_cart"),Ye([s()],Ve.prototype,"_protectionProduct"),Ye([s()],Ve.prototype,"_cartLastUpdated"),Ye([s()],Ve.prototype,"_hasFinishedSetup"),Ye([s()],Ve.prototype,"_shouldShowWidget"),Ye([s()],Ve.prototype,"_hasProtectionInCart"),Ye([s()],Ve.prototype,"_protectionCartItem"),Ye([s()],Ve.prototype,"_protectionVariant"),Ye([s()],Ve.prototype,"hasLoadedStrings"),Ye([s()],Ve.prototype,"fetchInterceptorCleanup"),Ye([s()],Ve.prototype,"intervalId"),Ye([s()],Ve.prototype,"_sellingPlanId"),Ye([s()],Ve.prototype,"_state"),Ye([s()],Ve.prototype,"_popup");var ze=Object.defineProperty,Ze=(t,e,i,o)=>{for(var n,r=void 0,a=t.length-1;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&ze(e,i,r),r};class We extends Et{constructor(){super(...arguments),this.env="prod",this.lang="en",this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=t=>{var e,i;if("shipaid-widget"===(null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source))return;const o=Date.now();if(!(o-this._lastCartEventAt<500)){this._lastCartEventAt=o;try{this.updateCart().catch((()=>{}))}catch{}}},this._onShipAidInternalCartUpdated=t=>{var e,i,o,n;if("shipaid-widget"===((null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source)||(null==(o=null==t?void 0:t.detail)?void 0:o.source)))return;const r=null==(n=null==t?void 0:t.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch((()=>{})):this.updateCart().catch((()=>{}))}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:t=>ke(t),post:(t,e)=>ke(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const t=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(t,{credentials:"same-origin"});if(!e.ok)return;const i=await e.json().catch((()=>null));if(!i||"object"!=typeof i)return;this._isReplacingCartSections=!0;for(const o of Object.keys(i)){const t=i[o];if("string"!=typeof t)continue;const e=document.createElement("div");if(e.innerHTML=t,"cart-drawer"!==o)if("main-cart-items"!==o)if("cart-icon-bubble"!==o);else{const t=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),i=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");t&&i&&i.replaceWith(t)}else{const i=e.querySelector("#main-cart-items"),o=document.getElementById("main-cart-items");if(i&&o)o.outerHTML=i.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=t)}}else{try{const t=e.querySelector("cart-drawer"),i=document.querySelector("cart-drawer");if(t&&i){t.classList.contains("is-empty")?i.classList.add("is-empty"):i.classList.remove("is-empty")}}catch{}try{const t=e.querySelector("cart-drawer-items"),i=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");t&&i&&(i.outerHTML=t.outerHTML)}catch{}const t=e.querySelector("#CartDrawer-CartItems"),i=document.getElementById("CartDrawer-CartItems");t&&i&&(i.outerHTML=t.outerHTML);const o=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");o&&n&&(n.outerHTML=o.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML)}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await wt(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",(()=>{this._aboutToUnload=!0}))}catch{}try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const o={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(se.LOADED,o))}catch(t){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var t,e,i,o;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var t;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(t=this._store.checkoutPlus)?void 0:t.enabled))}updated(t){if(t.has("dataSelector")||t.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}t.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach((t=>{var e;try{null==(e=t.parentNode)||e.removeChild(t)}catch{}}))}catch{}}_applyButtonStylesFrom(t,e={}){if(t)try{const i=window.getComputedStyle(t),o=i.color,n=i.backgroundColor,r=i.borderTopStyle,a=i.borderTopColor,s=i.borderTopWidth;this.style.setProperty("--cp-primary-color",o||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",s||""),Object.entries(e).forEach((([t,e])=>{this.style.setProperty(t,e)}))}catch{}}_enterToggleMode(t){const e="toggle"!==this._uiMode;this._uiMode="toggle",t&&(this._persistTogglePreference(t),this._desiredProtection="checked"===t),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(t){try{sessionStorage.setItem(me,t)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(me)}catch{}}_readTogglePreference(){try{const t=sessionStorage.getItem(me);return"checked"===t||"unchecked"===t?t:null}catch{return null}}_normalizeVariantId(t){if(!t)return null;if("number"==typeof t)return String(Math.trunc(t));if("string"==typeof t){const e=t.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const i=e.match(/\d+/g);if(null==i?void 0:i.length)return i[i.length-1]}if("object"==typeof t){if("id"in t)return this._normalizeVariantId(t.id);if("variant_id"in t)return this._normalizeVariantId(t.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const t=this._readTogglePreference();t?(this._uiMode="toggle",this._desiredProtection="checked"===t):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var t,e,i,o,n;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const r=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",a=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},s=(r||this.dataSelector||"").trim(),l=s?s.split(",").map((t=>t.trim())).filter(Boolean):Re,d=Array.from(document.querySelectorAll(l.join(", ")));if(!d.length)return;if(this.isClone){const t=d[0];return this._originalCheckoutButton=t,this._applyButtonStylesFrom(t,a||{}),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden",""),void(this.previousElementSibling!==t&&this.nextElementSibling!==t&&t.insertAdjacentElement("afterend",this))}const[c,...h]=d;c&&(this._originalCheckoutButton=c,this._applyButtonStylesFrom(c),c.setAttribute("data-shipaid-replaced","true"),c.hasAttribute("shipaid-hidden")||c.setAttribute("shipaid-hidden",""),this.previousElementSibling!==c&&this.nextElementSibling!==c&&c.insertAdjacentElement("afterend",this));for(const t of h){if("true"===t.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;t.setAttribute("data-shipaid-anchor",e),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden","");const i=document.createElement("shipaid-widget-v2");i.setAttribute("data-clone","true"),i.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{i.setAttribute("env",this.env)}catch{}try{i.setAttribute("lang",this.lang)}catch{}t.insertAdjacentElement("afterend",i)}}catch{}}}_startObserver(){var t;try{null==(t=this._observer)||t.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const t=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout((()=>{var t,e,i;const o=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),n=((null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||""||this.dataSelector||"").trim(),r=n?n.split(",").map((t=>t.trim())).filter(Boolean):Re,a=document.querySelectorAll(r.join(", "));let s=null;a.forEach(((t,e)=>{const i=t;0===e&&(s=i),i.setAttribute("data-shipaid-replaced","true"),i.setAttribute("shipaid-hidden","")})),!this._originalCheckoutButton&&s&&this._applyButtonStylesFrom(s);const l=a.length>0;o&&!l||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)}),150)};this._observer=new MutationObserver(t),this._observer.observe(document.body,{childList:!0,subtree:!0})}catch{}}disconnectedCallback(){var t,e,i;super.disconnectedCallback();try{null==(t=this._originalCheckoutButton)||t.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(i=this._itemsObserver)||i.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout((()=>this._mountNearCheckoutButton()),0))}catch{}try{document.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(t=!1){var e;try{t&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(t&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const i=(()=>{const t=(this.itemsSelector||"").trim();if(t)return document.querySelector(t);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const i of e){const t=document.querySelector(i);if(t)return t}return null})();if(i){this._itemsTargetEl=i;try{this._itemsObserver=new MutationObserver((()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout((()=>{this._updateCartInFlight||this.updateCart().catch((()=>{}))}),500)}})),this._itemsObserver.observe(i,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var t,e,i,o,n;const r=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const s={query:xe,variables:{store:r}},l=await this._fetch.post(a.toString(),s);if(null==(o=null==l?void 0:l.errors)?void 0:o.length)throw new Error(l.errors[0].message);const d=null==(n=null==l?void 0:l.data)?void 0:n.store;if(!d)throw new Error("Missing store from store query response.");return d}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${we}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(t,e){if(this._updateCartInFlight&&!t&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var i,o;t||(t=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=t,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(le.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:t}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout((()=>this._mountNearCheckoutButton()),0)}catch{}})().finally((()=>{this._updateCartInFlight=null})),this._updateCartInFlight}async _fetchCartThrottled(t=1e3){const e=Date.now();return t>0&&this._cartCache&&e-this._cartFetchLastAt<t?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then((t=>(this._cartCache=t,this._cartFetchLastAt=Date.now(),t))).finally((()=>{this._cartFetchPromise=null}))),this._cartFetchPromise)}async calculateProtectionTotal(t){if(t||(t=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,t)}getProtectionVariantForFee(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,t)}async calculateProtectionFeeForCartPlusAmountCents(t){if(!Number.isFinite(t)||t<=0)return{fee:0,variant:void 0};const e={total_price:Number(t),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(t),quantity:1,isVirtualProduct:!1}]},i=await this.calculateProtectionTotal(e);return{fee:i,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0}}async addProtection(){var t;if(!(null==(t=this._protectionVariant)?void 0:t.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===we));if(!e)return;const i={updates:{[String(e.id)]:0}},o=await this._fetch.post("/cart/update.js",i);await this.updateCart(o,{forceFetch:!1})}_currencyFormat(t){var e,i,o;const n=(null==(e=this._store)?void 0:e.currency)||(null==(o=null==(i=window.Shopify)?void 0:i.currency)?void 0:o.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(t))}async updateProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===we));if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart?this._hasRenderedLegacyOnce?this._enterToggleMode("checked"):this._removeTogglePreference():this._maybeRevertToLegacy();const i=await this.calculateProtectionTotal(this._cart),o=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0;this._protectionVariant=o,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(se.CART_UPDATED,r))}render(){var t,e,i,o,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return R;const r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled),s=r?re:ae,l=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,d=b`<style>
|
|
1567
|
+
`}};Ne.styles=Xt;let Ve=Ne;Ye([a({type:String,attribute:!0})],Ve.prototype,"env"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"useCustomStoreFront"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeDomain"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeAccessToken"),Ye([a({type:String,attribute:!0})],Ve.prototype,"cartId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disablePolling"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableActions"),Ye([a({type:Number,attribute:!0})],Ve.prototype,"pollingInterval"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableRefresh"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"refreshCart"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"persistPopup"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"defaultToggleButton"),Ye([a({type:String,attribute:!0})],Ve.prototype,"lang"),Ye([a({type:String,attribute:!0})],Ve.prototype,"currency"),Ye([a({type:String,attribute:!0})],Ve.prototype,"customerId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"supportSubscriptions"),Ye([a({type:String,attribute:"data-selector"})],Ve.prototype,"dataSelector"),Ye([a({type:String,attribute:"button-id"})],Ve.prototype,"buttonId"),Ye([a({type:String,attribute:"button-title"})],Ve.prototype,"buttonTitle"),Ye([a({type:String,attribute:"widget-title"})],Ve.prototype,"widgetTitle"),Ye([a({type:String,attribute:"button-classes"})],Ve.prototype,"buttonClasses"),Ye([a({type:String,attribute:"shadow-root-selector"})],Ve.prototype,"shadowRootSelector"),Ye([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ve.prototype,"useShipAidCheckout"),Ye([a({type:Boolean,attribute:"preview-green-shipaid"})],Ve.prototype,"previewGreenShipAid"),Ye([s()],Ve.prototype,"_storeDomain"),Ye([s()],Ve.prototype,"_store"),Ye([s()],Ve.prototype,"_cart"),Ye([s()],Ve.prototype,"_protectionProduct"),Ye([s()],Ve.prototype,"_cartLastUpdated"),Ye([s()],Ve.prototype,"_hasFinishedSetup"),Ye([s()],Ve.prototype,"_shouldShowWidget"),Ye([s()],Ve.prototype,"_hasProtectionInCart"),Ye([s()],Ve.prototype,"_protectionCartItem"),Ye([s()],Ve.prototype,"_protectionVariant"),Ye([s()],Ve.prototype,"hasLoadedStrings"),Ye([s()],Ve.prototype,"fetchInterceptorCleanup"),Ye([s()],Ve.prototype,"intervalId"),Ye([s()],Ve.prototype,"_sellingPlanId"),Ye([s()],Ve.prototype,"_state"),Ye([s()],Ve.prototype,"_popup");var ze=Object.defineProperty,Ze=(t,e,i,o)=>{for(var n,r=void 0,a=t.length-1;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&ze(e,i,r),r};class We extends Et{constructor(){super(...arguments),this.env="prod",this.lang="en",this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=t=>{var e,i;if("shipaid-widget"===(null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source))return;const o=Date.now();if(!(o-this._lastCartEventAt<500)){this._lastCartEventAt=o;try{this.updateCart().catch((()=>{}))}catch{}}},this._onShipAidInternalCartUpdated=t=>{var e,i,o,n;if("shipaid-widget"===((null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source)||(null==(o=null==t?void 0:t.detail)?void 0:o.source)))return;const r=null==(n=null==t?void 0:t.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch((()=>{})):this.updateCart().catch((()=>{}))}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:t=>ke(t),post:(t,e)=>ke(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const t=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(t,{credentials:"same-origin"});if(!e.ok)return;const i=await e.json().catch((()=>null));if(!i||"object"!=typeof i)return;this._isReplacingCartSections=!0;for(const o of Object.keys(i)){const t=i[o];if("string"!=typeof t)continue;const e=document.createElement("div");if(e.innerHTML=t,"cart-drawer"!==o)if("main-cart-items"!==o)if("cart-icon-bubble"!==o);else{const t=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),i=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");t&&i&&i.replaceWith(t)}else{const i=e.querySelector("#main-cart-items"),o=document.getElementById("main-cart-items");if(i&&o)o.outerHTML=i.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=t)}}else{try{const t=e.querySelector("cart-drawer"),i=document.querySelector("cart-drawer");if(t&&i){t.classList.contains("is-empty")?i.classList.add("is-empty"):i.classList.remove("is-empty")}}catch{}try{const t=e.querySelector("cart-drawer-items"),i=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");t&&i&&(i.outerHTML=t.outerHTML)}catch{}const t=e.querySelector("#CartDrawer-CartItems"),i=document.getElementById("CartDrawer-CartItems");t&&i&&(i.outerHTML=t.outerHTML);const o=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");o&&n&&(n.outerHTML=o.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML)}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await wt(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",(()=>{this._aboutToUnload=!0}))}catch{}try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const o={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(se.LOADED,o))}catch(t){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var t,e,i,o;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var t;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(t=this._store.checkoutPlus)?void 0:t.enabled))}updated(t){if(t.has("dataSelector")||t.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}t.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach((t=>{var e;try{null==(e=t.parentNode)||e.removeChild(t)}catch{}}))}catch{}}_applyButtonStylesFrom(t,e={}){if(t)try{const i=window.getComputedStyle(t),o=i.color,n=i.backgroundColor,r=i.borderTopStyle,a=i.borderTopColor,s=i.borderTopWidth;this.style.setProperty("--cp-primary-color",o||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",s||""),Object.entries(e).forEach((([t,e])=>{this.style.setProperty(t,e)}))}catch{}}_enterToggleMode(t){const e="toggle"!==this._uiMode;this._uiMode="toggle",t&&(this._persistTogglePreference(t),this._desiredProtection="checked"===t),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(t){try{sessionStorage.setItem(me,t)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(me)}catch{}}_readTogglePreference(){try{const t=sessionStorage.getItem(me);return"checked"===t||"unchecked"===t?t:null}catch{return null}}_normalizeVariantId(t){if(!t)return null;if("number"==typeof t)return String(Math.trunc(t));if("string"==typeof t){const e=t.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const i=e.match(/\d+/g);if(null==i?void 0:i.length)return i[i.length-1]}if("object"==typeof t){if("id"in t)return this._normalizeVariantId(t.id);if("variant_id"in t)return this._normalizeVariantId(t.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const t=this._readTogglePreference();t?(this._uiMode="toggle",this._desiredProtection="checked"===t):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var t,e,i,o,n;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const r=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",a=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},s=(r||this.dataSelector||"").trim(),l=s?s.split(",").map((t=>t.trim())).filter(Boolean):Re,d=Array.from(document.querySelectorAll(l.join(", ")));if(!d.length)return;if(this.isClone){const t=d[0];return this._originalCheckoutButton=t,this._applyButtonStylesFrom(t,a||{}),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden",""),void(this.previousElementSibling!==t&&this.nextElementSibling!==t&&t.insertAdjacentElement("afterend",this))}const[c,...h]=d;c&&(this._originalCheckoutButton=c,this._applyButtonStylesFrom(c,a||{}),c.setAttribute("data-shipaid-replaced","true"),c.hasAttribute("shipaid-hidden")||c.setAttribute("shipaid-hidden",""),this.previousElementSibling!==c&&this.nextElementSibling!==c&&c.insertAdjacentElement("afterend",this));for(const t of h){if("true"===t.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;t.setAttribute("data-shipaid-anchor",e),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden","");const i=document.createElement("shipaid-widget-v2");i.setAttribute("data-clone","true"),i.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{i.setAttribute("env",this.env)}catch{}try{i.setAttribute("lang",this.lang)}catch{}t.insertAdjacentElement("afterend",i)}}catch{}}}_startObserver(){var t;try{null==(t=this._observer)||t.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const t=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout((()=>{var t,e,i,o,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",s=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},l=(a||this.dataSelector||"").trim(),d=l?l.split(",").map((t=>t.trim())).filter(Boolean):Re,c=document.querySelectorAll(d.join(", "));let h=null;c.forEach(((t,e)=>{const i=t;0===e&&(h=i),i.setAttribute("data-shipaid-replaced","true"),i.setAttribute("shipaid-hidden","")})),!this._originalCheckoutButton&&h&&this._applyButtonStylesFrom(h,s||{});const p=c.length>0;r&&!p||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)}),150)};this._observer=new MutationObserver(t),this._observer.observe(document.body,{childList:!0,subtree:!0})}catch{}}disconnectedCallback(){var t,e,i;super.disconnectedCallback();try{null==(t=this._originalCheckoutButton)||t.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(i=this._itemsObserver)||i.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout((()=>this._mountNearCheckoutButton()),0))}catch{}try{document.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(t=!1){var e;try{t&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(t&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const i=(()=>{const t=(this.itemsSelector||"").trim();if(t)return document.querySelector(t);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const i of e){const t=document.querySelector(i);if(t)return t}return null})();if(i){this._itemsTargetEl=i;try{this._itemsObserver=new MutationObserver((()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout((()=>{this._updateCartInFlight||this.updateCart().catch((()=>{}))}),500)}})),this._itemsObserver.observe(i,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var t,e,i,o,n;const r=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const s={query:xe,variables:{store:r}},l=await this._fetch.post(a.toString(),s);if(null==(o=null==l?void 0:l.errors)?void 0:o.length)throw new Error(l.errors[0].message);const d=null==(n=null==l?void 0:l.data)?void 0:n.store;if(!d)throw new Error("Missing store from store query response.");return d}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${we}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(t,e){if(this._updateCartInFlight&&!t&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var i,o;t||(t=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=t,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(le.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:t}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout((()=>this._mountNearCheckoutButton()),0)}catch{}})().finally((()=>{this._updateCartInFlight=null})),this._updateCartInFlight}async _fetchCartThrottled(t=1e3){const e=Date.now();return t>0&&this._cartCache&&e-this._cartFetchLastAt<t?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then((t=>(this._cartCache=t,this._cartFetchLastAt=Date.now(),t))).finally((()=>{this._cartFetchPromise=null}))),this._cartFetchPromise)}async calculateProtectionTotal(t){if(t||(t=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,t)}getProtectionVariantForFee(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,t)}async calculateProtectionFeeForCartPlusAmountCents(t){if(!Number.isFinite(t)||t<=0)return{fee:0,variant:void 0};const e={total_price:Number(t),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(t),quantity:1,isVirtualProduct:!1}]},i=await this.calculateProtectionTotal(e);return{fee:i,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0}}async addProtection(){var t;if(!(null==(t=this._protectionVariant)?void 0:t.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===we));if(!e)return;const i={updates:{[String(e.id)]:0}},o=await this._fetch.post("/cart/update.js",i);await this.updateCart(o,{forceFetch:!1})}_currencyFormat(t){var e,i,o;const n=(null==(e=this._store)?void 0:e.currency)||(null==(o=null==(i=window.Shopify)?void 0:i.currency)?void 0:o.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(t))}async updateProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===we));if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart?this._hasRenderedLegacyOnce?this._enterToggleMode("checked"):this._removeTogglePreference():this._maybeRevertToLegacy();const i=await this.calculateProtectionTotal(this._cart),o=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0;this._protectionVariant=o,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(se.CART_UPDATED,r))}render(){var t,e,i,o,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return R;const r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled),s=r?re:ae,l=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,d=b`<style>
|
|
1568
1568
|
:host {
|
|
1569
1569
|
--cp-border:#111;
|
|
1570
1570
|
--cp-text:#111;
|
package/dist/widget.umd.js
CHANGED
|
@@ -1564,7 +1564,7 @@ function Lt(t,e,i){return t?e():null==i?void 0:i()}const Gt=nt`
|
|
|
1564
1564
|
<div class="shipaid">
|
|
1565
1565
|
${Lt(this._hasFinishedSetup,(()=>{var t,e,i,o,n;const r=null==(o=null==(i=null==(e=null==(t=this._store)?void 0:t.widgetConfigurations)?void 0:e.widget)?void 0:i.theme_checkout)?void 0:o.checkoutButtonSelector,a=sessionStorage.getItem("shipaidWidgetTheme");!a&&r&&sessionStorage.setItem("shipaidWidgetTheme",r),!this.useShipAidCheckout&&r||sessionStorage.removeItem("shipaidWidgetTheme");return this._shouldShowWidget&&this.planActive&&(null==(n=this._store)?void 0:n.widgetShowCart)?a?this.contactlessCheckoutButtonTemplate():this.promptTemplate():(this.useShipAidCheckout||document.querySelectorAll('[id*="shipaid-checkout-container"]').forEach((t=>t.remove())),this.getElementsBySelector(sessionStorage.getItem("shipaidWidgetTheme")||this.dataSelector).forEach((t=>t.removeAttribute("shipaid-hidden"))),R)}),(()=>sessionStorage.getItem("shipaidWidgetTheme")?this.contactlessCheckoutButtonTemplate():this.promptTemplate()))}
|
|
1566
1566
|
</div>
|
|
1567
|
-
`}};Ne.styles=Xt;let Ve=Ne;Ye([a({type:String,attribute:!0})],Ve.prototype,"env"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"useCustomStoreFront"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeDomain"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeAccessToken"),Ye([a({type:String,attribute:!0})],Ve.prototype,"cartId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disablePolling"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableActions"),Ye([a({type:Number,attribute:!0})],Ve.prototype,"pollingInterval"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableRefresh"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"refreshCart"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"persistPopup"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"defaultToggleButton"),Ye([a({type:String,attribute:!0})],Ve.prototype,"lang"),Ye([a({type:String,attribute:!0})],Ve.prototype,"currency"),Ye([a({type:String,attribute:!0})],Ve.prototype,"customerId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"supportSubscriptions"),Ye([a({type:String,attribute:"data-selector"})],Ve.prototype,"dataSelector"),Ye([a({type:String,attribute:"button-id"})],Ve.prototype,"buttonId"),Ye([a({type:String,attribute:"button-title"})],Ve.prototype,"buttonTitle"),Ye([a({type:String,attribute:"widget-title"})],Ve.prototype,"widgetTitle"),Ye([a({type:String,attribute:"button-classes"})],Ve.prototype,"buttonClasses"),Ye([a({type:String,attribute:"shadow-root-selector"})],Ve.prototype,"shadowRootSelector"),Ye([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ve.prototype,"useShipAidCheckout"),Ye([a({type:Boolean,attribute:"preview-green-shipaid"})],Ve.prototype,"previewGreenShipAid"),Ye([s()],Ve.prototype,"_storeDomain"),Ye([s()],Ve.prototype,"_store"),Ye([s()],Ve.prototype,"_cart"),Ye([s()],Ve.prototype,"_protectionProduct"),Ye([s()],Ve.prototype,"_cartLastUpdated"),Ye([s()],Ve.prototype,"_hasFinishedSetup"),Ye([s()],Ve.prototype,"_shouldShowWidget"),Ye([s()],Ve.prototype,"_hasProtectionInCart"),Ye([s()],Ve.prototype,"_protectionCartItem"),Ye([s()],Ve.prototype,"_protectionVariant"),Ye([s()],Ve.prototype,"hasLoadedStrings"),Ye([s()],Ve.prototype,"fetchInterceptorCleanup"),Ye([s()],Ve.prototype,"intervalId"),Ye([s()],Ve.prototype,"_sellingPlanId"),Ye([s()],Ve.prototype,"_state"),Ye([s()],Ve.prototype,"_popup");var ze=Object.defineProperty,Ze=(t,e,i,o)=>{for(var n,r=void 0,a=t.length-1;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&ze(e,i,r),r};class We extends Et{constructor(){super(...arguments),this.env="prod",this.lang="en",this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=t=>{var e,i;if("shipaid-widget"===(null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source))return;const o=Date.now();if(!(o-this._lastCartEventAt<500)){this._lastCartEventAt=o;try{this.updateCart().catch((()=>{}))}catch{}}},this._onShipAidInternalCartUpdated=t=>{var e,i,o,n;if("shipaid-widget"===((null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source)||(null==(o=null==t?void 0:t.detail)?void 0:o.source)))return;const r=null==(n=null==t?void 0:t.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch((()=>{})):this.updateCart().catch((()=>{}))}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:t=>ke(t),post:(t,e)=>ke(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const t=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(t,{credentials:"same-origin"});if(!e.ok)return;const i=await e.json().catch((()=>null));if(!i||"object"!=typeof i)return;this._isReplacingCartSections=!0;for(const o of Object.keys(i)){const t=i[o];if("string"!=typeof t)continue;const e=document.createElement("div");if(e.innerHTML=t,"cart-drawer"!==o)if("main-cart-items"!==o)if("cart-icon-bubble"!==o);else{const t=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),i=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");t&&i&&i.replaceWith(t)}else{const i=e.querySelector("#main-cart-items"),o=document.getElementById("main-cart-items");if(i&&o)o.outerHTML=i.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=t)}}else{try{const t=e.querySelector("cart-drawer"),i=document.querySelector("cart-drawer");if(t&&i){t.classList.contains("is-empty")?i.classList.add("is-empty"):i.classList.remove("is-empty")}}catch{}try{const t=e.querySelector("cart-drawer-items"),i=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");t&&i&&(i.outerHTML=t.outerHTML)}catch{}const t=e.querySelector("#CartDrawer-CartItems"),i=document.getElementById("CartDrawer-CartItems");t&&i&&(i.outerHTML=t.outerHTML);const o=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");o&&n&&(n.outerHTML=o.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML)}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await yt(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",(()=>{this._aboutToUnload=!0}))}catch{}try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const o={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(se.LOADED,o))}catch(t){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var t,e,i,o;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var t;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(t=this._store.checkoutPlus)?void 0:t.enabled))}updated(t){if(t.has("dataSelector")||t.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}t.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach((t=>{var e;try{null==(e=t.parentNode)||e.removeChild(t)}catch{}}))}catch{}}_applyButtonStylesFrom(t,e={}){if(t)try{const i=window.getComputedStyle(t),o=i.color,n=i.backgroundColor,r=i.borderTopStyle,a=i.borderTopColor,s=i.borderTopWidth;this.style.setProperty("--cp-primary-color",o||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",s||""),Object.entries(e).forEach((([t,e])=>{this.style.setProperty(t,e)}))}catch{}}_enterToggleMode(t){const e="toggle"!==this._uiMode;this._uiMode="toggle",t&&(this._persistTogglePreference(t),this._desiredProtection="checked"===t),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(t){try{sessionStorage.setItem(me,t)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(me)}catch{}}_readTogglePreference(){try{const t=sessionStorage.getItem(me);return"checked"===t||"unchecked"===t?t:null}catch{return null}}_normalizeVariantId(t){if(!t)return null;if("number"==typeof t)return String(Math.trunc(t));if("string"==typeof t){const e=t.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const i=e.match(/\d+/g);if(null==i?void 0:i.length)return i[i.length-1]}if("object"==typeof t){if("id"in t)return this._normalizeVariantId(t.id);if("variant_id"in t)return this._normalizeVariantId(t.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const t=this._readTogglePreference();t?(this._uiMode="toggle",this._desiredProtection="checked"===t):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var t,e,i,o,n;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const r=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",a=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},s=(r||this.dataSelector||"").trim(),l=s?s.split(",").map((t=>t.trim())).filter(Boolean):Re,d=Array.from(document.querySelectorAll(l.join(", ")));if(!d.length)return;if(this.isClone){const t=d[0];return this._originalCheckoutButton=t,this._applyButtonStylesFrom(t,a||{}),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden",""),void(this.previousElementSibling!==t&&this.nextElementSibling!==t&&t.insertAdjacentElement("afterend",this))}const[c,...h]=d;c&&(this._originalCheckoutButton=c,this._applyButtonStylesFrom(c),c.setAttribute("data-shipaid-replaced","true"),c.hasAttribute("shipaid-hidden")||c.setAttribute("shipaid-hidden",""),this.previousElementSibling!==c&&this.nextElementSibling!==c&&c.insertAdjacentElement("afterend",this));for(const t of h){if("true"===t.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;t.setAttribute("data-shipaid-anchor",e),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden","");const i=document.createElement("shipaid-widget-v2");i.setAttribute("data-clone","true"),i.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{i.setAttribute("env",this.env)}catch{}try{i.setAttribute("lang",this.lang)}catch{}t.insertAdjacentElement("afterend",i)}}catch{}}}_startObserver(){var t;try{null==(t=this._observer)||t.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const t=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout((()=>{var t,e,i;const o=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),n=((null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||""||this.dataSelector||"").trim(),r=n?n.split(",").map((t=>t.trim())).filter(Boolean):Re,a=document.querySelectorAll(r.join(", "));let s=null;a.forEach(((t,e)=>{const i=t;0===e&&(s=i),i.setAttribute("data-shipaid-replaced","true"),i.setAttribute("shipaid-hidden","")})),!this._originalCheckoutButton&&s&&this._applyButtonStylesFrom(s);const l=a.length>0;o&&!l||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)}),150)};this._observer=new MutationObserver(t),this._observer.observe(document.body,{childList:!0,subtree:!0})}catch{}}disconnectedCallback(){var t,e,i;super.disconnectedCallback();try{null==(t=this._originalCheckoutButton)||t.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(i=this._itemsObserver)||i.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout((()=>this._mountNearCheckoutButton()),0))}catch{}try{document.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(t=!1){var e;try{t&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(t&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const i=(()=>{const t=(this.itemsSelector||"").trim();if(t)return document.querySelector(t);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const i of e){const t=document.querySelector(i);if(t)return t}return null})();if(i){this._itemsTargetEl=i;try{this._itemsObserver=new MutationObserver((()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout((()=>{this._updateCartInFlight||this.updateCart().catch((()=>{}))}),500)}})),this._itemsObserver.observe(i,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var t,e,i,o,n;const r=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const s={query:xe,variables:{store:r}},l=await this._fetch.post(a.toString(),s);if(null==(o=null==l?void 0:l.errors)?void 0:o.length)throw new Error(l.errors[0].message);const d=null==(n=null==l?void 0:l.data)?void 0:n.store;if(!d)throw new Error("Missing store from store query response.");return d}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${ye}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(t,e){if(this._updateCartInFlight&&!t&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var i,o;t||(t=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=t,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(le.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:t}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout((()=>this._mountNearCheckoutButton()),0)}catch{}})().finally((()=>{this._updateCartInFlight=null})),this._updateCartInFlight}async _fetchCartThrottled(t=1e3){const e=Date.now();return t>0&&this._cartCache&&e-this._cartFetchLastAt<t?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then((t=>(this._cartCache=t,this._cartFetchLastAt=Date.now(),t))).finally((()=>{this._cartFetchPromise=null}))),this._cartFetchPromise)}async calculateProtectionTotal(t){if(t||(t=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,t)}getProtectionVariantForFee(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,t)}async calculateProtectionFeeForCartPlusAmountCents(t){if(!Number.isFinite(t)||t<=0)return{fee:0,variant:void 0};const e={total_price:Number(t),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(t),quantity:1,isVirtualProduct:!1}]},i=await this.calculateProtectionTotal(e);return{fee:i,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0}}async addProtection(){var t;if(!(null==(t=this._protectionVariant)?void 0:t.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===ye));if(!e)return;const i={updates:{[String(e.id)]:0}},o=await this._fetch.post("/cart/update.js",i);await this.updateCart(o,{forceFetch:!1})}_currencyFormat(t){var e,i,o;const n=(null==(e=this._store)?void 0:e.currency)||(null==(o=null==(i=window.Shopify)?void 0:i.currency)?void 0:o.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(t))}async updateProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===ye));if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart?this._hasRenderedLegacyOnce?this._enterToggleMode("checked"):this._removeTogglePreference():this._maybeRevertToLegacy();const i=await this.calculateProtectionTotal(this._cart),o=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0;this._protectionVariant=o,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(se.CART_UPDATED,r))}render(){var t,e,i,o,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return R;const r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled),s=r?re:ae,l=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,d=b`<style>
|
|
1567
|
+
`}};Ne.styles=Xt;let Ve=Ne;Ye([a({type:String,attribute:!0})],Ve.prototype,"env"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"useCustomStoreFront"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeDomain"),Ye([a({type:String,attribute:!0})],Ve.prototype,"storeAccessToken"),Ye([a({type:String,attribute:!0})],Ve.prototype,"cartId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disablePolling"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableActions"),Ye([a({type:Number,attribute:!0})],Ve.prototype,"pollingInterval"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"disableRefresh"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"refreshCart"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"persistPopup"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"defaultToggleButton"),Ye([a({type:String,attribute:!0})],Ve.prototype,"lang"),Ye([a({type:String,attribute:!0})],Ve.prototype,"currency"),Ye([a({type:String,attribute:!0})],Ve.prototype,"customerId"),Ye([a({type:Boolean,attribute:!0})],Ve.prototype,"supportSubscriptions"),Ye([a({type:String,attribute:"data-selector"})],Ve.prototype,"dataSelector"),Ye([a({type:String,attribute:"button-id"})],Ve.prototype,"buttonId"),Ye([a({type:String,attribute:"button-title"})],Ve.prototype,"buttonTitle"),Ye([a({type:String,attribute:"widget-title"})],Ve.prototype,"widgetTitle"),Ye([a({type:String,attribute:"button-classes"})],Ve.prototype,"buttonClasses"),Ye([a({type:String,attribute:"shadow-root-selector"})],Ve.prototype,"shadowRootSelector"),Ye([a({type:Boolean,attribute:"use-shipaid-checkout"})],Ve.prototype,"useShipAidCheckout"),Ye([a({type:Boolean,attribute:"preview-green-shipaid"})],Ve.prototype,"previewGreenShipAid"),Ye([s()],Ve.prototype,"_storeDomain"),Ye([s()],Ve.prototype,"_store"),Ye([s()],Ve.prototype,"_cart"),Ye([s()],Ve.prototype,"_protectionProduct"),Ye([s()],Ve.prototype,"_cartLastUpdated"),Ye([s()],Ve.prototype,"_hasFinishedSetup"),Ye([s()],Ve.prototype,"_shouldShowWidget"),Ye([s()],Ve.prototype,"_hasProtectionInCart"),Ye([s()],Ve.prototype,"_protectionCartItem"),Ye([s()],Ve.prototype,"_protectionVariant"),Ye([s()],Ve.prototype,"hasLoadedStrings"),Ye([s()],Ve.prototype,"fetchInterceptorCleanup"),Ye([s()],Ve.prototype,"intervalId"),Ye([s()],Ve.prototype,"_sellingPlanId"),Ye([s()],Ve.prototype,"_state"),Ye([s()],Ve.prototype,"_popup");var ze=Object.defineProperty,Ze=(t,e,i,o)=>{for(var n,r=void 0,a=t.length-1;a>=0;a--)(n=t[a])&&(r=n(e,i,r)||r);return r&&ze(e,i,r),r};class We extends Et{constructor(){super(...arguments),this.env="prod",this.lang="en",this.dataSelector="",this.isClone=!1,this._hasFinishedSetup=!1,this._hasProtectionInCart=!1,this._originalCheckoutButton=null,this._toggleLoading=!1,this._desiredProtection=!1,this.isDetailsOpen=!1,this._uiMode="legacy",this._toggleId=`shipaid-cp-toggle-${Math.random().toString(36).slice(2,8)}`,this._hasRenderedLegacyOnce=!1,this._observer=null,this._remountTimer=null,this._aboutToUnload=!1,this._isReplacingCartSections=!1,this.itemsSelector="",this._itemsObserver=null,this._itemsTargetEl=null,this._itemsDebounceTimer=null,this._cartFetchPromise=null,this._cartFetchLastAt=0,this._cartCache=null,this._updateCartInFlight=null,this._lastCartEventAt=0,this._lastEnsureVariantAt=0,this._onShipAidCartEvent=t=>{var e,i;if("shipaid-widget"===(null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source))return;const o=Date.now();if(!(o-this._lastCartEventAt<500)){this._lastCartEventAt=o;try{this.updateCart().catch((()=>{}))}catch{}}},this._onShipAidInternalCartUpdated=t=>{var e,i,o,n;if("shipaid-widget"===((null==(i=null==(e=null==t?void 0:t.detail)?void 0:e.data)?void 0:i.source)||(null==(o=null==t?void 0:t.detail)?void 0:o.source)))return;const r=null==(n=null==t?void 0:t.detail)?void 0:n.cart;try{r?this.updateCart(r,{forceFetch:!1}).catch((()=>{})):this.updateCart().catch((()=>{}))}catch{}},this._apiEndpoint="/apps/shipaid",this._fetch={get:t=>ke(t),post:(t,e)=>ke(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})},this.proceedToCheckout=()=>{try{window.location.assign("/checkout")}catch{}},this.toggleDetails=()=>{this.isDetailsOpen=!this.isDetailsOpen},this.handleLegacySecondaryClick=()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{this.proceedToCheckout()}finally{this._toggleLoading=!1}}},this.handleLegacyPrimaryClick=async()=>{if(!this._toggleLoading){this._toggleLoading=!0;try{try{this._hasProtectionInCart||(await this.addProtection(),this._enterToggleMode("checked"))}catch{}this.proceedToCheckout()}finally{this._toggleLoading=!1}}}}async _refreshShopifyCartUI(){try{const t=`/?sections=${encodeURIComponent(["cart-drawer","cart-icon-bubble","main-cart-items"].join(","))}`,e=await fetch(t,{credentials:"same-origin"});if(!e.ok)return;const i=await e.json().catch((()=>null));if(!i||"object"!=typeof i)return;this._isReplacingCartSections=!0;for(const o of Object.keys(i)){const t=i[o];if("string"!=typeof t)continue;const e=document.createElement("div");if(e.innerHTML=t,"cart-drawer"!==o)if("main-cart-items"!==o)if("cart-icon-bubble"!==o);else{const t=e.querySelector("#cart-icon-bubble, [data-cart-count-bubble]"),i=document.querySelector("#cart-icon-bubble, [data-cart-count-bubble]");t&&i&&i.replaceWith(t)}else{const i=e.querySelector("#main-cart-items"),o=document.getElementById("main-cart-items");if(i&&o)o.outerHTML=i.outerHTML;else{const e=document.getElementById("shopify-section-main-cart-items");e&&(e.outerHTML=t)}}else{try{const t=e.querySelector("cart-drawer"),i=document.querySelector("cart-drawer");if(t&&i){t.classList.contains("is-empty")?i.classList.add("is-empty"):i.classList.remove("is-empty")}}catch{}try{const t=e.querySelector("cart-drawer-items"),i=document.querySelector("cart-drawer cart-drawer-items, .cart-drawer cart-drawer-items");t&&i&&(i.outerHTML=t.outerHTML)}catch{}const t=e.querySelector("#CartDrawer-CartItems"),i=document.getElementById("CartDrawer-CartItems");t&&i&&(i.outerHTML=t.outerHTML);const o=e.querySelector(".cart-drawer__footer"),n=document.querySelector(".cart-drawer .cart-drawer__footer");o&&n&&(n.outerHTML=o.outerHTML);const r=e.querySelector(".cart__ctas"),a=document.querySelector(".cart-drawer .cart__ctas");r&&a&&(a.outerHTML=r.outerHTML)}}}catch{}finally{this._isReplacingCartSections=!1}}async connectedCallback(){super.connectedCallback(),await yt(this.lang),this._removeLegacyV1();try{window.addEventListener("beforeunload",(()=>{this._aboutToUnload=!0}))}catch{}try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i,await this.updateProtection(),this._desiredProtection=this._hasProtectionInCart,this._hasFinishedSetup=!0,this._shouldShowWidget()&&this._ensureLearnMoreCarousel();const o={bubbles:!0,composed:!0,detail:this._store};this.dispatchEvent(new CustomEvent(se.LOADED,o))}catch(t){this._hasFinishedSetup=!0}this._startObserver();try{"/cart"===window.location.pathname.replace(/\/$/,"")&&this._observeCartItems()}catch{}try{await this.ensureProtectionVariantForCheckout()}catch{}try{document.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.addEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.addEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_ensureLearnMoreCarousel(){var t,e,i,o;try{if(document.querySelector("shipaid-learn-more-carousel"))return;const n=document.createElement("shipaid-learn-more-carousel"),r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled);r&&n.setAttribute("green-protection","true"),a&&n.setAttribute("free-gift","true"),n.setAttribute("carousel-state","close"),document.body.appendChild(n)}catch{}}_shouldShowWidget(){var t;return!!this._store&&(!0!==this._store.planActive?(console.warn("[ShipAid] Plan is not active, skipping widget mount"),!1):!0===(null==(t=this._store.checkoutPlus)?void 0:t.enabled))}updated(t){if(t.has("dataSelector")||t.has("_hasFinishedSetup")){if(!this._shouldShowWidget())return;this._mountNearCheckoutButton()}t.has("itemsSelector")&&this._observeCartItems(!0)}_removeLegacyV1(){try{document.querySelectorAll("shipaid-widget").forEach((t=>{var e;try{null==(e=t.parentNode)||e.removeChild(t)}catch{}}))}catch{}}_applyButtonStylesFrom(t,e={}){if(t)try{const i=window.getComputedStyle(t),o=i.color,n=i.backgroundColor,r=i.borderTopStyle,a=i.borderTopColor,s=i.borderTopWidth;this.style.setProperty("--cp-primary-color",o||""),this.style.setProperty("--cp-primary-bg",n||""),this.style.setProperty("--cp-primary-border-style",r||""),this.style.setProperty("--cp-primary-border-color",a||""),this.style.setProperty("--cp-primary-border-width",s||""),Object.entries(e).forEach((([t,e])=>{this.style.setProperty(t,e)}))}catch{}}_enterToggleMode(t){const e="toggle"!==this._uiMode;this._uiMode="toggle",t&&(this._persistTogglePreference(t),this._desiredProtection="checked"===t),e&&this.requestUpdate()}_maybeRevertToLegacy(){"toggle"===this._uiMode&&(this._hasProtectionInCart||this._readTogglePreference()||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1,this.isDetailsOpen=!1,this.requestUpdate()))}_persistTogglePreference(t){try{sessionStorage.setItem(me,t)}catch{}}_removeTogglePreference(){try{sessionStorage.removeItem(me)}catch{}}_readTogglePreference(){try{const t=sessionStorage.getItem(me);return"checked"===t||"unchecked"===t?t:null}catch{return null}}_normalizeVariantId(t){if(!t)return null;if("number"==typeof t)return String(Math.trunc(t));if("string"==typeof t){const e=t.trim();if(!e)return null;if(/^\d+$/.test(e))return e;const i=e.match(/\d+/g);if(null==i?void 0:i.length)return i[i.length-1]}if("object"==typeof t){if("id"in t)return this._normalizeVariantId(t.id);if("variant_id"in t)return this._normalizeVariantId(t.variant_id)}return null}_applyCachedUiPreference(){if(!this._cart||!Array.isArray(this._cart.items)||0===this._cart.items.length)return this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);const t=this._readTogglePreference();t?(this._uiMode="toggle",this._desiredProtection="checked"===t):this._hasProtectionInCart||(this._uiMode="legacy",this._desiredProtection=!1,this._hasRenderedLegacyOnce=!1)}_mountNearCheckoutButton(){var t,e,i,o,n;if(this.isConnected&&this._shouldShowWidget()){this._removeLegacyV1();try{const r=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",a=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},s=(r||this.dataSelector||"").trim(),l=s?s.split(",").map((t=>t.trim())).filter(Boolean):Re,d=Array.from(document.querySelectorAll(l.join(", ")));if(!d.length)return;if(this.isClone){const t=d[0];return this._originalCheckoutButton=t,this._applyButtonStylesFrom(t,a||{}),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden",""),void(this.previousElementSibling!==t&&this.nextElementSibling!==t&&t.insertAdjacentElement("afterend",this))}const[c,...h]=d;c&&(this._originalCheckoutButton=c,this._applyButtonStylesFrom(c,a||{}),c.setAttribute("data-shipaid-replaced","true"),c.hasAttribute("shipaid-hidden")||c.setAttribute("shipaid-hidden",""),this.previousElementSibling!==c&&this.nextElementSibling!==c&&c.insertAdjacentElement("afterend",this));for(const t of h){if("true"===t.getAttribute("data-shipaid-replaced"))continue;const e=`shipaid-anchor-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;t.setAttribute("data-shipaid-anchor",e),t.setAttribute("data-shipaid-replaced","true"),t.hasAttribute("shipaid-hidden")||t.setAttribute("shipaid-hidden","");const i=document.createElement("shipaid-widget-v2");i.setAttribute("data-clone","true"),i.setAttribute("data-selector",`[data-shipaid-anchor='${e}']`);try{i.setAttribute("env",this.env)}catch{}try{i.setAttribute("lang",this.lang)}catch{}t.insertAdjacentElement("afterend",i)}}catch{}}}_startObserver(){var t;try{null==(t=this._observer)||t.disconnect()}catch{}try{if(!this._shouldShowWidget())return;const t=()=>{if(this._remountTimer)try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=window.setTimeout((()=>{var t,e,i,o,n;const r=!(!this._originalCheckoutButton||!document.contains(this._originalCheckoutButton)),a=(null==(i=null==(e=null==(t=this._store)?void 0:t.checkoutPlus)?void 0:e.selectors)?void 0:i.join(","))||"",s=(null==(n=null==(o=this._store)?void 0:o.checkoutPlus)?void 0:n.styles)||{},l=(a||this.dataSelector||"").trim(),d=l?l.split(",").map((t=>t.trim())).filter(Boolean):Re,c=document.querySelectorAll(d.join(", "));let h=null;c.forEach(((t,e)=>{const i=t;0===e&&(h=i),i.setAttribute("data-shipaid-replaced","true"),i.setAttribute("shipaid-hidden","")})),!this._originalCheckoutButton&&h&&this._applyButtonStylesFrom(h,s||{});const p=c.length>0;r&&!p||this._mountNearCheckoutButton(),this._itemsTargetEl&&!document.contains(this._itemsTargetEl)&&this._observeCartItems(!0)}),150)};this._observer=new MutationObserver(t),this._observer.observe(document.body,{childList:!0,subtree:!0})}catch{}}disconnectedCallback(){var t,e,i;super.disconnectedCallback();try{null==(t=this._originalCheckoutButton)||t.removeAttribute("shipaid-hidden")}catch{}try{null==(e=this._observer)||e.disconnect()}catch{}if(this._remountTimer){try{clearTimeout(this._remountTimer)}catch{}this._remountTimer=null}try{null==(i=this._itemsObserver)||i.disconnect()}catch{}if(this._itemsObserver=null,this._itemsDebounceTimer){try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=null}if(!this._aboutToUnload)try{document.contains(this)||(document.body.appendChild(this),setTimeout((()=>this._mountNearCheckoutButton()),0))}catch{}try{document.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{window.removeEventListener(le.CART_UPDATE,this._onShipAidCartEvent)}catch{}try{document.removeEventListener(se.CART_UPDATED,this._onShipAidInternalCartUpdated)}catch{}}_observeCartItems(t=!1){var e;try{t&&(null==(e=this._itemsObserver)||e.disconnect())}catch{}if(t&&(this._itemsTargetEl=null),!this._hasFinishedSetup)return;const i=(()=>{const t=(this.itemsSelector||"").trim();if(t)return document.querySelector(t);const e=['form[action*="/cart"] .cart__items',"#CartItems",".cart__items",".cart-items","[data-cart-items]"];for(const i of e){const t=document.querySelector(i);if(t)return t}return null})();if(i){this._itemsTargetEl=i;try{this._itemsObserver=new MutationObserver((()=>{if(!this._isReplacingCartSections){if(this._itemsDebounceTimer)try{clearTimeout(this._itemsDebounceTimer)}catch{}this._itemsDebounceTimer=window.setTimeout((()=>{this._updateCartInFlight||this.updateCart().catch((()=>{}))}),500)}})),this._itemsObserver.observe(i,{childList:!0,subtree:!0})}catch{}}}async _fetchShipAidData(){var t,e,i,o,n;const r=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!r)throw new Error("No shop found in Shopify object.");const a=new URL(window.location.href);a.pathname=this._apiEndpoint;const s={query:xe,variables:{store:r}},l=await this._fetch.post(a.toString(),s);if(null==(o=null==l?void 0:l.errors)?void 0:o.length)throw new Error(l.errors[0].message);const d=null==(n=null==l?void 0:l.data)?void 0:n.store;if(!d)throw new Error("Missing store from store query response.");return d}async _fetchCart(){return await this._fetch.get("/cart.js")}async _fetchProduct(){return(await this._fetch.get(`/products/${ye}.json`)).product}hasProtection(){return!!this._hasProtectionInCart}async updateCart(t,e){if(this._updateCartInFlight&&!t&&!(null==e?void 0:e.forceFetch))return this._updateCartInFlight;return this._updateCartInFlight=(async()=>{var i,o;t||(t=await this._fetchCartThrottled((null==e?void 0:e.forceFetch)?0:1e3)),this._cart=t,await this.updateProtection();const n=Date.now();if(n-this._lastEnsureVariantAt>2e3&&(await this.ensureProtectionVariantForCheckout(),this._lastEnsureVariantAt=n),null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled)try{await this._fetch.post("/cart/update.js",{attributes:{_inspired_external_action_triggered:!!this._hasProtectionInCart||""}})}catch(r){}document.dispatchEvent(new CustomEvent(le.CART_UPDATE,{detail:{data:{source:"shipaid-widget"},cart:t}}));try{await this._refreshShopifyCartUI()}catch{}try{setTimeout((()=>this._mountNearCheckoutButton()),0)}catch{}})().finally((()=>{this._updateCartInFlight=null})),this._updateCartInFlight}async _fetchCartThrottled(t=1e3){const e=Date.now();return t>0&&this._cartCache&&e-this._cartFetchLastAt<t?this._cartCache:(this._cartFetchPromise||(this._cartFetchPromise=this._fetchCart().then((t=>(this._cartCache=t,this._cartFetchLastAt=Date.now(),t))).finally((()=>{this._cartFetchPromise=null}))),this._cartFetchPromise)}async calculateProtectionTotal(t){if(t||(t=await this._fetchCartThrottled(1e3)),!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.calculateProtectionTotal(this._store,this._protectionProduct,t)}getProtectionVariantForFee(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return n.findProtectionVariant(this._store,this._protectionProduct,t)}async calculateProtectionFeeForCartPlusAmountCents(t){if(!Number.isFinite(t)||t<=0)return{fee:0,variant:void 0};const e={total_price:Number(t),item_count:1,items:[{variant_id:0,sku:"",tags:[],final_line_price:Number(t),quantity:1,isVirtualProduct:!1}]},i=await this.calculateProtectionTotal(e);return{fee:i,variant:this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0}}async addProtection(){var t;if(!(null==(t=this._protectionVariant)?void 0:t.id))throw new Error("No protection variant found.");const e={quantity:1,id:String(this._protectionVariant.id)};await this._fetch.post("/cart/add.js",e),await this.updateCart(void 0,{forceFetch:!0})}async removeProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===ye));if(!e)return;const i={updates:{[String(e.id)]:0}},o=await this._fetch.post("/cart/update.js",i);await this.updateCart(o,{forceFetch:!1})}_currencyFormat(t){var e,i,o;const n=(null==(e=this._store)?void 0:e.currency)||(null==(o=null==(i=window.Shopify)?void 0:i.currency)?void 0:o.active)||"USD";return new Intl.NumberFormat(void 0,{currency:n,style:"currency"}).format(Number(t))}async updateProtection(){var t;if(!(null==(t=this._cart)?void 0:t.items))return;const e=this._cart.items.find((t=>(null==t?void 0:t.handle)===ye));if(1===this._cart.items.length&&e)return await this.removeProtection(),this._removeTogglePreference(),this._uiMode="legacy",this._desiredProtection=!1,void(this._hasRenderedLegacyOnce=!1);this._hasProtectionInCart=Boolean(e),this._desiredProtection=this._hasProtectionInCart,this._hasProtectionInCart?this._hasRenderedLegacyOnce?this._enterToggleMode("checked"):this._removeTogglePreference():this._maybeRevertToLegacy();const i=await this.calculateProtectionTotal(this._cart),o=this._store&&this._protectionProduct?n.findProtectionVariant(this._store,this._protectionProduct,i):void 0;this._protectionVariant=o,this._applyCachedUiPreference();const r={bubbles:!0,composed:!0,detail:{protection:this._hasProtectionInCart,cart:this._cart,lineItem:e??null,data:{source:"shipaid-widget"}}};this.dispatchEvent(new CustomEvent(se.CART_UPDATED,r))}render(){var t,e,i,o,n;if(!this._hasFinishedSetup||!this._shouldShowWidget())return R;const r=Boolean(null==(e=null==(t=this._store)?void 0:t.greenProtection)?void 0:e.enabled),a=Boolean(null==(o=null==(i=this._store)?void 0:i.freeGifts)?void 0:o.enabled),s=r?re:ae,l=(null==(n=this._protectionVariant)?void 0:n.price)?this._currencyFormat(this._protectionVariant.price):null,d=b`<style>
|
|
1568
1568
|
:host {
|
|
1569
1569
|
--cp-border:#111;
|
|
1570
1570
|
--cp-text:#111;
|