@zonos/elements 1.3.217 → 1.3.218
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/cjs/{cart-54ff39d6.js → cart-c54d05ce.js} +2 -2
- package/dist/cjs/{handleFetch-0313ebba.js → handleFetch-45f35cac.js} +2 -1
- package/dist/cjs/index.cjs.js +8 -8
- package/dist/cjs/{localization-721a5ec3.js → localization-ab7e1902.js} +1 -1
- package/dist/cjs/{paypal-e7504122.js → paypal-d36b5dd1.js} +3 -3
- package/dist/cjs/{updateCheckoutSessionAttributes-8db49644.js → updateCheckoutSessionAttributes-c0853fdd.js} +1 -1
- package/dist/cjs/zonos-address_11.cjs.entry.js +3 -3
- package/dist/cjs/zonos-cart-items_14.cjs.entry.js +5 -5
- package/dist/cjs/zonos-checkout.cjs.entry.js +5 -5
- package/dist/cjs/zonos-controller.cjs.entry.js +3 -3
- package/dist/cjs/zonos-country-flag.cjs.entry.js +2 -2
- package/dist/cjs/zonos-country-select_4.cjs.entry.js +2 -2
- package/dist/cjs/zonos-empty-state-payment_4.cjs.entry.js +4 -4
- package/dist/cjs/zonos-hello-dialog.cjs.entry.js +2 -2
- package/dist/cjs/zonos-hello.cjs.entry.js +2 -2
- package/dist/cjs/zonos-language-select_2.cjs.entry.js +2 -2
- package/dist/collection/components/utils/getNextFallbackApi.js +1 -1
- package/dist/collection/components/utils/handleFetch.js +1 -0
- package/dist/esm/{cart-010402f9.js → cart-bb0ee971.js} +2 -2
- package/dist/esm/{handleFetch-fa90f7f6.js → handleFetch-99218189.js} +2 -1
- package/dist/esm/index.js +8 -8
- package/dist/esm/{localization-9db8b6e9.js → localization-d8326254.js} +1 -1
- package/dist/esm/{paypal-70b140d9.js → paypal-bd4520eb.js} +3 -3
- package/dist/esm/{updateCheckoutSessionAttributes-691cdc6d.js → updateCheckoutSessionAttributes-92f42882.js} +1 -1
- package/dist/esm/zonos-address_11.entry.js +3 -3
- package/dist/esm/zonos-cart-items_14.entry.js +5 -5
- package/dist/esm/zonos-checkout.entry.js +5 -5
- package/dist/esm/zonos-controller.entry.js +3 -3
- package/dist/esm/zonos-country-flag.entry.js +2 -2
- package/dist/esm/zonos-country-select_4.entry.js +2 -2
- package/dist/esm/zonos-empty-state-payment_4.entry.js +4 -4
- package/dist/esm/zonos-hello-dialog.entry.js +2 -2
- package/dist/esm/zonos-hello.entry.js +2 -2
- package/dist/esm/zonos-language-select_2.entry.js +2 -2
- package/dist/esm-es5/{cart-010402f9.js → cart-bb0ee971.js} +1 -1
- package/dist/esm-es5/{handleFetch-fa90f7f6.js → handleFetch-99218189.js} +1 -1
- package/dist/esm-es5/index.js +1 -1
- package/dist/esm-es5/{localization-9db8b6e9.js → localization-d8326254.js} +1 -1
- package/dist/esm-es5/{paypal-70b140d9.js → paypal-bd4520eb.js} +1 -1
- package/dist/esm-es5/{updateCheckoutSessionAttributes-691cdc6d.js → updateCheckoutSessionAttributes-92f42882.js} +1 -1
- package/dist/esm-es5/zonos-address_11.entry.js +1 -1
- package/dist/esm-es5/zonos-cart-items_14.entry.js +1 -1
- package/dist/esm-es5/zonos-checkout.entry.js +1 -1
- package/dist/esm-es5/zonos-controller.entry.js +1 -1
- package/dist/esm-es5/zonos-country-flag.entry.js +1 -1
- package/dist/esm-es5/zonos-country-select_4.entry.js +1 -1
- package/dist/esm-es5/zonos-empty-state-payment_4.entry.js +1 -1
- package/dist/esm-es5/zonos-hello-dialog.entry.js +1 -1
- package/dist/esm-es5/zonos-hello.entry.js +1 -1
- package/dist/esm-es5/zonos-language-select_2.entry.js +1 -1
- package/dist/scripts/index.d.ts +1 -1
- package/dist/scripts/index.js +1 -1
- package/dist/scripts/loadZonos.js +1 -1
- package/dist/scripts/zonos.js +1 -1
- package/dist/types/components/utils/getNextFallbackApi.d.ts +2 -2
- package/dist/zonos-elements/index.esm.js +1 -1
- package/dist/zonos-elements/{p-c1d86f32.system.js → p-062430f9.system.js} +1 -1
- package/dist/zonos-elements/{p-0e8bdf5c.js → p-0631d2b9.js} +1 -1
- package/dist/zonos-elements/{p-608f965f.system.js → p-0a6ac265.system.js} +1 -1
- package/dist/zonos-elements/p-0e28207a.js +1 -0
- package/dist/zonos-elements/{p-1efc348b.system.js → p-0ed63ce0.system.js} +1 -1
- package/dist/zonos-elements/{p-164ba7ae.system.entry.js → p-0f041dc5.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-37aa481c.system.entry.js → p-1432a217.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-a91024b6.system.entry.js → p-1b51b738.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-7c88d2ac.entry.js → p-3b8d11dd.entry.js} +1 -1
- package/dist/zonos-elements/{p-680149ed.entry.js → p-4333afcb.entry.js} +1 -1
- package/dist/zonos-elements/{p-f7300f5b.system.entry.js → p-4d0d89da.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-242dd7ca.system.entry.js → p-5dd9cb44.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-b83b382e.system.js → p-674981ad.system.js} +1 -1
- package/dist/zonos-elements/p-6d090b53.entry.js +1 -0
- package/dist/zonos-elements/{p-57f391e6.system.entry.js → p-73c8c551.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-0a7ef032.entry.js → p-795d223d.entry.js} +1 -1
- package/dist/zonos-elements/p-81b357f7.system.js +1 -1
- package/dist/zonos-elements/{p-a9d41e7c.system.entry.js → p-8218ff62.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-f54123b5.entry.js → p-82f80c8a.entry.js} +1 -1
- package/dist/zonos-elements/{p-65c68531.js → p-88f7256d.js} +1 -1
- package/dist/zonos-elements/{p-e11c61a5.entry.js → p-8b083884.entry.js} +1 -1
- package/dist/zonos-elements/{p-ef34e1ce.entry.js → p-a449940d.entry.js} +1 -1
- package/dist/zonos-elements/{p-58b3a0fc.entry.js → p-a5a4ad2f.entry.js} +1 -1
- package/dist/zonos-elements/{p-e1a7a85f.system.entry.js → p-a5d45585.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-9ddb4533.system.entry.js → p-a751e819.system.entry.js} +1 -1
- package/dist/zonos-elements/{p-d93ecc57.js → p-a8a312b2.js} +1 -1
- package/dist/zonos-elements/{p-dcedcdda.entry.js → p-b4792af0.entry.js} +1 -1
- package/dist/zonos-elements/{p-6d44f441.system.js → p-d3dbae8c.system.js} +1 -1
- package/dist/zonos-elements/{p-e17ac0d1.system.js → p-ebb9b902.system.js} +1 -1
- package/dist/zonos-elements/{p-afa4b4f0.js → p-ef75da6f.js} +1 -1
- package/dist/zonos-elements/{p-4cd33d08.entry.js → p-f3dbe934.entry.js} +1 -1
- package/dist/zonos-elements/{p-300e0d47.system.entry.js → p-f741407e.system.entry.js} +1 -1
- package/dist/zonos-elements/zonos-elements.esm.js +1 -1
- package/package.json +1 -1
- package/dist/zonos-elements/p-425096c9.js +0 -1
- package/dist/zonos-elements/p-ad8b1fe8.entry.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var __awaiter=this&&this.__awaiter||function(e,t,r,o){function n(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,i){function a(e){try{d(o.next(e))}catch(e){i(e)}}function s(e){try{d(o["throw"](e))}catch(e){i(e)}}function d(e){e.done?r(e.value):n(e.value).then(a,s)}d((o=o.apply(e,t||[])).next())}))};var __generator=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},o,n,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(e){return function(t){return d([e,t])}}function d(s){if(o)throw new TypeError("Generator is already executing.");while(a&&(a=0,s[0]&&(r=0)),r)try{if(o=1,n&&(i=s[0]&2?n["return"]:s[0]?n["throw"]||((i=n["return"])&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;if(n=0,i)s=[s[0]&2,i.value];switch(s[0]){case 0:case 1:i=s;break;case 4:r.label++;return{value:s[1],done:false};case 5:r.label++;n=s[1];s=[0];continue;case 7:s=r.ops.pop();r.trys.pop();continue;default:if(!(i=r.trys,i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){r.label=s[1];break}if(s[0]===6&&r.label<i[1]){r.label=i[1];i=s;break}if(i&&r.label<i[2]){r.label=i[2];r.ops.push(s);break}if(i[2])r.ops.pop();r.trys.pop();continue}s=t.call(e,r)}catch(e){s=[6,e];n=0}finally{o=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++){if(i||!(o in t)){if(!i)i=Array.prototype.slice.call(t,0,o);i[o]=t[o]}}return e.concat(i||Array.prototype.slice.call(t))};import{z as zonosStore,c as createStore}from"./zonosStore-c456b933.js";import{s as storageStore,l as localizationStore,t as translate,f as filterValidTests,b as storageStoreSetEnabledVariantTestKeys}from"./localization-9db8b6e9.js";import{l as log,f as fallbackApiList,h as handleFetch,g as getIsTestMode,a as getIsStagingMode,s as sendErrorLog,d as allLogs,b as logError,j as jsonParse}from"./handleFetch-fa90f7f6.js";import{i as isDarkColor}from"./isDarkColor-1f58b6be.js";import{g as getBorderRadius}from"./getBorderRadius-87593ff4.js";var extractName=function(e){var t=e.firstName,r=e.lastName,o=e.name;var n;if(!o&&!t&&!r){return{firstName:"",lastName:""}}var i=(o===null||o===void 0?void 0:o.split(/\s+/))||[];var a=(t===null||t===void 0?void 0:t.trim())||((n=i[0])===null||n===void 0?void 0:n.trim())||"";var s=(r===null||r===void 0?void 0:r.trim())||i.slice(1).join(" ").trim()||"";return{firstName:a,lastName:s}};var getTranslatedAddress=function(e){var t=e.currentAddress,r=e.translatedAddress;var o,n,i,a,s,d;var c=t.value.address,l=c.city,u=c.country,v=c.line1,S=c.line2,p=c.postal_code,f=c.state;var h=t.value.name||[t.value.firstName,t.value.lastName].join(" ");return{city:((o=r.city)===null||o===void 0?void 0:o[l])||l,country:u,line1:((n=r.line1)===null||n===void 0?void 0:n[v])||v,line2:((i=r.line2)===null||i===void 0?void 0:i[S||""])||S||"",name:((a=r.name)===null||a===void 0?void 0:a[h])||h,phone:t.value.phone||"",postal_code:((s=r.postal_code)===null||s===void 0?void 0:s[p])||p,state:((d=r.state)===null||d===void 0?void 0:d[f])||f}};var prepCartCalculateLandedCost=function(e){var t;var r=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";var o=stripeStore.stripeLinkEventData;var n=stripeStore.stripeAddressEventData;var i=stripeStore.stripeShippingSameAsBilling?stripeStore.stripeAddressEventData:stripeStore.stripeBillingAddressEventData;if(!n||!i){throw new Error("Missing stripe address data")}var a=getTranslatedAddress({currentAddress:n,translatedAddress:stripeStore.translatedAddress.address});var s=extractName({name:a.name}),d=s.firstName,c=s.lastName;var l=getTranslatedAddress({currentAddress:i,translatedAddress:stripeStore.translatedAddress.address});var u=extractName({name:l.name}),v=u.firstName,S=u.lastName;return{billingAddress:{addressLine1:l.line1,addressLine2:l.line2||"",city:l.city,country:l.country,postalCode:l.postal_code,state:l.state},billingContact:{firstName:v,lastName:S,phone:l.phone},cartCurrencyCode:(t=cartStore.items[0])===null||t===void 0?void 0:t.currencyCode,cartId:e,checkoutSessionId:storageStore.checkoutSessionId||"",contact:{companyName:stripeStore.companyName,email:o===null||o===void 0?void 0:o.value.email,firstName:d,lastName:c,phone:a.phone},isTest:!!r,landedCostAdjustments:cartStore.promoCode?[{amount:0,productId:null,promoCode:cartStore.promoCode,sku:null,type:"PROMO_CODE"}]:[],shipToTaxId:stripeStore.taxId,shippingAddress:{addressLine1:a.line1,addressLine2:a.line2,city:a.city,country:a.country,postalCode:a.postal_code,state:a.state}}};var prepCalculateLandedCost=function(){var e=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";var t=stripeStore.stripeLinkEventData;var r=stripeStore.stripeAddressEventData;var o=stripeStore.stripeShippingSameAsBilling?stripeStore.stripeAddressEventData:stripeStore.stripeBillingAddressEventData;log({stripeAddressData:r,stripeBillingAddressData:o},"info");if(!r||!o){throw new Error("Missing stripe address data")}var n=getTranslatedAddress({currentAddress:r,translatedAddress:stripeStore.translatedAddress.address});var i=extractName({name:n.name}),a=i.firstName,s=i.lastName;var d=getTranslatedAddress({currentAddress:o,translatedAddress:stripeStore.translatedAddress.address});var c=extractName({name:d.name}),l=c.firstName,u=c.lastName;var v=cartStore.adjustments.map((function(e){return{amount:e.amount,name:e.description||null,productId:e.productId,sku:e.sku,type:e.type}}));var S=cartStore.promoCode?__spreadArray([{amount:0,productId:null,promoCode:cartStore.promoCode,sku:null,type:"PROMO_CODE"}],v,true):v;return{billingAddress:{addressLine1:d.line1,addressLine2:d.line2||"",city:d.city,country:d.country,postalCode:d.postal_code,state:d.state},billingContact:{firstName:l,lastName:u,phone:d.phone},checkoutSessionId:storageStore.checkoutSessionId||"",contact:{companyName:stripeStore.companyName,email:t===null||t===void 0?void 0:t.value.email,firstName:a,lastName:s,phone:n.phone},isTest:e,items:cartStore.items,landedCostAdjustments:S,shipToTaxId:stripeStore.taxId,shippingAddress:{addressLine1:n.line1,addressLine2:n.line2,city:n.city,country:n.country,postalCode:n.postal_code,state:n.state}}};var triggerBuildLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s,d,c,l;return __generator(this,(function(u){switch(u.label){case 0:a=prepCalculateLandedCost();return[4,e({billingAddress:a.billingAddress,billingContact:a.billingContact,checkoutSessionId:a.checkoutSessionId,contact:a.contact,landedCostAdjustments:a.landedCostAdjustments,publicCredential:window.Zonos.zonosApiKey||"",shippingAddress:a.shippingAddress,zonosApiRoute:fallbackApiList["vercel"]})];case 1:s=u.sent();if(!s||!((t=s.checkoutSessionWorkflow)===null||t===void 0?void 0:t.length)&&((r=s.errors)===null||r===void 0?void 0:r.length)){throw new Error("Failed to build landed cost: ".concat(((n=(o=s===null||s===void 0?void 0:s.errors)===null||o===void 0?void 0:o[0])===null||n===void 0?void 0:n.message)||"Unknown error"))}return[4,handleFetch("/api/zonos-elements/validate-landed-cost",{body:s,headers:{"Content-Type":"application/json"},method:"POST"})];case 2:d=u.sent(),c=d.errors,l=d.json;if(!l||c.length){throw new Error("Invalid landed cost object: ".concat(((i=c.find(Boolean))===null||i===void 0?void 0:i.message)||"Unknown error"))}return[2,s]}}))}))};var calculateLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s;return __generator(this,(function(d){switch(d.label){case 0:r=zonosStore.checkoutSettings.buildLandedCost;if(!r)return[3,2];return[4,triggerBuildLandedCost(r)];case 1:o=d.sent();return[2,o];case 2:return[4,handleFetch("/api/zonos-elements/calculate-landed-cost",{body:prepCalculateLandedCost(),method:"POST",signal:e===null||e===void 0?void 0:e.signal})];case 3:n=d.sent(),i=n.errors,a=n.json;if(i.length||!a){s=((t=i[0])===null||t===void 0?void 0:t.message)==="The user aborted a request.";if(s){throw new Error("The landed cost calculation request was aborted to initiate a new one.")}i.forEach((function(e){console.warn("Error calculating landed cost: ".concat(e.message))}));if(!a){throw new Error("Failed to calculate landed cost")}return[2,a]}return[2,a]}}))}))};var cartCalculateLandedCost=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c,l;var u=e.abortController,v=e.cartId;return __generator(this,(function(e){switch(e.label){case 0:return[4,handleFetch("/api/zonos-elements/cart-calculate-landed-cost",{body:prepCartCalculateLandedCost(v),method:"POST",signal:u===null||u===void 0?void 0:u.signal})];case 1:a=e.sent(),s=a.errors,d=a.json;if(s.length||!d){c=typeof((t=s[0])===null||t===void 0?void 0:t.message)==="string"&&(((r=s[0])===null||r===void 0?void 0:r.message)==="The user aborted a request."||((o=s[0])===null||o===void 0?void 0:o.message.includes("signal is aborted"))||((n=s[0])===null||n===void 0?void 0:n.message.includes("The operation was aborted"))||((i=s[0])===null||i===void 0?void 0:i.message.includes("Fetch is aborted")));l=c?"The landed cost calculation request was aborted to initiate a new one.":"Failed to calculate landed cost";throw new Error(l)}return[2,d]}}))}))};var __rest=undefined&&undefined.__rest||function(e,t){var r={};for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0)r[o]=e[o];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var n=0,o=Object.getOwnPropertySymbols(e);n<o.length;n++){if(t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n]))r[o[n]]=e[o[n]]}return r};var calculateLandedCostNormalized=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i;return __generator(this,(function(a){switch(a.label){case 0:t=window.Zonos.cartId;if(!!t)return[3,2];return[4,calculateLandedCost(e)];case 1:r=a.sent();return[2,r];case 2:return[4,cartCalculateLandedCost({abortController:e,cartId:t})];case 3:o=a.sent(),n=o.cartWorkflow,i=__rest(o,["cartWorkflow"]);return[2,Object.assign(Object.assign({},i),{itemCreateWorkflow:n.items})]}}))}))};var trackConversionEvent=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c;var l=e.checkoutSessionId,u=e.eventName,v=e.metadata;return __generator(this,(function(e){switch(e.label){case 0:o=Date.now();n=__spreadArray([],window.Zonos.trackEventLogs,true);window.Zonos.trackEventLogs.push({checkoutSessionId:l,eventCreated:o,eventName:u});i=window.location.href.includes("zonos.com")&&!window.location.href.includes("checkout.zonos.com")||!!((t=window.Zonos)===null||t===void 0?void 0:t.zonosQaUrl)||!!((r=window.Zonos)===null||r===void 0?void 0:r.debug);a=getIsTestMode()||getIsStagingMode();if((a||i)&&!window.Zonos.zonosConversionTest){return[2]}s=localizationStore.selectedCountryCode;d=zonosStore.organizationId;if(!l){void sendErrorLog({endpoint:"trackConversionEventMetric",errors:['Event "'.concat(u,'" - No checkout session id found')],metadata:{allLogs:allLogs,checkoutSessionId:l,eventName:u,metadata:v,organizationId:d,trackEventLogs:n}});return[2]}if(!d){void sendErrorLog({endpoint:"trackConversionEventMetric",errors:['Event "'.concat(u,'" - No organization id found')],metadata:{allLogs:allLogs,checkoutSessionId:l,eventName:u,metadata:v,organizationId:d,trackEventLogs:n}})}c={checkoutSessionId:l,countryCode:s,eventCreated:o,eventName:u,metadata:Object.assign(Object.assign({},v),{trackEventLogs:n}),organizationId:d};return[4,handleFetch("/api/zonos-elements/track-conversion-event",{body:c,method:"POST"})];case 1:e.sent();return[2]}}))}))};var getExcludeAddressFieldsObject=function(e){var t=e.address,r=e.invalidAdddressList;if(!t){return}if(!r){return}var o={};if(r.city){o.city=t.city}if(r.line1){o.line1=t.line1}if(r.line2){o.line2=t.line2}if(r.postal_code){o.postal_code=t.postal_code}if(r.state){o.state=t.state}if(r.name){o.name=t.name}return Object.keys(o).length?o:undefined};var buildTranslateRequest=function(e){var t=e.addressInvalidCharactersList,r=e.billingAddressInvalidCharactersList,o=e.stripeAddressEventData,n=e.stripeBillingAddressEventData,i=e.stripeShippingSameAsBilling;var a=!!(o===null||o===void 0?void 0:o.complete);var s=i?a:!!(n===null||n===void 0?void 0:n.complete);if(!a||!s){return null}if(!t&&!r){return null}var d=o.value;var c=(n===null||n===void 0?void 0:n.value)||null;var l=extractName({firstName:d.firstName,lastName:d.lastName,name:d.name}),u=l.firstName,v=l.lastName;var S="".concat(u," ").concat(v);var p=extractName({firstName:c===null||c===void 0?void 0:c.firstName,lastName:c===null||c===void 0?void 0:c.lastName,name:(c===null||c===void 0?void 0:c.name)||""}),f=p.firstName,h=p.lastName;var m=f&&h?"".concat(f," ").concat(h):"";var g=d.address;var y=c===null||c===void 0?void 0:c.address;return{address:getExcludeAddressFieldsObject({address:Object.assign(Object.assign({},g),{name:S}),invalidAdddressList:t}),billingAddress:!i?getExcludeAddressFieldsObject({address:y?Object.assign(Object.assign({},y),{name:m}):null,invalidAdddressList:r}):undefined,destinationCountry:g.country}};var sortServiceLevelOptionsByAmount=function(e){var t=e.sort((function(e,t){return e.amount-t.amount}));return t};var getCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:if(!storageStore.checkoutSessionId){return[2,{errors:[{message:"No checkout session id found"}],json:null}]}e=new URLSearchParams;e.set("checkoutSessionId",storageStore.checkoutSessionId);return[4,handleFetch("/api/zonos-elements/get-checkout-session?".concat(e.toString()))];case 1:t=n.sent(),r=t.errors,o=t.json;return[2,{errors:r,json:o}]}}))}))};var validateCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:return[4,getCheckoutSession()];case 1:t=n.sent(),r=t.errors,o=t.json;if(r.length||!o){logError("Failed to retrieve checkout session info before confirming payment ",r);void sendErrorLog({endpoint:"validateCheckoutSession",errors:r.map((function(e){return e.message})),metadata:{allLogs:allLogs}});return[2,{errorMessage:translate("Unable to retrieve the checkout session at the moment. Please try again or contact our support team."),valid:false}]}if(!((e=o.checkoutSession.landedCost)===null||e===void 0?void 0:e.id)){logError("Landed cost is not found in the checkout session before confirming payment.");void sendErrorLog({endpoint:"validateCheckoutSession",errors:["No landed cost found before confirming payment"],metadata:{allLogs:allLogs}});return[2,{errorMessage:translate('No shipment rating selected. Please go back to the "Shipping" step and select a shipment rating to proceed.'),valid:false}]}return[2,{errorMessage:"",valid:true}]}}))}))};var addressRuleStyle=function(e){var t=e.theme;var r={".AccordionItem":{color:"var(--colorText)"},".AccordionItem--selected":{color:"var(--colorText)"},".Action":{color:"var(--colorText)"},".Input":{boxShadow:"none",fontSize:zonosStore.appearance.fontSizeInputValue?"".concat(zonosStore.appearance.fontSizeInputValue,"px"):undefined,padding:"0",paddingBottom:"8px",paddingLeft:"16px",paddingRight:"8px",paddingTop:"6px"},".Label--resting":{fontSize:zonosStore.appearance.fontSizeInputLabel?"".concat(zonosStore.appearance.fontSizeInputLabel,"px"):undefined},".PickerItem--highlight":{boxShadow:"0 0 0 2px var(--colorBackground)"},".PickerItem--highlight:hover":{backgroundColor:"var(--colorBackground)",boxShadow:"none"},".PickerItem--new":{color:"var(--colorText)"},".Tab--selected":{borderStyle:"solid",borderWidth:"1px"}};switch(t){case"DARK":{return Object.assign(Object.assign({},r),{".Action":Object.assign(Object.assign({},r[".Action"]),{color:"white"}),".PickerItem--new":Object.assign(Object.assign({},r[".PickerItem--new"]),{color:"white"})})}default:return r}};var defaultVariable=function(e){var t=e.borderStyle,r=e.theme;switch(r){case"DARK":return{borderRadius:getBorderRadius({overrideBorderStyle:t}),colorBackground:"#101117",colorBackgroundText:"#C5C6CA",colorText:"#C5C6CA",colorTextPlaceholder:"#C5C6CA"};default:return{borderRadius:getBorderRadius({overrideBorderStyle:t}),iconMenuColor:"var(--colorText)",iconMenuHoverColor:"var(--colorText)"}}};var _m=createStore((function(){return{checkoutSettlementCurrency:"USD",clientSecret:sessionStorage.getItem("zonos--client-secret")||"",companyName:"",companyNameUsedWhenAsyncAddressUpdate:"",customAddressErrors:{city:"",firstName:"",lastName:"",line1:"",phone:"",postalCode:"",showError:false,state:""},customBillingAddressErrors:{city:"",firstName:"",lastName:"",line1:"",phone:"",postalCode:"",showError:false,state:""},customErrorMessage:null,customerProfile:null,fetchingLandedCostAbortController:null,hasPaymentError:false,isFetchingLandedCost:false,isFetchingSession:false,partyBillingId:null,partyShippingId:null,shouldInventoryRefund:false,shouldRenderPayInUsdButton:false,skipPaymentIntent:new URLSearchParams(window.location.search).get("skipPaymentIntent")==="0"?false:true,stripe:null,stripeAddressElement:null,stripeAddressEventData:null,stripeAddressUsedWhenAsyncAddressUpdate:null,stripeAddressUsedWhenFetchingLC:null,stripeAddressUsedWhenValidatingAddress:null,stripeBillingAddressElement:null,stripeBillingAddressEventData:null,stripeBillingAddressUsedWhenAsyncAddressUpdate:null,stripeBillingAddressUsedWhenFetchingLC:null,stripeBillingAddressUsedWhenValidatingAddress:null,stripeCustomerSessionClientSecret:null,stripeElements:null,stripeElementsForBillingAddress:null,stripeElementsOptions:null,stripeLinkElement:null,stripeLinkEventData:null,stripeLinkUsedWhenFetchingLC:null,stripePaymentElement:null,stripePaymentEventData:null,stripeShippingSameAsBilling:true,taxId:"",taxIdUsedWhenAsyncAddressUpdate:"",translatedAddress:{address:{},billingAddress:{},firstName:{},lastName:{},name:{}}}})),stripeStoreOnChange=_m.onChange,reset$1=_m.reset,stripeStore=_m.state;var getStripeOptions=function(e){var t=e.clientSecret,r=e.overrideBorderRadius,o=e.overridePrimaryColor,n=e.overrideSecondaryColor,i=e.overrideTheme,a=e.paypalEnabled;var s=o||zonosStore.appearance.colorPrimary;var d=n||zonosStore.appearance.colorSecondary;var c=s&&isDarkColor(s)?"night":"flat";var l=i==="DARK"?"night":"flat";var u=a?["external_paypal"]:[];return{appearance:{labels:"floating",rules:Object.assign({},addressRuleStyle({theme:i||"LIGHT"})),theme:i?l:c,variables:Object.assign(Object.assign({},defaultVariable({borderStyle:r,theme:"LIGHT"})),{colorPrimary:d})},clientSecret:t||undefined,customerSessionClientSecret:stripeStore.stripeCustomerSessionClientSecret||undefined,externalPaymentMethodTypes:__spreadArray([],u,true),locale:localizationStore.selectedLocale}};var stripeStoreCleanupDomesticShippingSession=function(){window.sessionStorage.removeItem("zonos--bigcommerce-domestic-checkout-shipping")};var stripeStoreSaveDomesticShippingSession=function(e){window.sessionStorage.setItem("zonos--bigcommerce-domestic-checkout-shipping",JSON.stringify(e))};var stripeStoreGetDomesticShippingSession=function(){var e=window.sessionStorage.getItem("zonos--bigcommerce-domestic-checkout-shipping");return jsonParse(e)};var initStripeElements=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i;return __generator(this,(function(a){o=stripeStore.clientSecret;if(!stripeStore.stripe){log("Skip. Stripe is not initialized");return[2]}n=getStripeOptions({clientSecret:o,overrideBorderRadius:e===null||e===void 0?void 0:e.overrideBorderRadius,overridePrimaryColor:e===null||e===void 0?void 0:e.overridePrimaryColor,overrideSecondaryColor:e===null||e===void 0?void 0:e.overrideSecondaryColor,overrideTheme:e===null||e===void 0?void 0:e.overrideTheme,paypalEnabled:e===null||e===void 0?void 0:e.paypalEnabled});i=JSON.stringify(n)===JSON.stringify(stripeStore.stripeElementsOptions);if(!stripeStore.stripeElements||!stripeStore.stripeElementsForBillingAddress){stripeStore.stripeElements=(t=stripeStore.stripe)===null||t===void 0?void 0:t.elements(n);stripeStore.stripeElementsOptions=n;log("Stripe elements initialized");stripeStore.stripeElementsForBillingAddress=(r=stripeStore.stripe)===null||r===void 0?void 0:r.elements(n);log("Stripe elements for billing address initialized");return[2]}if(!i){stripeStore.stripeElements.update(n);stripeStore.stripeElementsForBillingAddress.update(n);stripeStore.stripeElementsOptions=n;void stripeStore.stripeElements.fetchUpdates()}log("Stripe elements updated");return[2]}))}))};var stripeStoreReset=function(){sessionStorage.removeItem("zonos--client-secret");reset$1();stripeStore.stripe=window.Zonos.stripe};var checkIsAddressOutdatedForValidation=function(){var e,t,r,o;var n=JSON.stringify((e=stripeStore.stripeAddressUsedWhenValidatingAddress)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.value);var i=!stripeStore.stripeShippingSameAsBilling&&JSON.stringify((r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.value)!==JSON.stringify((o=stripeStore.stripeBillingAddressUsedWhenValidatingAddress)===null||o===void 0?void 0:o.value);return n||i};var checkIsAddressOutdatedForAsyncAddressUpdate=function(){var e,t,r,o,n,i;var a=JSON.stringify((e=stripeStore.stripeLinkUsedWhenFetchingLC)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeLinkEventData)===null||t===void 0?void 0:t.value);var s=JSON.stringify((r=stripeStore.stripeAddressUsedWhenAsyncAddressUpdate)===null||r===void 0?void 0:r.value)!==JSON.stringify((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value);var d=!stripeStore.stripeShippingSameAsBilling&&JSON.stringify((n=stripeStore.stripeBillingAddressUsedWhenAsyncAddressUpdate)===null||n===void 0?void 0:n.value)!==JSON.stringify((i=stripeStore.stripeBillingAddressEventData)===null||i===void 0?void 0:i.value);var c=stripeStore.taxIdUsedWhenAsyncAddressUpdate!==stripeStore.taxId;var l=stripeStore.companyNameUsedWhenAsyncAddressUpdate!==stripeStore.companyName;return a||s||d||c||l};var buildAddressForPartyCreate=function(e){var t=e.address,r=e.firstName,o=e.lastName,n=e.name,i=e.phone;var a=extractName({firstName:r,lastName:o,name:n}),s=a.firstName,d=a.lastName;if(!s||!d){void sendErrorLog({endpoint:"PARTY_CREATE_NO_NAME_FOUND",errors:["No name found"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,firstName:r,lastName:o,name:n}})}if(!i){void sendErrorLog({endpoint:"PARTY_CREATE_NO_PHONE_FOUND",errors:["No phone found"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,phone:i}})}return{city:t.city,country:t.country,firstName:s,lastName:d,line1:t.line1,line2:t.line2,phone:i||"",postal_code:t.postal_code,state:t.state}};var stripeStoreAsyncAddressUpdate=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l,u;return __generator(this,(function(v){switch(v.label){case 0:if(!((e=stripeStore.stripeAddressEventData)===null||e===void 0?void 0:e.complete)||!stripeStore.stripeShippingSameAsBilling&&!((t=stripeStore.stripeBillingAddressEventData)===null||t===void 0?void 0:t.complete)||!stripeStore.stripeBillingAddressEventData){return[2,{partiesCreated:false}]}if(!cartStore.landedCostData){return[2,{partiesCreated:false}]}n=(r=cartStore.landedCostData.find(Boolean))===null||r===void 0?void 0:r.landedCost.rootId;if(!n){void sendErrorLog({endpoint:"PF_NO_SELECTED_LANDED_COST",errors:["No selected landed cost"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId}});return[2,{partiesCreated:false}]}i=checkIsAddressOutdatedForAsyncAddressUpdate();if(!i){return[2,{partiesCreated:false}]}a=buildAddressForPartyCreate({address:stripeStore.stripeAddressEventData.value.address,firstName:stripeStore.stripeAddressEventData.value.firstName,lastName:stripeStore.stripeAddressEventData.value.lastName,name:stripeStore.stripeAddressEventData.value.name,phone:stripeStore.stripeAddressEventData.value.phone});s=stripeStore.stripeShippingSameAsBilling?a:buildAddressForPartyCreate({address:stripeStore.stripeBillingAddressEventData.value.address,firstName:stripeStore.stripeBillingAddressEventData.value.firstName,lastName:stripeStore.stripeBillingAddressEventData.value.lastName,name:stripeStore.stripeBillingAddressEventData.value.name,phone:stripeStore.stripeBillingAddressEventData.value.phone});d=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";return[4,handleFetch("/api/zonos-elements/create-parties",{body:{address:a,billingAddress:s,companyName:stripeStore.companyName,email:((o=stripeStore.stripeLinkEventData)===null||o===void 0?void 0:o.value.email)||"",isTest:d,rootId:n,taxId:stripeStore.taxId},method:"POST"})];case 1:c=v.sent(),l=c.errors,u=c.json;if(l.length||!u){logError("Error occurs when creating parties",JSON.stringify(l,null,2));void sendErrorLog({endpoint:"PF_PARTY_CREATE_FAILED",errors:["Failed to create parties"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,errors:l,json:u}});return[2,{partiesCreated:false}]}stripeStore.companyNameUsedWhenAsyncAddressUpdate=stripeStore.companyName;stripeStore.stripeAddressUsedWhenAsyncAddressUpdate=stripeStore.stripeAddressEventData;stripeStore.stripeBillingAddressUsedWhenAsyncAddressUpdate=stripeStore.stripeBillingAddressEventData;stripeStore.taxIdUsedWhenAsyncAddressUpdate=stripeStore.taxId;stripeStore.partyBillingId=u.billToPartyId;stripeStore.partyShippingId=u.shipToPartyId;return[2,{partiesCreated:true}]}}))}))};var buildAddressForLCPrefetch=function(e){return{countryCode:e.address.country,postalCode:e.address.postal_code,state:e.address.state}};var checkIsAddressOutdatedForLCPrefetch=function(){var e,t;var r=JSON.stringify((e=stripeStore.stripeLinkUsedWhenFetchingLC)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeLinkEventData)===null||t===void 0?void 0:t.value);var o=stripeStore.stripeAddressEventData&&JSON.stringify(buildAddressForLCPrefetch(stripeStore.stripeAddressEventData.value))!==JSON.stringify(stripeStore.stripeAddressUsedWhenFetchingLC);var n=!stripeStore.stripeShippingSameAsBilling&&stripeStore.stripeBillingAddressEventData&&JSON.stringify(buildAddressForLCPrefetch(stripeStore.stripeBillingAddressEventData.value))!==JSON.stringify(stripeStore.stripeBillingAddressUsedWhenFetchingLC);return r||o||n};var isPrefetchInfoOutdated=function(){var e;var t=cartStore.landedCostData&&((e=cartStore.landedCostData.find(Boolean))===null||e===void 0?void 0:e.subtotals.items)!==cartStore.subtotal;var r=checkIsAddressOutdatedForLCPrefetch();log("isPrefetchInfoOutdated","info",{isAddressOutdated:r});return!cartStore.landedCostData&&!stripeStore.isFetchingLandedCost||r||t};var getCountryField=function(e){var t,r;var o=(t=zonosStore.genericSettings)===null||t===void 0?void 0:t.countryFields;var n=(r=zonosStore.genericSettings)===null||r===void 0?void 0:r.stripeCountryFieldLabels;var i=n&&e in n?n[e]:null;var a=o&&e in o?o[e]:null;if(cartStore.addressFormRenderType==="stripe"){return i||a}return a};var isAddressReadyToRequestLandedCost=function(){var e,t,r,o;var n=!!((e=stripeStore.stripeLinkEventData)===null||e===void 0?void 0:e.complete);var i=!!((t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.complete);var a=stripeStore.stripeShippingSameAsBilling?i:!!((r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.complete);var s=((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.address.country)||"US";var d=getCountryField(s);if(i&&a&&n){return true}if(!d||!stripeStore.stripeAddressEventData){return i&&a&&n}var c=stripeStore.stripeAddressEventData.value.address.line1.length>0;var l=stripeStore.stripeAddressEventData.value.firstName&&stripeStore.stripeAddressEventData.value.lastName;var u=!d.stateRequired||d.stateRequired&&stripeStore.stripeAddressEventData.value.address.state.length>0;var v=!d.zipRequired||d.zipRequired&&stripeStore.stripeAddressEventData.value.address.postal_code.length>=3;var S=stripeStore.stripeAddressEventData.value.phone&&stripeStore.stripeAddressEventData.value.phone.length>0;return n&&l&&c&&u&&v&&S};var stripeCalculateLandedCost=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l;return __generator(this,(function(u){switch(u.label){case 0:t=new AbortController;stripeStore.fetchingLandedCostAbortController=t;cartStoreResetCartItems();return[4,calculateLandedCostNormalized(t)];case 1:r=u.sent(),o=r.checkoutSessionWorkflow,n=r.errors,i=r.itemCreateWorkflow,a=r.landedCostCalculateWorkflow,s=r.partyCreateWorkflow,d=r.shipmentRatingCalculateWorkflow;cartStore.customQuotingError=((e=n===null||n===void 0?void 0:n.find((function(e){var t;return((t=e.extensions)===null||t===void 0?void 0:t.ruleMessageType)==="CUSTOM"})))===null||e===void 0?void 0:e.message)||null;cartStore.shippingData=sortServiceLevelOptionsByAmount((d===null||d===void 0?void 0:d.filter(Boolean))||[]);cartStoreCheckItemRestrictions(i);stripeStore.fetchingLandedCostAbortController=null;cartStore.partiesData=(s===null||s===void 0?void 0:s.filter(Boolean))||[];cartStore.landedCostData=(o===null||o===void 0?void 0:o.map((function(e){var t=a===null||a===void 0?void 0:a.find((function(t){return(t===null||t===void 0?void 0:t.id)===e.landedCostId}));if(!t){return null}return Object.assign(Object.assign({},e),{landedCost:t})})).filter(Boolean))||[];c=storageStore.checkoutSessionId;if(o===null||o===void 0?void 0:o.length){void trackConversionEvent({checkoutSessionId:c,eventName:"checkout_quoteReceived"})}l=cartStore.promoCodeApplied&&!cartStore.landedCostData.find((function(e){var t;return(t=e.landedCost.appliedAdjustments)===null||t===void 0?void 0:t.find((function(e){return e.type==="PROMO_CODE"}))}));cartStore.promoCodeError=l;if(!l){sessionStorage.setItem("zonos--promo-code",cartStore.promoCode)}return[2]}}))}))};var stripeStorePrefetchLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s,d,c,l,u,v,S,p;return __generator(this,(function(f){switch(f.label){case 0:i=(e===null||e===void 0?void 0:e.retries)||0;a=!!(e===null||e===void 0?void 0:e.applyingPromocode);s=isPrefetchInfoOutdated();d=isAddressReadyToRequestLandedCost();if(!d){return[2,{isRequestNotReady:true}]}if(s){(t=stripeStore.fetchingLandedCostAbortController)===null||t===void 0?void 0:t.abort();stripeStore.fetchingLandedCostAbortController=null}if(!s&&!a){return[2,{isRequestNotReady:false}]}if(i){stripeStore.isFetchingLandedCost=false;setTimeout((function(){stripeStore.isFetchingLandedCost=true}),300)}else{stripeStore.isFetchingLandedCost=true}if(stripeStore.stripeAddressEventData){stripeStore.stripeAddressUsedWhenFetchingLC={countryCode:stripeStore.stripeAddressEventData.value.address.country,postalCode:stripeStore.stripeAddressEventData.value.address.postal_code,state:stripeStore.stripeAddressEventData.value.address.state}}if(stripeStore.stripeBillingAddressEventData){stripeStore.stripeBillingAddressUsedWhenFetchingLC={countryCode:stripeStore.stripeBillingAddressEventData.value.address.country,postalCode:stripeStore.stripeBillingAddressEventData.value.address.postal_code,state:stripeStore.stripeBillingAddressEventData.value.address.state}}if(stripeStore.stripeLinkEventData){stripeStore.stripeLinkUsedWhenFetchingLC=Object.assign({},stripeStore.stripeLinkEventData)}f.label=1;case 1:f.trys.push([1,3,,7]);cartStoreResetCartItems();return[4,stripeCalculateLandedCost()];case 2:f.sent();c=(r=cartStore.shippingData)===null||r===void 0?void 0:r.find(Boolean);l=(o=cartStore.landedCostData)===null||o===void 0?void 0:o.find((function(e){return e.landedCost.shipmentRating.id===(c===null||c===void 0?void 0:c.id)}));u=!!l?l.subtotals:null;if(u){cartStoreApplySubtotals({method:(l===null||l===void 0?void 0:l.landedCost.method)||"DDP",subtotals:u})}return[3,7];case 3:v=f.sent();cartStore.landedCostData=[];cartStore.shippingData=[];S=["The landed cost calculation request was aborted to initiate a new one."];if(!(v instanceof Error&&v.message&&!S.includes(v.message)))return[3,6];if(!(i<1))return[3,5];return[4,stripeStorePrefetchLandedCost(Object.assign(Object.assign({},e),{retries:(i||0)+1}))];case 4:f.sent();return[2,{isRequestNotReady:false}];case 5:p=(n=stripeStore.stripeAddressEventData)===null||n===void 0?void 0:n.value;void sendErrorLog({endpoint:"Failed to fetch landed cost (".concat(i," retries)"),errors:[v.message],metadata:{cartId:window.Zonos.cartId,shipToAddress:p}});f.label=6;case 6:logError(v);return[3,7];case 7:stripeStore.isFetchingLandedCost=false;return[2,{isRequestNotReady:false}]}}))}))};var stripeStoreApplyPromoCode=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:return[4,stripeStorePrefetchLandedCost({applyingPromocode:true})];case 1:n.sent();if(cartStore.step==="payment"){cartStorePreviousStep()}return[4,stripeStoreAsyncAddressUpdate()];case 2:n.sent();r=(e=cartStore.shippingData)===null||e===void 0?void 0:e.find(Boolean);o=(t=cartStore.landedCostData)===null||t===void 0?void 0:t.find((function(e){return e.landedCost.id===(r===null||r===void 0?void 0:r.id)}));if(!r||!o){return[2]}return[4,cartStoreUpdateSelectedShippingOption(r,o.landedCostId)];case 3:n.sent();return[2]}}))}))};var stripeStoreResetPromoCode=function(){cartStore.promoCode="";sessionStorage.removeItem("zonos--promo-code");cartStore.promoCodeError=false;cartStore.promoCodeApplied=false};var stripeStoreRemovePromoCode=function(){return __awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(e){switch(e.label){case 0:if(cartStore.step==="payment"){cartStorePreviousStep()}stripeStoreResetPromoCode();return[4,stripeStoreApplyPromoCode()];case 1:e.sent();return[2]}}))}))};var stripeStoreMessageBasedOnStatus=function(e){var t=[];var r=true;switch(e){case"succeeded":{t=[translate("Your payment went through successfully! Thank you for shopping with us! We hope you had an enjoyable experience and your support means the world to us."),"",translate("We've sent an email confirmation of the order details for your review. And our team is carefully preparing your order so it arrives on time.")];r=false;break}case"requires_capture":case"processing":{t=[translate("Payment processing. We'll update you when payment is received.")];r=false;break}case"requires_payment_method":{t=[translate("Payment failed. Please try another payment method.")];break}case"requires_action":{r=false;t=[translate("Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.")]}default:{t=[translate("Something went wrong.")];break}}return{isError:r,messages:t}};var stripeStoreHandleInventoryCheck=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,s;return __generator(this,(function(c){switch(c.label){case 0:r=zonosStore.checkoutSettings.onInventoryCheck;o=!!((t=(e=window.Zonos.cartData)===null||e===void 0?void 0:e.metadata.find((function(e){return e.key==="referenceId"})))===null||t===void 0?void 0:t.value);if(!(window.Zonos.isLegacyCheckout&&window.Zonos.cartData&&o))return[3,2];return[4,handleFetch("/api/zonos-elements/legacy/inventory-check",{body:{cartData:window.Zonos.cartData},method:"POST"})];case 1:n=c.sent(),i=n.errors,a=n.json;if(i.length||!a){logError("Error occurs when handling inventory refund","warn",JSON.stringify(i));return[2,null]}if(!a.available||a.status===204){return[2,translate("The item you're looking for is currently unavailable in our inventory. Please check back later or contact support for assistance with availability.")]}if(a.available||a.status===200){stripeStore.shouldInventoryRefund=true;return[2,null]}return[2,null];case 2:if(typeof r!=="function"){return[2,null]}c.label=3;case 3:c.trys.push([3,5,,6]);return[4,r({items:cartStore.items})];case 4:s=c.sent();return[2,s];case 5:d=c.sent();s=d instanceof Error?d.message:"Unknown error";void sendErrorLog({endpoint:"onInventoryCheck",errors:["cartId: ".concat(window.Zonos.cartId," - ").concat(s)],metadata:{cartId:window.Zonos.cartId,href:window.location.href,items:cartStore.items}});throw d;case 6:return[2]}}))}))};var stripeStoreHandleInventoryRefund=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r;return __generator(this,(function(o){switch(o.label){case 0:r=!!((t=(e=window.Zonos.cartData)===null||e===void 0?void 0:e.metadata.find((function(e){return e.key==="referenceId"})))===null||t===void 0?void 0:t.value);if(!window.Zonos.isLegacyCheckout||!window.Zonos.cartData||!r){return[2]}return[4,handleFetch("/api/zonos-elements/legacy/inventory-refund",{body:{cartData:window.Zonos.cartData},method:"POST"})];case 1:o.sent();return[2]}}))}))};var stripeStoreRetrievePayment=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c;var l=e.clientSecret,u=e.storybookForceStatus;return __generator(this,(function(e){switch(e.label){case 0:if(u){t=stripeStoreMessageBasedOnStatus(u),r=t.isError,o=t.messages;return[2,{error:r,messages:o}]}n=l||stripeStore.clientSecret;if(!stripeStore.stripe||!n){logError("Failed to retrieve payment intent. Stripe is not initialized");return[2,{error:true,message:[translate("Something went wrong.")]}]}return[4,stripeStore.stripe.retrievePaymentIntent(n)];case 1:i=e.sent().paymentIntent;a=i===null||i===void 0?void 0:i.status;s=stripeStoreMessageBasedOnStatus(a),d=s.isError,c=s.messages;return[2,{error:d,messages:c,paymentIntentId:i===null||i===void 0?void 0:i.id,paymentMethod:i===null||i===void 0?void 0:i.payment_method,status:a}]}}))}))};var stripeStoreConfirmPayment=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l,u;return __generator(this,(function(v){switch(v.label){case 0:r=!!((e=stripeStore.stripePaymentEventData)===null||e===void 0?void 0:e.complete);o=stripeStore.stripeElements;n=stripeStore.stripe;i=stripeStore.clientSecret;stripeStore.customErrorMessage=null;if(!((t=cartStore.selectedLandedCost)===null||t===void 0?void 0:t.landedCost.id)){throw new Error("Attempted to confirm the payment when no landed cost is found in store")}return[4,validateCheckoutSession()];case 1:a=v.sent();if(!a.valid){stripeStore.customErrorMessage=a.errorMessage;throw new Error(a.errorMessage)}s=storageStore.checkoutSessionId;if(!(n&&o&&r&&i&&s))return[3,3];d=new URL(window.location.href);d.searchParams.set("payment_intent_client_secret",i);d.searchParams.set("zonosCheckoutSessionId",s);void trackConversionEvent({checkoutSessionId:s,eventName:"checkout_paymentInfoCompleted"});return[4,n.confirmPayment({confirmParams:{return_url:d.toString()},elements:o,redirect:"if_required"})];case 2:c=v.sent(),l=c.error,u=c.paymentIntent;log("Payment intent confirmed","info",{error:l,paymentIntent:u});if((u===null||u===void 0?void 0:u.status)==="requires_action"){throw new Error(translate("Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction."))}if(l){if(l.type==="card_error"||l.type==="validation_error"){throw new Error(l.message)}if(l.type==="invalid_request_error"){if(l.code==="payment_intent_unexpected_state"){return[2]}}throw new Error("An unexpected error occurred.")}if(u.status==="requires_payment_method"){throw new Error(translate("Payment failed. Please try another payment method."))}v.label=3;case 3:return[2]}}))}))};var getCheckoutSessionBody=function(){var e;var t=cartStore.items.reduce((function(e,t){return e+t.amount*t.quantity}),0);var r=storageStore.enabledVariantTestKeys||[];var o={adjustmentsAmount:cartStore.adjustments.reduce((function(e,t){return e+t.amount}),0),cartId:window.Zonos.cartId,currency:((e=cartStore.items.find(Boolean))===null||e===void 0?void 0:e.currencyCode)||"",customerAuthenticationToken:cartStore.customerAuthenticationToken||undefined,itemsAmount:t,metadata:[{key:"language",value:localizationStore.selectedLocale}],presentmentCountryCode:localizationStore.selectedCountryCode,skipPaymentIntent:stripeStore.skipPaymentIntent,varianceTestInput:r};return o};var stripeStoreGetPaymentIntent=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n;return __generator(this,(function(i){switch(i.label){case 0:if(!storageStore.checkoutSessionId){void sendErrorLog({endpoint:"Error creating payment intent",errors:["No checkout session id found when retrieving payment intent"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId}});cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2]}return[4,handleFetch("/api/zonos-elements/create-payment-intent",{body:{checkoutSessionId:storageStore.checkoutSessionId},method:"POST"})];case 1:t=i.sent(),r=t.errors,o=t.json;n=(e=o===null||o===void 0?void 0:o.checkoutSessionPaymentIntentCreate)===null||e===void 0?void 0:e.clientSecret;if(r.length||!n){logError("Error occurs when getting payment intent",JSON.stringify(r,null,2));void sendErrorLog({endpoint:"Error creating payment intent",errors:r.map((function(e){return e.message})),metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,clientSecret:n}});cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2]}cartStoreSetCheckoutSession(o.checkoutSessionPaymentIntentCreate);return[2]}}))}))};var stripeStoreInitCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s;return __generator(this,(function(d){switch(d.label){case 0:if(!localizationStore.targetCurrency){logError("Failed to create checkout session - missing localizationStore.targetCurrency");return[2,false]}stripeStore.isFetchingSession=true;r=getCheckoutSessionBody();log("Checkout session body","info",r);return[4,handleFetch("/api/zonos-elements/create-checkout-session",{body:r,method:"POST"})];case 1:o=d.sent(),n=o.errors,i=o.json;stripeStore.isFetchingSession=false;if(n.length||!i){a=(e=n.find((function(e){return e.message})))===null||e===void 0?void 0:e.message;if(Array.isArray(a)&&a.some((function(e){return e.message==="Cart is expired."}))){throw new Error("Cart is expired.")}logError("Error occurred when creating checkout session",JSON.stringify(n,null,2));return[2,false]}s=i.checkoutSessionCreate;cartStoreSetCheckoutSession(s);cartStoreApplySubtotals({method:((t=s.landedCost)===null||t===void 0?void 0:t.method)||"DDP",subtotals:s.subtotals});log("Exchange rate updated for cart items (checkout session create)","info",cartStore.exchangeRate);log("done-init-checkout-session");return[2,true]}}))}))};var stripeStoreUpdateCheckoutSessionBaseCurrency=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r;return __generator(this,(function(o){switch(o.label){case 0:e=storageStore.checkoutSessionId;if(!e){logError("Failed to update checkout session base currency");return[2,false]}if(zonosStore.checkoutSettings.allowedSettlementCurrencies==="LOCAL"){log('allowedSettlementCurrencies: "LOCAL". Skip updating checkout session base currency');return[2,true]}return[4,handleFetch("/api/zonos-elements/update-checkout-session-base-currency",{body:{checkoutSessionId:e,currencyCode:stripeStore.checkoutSettlementCurrency},method:"POST"})];case 1:t=o.sent().json;r=t===null||t===void 0?void 0:t.checkoutSessionBaseCurrencyUpdate.subtotals.presentmentCurrencyCode;if(!t||r!==stripeStore.checkoutSettlementCurrency){logError("Failed to update checkout session base currency");return[2,false]}log('Updated checkout session to settlement currency "'.concat(r,'".'));return[2,true]}}))}))};var stripeStoreUpdateCheckoutSession=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n;var i=e.adjustmentsAmount,a=e.cartId,s=e.currency,d=e.id,c=e.itemsAmount,l=e.landedCostId,u=e.presentmentCountryCode;return __generator(this,(function(e){switch(e.label){case 0:t=storageStore.enabledVariantTestKeys||[];return[4,handleFetch("/api/zonos-elements/update-checkout-session",{body:{adjustmentsAmount:i,billToPartyId:stripeStore.partyBillingId,cartId:a,currency:s,customerAuthenticationToken:cartStore.customerAuthenticationToken||undefined,id:d,itemsAmount:c,landedCostId:l,metadata:[{key:"language",value:localizationStore.selectedLocale}],presentmentCountryCode:u,shipToPartyId:stripeStore.partyShippingId,skipPaymentIntent:stripeStore.skipPaymentIntent,varianceTestInput:t},method:"POST"})];case 1:r=e.sent(),o=r.errors,n=r.json;if(o.length||!n){logError("Error occurs when updating checkout session",JSON.stringify(o,null,2));return[2,{errors:o,json:n}]}return[2,{errors:[],json:n}]}}))}))};var buildTranslatedAddress=function(e){var t,r,o,n,i,a;var s=e.currentAddress,d=e.translatedAddressResult;var c={};if(!d){return c}var l=d.city,u=d.line1,v=d.line2,S=d.name,p=d.postal_code,f=d.state;if(s.city&&l){c.city=(t={},t[s.city]=l,t)}if(s.line1&&u){c.line1=(r={},r[s.line1]=u,r)}if(s.line2&&v){c.line2=(o={},o[s.line2]=v,o)}if(s.postal_code&&p){c.postal_code=(n={},n[s.postal_code]=p,n)}if(s.state&&f){c.state=(i={},i[s.state]=f,i)}if(s.name&&S){c.name=(a={},a[s.name]=S,a)}return c};var stripeStoreTranslateAddressToLatin=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c,l,u;var v=e.addressInvalidCharactersList,S=e.billingAddressInvalidCharactersList;return __generator(this,(function(e){switch(e.label){case 0:i=buildTranslateRequest({addressInvalidCharactersList:v,billingAddressInvalidCharactersList:S,stripeAddressEventData:stripeStore.stripeAddressEventData,stripeBillingAddressEventData:stripeStore.stripeBillingAddressEventData,stripeShippingSameAsBilling:stripeStore.stripeShippingSameAsBilling});if(!i){stripeStore.translatedAddress={address:{},billingAddress:{}};return[2]}a=checkIsAddressOutdatedForValidation();if(!a){return[2]}return[4,handleFetch("/api/zonos-elements/validate-address",{body:i,method:"POST"})];case 1:s=e.sent(),d=s.errors,c=s.json;if(d.length||!c){logError("Error occurs when translating address to latin",JSON.stringify(d,null,2));stripeStore.translatedAddress={address:{},billingAddress:{}};return[2]}stripeStore.stripeAddressUsedWhenValidatingAddress=stripeStore.stripeAddressEventData;stripeStore.stripeBillingAddressUsedWhenValidatingAddress=stripeStore.stripeBillingAddressEventData;l=(t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.value.address;u=(r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.value.address;stripeStore.translatedAddress={address:l?buildTranslatedAddress({currentAddress:Object.assign(Object.assign({},l),{name:(o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.name}),translatedAddressResult:c.address||null}):{},billingAddress:!stripeStore.stripeShippingSameAsBilling?buildTranslatedAddress({currentAddress:Object.assign(Object.assign({},u),{name:(n=stripeStore.stripeBillingAddressEventData)===null||n===void 0?void 0:n.value.name}),translatedAddressResult:c.billingAddress||null}):{}};return[2]}}))}))};stripeStoreOnChange("clientSecret",(function(e){if(e&&stripeStore.stripe){sessionStorage.setItem("zonos--client-secret",e)}if(!e){sessionStorage.removeItem("zonos--client-secret")}}));var _o=createStore((function(){return{addressFormRenderType:"stripe",adjustmentTotal:0,adjustments:[],checkoutSession:null,checkoutSessionTimeoutShow:false,checkoutTimeoutInterval:null,currency:"USD",customQuotingError:null,customerAuthenticationToken:null,displayBaseCurrency:false,dutiesTaxesFees:null,dutiesTaxesFeesEstimate:null,error:null,exchangeRate:null,externalConfirmationPageURL:null,inventoryCheckErrorMessage:null,isSelectedShippingAboveDeminimis:false,isSelectedShippingGuarantee:false,isStagingMode:getIsStagingMode(),items:[],landedCostData:null,landedCostMethod:"DDP",partiesData:[],promoCode:sessionStorage.getItem("zonos--promo-code")||"",promoCodeApplied:!!sessionStorage.getItem("zonos--promo-code"),promoCodeError:false,restrictedItems:[],selectedLandedCost:null,selectedShippingOption:null,selectedShippingOptionExpectedDate:"",selectedShippingOptionTransitTime:"",shipping:0,shippingData:null,shouldHideDiscountInput:false,step:"customer-info",subtotal:0,tabItems:{"customer-info":{index:1,isDone:false,label:"Customer",value:"customer-info"},shipping:{index:2,isDone:false,label:"Shipping",value:"shipping"},payment:{index:3,isDone:false,label:"Payment",value:"payment"}},total:0}})),cartStoreOnChange=_o.onChange,reset=_o.reset,cartStore=_o.state;var getTransitUnit=function(e){switch(e){case"DAYS":return translate("days");case"WEEKS":return translate("weeks");case"BUSINESS_DAYS":default:return translate("business days")}};var cartStoreGetShippingTransitInfo=function(e){var t;var r=(t=e.shippingProfile)===null||t===void 0?void 0:t.transitTime;if(!(r===null||r===void 0?void 0:r.min)||!(r===null||r===void 0?void 0:r.max)||!(r===null||r===void 0?void 0:r.type)){return null}return{maxTransit:r.max,minTransit:r.min,unit:getTransitUnit(r.type)}};var getMatchItem=function(e){var t=e.item1,r=e.item2;if(!t||!r){return false}return r.sku&&t.sku&&t.sku===r.sku||r.description&&t.description&&t.description===r.description||t.name&&r.name&&t.name===r.name};var cartStoreCheckItemRestrictions=function(e){log("Checking item restrictions");var t=e.map((function(e){if(!e.restriction){return null}var t=e.restriction;var r=cartStore.items.find((function(t){return getMatchItem({item1:t,item2:e})}));return Object.assign(Object.assign({matchedItem:r},e),{restriction:t})})).filter(Boolean);cartStore.restrictedItems=t;cartStore.items=cartStore.items.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:!!t.find((function(t){return getMatchItem({item1:t,item2:e})}))})}));return{cartItems:cartStore.items,restrictedItems:t}};var cartStoreReset=function(){storageStore.checkoutSessionId=null;reset()};var cartStoreUpdateToErrorState=function(e){var t=e.messages,r=e.title;cartStoreReset();stripeStoreReset();cartStore.step="error";cartStore.error={messages:t,title:r}};var cartStoreApplySubtotals=function(e){var t=e.dutiesTaxesFeesEstimate,r=e.method,o=e.subtotals;cartStore.exchangeRate=o.exchangeRate;cartStore.adjustmentTotal=o.adjustments;cartStore.dutiesTaxesFees=r==="DAP"?null:o.landedCostTotal;cartStore.subtotal=o.items;cartStore.total=o.total;cartStore.currency=o.presentmentCurrencyCode;cartStore.dutiesTaxesFeesEstimate=t||null};var cartStoreHasOneEligibleItem=function(){var e=cartStore.items.filter((function(e){return e.amount>0}));return!!e.find((function(e){return!e.isRestricted}))};var cartStoreSetCheckoutSession=function(e){var t,r,o,n,i;stripeStore.clientSecret=e.clientSecret;stripeStore.stripeCustomerSessionClientSecret=e.customerSessionClientSecret;stripeStore.customerProfile=e.customerProfile;cartStore.checkoutSession=e;if(!e.id){void sendErrorLog({endpoint:"cartStoreSetCheckoutSession",errors:["Missing checkout session id in checkout session"],metadata:{allLogs:allLogs,checkoutSession:e}})}if(e.id){storageStore.checkoutSessionId=e.id}var a=filterValidTests(e.varianceTestResults||[]);storageStoreSetEnabledVariantTestKeys(a);var s=((o=(r=(t=cartStore.checkoutSession)===null||t===void 0?void 0:t.metadata)===null||r===void 0?void 0:r.find((function(e){return(e===null||e===void 0?void 0:e.key)==="externalConfirmationPageURL"})))===null||o===void 0?void 0:o.value)||((i=(n=window.Zonos.cartData)===null||n===void 0?void 0:n.metadata.find((function(e){return(e===null||e===void 0?void 0:e.key)==="externalConfirmationPageURL"})))===null||i===void 0?void 0:i.value)||null;if(s){log("Found externalConfirmationPageURL: ".concat(s));cartStore.externalConfirmationPageURL=s}};var cartStoreReCalculateTotal=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a;var s=e.adjustmentsAmount,d=e.cartId,c=e.currency,l=e.dutiesTaxesFeesEstimate,u=e.itemsAmount,v=e.landedCostId,S=e.shouldInitSessionOnFailure;return __generator(this,(function(e){switch(e.label){case 0:if(v&&cartStore.selectedLandedCost){r=cartStore.selectedLandedCost.subtotals;cartStoreApplySubtotals({dutiesTaxesFeesEstimate:l,method:cartStore.landedCostMethod,subtotals:r});log("Exchange rate updated for cart items (landed cost subtotal)","info",cartStore.exchangeRate)}if(!storageStore.checkoutSessionId){log("Could not update cart total without checkout session id","info");return[2,false]}return[4,stripeStoreUpdateCheckoutSession({adjustmentsAmount:s,billToPartyId:stripeStore.partyBillingId,cartId:d,currency:c,id:storageStore.checkoutSessionId,itemsAmount:u,landedCostId:v,presentmentCountryCode:localizationStore.selectedCountryCode,shipToPartyId:stripeStore.partyShippingId,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:o=e.sent(),n=o.errors,i=o.json;if(!(n.length>0||!i))return[3,4];logError("Error occurs when updating checkout session.");if(!S)return[3,3];log("Initiating checkout session on failure","info");return[4,stripeStoreInitCheckoutSession()];case 2:a=e.sent();log("stripeStoreInitCheckoutSession: ".concat(a));if(!a){cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2,false]}return[2,true];case 3:return[2,false];case 4:if(!v){cartStoreApplySubtotals({method:((t=i.checkoutSessionUpdate.landedCost)===null||t===void 0?void 0:t.method)||"DDP",subtotals:i.checkoutSessionUpdate.subtotals});log("Exchange rate updated for cart items (checkout session update)","info",cartStore.exchangeRate)}cartStoreSetCheckoutSession(i.checkoutSessionUpdate);return[2,true]}}))}))};var cartStoreGetMethod=function(e){var t,r,o;if(e.method==="DAP"&&((r=(t=zonosStore.genericSettings)===null||t===void 0?void 0:t.domesticCountries)===null||r===void 0?void 0:r.includes(((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.address.country)||"US"))){return"DDP"}if(e.method==="DAP"&&e.remittance.length&&e.landedCostGuaranteeCode==="ZONOS"){return"DDP"}return e.method};var cartStoreUpdateSelectedShippingOption=function(e,t){return __awaiter(void 0,void 0,void 0,(function(){var r,o,n,i,a,s,d,c,l,u,v,S,p,f,h,m,g,y,w,C,b,A,O,_;return __generator(this,(function(k){switch(k.label){case 0:cartStore.selectedShippingOption=e;S=cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);if(S){p=S.maxTransit,f=S.minTransit,h=S.unit;cartStore.selectedShippingOptionTransitTime="".concat(f,"-").concat(p," ").concat(h)}else{cartStore.selectedShippingOptionTransitTime=""}m=(r=cartStore.landedCostData)===null||r===void 0?void 0:r.find((function(e){return e.landedCostId===t}));cartStore.selectedLandedCost=m||null;if(!m){return[2,false]}g=((o=m.landedCost.amountSubtotals)===null||o===void 0?void 0:o.landedCostTotal)||0;y=m.subtotals.exchangeRate.rate;w=g*y;if(w){log("DAP quote, using estimate: ".concat(w),"info")}cartStore.landedCostMethod=cartStoreGetMethod(m.landedCost);cartStore.shipping=m.subtotals.shipping;C=((n=m===null||m===void 0?void 0:m.landedCost)===null||n===void 0?void 0:n.landedCostGuaranteeCode)==="ZONOS";b=!!((a=(i=m===null||m===void 0?void 0:m.landedCost)===null||i===void 0?void 0:i.deMinimis)===null||a===void 0?void 0:a.find((function(e){return["DUTY","TAX"].includes(e.type)&&e.threshold==="ABOVE"})));cartStore.isSelectedShippingAboveDeminimis=b;cartStore.isSelectedShippingGuarantee=C;return[4,cartStoreReCalculateTotal({adjustmentsAmount:cartStore.adjustmentTotal,billToPartyId:stripeStore.partyBillingId,cartId:window.Zonos.cartId,dutiesTaxesFeesEstimate:w,landedCostId:(s=m.landedCost)===null||s===void 0?void 0:s.id,shipToPartyId:stripeStore.partyShippingId,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:A=k.sent();O=(d=cartStore.items.find(Boolean))===null||d===void 0?void 0:d.currencyCode;_=((c=stripeStore.stripeAddressEventData)===null||c===void 0?void 0:c.value.address.country)||"US";stripeStore.shouldRenderPayInUsdButton=O==="USD"&&zonosStore.checkoutSettings.allowedSettlementCurrencies==="LOCAL_AND_USD"&&((l=cartStore.checkoutSession)===null||l===void 0?void 0:l.subtotals.presentmentCurrencyCode)!=="USD"&&!!((v=(u=zonosStore.genericSettings)===null||u===void 0?void 0:u.usdSettlementCountryEnabled)===null||v===void 0?void 0:v.includes(_));return[2,A]}}))}))};var cartStoreStartCheckoutInterval=function(e){var t=e.isPreview,r=e.sessionTimeout;if(t){return}var o=new URLSearchParams(window.location.search).get("zonosCheckoutTimeout");var n=o&&!isNaN(parseInt(o,10))?parseInt(o,10):r;log("==START CHECKOUT TIMEOUT - ".concat(n,"=="));cartStore.checkoutTimeoutInterval=setTimeout((function(){cartStore.checkoutSessionTimeoutShow=true}),n)};var cartStoreClearCheckoutInterval=function(){if(cartStore.checkoutTimeoutInterval){clearTimeout(cartStore.checkoutTimeoutInterval);cartStore.checkoutTimeoutInterval=null}};var getCartItemToUse=function(e){return e.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:false})}))};var cartStoreResetCartItems=function(){cartStore.items=cartStore.items.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:false})}));cartStore.restrictedItems=[]};var cartStoreUpdateItems=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n;var i=e.adjustments,a=e.cartItems;return __generator(this,(function(e){switch(e.label){case 0:cartStore.adjustments=i;cartStore.items=getCartItemToUse(a);r=(t=a.find(Boolean))===null||t===void 0?void 0:t.currencyCode;o=a.reduce((function(e,t){return e+t.amount*t.quantity}),0);n=i.reduce((function(e,t){return e+t.amount}),0);if(!r||!o){return[2]}cartStore.currency=r;stripeStore.isFetchingSession=true;return[4,cartStoreReCalculateTotal({adjustmentsAmount:n,billToPartyId:stripeStore.partyBillingId,cartId:window.Zonos.cartId,currency:r,dutiesTaxesFeesEstimate:0,itemsAmount:o,shipToPartyId:stripeStore.partyShippingId,shouldInitSessionOnFailure:true,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:e.sent();stripeStore.isFetchingSession=false;return[2]}}))}))};var cartStoreResetSelectedShippingOption=function(){cartStore.selectedShippingOption=null;cartStore.isSelectedShippingAboveDeminimis=false;cartStore.isSelectedShippingGuarantee=false;cartStore.selectedShippingOptionTransitTime="";cartStore.dutiesTaxesFees=0;cartStore.dutiesTaxesFeesEstimate=0;cartStore.shipping=0;cartStore.total=cartStore.subtotal};var cartStorePreviousStep=function(){if(cartStore.step==="shipping"){cartStore.step="customer-info";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})})}else if(cartStore.step==="payment"){cartStore.step="shipping";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})})}else if(cartStore.step==="finish"){cartStore.step="payment";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{payment:Object.assign(Object.assign({},cartStore.tabItems.payment),{isDone:false})})}};var cartStoreNextStep=function(){if(cartStore.step==="customer-info"){cartStore.step="shipping";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems["customer-info"]),{isDone:true})})}else if(cartStore.step==="shipping"){cartStore.step="payment";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:true})})}else if(cartStore.step==="payment"){cartStore.step="finish"}};var cartStoreResetTabItems=function(){cartStore.step="customer-info";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems["customer-info"]),{isDone:false}),payment:Object.assign(Object.assign({},cartStore.tabItems.payment),{isDone:false}),shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})});cartStoreResetSelectedShippingOption()};export{cartStoreHasOneEligibleItem as A,stripeStoreApplyPromoCode as B,stripeStoreRemovePromoCode as C,stripeStoreResetPromoCode as D,stripeStoreMessageBasedOnStatus as E,stripeStoreTranslateAddressToLatin as F,extractName as G,cartStoreOnChange as H,stripeStoreAsyncAddressUpdate as I,cartStoreUpdateSelectedShippingOption as J,cartStoreGetShippingTransitInfo as K,cartStoreGetMethod as L,sortServiceLevelOptionsByAmount as M,stripeStoreCleanupDomesticShippingSession as a,stripeStoreSaveDomesticShippingSession as b,stripeStore as c,stripeStoreRetrievePayment as d,cartStore as e,cartStoreUpdateItems as f,cartStoreReset as g,cartStoreResetTabItems as h,initStripeElements as i,cartStoreClearCheckoutInterval as j,stripeStoreInitCheckoutSession as k,stripeStoreGetPaymentIntent as l,cartStoreStartCheckoutInterval as m,getCheckoutSessionBody as n,cartStoreUpdateToErrorState as o,cartStoreSetCheckoutSession as p,stripeStorePrefetchLandedCost as q,cartStoreNextStep as r,stripeStoreGetDomesticShippingSession as s,trackConversionEvent as t,stripeStoreUpdateCheckoutSessionBaseCurrency as u,stripeStoreHandleInventoryCheck as v,stripeStoreConfirmPayment as w,stripeStoreHandleInventoryRefund as x,stripeStoreReset as y,validateCheckoutSession as z};
|
|
1
|
+
var __awaiter=this&&this.__awaiter||function(e,t,r,o){function n(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,i){function a(e){try{d(o.next(e))}catch(e){i(e)}}function s(e){try{d(o["throw"](e))}catch(e){i(e)}}function d(e){e.done?r(e.value):n(e.value).then(a,s)}d((o=o.apply(e,t||[])).next())}))};var __generator=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},o,n,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(e){return function(t){return d([e,t])}}function d(s){if(o)throw new TypeError("Generator is already executing.");while(a&&(a=0,s[0]&&(r=0)),r)try{if(o=1,n&&(i=s[0]&2?n["return"]:s[0]?n["throw"]||((i=n["return"])&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;if(n=0,i)s=[s[0]&2,i.value];switch(s[0]){case 0:case 1:i=s;break;case 4:r.label++;return{value:s[1],done:false};case 5:r.label++;n=s[1];s=[0];continue;case 7:s=r.ops.pop();r.trys.pop();continue;default:if(!(i=r.trys,i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){r.label=s[1];break}if(s[0]===6&&r.label<i[1]){r.label=i[1];i=s;break}if(i&&r.label<i[2]){r.label=i[2];r.ops.push(s);break}if(i[2])r.ops.pop();r.trys.pop();continue}s=t.call(e,r)}catch(e){s=[6,e];n=0}finally{o=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o<n;o++){if(i||!(o in t)){if(!i)i=Array.prototype.slice.call(t,0,o);i[o]=t[o]}}return e.concat(i||Array.prototype.slice.call(t))};import{z as zonosStore,c as createStore}from"./zonosStore-c456b933.js";import{s as storageStore,l as localizationStore,t as translate,f as filterValidTests,b as storageStoreSetEnabledVariantTestKeys}from"./localization-d8326254.js";import{l as log,f as fallbackApiList,h as handleFetch,g as getIsTestMode,a as getIsStagingMode,s as sendErrorLog,d as allLogs,b as logError,j as jsonParse}from"./handleFetch-99218189.js";import{i as isDarkColor}from"./isDarkColor-1f58b6be.js";import{g as getBorderRadius}from"./getBorderRadius-87593ff4.js";var extractName=function(e){var t=e.firstName,r=e.lastName,o=e.name;var n;if(!o&&!t&&!r){return{firstName:"",lastName:""}}var i=(o===null||o===void 0?void 0:o.split(/\s+/))||[];var a=(t===null||t===void 0?void 0:t.trim())||((n=i[0])===null||n===void 0?void 0:n.trim())||"";var s=(r===null||r===void 0?void 0:r.trim())||i.slice(1).join(" ").trim()||"";return{firstName:a,lastName:s}};var getTranslatedAddress=function(e){var t=e.currentAddress,r=e.translatedAddress;var o,n,i,a,s,d;var c=t.value.address,l=c.city,u=c.country,v=c.line1,S=c.line2,p=c.postal_code,f=c.state;var h=t.value.name||[t.value.firstName,t.value.lastName].join(" ");return{city:((o=r.city)===null||o===void 0?void 0:o[l])||l,country:u,line1:((n=r.line1)===null||n===void 0?void 0:n[v])||v,line2:((i=r.line2)===null||i===void 0?void 0:i[S||""])||S||"",name:((a=r.name)===null||a===void 0?void 0:a[h])||h,phone:t.value.phone||"",postal_code:((s=r.postal_code)===null||s===void 0?void 0:s[p])||p,state:((d=r.state)===null||d===void 0?void 0:d[f])||f}};var prepCartCalculateLandedCost=function(e){var t;var r=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";var o=stripeStore.stripeLinkEventData;var n=stripeStore.stripeAddressEventData;var i=stripeStore.stripeShippingSameAsBilling?stripeStore.stripeAddressEventData:stripeStore.stripeBillingAddressEventData;if(!n||!i){throw new Error("Missing stripe address data")}var a=getTranslatedAddress({currentAddress:n,translatedAddress:stripeStore.translatedAddress.address});var s=extractName({name:a.name}),d=s.firstName,c=s.lastName;var l=getTranslatedAddress({currentAddress:i,translatedAddress:stripeStore.translatedAddress.address});var u=extractName({name:l.name}),v=u.firstName,S=u.lastName;return{billingAddress:{addressLine1:l.line1,addressLine2:l.line2||"",city:l.city,country:l.country,postalCode:l.postal_code,state:l.state},billingContact:{firstName:v,lastName:S,phone:l.phone},cartCurrencyCode:(t=cartStore.items[0])===null||t===void 0?void 0:t.currencyCode,cartId:e,checkoutSessionId:storageStore.checkoutSessionId||"",contact:{companyName:stripeStore.companyName,email:o===null||o===void 0?void 0:o.value.email,firstName:d,lastName:c,phone:a.phone},isTest:!!r,landedCostAdjustments:cartStore.promoCode?[{amount:0,productId:null,promoCode:cartStore.promoCode,sku:null,type:"PROMO_CODE"}]:[],shipToTaxId:stripeStore.taxId,shippingAddress:{addressLine1:a.line1,addressLine2:a.line2,city:a.city,country:a.country,postalCode:a.postal_code,state:a.state}}};var prepCalculateLandedCost=function(){var e=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";var t=stripeStore.stripeLinkEventData;var r=stripeStore.stripeAddressEventData;var o=stripeStore.stripeShippingSameAsBilling?stripeStore.stripeAddressEventData:stripeStore.stripeBillingAddressEventData;log({stripeAddressData:r,stripeBillingAddressData:o},"info");if(!r||!o){throw new Error("Missing stripe address data")}var n=getTranslatedAddress({currentAddress:r,translatedAddress:stripeStore.translatedAddress.address});var i=extractName({name:n.name}),a=i.firstName,s=i.lastName;var d=getTranslatedAddress({currentAddress:o,translatedAddress:stripeStore.translatedAddress.address});var c=extractName({name:d.name}),l=c.firstName,u=c.lastName;var v=cartStore.adjustments.map((function(e){return{amount:e.amount,name:e.description||null,productId:e.productId,sku:e.sku,type:e.type}}));var S=cartStore.promoCode?__spreadArray([{amount:0,productId:null,promoCode:cartStore.promoCode,sku:null,type:"PROMO_CODE"}],v,true):v;return{billingAddress:{addressLine1:d.line1,addressLine2:d.line2||"",city:d.city,country:d.country,postalCode:d.postal_code,state:d.state},billingContact:{firstName:l,lastName:u,phone:d.phone},checkoutSessionId:storageStore.checkoutSessionId||"",contact:{companyName:stripeStore.companyName,email:t===null||t===void 0?void 0:t.value.email,firstName:a,lastName:s,phone:n.phone},isTest:e,items:cartStore.items,landedCostAdjustments:S,shipToTaxId:stripeStore.taxId,shippingAddress:{addressLine1:n.line1,addressLine2:n.line2,city:n.city,country:n.country,postalCode:n.postal_code,state:n.state}}};var triggerBuildLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s,d,c,l;return __generator(this,(function(u){switch(u.label){case 0:a=prepCalculateLandedCost();return[4,e({billingAddress:a.billingAddress,billingContact:a.billingContact,checkoutSessionId:a.checkoutSessionId,contact:a.contact,landedCostAdjustments:a.landedCostAdjustments,publicCredential:window.Zonos.zonosApiKey||"",shippingAddress:a.shippingAddress,zonosApiRoute:fallbackApiList["vercel"]})];case 1:s=u.sent();if(!s||!((t=s.checkoutSessionWorkflow)===null||t===void 0?void 0:t.length)&&((r=s.errors)===null||r===void 0?void 0:r.length)){throw new Error("Failed to build landed cost: ".concat(((n=(o=s===null||s===void 0?void 0:s.errors)===null||o===void 0?void 0:o[0])===null||n===void 0?void 0:n.message)||"Unknown error"))}return[4,handleFetch("/api/zonos-elements/validate-landed-cost",{body:s,headers:{"Content-Type":"application/json"},method:"POST"})];case 2:d=u.sent(),c=d.errors,l=d.json;if(!l||c.length){throw new Error("Invalid landed cost object: ".concat(((i=c.find(Boolean))===null||i===void 0?void 0:i.message)||"Unknown error"))}return[2,s]}}))}))};var calculateLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s;return __generator(this,(function(d){switch(d.label){case 0:r=zonosStore.checkoutSettings.buildLandedCost;if(!r)return[3,2];return[4,triggerBuildLandedCost(r)];case 1:o=d.sent();return[2,o];case 2:return[4,handleFetch("/api/zonos-elements/calculate-landed-cost",{body:prepCalculateLandedCost(),method:"POST",signal:e===null||e===void 0?void 0:e.signal})];case 3:n=d.sent(),i=n.errors,a=n.json;if(i.length||!a){s=((t=i[0])===null||t===void 0?void 0:t.message)==="The user aborted a request.";if(s){throw new Error("The landed cost calculation request was aborted to initiate a new one.")}i.forEach((function(e){console.warn("Error calculating landed cost: ".concat(e.message))}));if(!a){throw new Error("Failed to calculate landed cost")}return[2,a]}return[2,a]}}))}))};var cartCalculateLandedCost=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c,l;var u=e.abortController,v=e.cartId;return __generator(this,(function(e){switch(e.label){case 0:return[4,handleFetch("/api/zonos-elements/cart-calculate-landed-cost",{body:prepCartCalculateLandedCost(v),method:"POST",signal:u===null||u===void 0?void 0:u.signal})];case 1:a=e.sent(),s=a.errors,d=a.json;if(s.length||!d){c=typeof((t=s[0])===null||t===void 0?void 0:t.message)==="string"&&(((r=s[0])===null||r===void 0?void 0:r.message)==="The user aborted a request."||((o=s[0])===null||o===void 0?void 0:o.message.includes("signal is aborted"))||((n=s[0])===null||n===void 0?void 0:n.message.includes("The operation was aborted"))||((i=s[0])===null||i===void 0?void 0:i.message.includes("Fetch is aborted")));l=c?"The landed cost calculation request was aborted to initiate a new one.":"Failed to calculate landed cost";throw new Error(l)}return[2,d]}}))}))};var __rest=undefined&&undefined.__rest||function(e,t){var r={};for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0)r[o]=e[o];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var n=0,o=Object.getOwnPropertySymbols(e);n<o.length;n++){if(t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n]))r[o[n]]=e[o[n]]}return r};var calculateLandedCostNormalized=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i;return __generator(this,(function(a){switch(a.label){case 0:t=window.Zonos.cartId;if(!!t)return[3,2];return[4,calculateLandedCost(e)];case 1:r=a.sent();return[2,r];case 2:return[4,cartCalculateLandedCost({abortController:e,cartId:t})];case 3:o=a.sent(),n=o.cartWorkflow,i=__rest(o,["cartWorkflow"]);return[2,Object.assign(Object.assign({},i),{itemCreateWorkflow:n.items})]}}))}))};var trackConversionEvent=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c;var l=e.checkoutSessionId,u=e.eventName,v=e.metadata;return __generator(this,(function(e){switch(e.label){case 0:o=Date.now();n=__spreadArray([],window.Zonos.trackEventLogs,true);window.Zonos.trackEventLogs.push({checkoutSessionId:l,eventCreated:o,eventName:u});i=window.location.href.includes("zonos.com")&&!window.location.href.includes("checkout.zonos.com")||!!((t=window.Zonos)===null||t===void 0?void 0:t.zonosQaUrl)||!!((r=window.Zonos)===null||r===void 0?void 0:r.debug);a=getIsTestMode()||getIsStagingMode();if((a||i)&&!window.Zonos.zonosConversionTest){return[2]}s=localizationStore.selectedCountryCode;d=zonosStore.organizationId;if(!l){void sendErrorLog({endpoint:"trackConversionEventMetric",errors:['Event "'.concat(u,'" - No checkout session id found')],metadata:{allLogs:allLogs,checkoutSessionId:l,eventName:u,metadata:v,organizationId:d,trackEventLogs:n}});return[2]}if(!d){void sendErrorLog({endpoint:"trackConversionEventMetric",errors:['Event "'.concat(u,'" - No organization id found')],metadata:{allLogs:allLogs,checkoutSessionId:l,eventName:u,metadata:v,organizationId:d,trackEventLogs:n}})}c={checkoutSessionId:l,countryCode:s,eventCreated:o,eventName:u,metadata:Object.assign(Object.assign({},v),{trackEventLogs:n}),organizationId:d};return[4,handleFetch("/api/zonos-elements/track-conversion-event",{body:c,method:"POST"})];case 1:e.sent();return[2]}}))}))};var getExcludeAddressFieldsObject=function(e){var t=e.address,r=e.invalidAdddressList;if(!t){return}if(!r){return}var o={};if(r.city){o.city=t.city}if(r.line1){o.line1=t.line1}if(r.line2){o.line2=t.line2}if(r.postal_code){o.postal_code=t.postal_code}if(r.state){o.state=t.state}if(r.name){o.name=t.name}return Object.keys(o).length?o:undefined};var buildTranslateRequest=function(e){var t=e.addressInvalidCharactersList,r=e.billingAddressInvalidCharactersList,o=e.stripeAddressEventData,n=e.stripeBillingAddressEventData,i=e.stripeShippingSameAsBilling;var a=!!(o===null||o===void 0?void 0:o.complete);var s=i?a:!!(n===null||n===void 0?void 0:n.complete);if(!a||!s){return null}if(!t&&!r){return null}var d=o.value;var c=(n===null||n===void 0?void 0:n.value)||null;var l=extractName({firstName:d.firstName,lastName:d.lastName,name:d.name}),u=l.firstName,v=l.lastName;var S="".concat(u," ").concat(v);var p=extractName({firstName:c===null||c===void 0?void 0:c.firstName,lastName:c===null||c===void 0?void 0:c.lastName,name:(c===null||c===void 0?void 0:c.name)||""}),f=p.firstName,h=p.lastName;var m=f&&h?"".concat(f," ").concat(h):"";var g=d.address;var y=c===null||c===void 0?void 0:c.address;return{address:getExcludeAddressFieldsObject({address:Object.assign(Object.assign({},g),{name:S}),invalidAdddressList:t}),billingAddress:!i?getExcludeAddressFieldsObject({address:y?Object.assign(Object.assign({},y),{name:m}):null,invalidAdddressList:r}):undefined,destinationCountry:g.country}};var sortServiceLevelOptionsByAmount=function(e){var t=e.sort((function(e,t){return e.amount-t.amount}));return t};var getCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:if(!storageStore.checkoutSessionId){return[2,{errors:[{message:"No checkout session id found"}],json:null}]}e=new URLSearchParams;e.set("checkoutSessionId",storageStore.checkoutSessionId);return[4,handleFetch("/api/zonos-elements/get-checkout-session?".concat(e.toString()))];case 1:t=n.sent(),r=t.errors,o=t.json;return[2,{errors:r,json:o}]}}))}))};var validateCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:return[4,getCheckoutSession()];case 1:t=n.sent(),r=t.errors,o=t.json;if(r.length||!o){logError("Failed to retrieve checkout session info before confirming payment ",r);void sendErrorLog({endpoint:"validateCheckoutSession",errors:r.map((function(e){return e.message})),metadata:{allLogs:allLogs}});return[2,{errorMessage:translate("Unable to retrieve the checkout session at the moment. Please try again or contact our support team."),valid:false}]}if(!((e=o.checkoutSession.landedCost)===null||e===void 0?void 0:e.id)){logError("Landed cost is not found in the checkout session before confirming payment.");void sendErrorLog({endpoint:"validateCheckoutSession",errors:["No landed cost found before confirming payment"],metadata:{allLogs:allLogs}});return[2,{errorMessage:translate('No shipment rating selected. Please go back to the "Shipping" step and select a shipment rating to proceed.'),valid:false}]}return[2,{errorMessage:"",valid:true}]}}))}))};var addressRuleStyle=function(e){var t=e.theme;var r={".AccordionItem":{color:"var(--colorText)"},".AccordionItem--selected":{color:"var(--colorText)"},".Action":{color:"var(--colorText)"},".Input":{boxShadow:"none",fontSize:zonosStore.appearance.fontSizeInputValue?"".concat(zonosStore.appearance.fontSizeInputValue,"px"):undefined,padding:"0",paddingBottom:"8px",paddingLeft:"16px",paddingRight:"8px",paddingTop:"6px"},".Label--resting":{fontSize:zonosStore.appearance.fontSizeInputLabel?"".concat(zonosStore.appearance.fontSizeInputLabel,"px"):undefined},".PickerItem--highlight":{boxShadow:"0 0 0 2px var(--colorBackground)"},".PickerItem--highlight:hover":{backgroundColor:"var(--colorBackground)",boxShadow:"none"},".PickerItem--new":{color:"var(--colorText)"},".Tab--selected":{borderStyle:"solid",borderWidth:"1px"}};switch(t){case"DARK":{return Object.assign(Object.assign({},r),{".Action":Object.assign(Object.assign({},r[".Action"]),{color:"white"}),".PickerItem--new":Object.assign(Object.assign({},r[".PickerItem--new"]),{color:"white"})})}default:return r}};var defaultVariable=function(e){var t=e.borderStyle,r=e.theme;switch(r){case"DARK":return{borderRadius:getBorderRadius({overrideBorderStyle:t}),colorBackground:"#101117",colorBackgroundText:"#C5C6CA",colorText:"#C5C6CA",colorTextPlaceholder:"#C5C6CA"};default:return{borderRadius:getBorderRadius({overrideBorderStyle:t}),iconMenuColor:"var(--colorText)",iconMenuHoverColor:"var(--colorText)"}}};var _m=createStore((function(){return{checkoutSettlementCurrency:"USD",clientSecret:sessionStorage.getItem("zonos--client-secret")||"",companyName:"",companyNameUsedWhenAsyncAddressUpdate:"",customAddressErrors:{city:"",firstName:"",lastName:"",line1:"",phone:"",postalCode:"",showError:false,state:""},customBillingAddressErrors:{city:"",firstName:"",lastName:"",line1:"",phone:"",postalCode:"",showError:false,state:""},customErrorMessage:null,customerProfile:null,fetchingLandedCostAbortController:null,hasPaymentError:false,isFetchingLandedCost:false,isFetchingSession:false,partyBillingId:null,partyShippingId:null,shouldInventoryRefund:false,shouldRenderPayInUsdButton:false,skipPaymentIntent:new URLSearchParams(window.location.search).get("skipPaymentIntent")==="0"?false:true,stripe:null,stripeAddressElement:null,stripeAddressEventData:null,stripeAddressUsedWhenAsyncAddressUpdate:null,stripeAddressUsedWhenFetchingLC:null,stripeAddressUsedWhenValidatingAddress:null,stripeBillingAddressElement:null,stripeBillingAddressEventData:null,stripeBillingAddressUsedWhenAsyncAddressUpdate:null,stripeBillingAddressUsedWhenFetchingLC:null,stripeBillingAddressUsedWhenValidatingAddress:null,stripeCustomerSessionClientSecret:null,stripeElements:null,stripeElementsForBillingAddress:null,stripeElementsOptions:null,stripeLinkElement:null,stripeLinkEventData:null,stripeLinkUsedWhenFetchingLC:null,stripePaymentElement:null,stripePaymentEventData:null,stripeShippingSameAsBilling:true,taxId:"",taxIdUsedWhenAsyncAddressUpdate:"",translatedAddress:{address:{},billingAddress:{},firstName:{},lastName:{},name:{}}}})),stripeStoreOnChange=_m.onChange,reset$1=_m.reset,stripeStore=_m.state;var getStripeOptions=function(e){var t=e.clientSecret,r=e.overrideBorderRadius,o=e.overridePrimaryColor,n=e.overrideSecondaryColor,i=e.overrideTheme,a=e.paypalEnabled;var s=o||zonosStore.appearance.colorPrimary;var d=n||zonosStore.appearance.colorSecondary;var c=s&&isDarkColor(s)?"night":"flat";var l=i==="DARK"?"night":"flat";var u=a?["external_paypal"]:[];return{appearance:{labels:"floating",rules:Object.assign({},addressRuleStyle({theme:i||"LIGHT"})),theme:i?l:c,variables:Object.assign(Object.assign({},defaultVariable({borderStyle:r,theme:"LIGHT"})),{colorPrimary:d})},clientSecret:t||undefined,customerSessionClientSecret:stripeStore.stripeCustomerSessionClientSecret||undefined,externalPaymentMethodTypes:__spreadArray([],u,true),locale:localizationStore.selectedLocale}};var stripeStoreCleanupDomesticShippingSession=function(){window.sessionStorage.removeItem("zonos--bigcommerce-domestic-checkout-shipping")};var stripeStoreSaveDomesticShippingSession=function(e){window.sessionStorage.setItem("zonos--bigcommerce-domestic-checkout-shipping",JSON.stringify(e))};var stripeStoreGetDomesticShippingSession=function(){var e=window.sessionStorage.getItem("zonos--bigcommerce-domestic-checkout-shipping");return jsonParse(e)};var initStripeElements=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i;return __generator(this,(function(a){o=stripeStore.clientSecret;if(!stripeStore.stripe){log("Skip. Stripe is not initialized");return[2]}n=getStripeOptions({clientSecret:o,overrideBorderRadius:e===null||e===void 0?void 0:e.overrideBorderRadius,overridePrimaryColor:e===null||e===void 0?void 0:e.overridePrimaryColor,overrideSecondaryColor:e===null||e===void 0?void 0:e.overrideSecondaryColor,overrideTheme:e===null||e===void 0?void 0:e.overrideTheme,paypalEnabled:e===null||e===void 0?void 0:e.paypalEnabled});i=JSON.stringify(n)===JSON.stringify(stripeStore.stripeElementsOptions);if(!stripeStore.stripeElements||!stripeStore.stripeElementsForBillingAddress){stripeStore.stripeElements=(t=stripeStore.stripe)===null||t===void 0?void 0:t.elements(n);stripeStore.stripeElementsOptions=n;log("Stripe elements initialized");stripeStore.stripeElementsForBillingAddress=(r=stripeStore.stripe)===null||r===void 0?void 0:r.elements(n);log("Stripe elements for billing address initialized");return[2]}if(!i){stripeStore.stripeElements.update(n);stripeStore.stripeElementsForBillingAddress.update(n);stripeStore.stripeElementsOptions=n;void stripeStore.stripeElements.fetchUpdates()}log("Stripe elements updated");return[2]}))}))};var stripeStoreReset=function(){sessionStorage.removeItem("zonos--client-secret");reset$1();stripeStore.stripe=window.Zonos.stripe};var checkIsAddressOutdatedForValidation=function(){var e,t,r,o;var n=JSON.stringify((e=stripeStore.stripeAddressUsedWhenValidatingAddress)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.value);var i=!stripeStore.stripeShippingSameAsBilling&&JSON.stringify((r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.value)!==JSON.stringify((o=stripeStore.stripeBillingAddressUsedWhenValidatingAddress)===null||o===void 0?void 0:o.value);return n||i};var checkIsAddressOutdatedForAsyncAddressUpdate=function(){var e,t,r,o,n,i;var a=JSON.stringify((e=stripeStore.stripeLinkUsedWhenFetchingLC)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeLinkEventData)===null||t===void 0?void 0:t.value);var s=JSON.stringify((r=stripeStore.stripeAddressUsedWhenAsyncAddressUpdate)===null||r===void 0?void 0:r.value)!==JSON.stringify((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value);var d=!stripeStore.stripeShippingSameAsBilling&&JSON.stringify((n=stripeStore.stripeBillingAddressUsedWhenAsyncAddressUpdate)===null||n===void 0?void 0:n.value)!==JSON.stringify((i=stripeStore.stripeBillingAddressEventData)===null||i===void 0?void 0:i.value);var c=stripeStore.taxIdUsedWhenAsyncAddressUpdate!==stripeStore.taxId;var l=stripeStore.companyNameUsedWhenAsyncAddressUpdate!==stripeStore.companyName;return a||s||d||c||l};var buildAddressForPartyCreate=function(e){var t=e.address,r=e.firstName,o=e.lastName,n=e.name,i=e.phone;var a=extractName({firstName:r,lastName:o,name:n}),s=a.firstName,d=a.lastName;if(!s||!d){void sendErrorLog({endpoint:"PARTY_CREATE_NO_NAME_FOUND",errors:["No name found"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,firstName:r,lastName:o,name:n}})}if(!i){void sendErrorLog({endpoint:"PARTY_CREATE_NO_PHONE_FOUND",errors:["No phone found"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,phone:i}})}return{city:t.city,country:t.country,firstName:s,lastName:d,line1:t.line1,line2:t.line2,phone:i||"",postal_code:t.postal_code,state:t.state}};var stripeStoreAsyncAddressUpdate=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l,u;return __generator(this,(function(v){switch(v.label){case 0:if(!((e=stripeStore.stripeAddressEventData)===null||e===void 0?void 0:e.complete)||!stripeStore.stripeShippingSameAsBilling&&!((t=stripeStore.stripeBillingAddressEventData)===null||t===void 0?void 0:t.complete)||!stripeStore.stripeBillingAddressEventData){return[2,{partiesCreated:false}]}if(!cartStore.landedCostData){return[2,{partiesCreated:false}]}n=(r=cartStore.landedCostData.find(Boolean))===null||r===void 0?void 0:r.landedCost.rootId;if(!n){void sendErrorLog({endpoint:"PF_NO_SELECTED_LANDED_COST",errors:["No selected landed cost"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId}});return[2,{partiesCreated:false}]}i=checkIsAddressOutdatedForAsyncAddressUpdate();if(!i){return[2,{partiesCreated:false}]}a=buildAddressForPartyCreate({address:stripeStore.stripeAddressEventData.value.address,firstName:stripeStore.stripeAddressEventData.value.firstName,lastName:stripeStore.stripeAddressEventData.value.lastName,name:stripeStore.stripeAddressEventData.value.name,phone:stripeStore.stripeAddressEventData.value.phone});s=stripeStore.stripeShippingSameAsBilling?a:buildAddressForPartyCreate({address:stripeStore.stripeBillingAddressEventData.value.address,firstName:stripeStore.stripeBillingAddressEventData.value.firstName,lastName:stripeStore.stripeBillingAddressEventData.value.lastName,name:stripeStore.stripeBillingAddressEventData.value.name,phone:stripeStore.stripeBillingAddressEventData.value.phone});d=new URLSearchParams(window.location.search).get("zonosE2ETest")==="1";return[4,handleFetch("/api/zonos-elements/create-parties",{body:{address:a,billingAddress:s,companyName:stripeStore.companyName,email:((o=stripeStore.stripeLinkEventData)===null||o===void 0?void 0:o.value.email)||"",isTest:d,rootId:n,taxId:stripeStore.taxId},method:"POST"})];case 1:c=v.sent(),l=c.errors,u=c.json;if(l.length||!u){logError("Error occurs when creating parties",JSON.stringify(l,null,2));void sendErrorLog({endpoint:"PF_PARTY_CREATE_FAILED",errors:["Failed to create parties"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,errors:l,json:u}});return[2,{partiesCreated:false}]}stripeStore.companyNameUsedWhenAsyncAddressUpdate=stripeStore.companyName;stripeStore.stripeAddressUsedWhenAsyncAddressUpdate=stripeStore.stripeAddressEventData;stripeStore.stripeBillingAddressUsedWhenAsyncAddressUpdate=stripeStore.stripeBillingAddressEventData;stripeStore.taxIdUsedWhenAsyncAddressUpdate=stripeStore.taxId;stripeStore.partyBillingId=u.billToPartyId;stripeStore.partyShippingId=u.shipToPartyId;return[2,{partiesCreated:true}]}}))}))};var buildAddressForLCPrefetch=function(e){return{countryCode:e.address.country,postalCode:e.address.postal_code,state:e.address.state}};var checkIsAddressOutdatedForLCPrefetch=function(){var e,t;var r=JSON.stringify((e=stripeStore.stripeLinkUsedWhenFetchingLC)===null||e===void 0?void 0:e.value)!==JSON.stringify((t=stripeStore.stripeLinkEventData)===null||t===void 0?void 0:t.value);var o=stripeStore.stripeAddressEventData&&JSON.stringify(buildAddressForLCPrefetch(stripeStore.stripeAddressEventData.value))!==JSON.stringify(stripeStore.stripeAddressUsedWhenFetchingLC);var n=!stripeStore.stripeShippingSameAsBilling&&stripeStore.stripeBillingAddressEventData&&JSON.stringify(buildAddressForLCPrefetch(stripeStore.stripeBillingAddressEventData.value))!==JSON.stringify(stripeStore.stripeBillingAddressUsedWhenFetchingLC);return r||o||n};var isPrefetchInfoOutdated=function(){var e;var t=cartStore.landedCostData&&((e=cartStore.landedCostData.find(Boolean))===null||e===void 0?void 0:e.subtotals.items)!==cartStore.subtotal;var r=checkIsAddressOutdatedForLCPrefetch();log("isPrefetchInfoOutdated","info",{isAddressOutdated:r});return!cartStore.landedCostData&&!stripeStore.isFetchingLandedCost||r||t};var getCountryField=function(e){var t,r;var o=(t=zonosStore.genericSettings)===null||t===void 0?void 0:t.countryFields;var n=(r=zonosStore.genericSettings)===null||r===void 0?void 0:r.stripeCountryFieldLabels;var i=n&&e in n?n[e]:null;var a=o&&e in o?o[e]:null;if(cartStore.addressFormRenderType==="stripe"){return i||a}return a};var isAddressReadyToRequestLandedCost=function(){var e,t,r,o;var n=!!((e=stripeStore.stripeLinkEventData)===null||e===void 0?void 0:e.complete);var i=!!((t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.complete);var a=stripeStore.stripeShippingSameAsBilling?i:!!((r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.complete);var s=((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.address.country)||"US";var d=getCountryField(s);if(i&&a&&n){return true}if(!d||!stripeStore.stripeAddressEventData){return i&&a&&n}var c=stripeStore.stripeAddressEventData.value.address.line1.length>0;var l=stripeStore.stripeAddressEventData.value.firstName&&stripeStore.stripeAddressEventData.value.lastName;var u=!d.stateRequired||d.stateRequired&&stripeStore.stripeAddressEventData.value.address.state.length>0;var v=!d.zipRequired||d.zipRequired&&stripeStore.stripeAddressEventData.value.address.postal_code.length>=3;var S=stripeStore.stripeAddressEventData.value.phone&&stripeStore.stripeAddressEventData.value.phone.length>0;return n&&l&&c&&u&&v&&S};var stripeCalculateLandedCost=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l;return __generator(this,(function(u){switch(u.label){case 0:t=new AbortController;stripeStore.fetchingLandedCostAbortController=t;cartStoreResetCartItems();return[4,calculateLandedCostNormalized(t)];case 1:r=u.sent(),o=r.checkoutSessionWorkflow,n=r.errors,i=r.itemCreateWorkflow,a=r.landedCostCalculateWorkflow,s=r.partyCreateWorkflow,d=r.shipmentRatingCalculateWorkflow;cartStore.customQuotingError=((e=n===null||n===void 0?void 0:n.find((function(e){var t;return((t=e.extensions)===null||t===void 0?void 0:t.ruleMessageType)==="CUSTOM"})))===null||e===void 0?void 0:e.message)||null;cartStore.shippingData=sortServiceLevelOptionsByAmount((d===null||d===void 0?void 0:d.filter(Boolean))||[]);cartStoreCheckItemRestrictions(i);stripeStore.fetchingLandedCostAbortController=null;cartStore.partiesData=(s===null||s===void 0?void 0:s.filter(Boolean))||[];cartStore.landedCostData=(o===null||o===void 0?void 0:o.map((function(e){var t=a===null||a===void 0?void 0:a.find((function(t){return(t===null||t===void 0?void 0:t.id)===e.landedCostId}));if(!t){return null}return Object.assign(Object.assign({},e),{landedCost:t})})).filter(Boolean))||[];c=storageStore.checkoutSessionId;if(o===null||o===void 0?void 0:o.length){void trackConversionEvent({checkoutSessionId:c,eventName:"checkout_quoteReceived"})}l=cartStore.promoCodeApplied&&!cartStore.landedCostData.find((function(e){var t;return(t=e.landedCost.appliedAdjustments)===null||t===void 0?void 0:t.find((function(e){return e.type==="PROMO_CODE"}))}));cartStore.promoCodeError=l;if(!l){sessionStorage.setItem("zonos--promo-code",cartStore.promoCode)}return[2]}}))}))};var stripeStorePrefetchLandedCost=function(e){return __awaiter(void 0,void 0,void 0,(function(){var t,r,o,n,i,a,s,d,c,l,u,v,S,p;return __generator(this,(function(f){switch(f.label){case 0:i=(e===null||e===void 0?void 0:e.retries)||0;a=!!(e===null||e===void 0?void 0:e.applyingPromocode);s=isPrefetchInfoOutdated();d=isAddressReadyToRequestLandedCost();if(!d){return[2,{isRequestNotReady:true}]}if(s){(t=stripeStore.fetchingLandedCostAbortController)===null||t===void 0?void 0:t.abort();stripeStore.fetchingLandedCostAbortController=null}if(!s&&!a){return[2,{isRequestNotReady:false}]}if(i){stripeStore.isFetchingLandedCost=false;setTimeout((function(){stripeStore.isFetchingLandedCost=true}),300)}else{stripeStore.isFetchingLandedCost=true}if(stripeStore.stripeAddressEventData){stripeStore.stripeAddressUsedWhenFetchingLC={countryCode:stripeStore.stripeAddressEventData.value.address.country,postalCode:stripeStore.stripeAddressEventData.value.address.postal_code,state:stripeStore.stripeAddressEventData.value.address.state}}if(stripeStore.stripeBillingAddressEventData){stripeStore.stripeBillingAddressUsedWhenFetchingLC={countryCode:stripeStore.stripeBillingAddressEventData.value.address.country,postalCode:stripeStore.stripeBillingAddressEventData.value.address.postal_code,state:stripeStore.stripeBillingAddressEventData.value.address.state}}if(stripeStore.stripeLinkEventData){stripeStore.stripeLinkUsedWhenFetchingLC=Object.assign({},stripeStore.stripeLinkEventData)}f.label=1;case 1:f.trys.push([1,3,,7]);cartStoreResetCartItems();return[4,stripeCalculateLandedCost()];case 2:f.sent();c=(r=cartStore.shippingData)===null||r===void 0?void 0:r.find(Boolean);l=(o=cartStore.landedCostData)===null||o===void 0?void 0:o.find((function(e){return e.landedCost.shipmentRating.id===(c===null||c===void 0?void 0:c.id)}));u=!!l?l.subtotals:null;if(u){cartStoreApplySubtotals({method:(l===null||l===void 0?void 0:l.landedCost.method)||"DDP",subtotals:u})}return[3,7];case 3:v=f.sent();cartStore.landedCostData=[];cartStore.shippingData=[];S=["The landed cost calculation request was aborted to initiate a new one."];if(!(v instanceof Error&&v.message&&!S.includes(v.message)))return[3,6];if(!(i<1))return[3,5];return[4,stripeStorePrefetchLandedCost(Object.assign(Object.assign({},e),{retries:(i||0)+1}))];case 4:f.sent();return[2,{isRequestNotReady:false}];case 5:p=(n=stripeStore.stripeAddressEventData)===null||n===void 0?void 0:n.value;void sendErrorLog({endpoint:"Failed to fetch landed cost (".concat(i," retries)"),errors:[v.message],metadata:{cartId:window.Zonos.cartId,shipToAddress:p}});f.label=6;case 6:logError(v);return[3,7];case 7:stripeStore.isFetchingLandedCost=false;return[2,{isRequestNotReady:false}]}}))}))};var stripeStoreApplyPromoCode=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o;return __generator(this,(function(n){switch(n.label){case 0:return[4,stripeStorePrefetchLandedCost({applyingPromocode:true})];case 1:n.sent();if(cartStore.step==="payment"){cartStorePreviousStep()}return[4,stripeStoreAsyncAddressUpdate()];case 2:n.sent();r=(e=cartStore.shippingData)===null||e===void 0?void 0:e.find(Boolean);o=(t=cartStore.landedCostData)===null||t===void 0?void 0:t.find((function(e){return e.landedCost.id===(r===null||r===void 0?void 0:r.id)}));if(!r||!o){return[2]}return[4,cartStoreUpdateSelectedShippingOption(r,o.landedCostId)];case 3:n.sent();return[2]}}))}))};var stripeStoreResetPromoCode=function(){cartStore.promoCode="";sessionStorage.removeItem("zonos--promo-code");cartStore.promoCodeError=false;cartStore.promoCodeApplied=false};var stripeStoreRemovePromoCode=function(){return __awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(e){switch(e.label){case 0:if(cartStore.step==="payment"){cartStorePreviousStep()}stripeStoreResetPromoCode();return[4,stripeStoreApplyPromoCode()];case 1:e.sent();return[2]}}))}))};var stripeStoreMessageBasedOnStatus=function(e){var t=[];var r=true;switch(e){case"succeeded":{t=[translate("Your payment went through successfully! Thank you for shopping with us! We hope you had an enjoyable experience and your support means the world to us."),"",translate("We've sent an email confirmation of the order details for your review. And our team is carefully preparing your order so it arrives on time.")];r=false;break}case"requires_capture":case"processing":{t=[translate("Payment processing. We'll update you when payment is received.")];r=false;break}case"requires_payment_method":{t=[translate("Payment failed. Please try another payment method.")];break}case"requires_action":{r=false;t=[translate("Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.")]}default:{t=[translate("Something went wrong.")];break}}return{isError:r,messages:t}};var stripeStoreHandleInventoryCheck=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,s;return __generator(this,(function(c){switch(c.label){case 0:r=zonosStore.checkoutSettings.onInventoryCheck;o=!!((t=(e=window.Zonos.cartData)===null||e===void 0?void 0:e.metadata.find((function(e){return e.key==="referenceId"})))===null||t===void 0?void 0:t.value);if(!(window.Zonos.isLegacyCheckout&&window.Zonos.cartData&&o))return[3,2];return[4,handleFetch("/api/zonos-elements/legacy/inventory-check",{body:{cartData:window.Zonos.cartData},method:"POST"})];case 1:n=c.sent(),i=n.errors,a=n.json;if(i.length||!a){logError("Error occurs when handling inventory refund","warn",JSON.stringify(i));return[2,null]}if(!a.available||a.status===204){return[2,translate("The item you're looking for is currently unavailable in our inventory. Please check back later or contact support for assistance with availability.")]}if(a.available||a.status===200){stripeStore.shouldInventoryRefund=true;return[2,null]}return[2,null];case 2:if(typeof r!=="function"){return[2,null]}c.label=3;case 3:c.trys.push([3,5,,6]);return[4,r({items:cartStore.items})];case 4:s=c.sent();return[2,s];case 5:d=c.sent();s=d instanceof Error?d.message:"Unknown error";void sendErrorLog({endpoint:"onInventoryCheck",errors:["cartId: ".concat(window.Zonos.cartId," - ").concat(s)],metadata:{cartId:window.Zonos.cartId,href:window.location.href,items:cartStore.items}});throw d;case 6:return[2]}}))}))};var stripeStoreHandleInventoryRefund=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r;return __generator(this,(function(o){switch(o.label){case 0:r=!!((t=(e=window.Zonos.cartData)===null||e===void 0?void 0:e.metadata.find((function(e){return e.key==="referenceId"})))===null||t===void 0?void 0:t.value);if(!window.Zonos.isLegacyCheckout||!window.Zonos.cartData||!r){return[2]}return[4,handleFetch("/api/zonos-elements/legacy/inventory-refund",{body:{cartData:window.Zonos.cartData},method:"POST"})];case 1:o.sent();return[2]}}))}))};var stripeStoreRetrievePayment=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c;var l=e.clientSecret,u=e.storybookForceStatus;return __generator(this,(function(e){switch(e.label){case 0:if(u){t=stripeStoreMessageBasedOnStatus(u),r=t.isError,o=t.messages;return[2,{error:r,messages:o}]}n=l||stripeStore.clientSecret;if(!stripeStore.stripe||!n){logError("Failed to retrieve payment intent. Stripe is not initialized");return[2,{error:true,message:[translate("Something went wrong.")]}]}return[4,stripeStore.stripe.retrievePaymentIntent(n)];case 1:i=e.sent().paymentIntent;a=i===null||i===void 0?void 0:i.status;s=stripeStoreMessageBasedOnStatus(a),d=s.isError,c=s.messages;return[2,{error:d,messages:c,paymentIntentId:i===null||i===void 0?void 0:i.id,paymentMethod:i===null||i===void 0?void 0:i.payment_method,status:a}]}}))}))};var stripeStoreConfirmPayment=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s,d,c,l,u;return __generator(this,(function(v){switch(v.label){case 0:r=!!((e=stripeStore.stripePaymentEventData)===null||e===void 0?void 0:e.complete);o=stripeStore.stripeElements;n=stripeStore.stripe;i=stripeStore.clientSecret;stripeStore.customErrorMessage=null;if(!((t=cartStore.selectedLandedCost)===null||t===void 0?void 0:t.landedCost.id)){throw new Error("Attempted to confirm the payment when no landed cost is found in store")}return[4,validateCheckoutSession()];case 1:a=v.sent();if(!a.valid){stripeStore.customErrorMessage=a.errorMessage;throw new Error(a.errorMessage)}s=storageStore.checkoutSessionId;if(!(n&&o&&r&&i&&s))return[3,3];d=new URL(window.location.href);d.searchParams.set("payment_intent_client_secret",i);d.searchParams.set("zonosCheckoutSessionId",s);void trackConversionEvent({checkoutSessionId:s,eventName:"checkout_paymentInfoCompleted"});return[4,n.confirmPayment({confirmParams:{return_url:d.toString()},elements:o,redirect:"if_required"})];case 2:c=v.sent(),l=c.error,u=c.paymentIntent;log("Payment intent confirmed","info",{error:l,paymentIntent:u});if((u===null||u===void 0?void 0:u.status)==="requires_action"){throw new Error(translate("Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction."))}if(l){if(l.type==="card_error"||l.type==="validation_error"){throw new Error(l.message)}if(l.type==="invalid_request_error"){if(l.code==="payment_intent_unexpected_state"){return[2]}}throw new Error("An unexpected error occurred.")}if(u.status==="requires_payment_method"){throw new Error(translate("Payment failed. Please try another payment method."))}v.label=3;case 3:return[2]}}))}))};var getCheckoutSessionBody=function(){var e;var t=cartStore.items.reduce((function(e,t){return e+t.amount*t.quantity}),0);var r=storageStore.enabledVariantTestKeys||[];var o={adjustmentsAmount:cartStore.adjustments.reduce((function(e,t){return e+t.amount}),0),cartId:window.Zonos.cartId,currency:((e=cartStore.items.find(Boolean))===null||e===void 0?void 0:e.currencyCode)||"",customerAuthenticationToken:cartStore.customerAuthenticationToken||undefined,itemsAmount:t,metadata:[{key:"language",value:localizationStore.selectedLocale}],presentmentCountryCode:localizationStore.selectedCountryCode,skipPaymentIntent:stripeStore.skipPaymentIntent,varianceTestInput:r};return o};var stripeStoreGetPaymentIntent=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n;return __generator(this,(function(i){switch(i.label){case 0:if(!storageStore.checkoutSessionId){void sendErrorLog({endpoint:"Error creating payment intent",errors:["No checkout session id found when retrieving payment intent"],metadata:{allLogs:allLogs,cartId:window.Zonos.cartId}});cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2]}return[4,handleFetch("/api/zonos-elements/create-payment-intent",{body:{checkoutSessionId:storageStore.checkoutSessionId},method:"POST"})];case 1:t=i.sent(),r=t.errors,o=t.json;n=(e=o===null||o===void 0?void 0:o.checkoutSessionPaymentIntentCreate)===null||e===void 0?void 0:e.clientSecret;if(r.length||!n){logError("Error occurs when getting payment intent",JSON.stringify(r,null,2));void sendErrorLog({endpoint:"Error creating payment intent",errors:r.map((function(e){return e.message})),metadata:{allLogs:allLogs,cartId:window.Zonos.cartId,checkoutSessionId:storageStore.checkoutSessionId,clientSecret:n}});cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2]}cartStoreSetCheckoutSession(o.checkoutSessionPaymentIntentCreate);return[2]}}))}))};var stripeStoreInitCheckoutSession=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r,o,n,i,a,s;return __generator(this,(function(d){switch(d.label){case 0:if(!localizationStore.targetCurrency){logError("Failed to create checkout session - missing localizationStore.targetCurrency");return[2,false]}stripeStore.isFetchingSession=true;r=getCheckoutSessionBody();log("Checkout session body","info",r);return[4,handleFetch("/api/zonos-elements/create-checkout-session",{body:r,method:"POST"})];case 1:o=d.sent(),n=o.errors,i=o.json;stripeStore.isFetchingSession=false;if(n.length||!i){a=(e=n.find((function(e){return e.message})))===null||e===void 0?void 0:e.message;if(Array.isArray(a)&&a.some((function(e){return e.message==="Cart is expired."}))){throw new Error("Cart is expired.")}logError("Error occurred when creating checkout session",JSON.stringify(n,null,2));return[2,false]}s=i.checkoutSessionCreate;cartStoreSetCheckoutSession(s);cartStoreApplySubtotals({method:((t=s.landedCost)===null||t===void 0?void 0:t.method)||"DDP",subtotals:s.subtotals});log("Exchange rate updated for cart items (checkout session create)","info",cartStore.exchangeRate);log("done-init-checkout-session");return[2,true]}}))}))};var stripeStoreUpdateCheckoutSessionBaseCurrency=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,t,r;return __generator(this,(function(o){switch(o.label){case 0:e=storageStore.checkoutSessionId;if(!e){logError("Failed to update checkout session base currency");return[2,false]}if(zonosStore.checkoutSettings.allowedSettlementCurrencies==="LOCAL"){log('allowedSettlementCurrencies: "LOCAL". Skip updating checkout session base currency');return[2,true]}return[4,handleFetch("/api/zonos-elements/update-checkout-session-base-currency",{body:{checkoutSessionId:e,currencyCode:stripeStore.checkoutSettlementCurrency},method:"POST"})];case 1:t=o.sent().json;r=t===null||t===void 0?void 0:t.checkoutSessionBaseCurrencyUpdate.subtotals.presentmentCurrencyCode;if(!t||r!==stripeStore.checkoutSettlementCurrency){logError("Failed to update checkout session base currency");return[2,false]}log('Updated checkout session to settlement currency "'.concat(r,'".'));return[2,true]}}))}))};var stripeStoreUpdateCheckoutSession=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n;var i=e.adjustmentsAmount,a=e.cartId,s=e.currency,d=e.id,c=e.itemsAmount,l=e.landedCostId,u=e.presentmentCountryCode;return __generator(this,(function(e){switch(e.label){case 0:t=storageStore.enabledVariantTestKeys||[];return[4,handleFetch("/api/zonos-elements/update-checkout-session",{body:{adjustmentsAmount:i,billToPartyId:stripeStore.partyBillingId,cartId:a,currency:s,customerAuthenticationToken:cartStore.customerAuthenticationToken||undefined,id:d,itemsAmount:c,landedCostId:l,metadata:[{key:"language",value:localizationStore.selectedLocale}],presentmentCountryCode:u,shipToPartyId:stripeStore.partyShippingId,skipPaymentIntent:stripeStore.skipPaymentIntent,varianceTestInput:t},method:"POST"})];case 1:r=e.sent(),o=r.errors,n=r.json;if(o.length||!n){logError("Error occurs when updating checkout session",JSON.stringify(o,null,2));return[2,{errors:o,json:n}]}return[2,{errors:[],json:n}]}}))}))};var buildTranslatedAddress=function(e){var t,r,o,n,i,a;var s=e.currentAddress,d=e.translatedAddressResult;var c={};if(!d){return c}var l=d.city,u=d.line1,v=d.line2,S=d.name,p=d.postal_code,f=d.state;if(s.city&&l){c.city=(t={},t[s.city]=l,t)}if(s.line1&&u){c.line1=(r={},r[s.line1]=u,r)}if(s.line2&&v){c.line2=(o={},o[s.line2]=v,o)}if(s.postal_code&&p){c.postal_code=(n={},n[s.postal_code]=p,n)}if(s.state&&f){c.state=(i={},i[s.state]=f,i)}if(s.name&&S){c.name=(a={},a[s.name]=S,a)}return c};var stripeStoreTranslateAddressToLatin=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a,s,d,c,l,u;var v=e.addressInvalidCharactersList,S=e.billingAddressInvalidCharactersList;return __generator(this,(function(e){switch(e.label){case 0:i=buildTranslateRequest({addressInvalidCharactersList:v,billingAddressInvalidCharactersList:S,stripeAddressEventData:stripeStore.stripeAddressEventData,stripeBillingAddressEventData:stripeStore.stripeBillingAddressEventData,stripeShippingSameAsBilling:stripeStore.stripeShippingSameAsBilling});if(!i){stripeStore.translatedAddress={address:{},billingAddress:{}};return[2]}a=checkIsAddressOutdatedForValidation();if(!a){return[2]}return[4,handleFetch("/api/zonos-elements/validate-address",{body:i,method:"POST"})];case 1:s=e.sent(),d=s.errors,c=s.json;if(d.length||!c){logError("Error occurs when translating address to latin",JSON.stringify(d,null,2));stripeStore.translatedAddress={address:{},billingAddress:{}};return[2]}stripeStore.stripeAddressUsedWhenValidatingAddress=stripeStore.stripeAddressEventData;stripeStore.stripeBillingAddressUsedWhenValidatingAddress=stripeStore.stripeBillingAddressEventData;l=(t=stripeStore.stripeAddressEventData)===null||t===void 0?void 0:t.value.address;u=(r=stripeStore.stripeBillingAddressEventData)===null||r===void 0?void 0:r.value.address;stripeStore.translatedAddress={address:l?buildTranslatedAddress({currentAddress:Object.assign(Object.assign({},l),{name:(o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.name}),translatedAddressResult:c.address||null}):{},billingAddress:!stripeStore.stripeShippingSameAsBilling?buildTranslatedAddress({currentAddress:Object.assign(Object.assign({},u),{name:(n=stripeStore.stripeBillingAddressEventData)===null||n===void 0?void 0:n.value.name}),translatedAddressResult:c.billingAddress||null}):{}};return[2]}}))}))};stripeStoreOnChange("clientSecret",(function(e){if(e&&stripeStore.stripe){sessionStorage.setItem("zonos--client-secret",e)}if(!e){sessionStorage.removeItem("zonos--client-secret")}}));var _o=createStore((function(){return{addressFormRenderType:"stripe",adjustmentTotal:0,adjustments:[],checkoutSession:null,checkoutSessionTimeoutShow:false,checkoutTimeoutInterval:null,currency:"USD",customQuotingError:null,customerAuthenticationToken:null,displayBaseCurrency:false,dutiesTaxesFees:null,dutiesTaxesFeesEstimate:null,error:null,exchangeRate:null,externalConfirmationPageURL:null,inventoryCheckErrorMessage:null,isSelectedShippingAboveDeminimis:false,isSelectedShippingGuarantee:false,isStagingMode:getIsStagingMode(),items:[],landedCostData:null,landedCostMethod:"DDP",partiesData:[],promoCode:sessionStorage.getItem("zonos--promo-code")||"",promoCodeApplied:!!sessionStorage.getItem("zonos--promo-code"),promoCodeError:false,restrictedItems:[],selectedLandedCost:null,selectedShippingOption:null,selectedShippingOptionExpectedDate:"",selectedShippingOptionTransitTime:"",shipping:0,shippingData:null,shouldHideDiscountInput:false,step:"customer-info",subtotal:0,tabItems:{"customer-info":{index:1,isDone:false,label:"Customer",value:"customer-info"},shipping:{index:2,isDone:false,label:"Shipping",value:"shipping"},payment:{index:3,isDone:false,label:"Payment",value:"payment"}},total:0}})),cartStoreOnChange=_o.onChange,reset=_o.reset,cartStore=_o.state;var getTransitUnit=function(e){switch(e){case"DAYS":return translate("days");case"WEEKS":return translate("weeks");case"BUSINESS_DAYS":default:return translate("business days")}};var cartStoreGetShippingTransitInfo=function(e){var t;var r=(t=e.shippingProfile)===null||t===void 0?void 0:t.transitTime;if(!(r===null||r===void 0?void 0:r.min)||!(r===null||r===void 0?void 0:r.max)||!(r===null||r===void 0?void 0:r.type)){return null}return{maxTransit:r.max,minTransit:r.min,unit:getTransitUnit(r.type)}};var getMatchItem=function(e){var t=e.item1,r=e.item2;if(!t||!r){return false}return r.sku&&t.sku&&t.sku===r.sku||r.description&&t.description&&t.description===r.description||t.name&&r.name&&t.name===r.name};var cartStoreCheckItemRestrictions=function(e){log("Checking item restrictions");var t=e.map((function(e){if(!e.restriction){return null}var t=e.restriction;var r=cartStore.items.find((function(t){return getMatchItem({item1:t,item2:e})}));return Object.assign(Object.assign({matchedItem:r},e),{restriction:t})})).filter(Boolean);cartStore.restrictedItems=t;cartStore.items=cartStore.items.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:!!t.find((function(t){return getMatchItem({item1:t,item2:e})}))})}));return{cartItems:cartStore.items,restrictedItems:t}};var cartStoreReset=function(){storageStore.checkoutSessionId=null;reset()};var cartStoreUpdateToErrorState=function(e){var t=e.messages,r=e.title;cartStoreReset();stripeStoreReset();cartStore.step="error";cartStore.error={messages:t,title:r}};var cartStoreApplySubtotals=function(e){var t=e.dutiesTaxesFeesEstimate,r=e.method,o=e.subtotals;cartStore.exchangeRate=o.exchangeRate;cartStore.adjustmentTotal=o.adjustments;cartStore.dutiesTaxesFees=r==="DAP"?null:o.landedCostTotal;cartStore.subtotal=o.items;cartStore.total=o.total;cartStore.currency=o.presentmentCurrencyCode;cartStore.dutiesTaxesFeesEstimate=t||null};var cartStoreHasOneEligibleItem=function(){var e=cartStore.items.filter((function(e){return e.amount>0}));return!!e.find((function(e){return!e.isRestricted}))};var cartStoreSetCheckoutSession=function(e){var t,r,o,n,i;stripeStore.clientSecret=e.clientSecret;stripeStore.stripeCustomerSessionClientSecret=e.customerSessionClientSecret;stripeStore.customerProfile=e.customerProfile;cartStore.checkoutSession=e;if(!e.id){void sendErrorLog({endpoint:"cartStoreSetCheckoutSession",errors:["Missing checkout session id in checkout session"],metadata:{allLogs:allLogs,checkoutSession:e}})}if(e.id){storageStore.checkoutSessionId=e.id}var a=filterValidTests(e.varianceTestResults||[]);storageStoreSetEnabledVariantTestKeys(a);var s=((o=(r=(t=cartStore.checkoutSession)===null||t===void 0?void 0:t.metadata)===null||r===void 0?void 0:r.find((function(e){return(e===null||e===void 0?void 0:e.key)==="externalConfirmationPageURL"})))===null||o===void 0?void 0:o.value)||((i=(n=window.Zonos.cartData)===null||n===void 0?void 0:n.metadata.find((function(e){return(e===null||e===void 0?void 0:e.key)==="externalConfirmationPageURL"})))===null||i===void 0?void 0:i.value)||null;if(s){log("Found externalConfirmationPageURL: ".concat(s));cartStore.externalConfirmationPageURL=s}};var cartStoreReCalculateTotal=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n,i,a;var s=e.adjustmentsAmount,d=e.cartId,c=e.currency,l=e.dutiesTaxesFeesEstimate,u=e.itemsAmount,v=e.landedCostId,S=e.shouldInitSessionOnFailure;return __generator(this,(function(e){switch(e.label){case 0:if(v&&cartStore.selectedLandedCost){r=cartStore.selectedLandedCost.subtotals;cartStoreApplySubtotals({dutiesTaxesFeesEstimate:l,method:cartStore.landedCostMethod,subtotals:r});log("Exchange rate updated for cart items (landed cost subtotal)","info",cartStore.exchangeRate)}if(!storageStore.checkoutSessionId){log("Could not update cart total without checkout session id","info");return[2,false]}return[4,stripeStoreUpdateCheckoutSession({adjustmentsAmount:s,billToPartyId:stripeStore.partyBillingId,cartId:d,currency:c,id:storageStore.checkoutSessionId,itemsAmount:u,landedCostId:v,presentmentCountryCode:localizationStore.selectedCountryCode,shipToPartyId:stripeStore.partyShippingId,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:o=e.sent(),n=o.errors,i=o.json;if(!(n.length>0||!i))return[3,4];logError("Error occurs when updating checkout session.");if(!S)return[3,3];log("Initiating checkout session on failure","info");return[4,stripeStoreInitCheckoutSession()];case 2:a=e.sent();log("stripeStoreInitCheckoutSession: ".concat(a));if(!a){cartStoreUpdateToErrorState({messages:[translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists")],title:translate("Error creating Checkout")});return[2,false]}return[2,true];case 3:return[2,false];case 4:if(!v){cartStoreApplySubtotals({method:((t=i.checkoutSessionUpdate.landedCost)===null||t===void 0?void 0:t.method)||"DDP",subtotals:i.checkoutSessionUpdate.subtotals});log("Exchange rate updated for cart items (checkout session update)","info",cartStore.exchangeRate)}cartStoreSetCheckoutSession(i.checkoutSessionUpdate);return[2,true]}}))}))};var cartStoreGetMethod=function(e){var t,r,o;if(e.method==="DAP"&&((r=(t=zonosStore.genericSettings)===null||t===void 0?void 0:t.domesticCountries)===null||r===void 0?void 0:r.includes(((o=stripeStore.stripeAddressEventData)===null||o===void 0?void 0:o.value.address.country)||"US"))){return"DDP"}if(e.method==="DAP"&&e.remittance.length&&e.landedCostGuaranteeCode==="ZONOS"){return"DDP"}return e.method};var cartStoreUpdateSelectedShippingOption=function(e,t){return __awaiter(void 0,void 0,void 0,(function(){var r,o,n,i,a,s,d,c,l,u,v,S,p,f,h,m,g,y,w,C,b,A,O,_;return __generator(this,(function(k){switch(k.label){case 0:cartStore.selectedShippingOption=e;S=cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);if(S){p=S.maxTransit,f=S.minTransit,h=S.unit;cartStore.selectedShippingOptionTransitTime="".concat(f,"-").concat(p," ").concat(h)}else{cartStore.selectedShippingOptionTransitTime=""}m=(r=cartStore.landedCostData)===null||r===void 0?void 0:r.find((function(e){return e.landedCostId===t}));cartStore.selectedLandedCost=m||null;if(!m){return[2,false]}g=((o=m.landedCost.amountSubtotals)===null||o===void 0?void 0:o.landedCostTotal)||0;y=m.subtotals.exchangeRate.rate;w=g*y;if(w){log("DAP quote, using estimate: ".concat(w),"info")}cartStore.landedCostMethod=cartStoreGetMethod(m.landedCost);cartStore.shipping=m.subtotals.shipping;C=((n=m===null||m===void 0?void 0:m.landedCost)===null||n===void 0?void 0:n.landedCostGuaranteeCode)==="ZONOS";b=!!((a=(i=m===null||m===void 0?void 0:m.landedCost)===null||i===void 0?void 0:i.deMinimis)===null||a===void 0?void 0:a.find((function(e){return["DUTY","TAX"].includes(e.type)&&e.threshold==="ABOVE"})));cartStore.isSelectedShippingAboveDeminimis=b;cartStore.isSelectedShippingGuarantee=C;return[4,cartStoreReCalculateTotal({adjustmentsAmount:cartStore.adjustmentTotal,billToPartyId:stripeStore.partyBillingId,cartId:window.Zonos.cartId,dutiesTaxesFeesEstimate:w,landedCostId:(s=m.landedCost)===null||s===void 0?void 0:s.id,shipToPartyId:stripeStore.partyShippingId,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:A=k.sent();O=(d=cartStore.items.find(Boolean))===null||d===void 0?void 0:d.currencyCode;_=((c=stripeStore.stripeAddressEventData)===null||c===void 0?void 0:c.value.address.country)||"US";stripeStore.shouldRenderPayInUsdButton=O==="USD"&&zonosStore.checkoutSettings.allowedSettlementCurrencies==="LOCAL_AND_USD"&&((l=cartStore.checkoutSession)===null||l===void 0?void 0:l.subtotals.presentmentCurrencyCode)!=="USD"&&!!((v=(u=zonosStore.genericSettings)===null||u===void 0?void 0:u.usdSettlementCountryEnabled)===null||v===void 0?void 0:v.includes(_));return[2,A]}}))}))};var cartStoreStartCheckoutInterval=function(e){var t=e.isPreview,r=e.sessionTimeout;if(t){return}var o=new URLSearchParams(window.location.search).get("zonosCheckoutTimeout");var n=o&&!isNaN(parseInt(o,10))?parseInt(o,10):r;log("==START CHECKOUT TIMEOUT - ".concat(n,"=="));cartStore.checkoutTimeoutInterval=setTimeout((function(){cartStore.checkoutSessionTimeoutShow=true}),n)};var cartStoreClearCheckoutInterval=function(){if(cartStore.checkoutTimeoutInterval){clearTimeout(cartStore.checkoutTimeoutInterval);cartStore.checkoutTimeoutInterval=null}};var getCartItemToUse=function(e){return e.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:false})}))};var cartStoreResetCartItems=function(){cartStore.items=cartStore.items.map((function(e){return Object.assign(Object.assign({},e),{isRestricted:false})}));cartStore.restrictedItems=[]};var cartStoreUpdateItems=function(e){return __awaiter(void 0,[e],void 0,(function(e){var t,r,o,n;var i=e.adjustments,a=e.cartItems;return __generator(this,(function(e){switch(e.label){case 0:cartStore.adjustments=i;cartStore.items=getCartItemToUse(a);r=(t=a.find(Boolean))===null||t===void 0?void 0:t.currencyCode;o=a.reduce((function(e,t){return e+t.amount*t.quantity}),0);n=i.reduce((function(e,t){return e+t.amount}),0);if(!r||!o){return[2]}cartStore.currency=r;stripeStore.isFetchingSession=true;return[4,cartStoreReCalculateTotal({adjustmentsAmount:n,billToPartyId:stripeStore.partyBillingId,cartId:window.Zonos.cartId,currency:r,dutiesTaxesFeesEstimate:0,itemsAmount:o,shipToPartyId:stripeStore.partyShippingId,shouldInitSessionOnFailure:true,varianceTestInput:storageStore.enabledVariantTestKeys||[]})];case 1:e.sent();stripeStore.isFetchingSession=false;return[2]}}))}))};var cartStoreResetSelectedShippingOption=function(){cartStore.selectedShippingOption=null;cartStore.isSelectedShippingAboveDeminimis=false;cartStore.isSelectedShippingGuarantee=false;cartStore.selectedShippingOptionTransitTime="";cartStore.dutiesTaxesFees=0;cartStore.dutiesTaxesFeesEstimate=0;cartStore.shipping=0;cartStore.total=cartStore.subtotal};var cartStorePreviousStep=function(){if(cartStore.step==="shipping"){cartStore.step="customer-info";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})})}else if(cartStore.step==="payment"){cartStore.step="shipping";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})})}else if(cartStore.step==="finish"){cartStore.step="payment";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{payment:Object.assign(Object.assign({},cartStore.tabItems.payment),{isDone:false})})}};var cartStoreNextStep=function(){if(cartStore.step==="customer-info"){cartStore.step="shipping";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems["customer-info"]),{isDone:true})})}else if(cartStore.step==="shipping"){cartStore.step="payment";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:true})})}else if(cartStore.step==="payment"){cartStore.step="finish"}};var cartStoreResetTabItems=function(){cartStore.step="customer-info";cartStore.tabItems=Object.assign(Object.assign({},cartStore.tabItems),{"customer-info":Object.assign(Object.assign({},cartStore.tabItems["customer-info"]),{isDone:false}),payment:Object.assign(Object.assign({},cartStore.tabItems.payment),{isDone:false}),shipping:Object.assign(Object.assign({},cartStore.tabItems.shipping),{isDone:false})});cartStoreResetSelectedShippingOption()};export{cartStoreHasOneEligibleItem as A,stripeStoreApplyPromoCode as B,stripeStoreRemovePromoCode as C,stripeStoreResetPromoCode as D,stripeStoreMessageBasedOnStatus as E,stripeStoreTranslateAddressToLatin as F,extractName as G,cartStoreOnChange as H,stripeStoreAsyncAddressUpdate as I,cartStoreUpdateSelectedShippingOption as J,cartStoreGetShippingTransitInfo as K,cartStoreGetMethod as L,sortServiceLevelOptionsByAmount as M,stripeStoreCleanupDomesticShippingSession as a,stripeStoreSaveDomesticShippingSession as b,stripeStore as c,stripeStoreRetrievePayment as d,cartStore as e,cartStoreUpdateItems as f,cartStoreReset as g,cartStoreResetTabItems as h,initStripeElements as i,cartStoreClearCheckoutInterval as j,stripeStoreInitCheckoutSession as k,stripeStoreGetPaymentIntent as l,cartStoreStartCheckoutInterval as m,getCheckoutSessionBody as n,cartStoreUpdateToErrorState as o,cartStoreSetCheckoutSession as p,stripeStorePrefetchLandedCost as q,cartStoreNextStep as r,stripeStoreGetDomesticShippingSession as s,trackConversionEvent as t,stripeStoreUpdateCheckoutSessionBaseCurrency as u,stripeStoreHandleInventoryCheck as v,stripeStoreConfirmPayment as w,stripeStoreHandleInventoryRefund as x,stripeStoreReset as y,validateCheckoutSession as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __awaiter=this&&this.__awaiter||function(e,n,r,o){function t(e){return e instanceof r?e:new r((function(n){n(e)}))}return new(r||(r=Promise))((function(r,a){function i(e){try{u(o.next(e))}catch(e){a(e)}}function s(e){try{u(o["throw"](e))}catch(e){a(e)}}function u(e){e.done?r(e.value):t(e.value).then(i,s)}u((o=o.apply(e,n||[])).next())}))};var __generator=this&&this.__generator||function(e,n){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},o,t,a,i;return i={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(e){return function(n){return u([e,n])}}function u(s){if(o)throw new TypeError("Generator is already executing.");while(i&&(i=0,s[0]&&(r=0)),r)try{if(o=1,t&&(a=s[0]&2?t["return"]:s[0]?t["throw"]||((a=t["return"])&&a.call(t),0):t.next)&&!(a=a.call(t,s[1])).done)return a;if(t=0,a)s=[s[0]&2,a.value];switch(s[0]){case 0:case 1:a=s;break;case 4:r.label++;return{value:s[1],done:false};case 5:r.label++;t=s[1];s=[0];continue;case 7:s=r.ops.pop();r.trys.pop();continue;default:if(!(a=r.trys,a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){r.label=s[1];break}if(s[0]===6&&r.label<a[1]){r.label=a[1];a=s;break}if(a&&r.label<a[2]){r.label=a[2];r.ops.push(s);break}if(a[2])r.ops.pop();r.trys.pop();continue}s=n.call(e,r)}catch(e){s=[6,e];t=0}finally{o=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,n,r){if(r||arguments.length===2)for(var o=0,t=n.length,a;o<t;o++){if(a||!(o in n)){if(!a)a=Array.prototype.slice.call(n,0,o);a[o]=n[o]}}return e.concat(a||Array.prototype.slice.call(n))};var startTime=performance.now();var allLogs=[];var getElapsedTime=function(){var e=performance.now()-startTime;var n=e>1e3?"".concat((e/1e3).toFixed(2),"s"):"".concat(e.toFixed(2),"ms");return{elapsedTime:e,elapsedTimePretty:n}};var prepInfo=function(e){if(typeof e==="string"){return e}try{var n=JSON.stringify(e);return n}catch(n){if(e&&typeof e.toString==="function"){var r=e.toString();return r}return"Unable to stringify info"}};var log=function(e,n){var r=[];for(var o=2;o<arguments.length;o++){r[o-2]=arguments[o]}var t,a;var i=getElapsedTime().elapsedTimePretty;var s=__spreadArray(["(".concat(i,")")],r,true);var u=s.map(prepInfo).join(" ");allLogs.push([n,e,u].filter(Boolean).join(" "));var l=!!((t=window.Zonos)===null||t===void 0?void 0:t.debug)||!!window.location.search.match(/\?.*(&*)zonosDebug=1/);if(!l){return}var d=document.querySelector("iframe#zonos---debug-logging-iframe");if(!d){d=document.createElement("iframe");d.id="zonos---debug-logging-iframe";d.style.display="none";d.style.opacity="0";d.style.position="absolute";d.style.top="-9999px";d.style.left="-9999px";d.style.width="1px";d.style.height="1px";d.style.border="none";d.style.overflow="hidden";d.style.visibility="hidden";document.body.appendChild(d)}var c=((a=d.contentWindow)===null||a===void 0?void 0:a.window.console)||window.console;switch(n){case"warn":c.warn.apply(c,__spreadArray([e],s,false));break;case"info":c.info.apply(c,__spreadArray([e],s,false));break;case"error":c.error.apply(c,__spreadArray([e],s,false));break;default:c.groupCollapsed.apply(c,__spreadArray([e],s,false));c.trace();c.groupEnd();break}};var logError=function(e){var n=[];for(var r=1;r<arguments.length;r++){n[r-1]=arguments[r]}log.apply(void 0,__spreadArray([e,"error"],n,false))};var getIsStagingMode=function(){return window.location.search.includes("zonosStagingMode=1")};var getIsTestMode=function(){var e;return((e=window.Zonos.zonosApiKey)===null||e===void 0?void 0:e.includes("test"))||window.location.search.includes("zonosTestMode=1")};var fallbackApiType=["vercel","cloudflare"];var MAIN_BASE_API_TYPE=fallbackApiType[0];var fallbackApiList={cloudflare:"https://route.elements.zonos.com",vercel:"https://route.js.zonos.com"};var MAIN_BASE_API=fallbackApiList[MAIN_BASE_API_TYPE];var getNextFallbackApiType=function(e){if(e===void 0){e=MAIN_BASE_API_TYPE}var n=fallbackApiType.indexOf(e);var r=fallbackApiType[n+1];if(!r){return null}return r};var jsonParse=function(e){if(typeof e==="string"){try{var n=JSON.parse(e);return n}catch(e){return null}}return null};var checkoutBreakpoint=890;var isCheckoutMobile=function(e){return e||window.innerWidth<checkoutBreakpoint};var getNavigatorConnection=function(){var e="connection"in window.navigator?window.navigator.connection:null;var n="mozConnection"in window.navigator?window.navigator.mozConnection:null;var r="webkitConnection"in window.navigator?window.navigator.webkitConnection:null;var o=e||n||r;return o};var getAdditionalLogMetadata=function(){var e="userAgentData"in window.navigator?window.navigator.userAgentData:null;var n=getNavigatorConnection();return{connectionDownlink:n===null||n===void 0?void 0:n.downlink,connectionEffectiveType:n===null||n===void 0?void 0:n.effectiveType,connectionRtt:n===null||n===void 0?void 0:n.rtt,connectionSaveData:n===null||n===void 0?void 0:n.saveData,isHostedCheckout:window.Zonos.isLegacyCheckout,screenHeight:window.screen.height,screenWidth:window.innerWidth,userAgent:e&&e.brands.length>0?e:window.navigator.userAgent}};var blackListPaths=["/api/zonos-elements/log-script-load","/api/zonos-elements/log-bulk-load-data"];var prepLoadTimeApiLog=function(e){var n=e.apiPath,r=e.apiType,o=e.loadTimeInternal,t=e.loadTimeTotal;if(blackListPaths.includes(n)){return}var a=t-o;if(a<0){return}var i=n.split("?")[0]||n;var s=getAdditionalLogMetadata();var u=typeof s.userAgent==="object"&&s.userAgent.mobile;var l={apiType:r,connectionType:s.connectionEffectiveType,href:i,isHostedCheckout:window.Zonos.isLegacyCheckout,isMobile:isCheckoutMobile(u),loadTimeBrowserApi:a,loadTimeInternal:o,loadTimeTotal:t,metadata:Object.assign({},s),screenHeight:s.screenHeight,screenWidth:s.screenWidth,userAgent:typeof s.userAgent==="string"?s.userAgent:s.userAgent["brands"].map((function(e){return e.brand})).filter((function(e){return!/Not.*A.*Brand.*/.test(e)})).join(",")};window.Zonos.loadTimeApiInfoList.push(l)};var postReleaseReportingDuration=1*3600*1e3;var sendErrorLog=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a;var i=e.endpoint,s=e.errors,u=e.metadata,l=e.shouldPostReleaseErrorReporting;return __generator(this,(function(e){log("sendErrorLog","warn",i,u,s);if(l){n=Number(window.Zonos.releaseDate);r=(new Date).getTime();if(r-n>postReleaseReportingDuration){return[2]}}o="userAgentData"in window.navigator?window.navigator.userAgentData:null;t={endpoint:i,errors:s,href:window.location.href,metadata:Object.assign({appVersion:window.Zonos.version,domain:window.Zonos.domain,publicCredential:window.Zonos.zonosApiKey,userAgent:o&&o.brands.length>0?o:window.navigator.userAgent},u)};try{void fetch("".concat(MAIN_BASE_API,"/api/zonos-elements/log-error"),{body:JSON.stringify(t),headers:{"Zonos-Referer":window.location.hostname},method:"POST"})}catch(e){a=getNextFallbackApiType();if(!a){return[2]}void fetch("".concat(fallbackApiList[a],"/api/zonos-elements/log-error"),{body:JSON.stringify(t),method:"POST"})}return[2]}))}))};var __rest=undefined&&undefined.__rest||function(e,n){var r={};for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&n.indexOf(o)<0)r[o]=e[o];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var t=0,o=Object.getOwnPropertySymbols(e);t<o.length;t++){if(n.indexOf(o[t])<0&&Object.prototype.propertyIsEnumerable.call(e,o[t]))r[o[t]]=e[o[t]]}return r};var getResponseBody=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o;var t=e.response,a=e.shouldLog,i=a===void 0?true:a,s=e.shouldThrow,u=s===void 0?false:s;return __generator(this,(function(e){switch(e.label){case 0:e.trys.push([0,2,,3]);return[4,t.text()];case 1:n=e.sent();r=jsonParse(n);if(!r){throw new Error("Failed to parse content: ".concat(n))}return[2,r];case 2:o=e.sent();if(u){throw o}if(i){console.error(o)}return[2,null];case 3:return[2]}}))}))};var encodeString=function(e){try{var n=btoa(e).replace(/=/g,"");return n}catch(n){return e.replace(/[^A-Za-z0-9]/g,"").split("").reverse().join("")}};var handleRequest=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a,i,s,u,l,d,c,d,f,v,s,p,s;var w=e.basePathType,g=e.options,h=e.path;return __generator(this,(function(e){switch(e.label){case 0:r=window.Zonos.zonosQaUrlApi||fallbackApiList[w]||MAIN_BASE_API_TYPE;o=r+h;t=new URL(o);a=window.Zonos.cartId?"".concat(window.location.hostname,"-").concat(window.Zonos.cartId):window.location.hostname;t.searchParams.set("zToken",encodeString(a));e.label=1;case 1:e.trys.push([1,3,,4]);return[4,fetch(t.toString(),g)];case 2:n=e.sent();return[3,4];case 3:i=e.sent();if(i instanceof Error){return[2,{baseUrl:r,errors:[{message:i.message,type:"unknown"}],json:null,response:null,zonosMode:null}]}s="Failed to fetch";return[2,{baseUrl:r,errors:[{message:s,type:"unknown"}],json:null,response:null,zonosMode:null}];case 4:u=n.headers.get("Zonos-Mode");l=window.Zonos.zonosQaUrl;if(!window.Zonos.modeAlerted&&u&&l){window.Zonos.modeAlerted=true}if(!n.ok)return[3,6];return[4,getResponseBody({response:n})];case 5:d=e.sent();return[2,{baseUrl:r,errors:[],json:d,response:n,zonosMode:u}];case 6:c=n.status.toString();e.label=7;case 7:e.trys.push([7,9,,10]);return[4,getResponseBody({response:n,shouldThrow:true})];case 8:d=e.sent();if(d&&"errors"in d&&Array.isArray(d.errors)){f=d.errors;v=f.map((function(e){if(typeof e==="string"){return{message:e,type:c}}return e}));return[2,{baseUrl:r,errors:v,json:null,response:n,zonosMode:u}]}s=JSON.stringify(d);return[2,{baseUrl:r,errors:[{message:s,type:c}],json:null,response:n,zonosMode:u}];case 9:p=e.sent();s="Unknown error";return[2,{baseUrl:r,errors:[{message:"".concat(c,": ").concat(s),type:c}],json:null,response:null,zonosMode:u}];case 10:return[2]}}))}))};var handleRequestWithFallback=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a,i,s,u,l,d,c,f,v,p,w,g,h;var b=e.basePathType,y=e.options,_=e.path;return __generator(this,(function(e){switch(e.label){case 0:o=_.startsWith("/api/bigcommerce");t=o?"vercel":b;a=performance.now();return[4,handleRequest({basePathType:t,options:y,path:_})];case 1:i=e.sent(),s=i.errors,u=i.response,l=__rest(i,["errors","response"]);d=performance.now();c=d-a;log("".concat(_," (").concat(c.toFixed(2),"ms)"),"info");f=u===null||u===void 0?void 0:u.headers.get("Zonos-Duration");if((u===null||u===void 0?void 0:u.status)===200){prepLoadTimeApiLog({apiPath:_,apiType:t,loadTimeInternal:f?Number(f):0,loadTimeTotal:c})}v=getNextFallbackApiType(t);p=s.find((function(e){var n=e.type;return n==="unknown"}));w=s.find((function(e){var n=e.message;return typeof n==="string"&&(n.includes("signal is aborted")||n.includes("The operation was aborted")||n.includes("Fetch is aborted"))}));g=!!p||(u===null||u===void 0?void 0:u.status)===404||(u===null||u===void 0?void 0:u.status)===500;h=v&&g;if(g&&!w){void sendErrorLog({endpoint:fallbackApiList[t]+_,errors:s.map((function(e){var n=e.message;return"API: ".concat(n)})),metadata:{currentBasePath:t,nextFallbackApiType:v,requestHeaders:y===null||y===void 0?void 0:y.headers,requestPayload:jsonParse((n=y===null||y===void 0?void 0:y.body)===null||n===void 0?void 0:n.toString())||((r=y===null||y===void 0?void 0:y.body)===null||r===void 0?void 0:r.toString()),status:u===null||u===void 0?void 0:u.status,statusText:u===null||u===void 0?void 0:u.statusText},shouldPostReleaseErrorReporting:true})}if(h){log('=== "'.concat(_,'" failed to fetch, trying next fallback ').concat(v));return[2,handleRequestWithFallback({basePathType:v,options:y,path:_})]}return[2,Object.assign({errors:s,response:u},l)]}}))}))};var handleFetch=function(e,n){return __awaiter(void 0,void 0,void 0,(function(){var r,o,t,a,i,s;return __generator(this,(function(u){r=__rest(n||{},[]);o=r.body?JSON.stringify(r.body):undefined;t=r.method||"GET";a=Object.assign({"Content-Type":"application/json","Zonos-Is-BigCommerce":window.Zonos.isBigCommerce.toString(),"Zonos-Referer":window.location.hostname,"Zonos-Staging-Mode":getIsStagingMode()?"1":undefined,"Zonos-Test-Mode":getIsTestMode()?"1":undefined,"Zonos-Version":window.Zonos.version,credentialtoken:window.Zonos.zonosApiKey||"Empty credential token from zonos-elements"},r.headers);Object.keys(a).forEach((function(e){return a[e]===undefined&&delete a[e]}));i=Object.assign(Object.assign({},r),{body:t==="GET"?undefined:o,headers:a,method:t});s=new URLSearchParams(window.location.search).get("useFallbackApi");return[2,handleRequestWithFallback({basePathType:s||MAIN_BASE_API_TYPE,options:i,path:e})]}))}))};export{getIsStagingMode as a,logError as b,getElapsedTime as c,allLogs as d,getAdditionalLogMetadata as e,fallbackApiList as f,getIsTestMode as g,handleFetch as h,isCheckoutMobile as i,jsonParse as j,log as l,sendErrorLog as s};
|
|
1
|
+
var __awaiter=this&&this.__awaiter||function(e,n,r,o){function t(e){return e instanceof r?e:new r((function(n){n(e)}))}return new(r||(r=Promise))((function(r,a){function i(e){try{u(o.next(e))}catch(e){a(e)}}function s(e){try{u(o["throw"](e))}catch(e){a(e)}}function u(e){e.done?r(e.value):t(e.value).then(i,s)}u((o=o.apply(e,n||[])).next())}))};var __generator=this&&this.__generator||function(e,n){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},o,t,a,i;return i={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(i[Symbol.iterator]=function(){return this}),i;function s(e){return function(n){return u([e,n])}}function u(s){if(o)throw new TypeError("Generator is already executing.");while(i&&(i=0,s[0]&&(r=0)),r)try{if(o=1,t&&(a=s[0]&2?t["return"]:s[0]?t["throw"]||((a=t["return"])&&a.call(t),0):t.next)&&!(a=a.call(t,s[1])).done)return a;if(t=0,a)s=[s[0]&2,a.value];switch(s[0]){case 0:case 1:a=s;break;case 4:r.label++;return{value:s[1],done:false};case 5:r.label++;t=s[1];s=[0];continue;case 7:s=r.ops.pop();r.trys.pop();continue;default:if(!(a=r.trys,a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){r=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){r.label=s[1];break}if(s[0]===6&&r.label<a[1]){r.label=a[1];a=s;break}if(a&&r.label<a[2]){r.label=a[2];r.ops.push(s);break}if(a[2])r.ops.pop();r.trys.pop();continue}s=n.call(e,r)}catch(e){s=[6,e];t=0}finally{o=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,n,r){if(r||arguments.length===2)for(var o=0,t=n.length,a;o<t;o++){if(a||!(o in n)){if(!a)a=Array.prototype.slice.call(n,0,o);a[o]=n[o]}}return e.concat(a||Array.prototype.slice.call(n))};var startTime=performance.now();var allLogs=[];var getElapsedTime=function(){var e=performance.now()-startTime;var n=e>1e3?"".concat((e/1e3).toFixed(2),"s"):"".concat(e.toFixed(2),"ms");return{elapsedTime:e,elapsedTimePretty:n}};var prepInfo=function(e){if(typeof e==="string"){return e}try{var n=JSON.stringify(e);return n}catch(n){if(e&&typeof e.toString==="function"){var r=e.toString();return r}return"Unable to stringify info"}};var log=function(e,n){var r=[];for(var o=2;o<arguments.length;o++){r[o-2]=arguments[o]}var t,a;var i=getElapsedTime().elapsedTimePretty;var s=__spreadArray(["(".concat(i,")")],r,true);var u=s.map(prepInfo).join(" ");allLogs.push([n,e,u].filter(Boolean).join(" "));var l=!!((t=window.Zonos)===null||t===void 0?void 0:t.debug)||!!window.location.search.match(/\?.*(&*)zonosDebug=1/);if(!l){return}var d=document.querySelector("iframe#zonos---debug-logging-iframe");if(!d){d=document.createElement("iframe");d.id="zonos---debug-logging-iframe";d.style.display="none";d.style.opacity="0";d.style.position="absolute";d.style.top="-9999px";d.style.left="-9999px";d.style.width="1px";d.style.height="1px";d.style.border="none";d.style.overflow="hidden";d.style.visibility="hidden";document.body.appendChild(d)}var c=((a=d.contentWindow)===null||a===void 0?void 0:a.window.console)||window.console;switch(n){case"warn":c.warn.apply(c,__spreadArray([e],s,false));break;case"info":c.info.apply(c,__spreadArray([e],s,false));break;case"error":c.error.apply(c,__spreadArray([e],s,false));break;default:c.groupCollapsed.apply(c,__spreadArray([e],s,false));c.trace();c.groupEnd();break}};var logError=function(e){var n=[];for(var r=1;r<arguments.length;r++){n[r-1]=arguments[r]}log.apply(void 0,__spreadArray([e,"error"],n,false))};var getIsStagingMode=function(){return window.location.search.includes("zonosStagingMode=1")};var getIsTestMode=function(){var e;return((e=window.Zonos.zonosApiKey)===null||e===void 0?void 0:e.includes("test"))||window.location.search.includes("zonosTestMode=1")};var fallbackApiType=["cloudflare","vercel"];var MAIN_BASE_API_TYPE=fallbackApiType[0];var fallbackApiList={cloudflare:"https://route.elements.zonos.com",vercel:"https://route.js.zonos.com"};var MAIN_BASE_API=fallbackApiList[MAIN_BASE_API_TYPE];var getNextFallbackApiType=function(e){if(e===void 0){e=MAIN_BASE_API_TYPE}var n=fallbackApiType.indexOf(e);var r=fallbackApiType[n+1];if(!r){return null}return r};var jsonParse=function(e){if(typeof e==="string"){try{var n=JSON.parse(e);return n}catch(e){return null}}return null};var checkoutBreakpoint=890;var isCheckoutMobile=function(e){return e||window.innerWidth<checkoutBreakpoint};var getNavigatorConnection=function(){var e="connection"in window.navigator?window.navigator.connection:null;var n="mozConnection"in window.navigator?window.navigator.mozConnection:null;var r="webkitConnection"in window.navigator?window.navigator.webkitConnection:null;var o=e||n||r;return o};var getAdditionalLogMetadata=function(){var e="userAgentData"in window.navigator?window.navigator.userAgentData:null;var n=getNavigatorConnection();return{connectionDownlink:n===null||n===void 0?void 0:n.downlink,connectionEffectiveType:n===null||n===void 0?void 0:n.effectiveType,connectionRtt:n===null||n===void 0?void 0:n.rtt,connectionSaveData:n===null||n===void 0?void 0:n.saveData,isHostedCheckout:window.Zonos.isLegacyCheckout,screenHeight:window.screen.height,screenWidth:window.innerWidth,userAgent:e&&e.brands.length>0?e:window.navigator.userAgent}};var blackListPaths=["/api/zonos-elements/log-script-load","/api/zonos-elements/log-bulk-load-data"];var prepLoadTimeApiLog=function(e){var n=e.apiPath,r=e.apiType,o=e.loadTimeInternal,t=e.loadTimeTotal;if(blackListPaths.includes(n)){return}var a=t-o;if(a<0){return}var i=n.split("?")[0]||n;var s=getAdditionalLogMetadata();var u=typeof s.userAgent==="object"&&s.userAgent.mobile;var l={apiType:r,connectionType:s.connectionEffectiveType,href:i,isHostedCheckout:window.Zonos.isLegacyCheckout,isMobile:isCheckoutMobile(u),loadTimeBrowserApi:a,loadTimeInternal:o,loadTimeTotal:t,metadata:Object.assign({},s),screenHeight:s.screenHeight,screenWidth:s.screenWidth,userAgent:typeof s.userAgent==="string"?s.userAgent:s.userAgent["brands"].map((function(e){return e.brand})).filter((function(e){return!/Not.*A.*Brand.*/.test(e)})).join(",")};window.Zonos.loadTimeApiInfoList.push(l)};var postReleaseReportingDuration=1*3600*1e3;var sendErrorLog=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a;var i=e.endpoint,s=e.errors,u=e.metadata,l=e.shouldPostReleaseErrorReporting;return __generator(this,(function(e){log("sendErrorLog","warn",i,u,s);if(l){n=Number(window.Zonos.releaseDate);r=(new Date).getTime();if(r-n>postReleaseReportingDuration){return[2]}}o="userAgentData"in window.navigator?window.navigator.userAgentData:null;t={endpoint:i,errors:s,href:window.location.href,metadata:Object.assign({appVersion:window.Zonos.version,domain:window.Zonos.domain,publicCredential:window.Zonos.zonosApiKey,userAgent:o&&o.brands.length>0?o:window.navigator.userAgent},u)};try{void fetch("".concat(MAIN_BASE_API,"/api/zonos-elements/log-error"),{body:JSON.stringify(t),headers:{"Zonos-Referer":window.location.hostname},method:"POST"})}catch(e){a=getNextFallbackApiType();if(!a){return[2]}void fetch("".concat(fallbackApiList[a],"/api/zonos-elements/log-error"),{body:JSON.stringify(t),method:"POST"})}return[2]}))}))};var __rest=undefined&&undefined.__rest||function(e,n){var r={};for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)&&n.indexOf(o)<0)r[o]=e[o];if(e!=null&&typeof Object.getOwnPropertySymbols==="function")for(var t=0,o=Object.getOwnPropertySymbols(e);t<o.length;t++){if(n.indexOf(o[t])<0&&Object.prototype.propertyIsEnumerable.call(e,o[t]))r[o[t]]=e[o[t]]}return r};var getResponseBody=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o;var t=e.response,a=e.shouldLog,i=a===void 0?true:a,s=e.shouldThrow,u=s===void 0?false:s;return __generator(this,(function(e){switch(e.label){case 0:e.trys.push([0,2,,3]);return[4,t.text()];case 1:n=e.sent();r=jsonParse(n);if(!r){throw new Error("Failed to parse content: ".concat(n))}return[2,r];case 2:o=e.sent();if(u){throw o}if(i){console.error(o)}return[2,null];case 3:return[2]}}))}))};var encodeString=function(e){try{var n=btoa(e).replace(/=/g,"");return n}catch(n){return e.replace(/[^A-Za-z0-9]/g,"").split("").reverse().join("")}};var handleRequest=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a,i,s,u,l,d,c,d,f,v,s,p,s;var w=e.basePathType,g=e.options,h=e.path;return __generator(this,(function(e){switch(e.label){case 0:r=window.Zonos.zonosQaUrlApi||fallbackApiList[w]||MAIN_BASE_API_TYPE;o=r+h;t=new URL(o);a=window.Zonos.cartId?"".concat(window.location.hostname,"-").concat(window.Zonos.cartId):window.location.hostname;t.searchParams.set("zToken",encodeString(a));e.label=1;case 1:e.trys.push([1,3,,4]);return[4,fetch(t.toString(),g)];case 2:n=e.sent();return[3,4];case 3:i=e.sent();if(i instanceof Error){return[2,{baseUrl:r,errors:[{message:i.message,type:"unknown"}],json:null,response:null,zonosMode:null}]}s="Failed to fetch";return[2,{baseUrl:r,errors:[{message:s,type:"unknown"}],json:null,response:null,zonosMode:null}];case 4:u=n.headers.get("Zonos-Mode");l=window.Zonos.zonosQaUrl;if(!window.Zonos.modeAlerted&&u&&l){window.Zonos.modeAlerted=true}if(!n.ok)return[3,6];return[4,getResponseBody({response:n})];case 5:d=e.sent();return[2,{baseUrl:r,errors:[],json:d,response:n,zonosMode:u}];case 6:c=n.status.toString();e.label=7;case 7:e.trys.push([7,9,,10]);return[4,getResponseBody({response:n,shouldThrow:true})];case 8:d=e.sent();if(d&&"errors"in d&&Array.isArray(d.errors)){f=d.errors;v=f.map((function(e){if(typeof e==="string"){return{message:e,type:c}}return e}));return[2,{baseUrl:r,errors:v,json:null,response:n,zonosMode:u}]}s=JSON.stringify(d);return[2,{baseUrl:r,errors:[{message:s,type:c}],json:null,response:n,zonosMode:u}];case 9:p=e.sent();s="Unknown error";return[2,{baseUrl:r,errors:[{message:"".concat(c,": ").concat(s),type:c}],json:null,response:null,zonosMode:u}];case 10:return[2]}}))}))};var handleRequestWithFallback=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,r,o,t,a,i,s,u,l,d,c,f,v,p,w,g,h;var b=e.basePathType,y=e.options,_=e.path;return __generator(this,(function(e){switch(e.label){case 0:o=_.startsWith("/api/bigcommerce");t=o?"vercel":b;a=performance.now();return[4,handleRequest({basePathType:t,options:y,path:_})];case 1:i=e.sent(),s=i.errors,u=i.response,l=__rest(i,["errors","response"]);d=performance.now();c=d-a;log("".concat(_," (").concat(c.toFixed(2),"ms)"),"info");f=u===null||u===void 0?void 0:u.headers.get("Zonos-Duration");if((u===null||u===void 0?void 0:u.status)===200){prepLoadTimeApiLog({apiPath:_,apiType:t,loadTimeInternal:f?Number(f):0,loadTimeTotal:c})}v=getNextFallbackApiType(t);p=s.find((function(e){var n=e.type;return n==="unknown"}));w=s.find((function(e){var n=e.message;return typeof n==="string"&&(n.includes("signal is aborted")||n.includes("The operation was aborted")||n.includes("Fetch is aborted"))}));g=!!p||(u===null||u===void 0?void 0:u.status)===404||(u===null||u===void 0?void 0:u.status)===500;h=v&&g;if(g&&!w){void sendErrorLog({endpoint:fallbackApiList[t]+_,errors:s.map((function(e){var n=e.message;return"API: ".concat(n)})),metadata:{currentBasePath:t,nextFallbackApiType:v,requestHeaders:y===null||y===void 0?void 0:y.headers,requestPayload:jsonParse((n=y===null||y===void 0?void 0:y.body)===null||n===void 0?void 0:n.toString())||((r=y===null||y===void 0?void 0:y.body)===null||r===void 0?void 0:r.toString()),shouldCallFallback:h,status:u===null||u===void 0?void 0:u.status,statusText:u===null||u===void 0?void 0:u.statusText},shouldPostReleaseErrorReporting:true})}if(h){log('=== "'.concat(_,'" failed to fetch, trying next fallback ').concat(v));return[2,handleRequestWithFallback({basePathType:v,options:y,path:_})]}return[2,Object.assign({errors:s,response:u},l)]}}))}))};var handleFetch=function(e,n){return __awaiter(void 0,void 0,void 0,(function(){var r,o,t,a,i,s;return __generator(this,(function(u){r=__rest(n||{},[]);o=r.body?JSON.stringify(r.body):undefined;t=r.method||"GET";a=Object.assign({"Content-Type":"application/json","Zonos-Is-BigCommerce":window.Zonos.isBigCommerce.toString(),"Zonos-Referer":window.location.hostname,"Zonos-Staging-Mode":getIsStagingMode()?"1":undefined,"Zonos-Test-Mode":getIsTestMode()?"1":undefined,"Zonos-Version":window.Zonos.version,credentialtoken:window.Zonos.zonosApiKey||"Empty credential token from zonos-elements"},r.headers);Object.keys(a).forEach((function(e){return a[e]===undefined&&delete a[e]}));i=Object.assign(Object.assign({},r),{body:t==="GET"?undefined:o,headers:a,method:t});s=new URLSearchParams(window.location.search).get("useFallbackApi");return[2,handleRequestWithFallback({basePathType:s||MAIN_BASE_API_TYPE,options:i,path:e})]}))}))};export{getIsStagingMode as a,logError as b,getElapsedTime as c,allLogs as d,getAdditionalLogMetadata as e,fallbackApiList as f,getIsTestMode as g,handleFetch as h,isCheckoutMobile as i,jsonParse as j,log as l,sendErrorLog as s};
|
package/dist/esm-es5/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __awaiter=this&&this.__awaiter||function(e,n,t,o){function r(e){return e instanceof t?e:new t((function(n){n(e)}))}return new(t||(t=Promise))((function(t,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o["throw"](e))}catch(e){i(e)}}function c(e){e.done?t(e.value):r(e.value).then(a,s)}c((o=o.apply(e,n||[])).next())}))};var __generator=this&&this.__generator||function(e,n){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},o,r,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(e){return function(n){return c([e,n])}}function c(s){if(o)throw new TypeError("Generator is already executing.");while(a&&(a=0,s[0]&&(t=0)),t)try{if(o=1,r&&(i=s[0]&2?r["return"]:s[0]?r["throw"]||((i=r["return"])&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;if(r=0,i)s=[s[0]&2,i.value];switch(s[0]){case 0:case 1:i=s;break;case 4:t.label++;return{value:s[1],done:false};case 5:t.label++;r=s[1];s=[0];continue;case 7:s=t.ops.pop();t.trys.pop();continue;default:if(!(i=t.trys,i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1];i=s;break}if(i&&t.label<i[2]){t.label=i[2];t.ops.push(s);break}if(i[2])t.ops.pop();t.trys.pop();continue}s=n.call(e,t)}catch(e){s=[6,e];r=0}finally{o=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,n,t){if(t||arguments.length===2)for(var o=0,r=n.length,i;o<r;o++){if(i||!(o in n)){if(!i)i=Array.prototype.slice.call(n,0,o);i[o]=n[o]}}return e.concat(i||Array.prototype.slice.call(n))};import{c as createCustomEvent}from"./createCustomEvent-58159025.js";import{g as getGenericSettingsOverride,I as IframeService}from"./getGenericSettingsOverride-0bc3e118.js";import{g as getIsTestMode,a as getIsStagingMode,l as log,h as handleFetch,b as logError}from"./handleFetch-fa90f7f6.js";import{g as getAbandonedCartRenewTokenValue,_ as _getIsValidCartId,c as checkoutHiddenBtnSelector,a as checkoutHiddenInternationalBtnSelector}from"./CheckoutConfig-724d7bae.js";export{c as checkoutHiddenBtnSelector,a as checkoutHiddenInternationalBtnSelector,d as domesticRedirectedBtnSelector}from"./CheckoutConfig-724d7bae.js";export{a as availableTestKeys}from"./VarianceTest-fef2d958.js";export{c as countryRequireTaxId,e as euCountryCodes,s as shipToTaxIdLabels}from"./TaxId-50d72254.js";var checkIfLoadVersionDomain=function(e){var n=e.loadScriptSrc;if(!n){return{currentLoadScriptUrl:"",isForceLoadVersionDomain:false,isWhiteListed:false}}var t=["dev.elements.zonos.com","dev.assets-checkout.zonos.com",".js.zonos.com","zonos-elements-test-git","zonos-elements-git"];var o=["qa.js.zonos.com"];var r=new URL(n).origin;var i=t.some((function(e){return r.includes(e)}));var a=o.some((function(e){return r.includes(e)}));return{currentLoadScriptUrl:r,isForceLoadVersionDomain:a,isWhiteListed:i}};var fallbackList=["jsdelivr","cdnjs","unpkg","vercel"];var MAIN_LOAD_CDN_TYPE="jsdelivr";var getNextFallbackUrl=function(e){var n=fallbackList.indexOf(e);var t=fallbackList[n+1];return t||null};var getWithTestPublicCredential=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,n,t,o,r,i;return __generator(this,(function(a){switch(a.label){case 0:e=getIsTestMode();n=getIsStagingMode();if(!e&&!n||!window.Zonos.zonosApiKey){return[2,null]}log("[ZONOS - loadZonos] Attempt test public credential","info");if(!!window.Zonos.zonosApiKey.includes("credential_test")){log("[ZONOS - loadZonos] Test mode is enabled but the API key is already a test key","info");return[2,null]}return[4,handleFetch("/api/get-test-public-credential")];case 1:t=a.sent(),o=t.errors,r=t.json;if(o.length||!r){logError("[ZONOS - loadZonos] Failed to get test public credential. Keep using production key",o);return[2,null]}i=r.publicCredential;if(!i){logError("[ZONOS - loadZonos] No test public key credential. Keep using production key");return[2,null]}log("[ZONOS - loadZonos] Retrieve new test public token ".concat(i),"info");return[2,i]}}))}))};var extractZonosQaUrl=function(e){if(!e){return null}var n=new URL(e).searchParams;var t=n.get("zonosQaUrl");if(!t){return null}var o=/[^a-zA-Z0-9-_]+/.test(t);if(!!o){return null}return t};var getZonosQaUrl=function(){var e=window&&window.location.href.includes("forceLoadCdn");if(typeof window==="undefined"||e){return null}var n=extractZonosQaUrl(window.location.href);var t="https://v1.3.217.js.zonos.com";if(!n&&(t.includes("test.")||t.includes("test-"))){return t}if(!n&&["dev.demo.elements.zonos.com","dev.checkout.elements.zonos.com"].includes(window.location.hostname)){return"https://dev.elements.zonos.com"}if(!n){return null}if(n==="dev-elements"){return"https://dev.elements.zonos.com"}var o="preview.js.zonos.com";var r="https://".concat(n,".").concat(o);log("[ZONOS-WARNING] using '".concat(r,"' for loading elements script"),"warn");void fetch(r).then((function(){window.sessionStorage.removeItem("zonos--checkout-session-id");window.sessionStorage.removeItem("zonos--client-secret")})).catch((function(){alert("[ZONOS-WARNING] '".concat(r,"' IS NO LONGER AVAILABLE. REMOVING zonosQaUrl PARAM AND RELOADING THE PAGE"));var e=new URLSearchParams(window.location.search);e.delete("zonosQaUrl");var n=window.location.pathname;var t="".concat(n,"?").concat(e.toString());window.history.replaceState(window.history.state,"",t);window.location.reload();return null}));return r};var V3_URL="https://js.stripe.com/v3";var V3_URL_REGEX=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var EXISTING_SCRIPT_MESSAGE="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used";var zonosStripeFindScript=function(){var e=document.querySelectorAll('script[src^="'.concat(V3_URL,'"]'));for(var n=0;n<e.length;n++){var t=e[n];if(!t){continue}if(!V3_URL_REGEX.test(t.src)){continue}return t}return null};var stripePromise$1=null;var injectScript=function(e){var n=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"";var t=document.createElement("script");t.src="".concat(V3_URL).concat(n);var o=document.head||document.body;if(!o){logError("Expected document.body not to be null. Stripe.js requires a <body> element.");return null}o.appendChild(t);return t};var zonosStripeLoadScript=function(e){if(stripePromise$1!==null){return stripePromise$1}stripePromise$1=new Promise((function(n,t){if(typeof window==="undefined"||typeof document==="undefined"){n(null);return}if(window.Stripe&&e){console.warn(EXISTING_SCRIPT_MESSAGE)}if(window.Stripe){n(window.Stripe);return}try{var o=zonosStripeFindScript();if(o&&e){console.warn(EXISTING_SCRIPT_MESSAGE)}else if(!o){o=injectScript(e)}o===null||o===void 0?void 0:o.addEventListener("load",(function(){if(window.Stripe){n(window.Stripe)}else{t(new Error("Stripe.js not available"))}}));o===null||o===void 0?void 0:o.addEventListener("error",(function(){t(new Error("Failed to load Stripe.js"))}))}catch(e){t(e);return}}));return stripePromise$1};var registerWrapper=function(e,n){if(!e||!e._registerWrapper){return}e._registerWrapper({name:"stripe-js",startTime:n})};var initStripe=function(e,n,t){if(e===null){return null}var o=e.apply(undefined,n);registerWrapper(o,t);return o};var stripePromise=Promise.resolve().then((function(){return zonosStripeLoadScript(null)}));var loadCalled=false;stripePromise.catch((function(e){if(!loadCalled){console.warn(e)}}));var zonosLoadStripe=function(){var e=[];for(var n=0;n<arguments.length;n++){e[n]=arguments[n]}return __awaiter(void 0,void 0,void 0,(function(){var n;return __generator(this,(function(t){loadCalled=true;n=Date.now();return[2,stripePromise.then((function(t){return initStripe(t,e,n)}))]}))}))};var TEMP_CART_ID_QUERY_PARAM="tempCartUUID";var getCartIdFromQueryParam=function(){var e=new URLSearchParams(window.location.search);var n=e.get(TEMP_CART_ID_QUERY_PARAM);return n};var getCartInfoById=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,t,o,r,i,a,s,c,u;var d=e.cartId,l=e.retries;return __generator(this,(function(e){switch(e.label){case 0:n=getIsTestMode();t=getGenericSettingsOverride();o=getAbandonedCartRenewTokenValue()||undefined;r=new URLSearchParams;if(t.overrideShouldEnabledCustomAddress){r.set("overrideShouldEnabledCustomAddress",t.overrideShouldEnabledCustomAddress)}return[4,handleFetch("/api/zonos-elements/get-cart?".concat(r.toString()),{body:{isTestMode:n,renewCartExpirationToken:o,tempCartUUID:d},headers:{"Content-Type":"application/json"},method:"POST"})];case 1:i=e.sent(),a=i.errors,s=i.json,c=i.zonosMode;u=!s||a.length;if(!(u&&l))return[3,3];log("[ZONOS - loadZonos] temp cart not ready, retrying in 1 second","info",{retries:l});return[4,new Promise((function(e){return setTimeout(e,500)}))];case 2:e.sent();return[2,getCartInfoById({cartId:d,retries:l-1})];case 3:if(u){return[2,null]}return[2,Object.assign(Object.assign({},s),{zonosMode:c})]}}))}))};var setupCartDataWithSettings=function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t,o,r;return __generator(this,(function(i){switch(i.label){case 0:n=_getIsValidCartId(e),t=n.isDgsCartId,o=n.isLegacyCartId;if(!o&&!t){logError("[ZONOS - loadZonos] invalid cart id");return[2,null]}return[4,getCartInfoById({cartId:e,retries:5})];case 1:r=i.sent();log("[ZONOS - loadZonos] getting temp cart data","info",r);if(!r){logError("[ZONOS - loadZonos] Error getting temp cart data, stop checkout process.");return[2,null]}window.Zonos.storeId=r.cartData.storeId;window.Zonos.zonosApiKey=r.cartData.credentialToken;window.Zonos.zonosMode=r.zonosMode;return[2,{cartData:r.cartData,settings:r.settings,storeFavicon:r.storeFaviconUrl,storeId:r.cartData.storeId,storeLogo:r.storeLogoUrl,zonosApiKey:r.cartData.credentialToken}]}}))}))};var _a;var zonosLoadUrl=function(){if(typeof document==="undefined"){return null}var e=document.querySelector('script[src*="/zonos.js"]');var n=checkIfLoadVersionDomain({loadScriptSrc:e===null||e===void 0?void 0:e.src}),t=n.currentLoadScriptUrl,o=n.isWhiteListed;if(o){return t}return null}();var ZONOS_URL="https://v1.3.217.js.zonos.com";var JS_DELIVR_ZONOS_URL=zonosLoadUrl||"https://cdn.jsdelivr.net/npm/@zonos/elements@1.3.217";var UNPKG_ZONOS_URL="https://unpkg.com/@zonos/elements@1.3.217";var CDNJS_ZONOS_URL="https://cdnjs.cloudflare.com/ajax/libs/zonos-elements/1.3.217";var GOOGLE_FONT_URL="https://fonts.googleapis.com";var GOOGLE_FONT_REGEX=/^https:\/\/fonts\.googleapis\.com/;var Zonos=function(){function e(){}return e}();_a=Zonos;Zonos.doneInit=false;Zonos.cartSettings=null;Zonos.debug=typeof window!=="undefined"&&!!window.location.search.match(/\?.*(&*)zonosDebug=1/);Zonos.zonosConversionTest=typeof window!=="undefined"&&!!window.location.search.match(/\?.*(&*)zonosConversionTest/);Zonos._paypalMockResponse=null;Zonos.iframeLogType=typeof window!=="undefined"?new URLSearchParams(window.location.search).get("iframeLogType"):null;Zonos.isBigCommerce=false;Zonos.releaseDate="1749758631773";Zonos.isLegacyCheckout=false;Zonos.domain=typeof window!=="undefined"?window.location!=window.parent.location&&document.referrer||document.location.hostname:"";Zonos.showBaseForeign=typeof window!=="undefined"&&window.location.search.includes("zonosShowBaseForeign");Zonos.overrideUseCustomAddressForm=false;Zonos.isNpm=true;Zonos.zonosQaUrl=null;Zonos.zonosQaUrlApi=null;Zonos.trackEventLogs=[];Zonos.version="v".concat("1.3.217");Zonos.modeAlerted=false;Zonos.cartData=null;Zonos.paypal=null;Zonos.zonosMode=null;Zonos.IframeService=IframeService;Zonos.getCurrentTimestamp=function(){return(new Date).getTime()};Zonos.zonosController=null;Zonos.loadTimeApiInfoList=[];Zonos.logIntervalId=null;Zonos.init=function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t,o,r,i,a,s,c,u,d,l,f,v,m,_;return __generator(this,(function(p){switch(p.label){case 0:n=e.appearance,t=e.checkoutSettings,o=e.currencyConverter,r=e.helloSettings,i=e.onCountryChange,a=e.overrideCurrencyFormat,s=e.storeId,c=e.zonosApiKey;_a.cartId=getCartIdFromQueryParam();if(_a.doneInit){return[2]}log("====== ZONOS DEBUG MODE: on (".concat(_a.version,") ======"));_a.zonosApiKey=c;_a.storeId=s;if(!_a.isNpm)return[3,4];log("====== ZONOS LOADING FROM NPM ======");u=getZonosQaUrl();if(u&&!window.isZonosPreview){log('====== RE-INJECT "zonos.js" FROM PRVIEW: '.concat(u," ======"),"info");d=document.createElement("script");d.src="".concat(u,"/dist/scripts/zonos.js");document.head.appendChild(d);d.addEventListener("load",(function(){window.Zonos.isNpm=_a.isNpm;window.Zonos.isBigCommerce=_a.isBigCommerce;window.Zonos.isLegacyCheckout=_a.isLegacyCheckout;void window.Zonos.init(e)}));d.addEventListener("error",(function(){alert('[ZONOS - loadZonos] Failed to load "loadZonos.js" from zonosQaUrl: '.concat(u))}));window.isZonosPreview=true;return[2]}if(!c&&!_a.cartId){logError("Zonos API key is required unless `tempCartUUID` is provided in url query params.");return[2]}if(!(!_a.cartData&&_a.cartId))return[3,2];log("Initialize cart data");return[4,setupCartDataWithSettings(_a.cartId)];case 1:l=p.sent();if(!l){logError("Failed to get cart data");return[2]}_a.cartData=l.cartData;_a.zonosApiKey=l.zonosApiKey;_a.cartSettings=l.settings;p.label=2;case 2:return[4,getWithTestPublicCredential()];case 3:f=p.sent();if(f){_a.zonosApiKey=f}p.label=4;case 4:v=new URL(window.location.href).searchParams.get("payment_intent_client_secret")||sessionStorage.getItem("zonos--client-secret");m=_a.cartId&&_a.cartData||!!v;if(m){log("Cart data or stripe client secret is available, inject hidden button and trigger checkout");_=document.createElement("button");_.style.display="none";_.id="".concat(checkoutHiddenBtnSelector);document.body.appendChild(_)}log("init zonos");_a.restoreNativeBrowserFunctions();_a.injectCustomScriptForHostedCheckout();_a.injectZonosCdn();_a.injectZonosCss();_a.injectFonts();_a.injectCheckoutInternationalButton();_a.injectController({config:{appearance:n,checkoutSettings:t,currencyConverter:o,helloSettings:r,onCountryChange:i,overrideCurrencyFormat:a}});_a.doneInit=true;return[2]}}))}))};Zonos.injectCheckoutInternationalButton=function(){if(!document.querySelector("#".concat(checkoutHiddenInternationalBtnSelector))){var e=document.createElement("button");e.id=checkoutHiddenInternationalBtnSelector;e.style.display="none";document.body.appendChild(e)}};Zonos.injectCustomScriptForHostedCheckout=function(){var e=_a.cartData;var n=(e===null||e===void 0?void 0:e.metadata)||[];var t=n.find((function(e){return e.key==="customHeaderScript"}));var o=n.find((function(e){return e.key==="customFooterScript"}));if(!window.Zonos.isLegacyCheckout||!t&&!o){log("Skip injecting custom script for hosted checkout","info",{footerScript:o,headerScript:t,isLegacyCheckout:window.Zonos.isLegacyCheckout});return}if(t){log("Injecting custom header script");var r=document.createElement("script");r.textContent=t.value;document.head.appendChild(r)}if(o){log("Injecting custom footer script");var r=document.createElement("script");r.textContent=o.value;document.body.appendChild(r)}};Zonos.displayCurrency=function(){var e=document.querySelector("zonos-hello");if(e){void e.displayCurrency()}};Zonos.triggerCheckoutInternational=function(){return __awaiter(void 0,void 0,void 0,(function(){var e;return __generator(this,(function(n){e=document.querySelector("#".concat(checkoutHiddenInternationalBtnSelector));setTimeout((function(){if(e){e.dispatchEvent(createCustomEvent("click"))}}),10);return[2]}))}))};Zonos.openHelloDialog=function(e){var n=document.querySelector("zonos-hello");if(n){void n.openHelloDialog(e!==null&&e!==void 0?e:true)}};Zonos.showNotification=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.showNotification(e))};Zonos.updateOrganizationName=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.updateOrganizationName(e))};Zonos.disablePlaceOrderButtons=function(e){var n=e.autoEnable,t=n===void 0?true:n,o=e.config,r=e.disable,i=e.placeOrderButtonSelector;var a;if((a=o.checkoutSettings)===null||a===void 0?void 0:a.disablePlaceOrderButtonActivation){return}if(i){var s=document.querySelectorAll(i);var c=function(e){var n=e.target;if(n.getAttribute("disabled")){e.preventDefault();e.stopPropagation()}};s.forEach((function(e){var n=e.getAttribute("data-zonos-checkout-attached");if(n){return}if(r){e.setAttribute("disabled","true");e.addEventListener("click",c)}else{e.removeAttribute("disabled");e.removeEventListener("click",c)}}));if(t&&r){setTimeout((function(){s.forEach((function(e){e.removeAttribute("disabled");e.removeEventListener("click",c)}))}),5e3)}}};Zonos.restoreNativeBrowserFunctions=function(){var e;var n=new URL(window.location.href).searchParams.get("useMerchantPolyfill")==="1";if(n){return}var t="zonos---native-browser";var o=document.querySelector("iframe#".concat(t));if(!o){o=document.createElement("iframe");o.id=t;o.style.display="none";o.style.opacity="0";o.style.position="absolute";o.style.top="-9999px";o.style.left="-9999px";o.style.width="1px";o.style.height="1px";o.style.border="none";o.style.overflow="hidden";o.style.visibility="hidden";document.body.appendChild(o)}var r=((e=o.contentWindow)===null||e===void 0?void 0:e.window.Array.from)||Array.from;Array.from=r;document.body.removeChild(o)};Zonos.injectController=function(e){var n=e.config;var t,o;if(document.querySelector("zonos-controller")){return}if((t=n.checkoutSettings)===null||t===void 0?void 0:t.placeOrderButtonSelector){var r=n.checkoutSettings.placeOrderButtonSelector;_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:r});var i=new MutationObserver((function(){_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:r})}));i.observe(document.body,{childList:true,subtree:true})}if((o=n.checkoutSettings)===null||o===void 0?void 0:o.alwaysTriggerInternationalCheckoutSelector){var a=n.checkoutSettings.alwaysTriggerInternationalCheckoutSelector;_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:a});var i=new MutationObserver((function(){_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:a})}));i.observe(document.body,{childList:true,subtree:true})}var s=document.createElement("zonos-controller");s.config=n;s.zonosApiKey=_a.zonosApiKey||"";s.addEventListener("stripeInitEvent",(function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t;return __generator(this,(function(o){switch(o.label){case 0:n=e.detail;log("loading Stripe");return[4,zonosLoadStripe(n.publishableKey)];case 1:t=o.sent();if(!t){logError("API seems to be invalid or missing. Failed to load Stripe");return[2]}window.Zonos.stripe=t;void s.initCheckoutElement(t);return[2]}}))}))}));document.body.appendChild(s);_a.zonosController=s;log("Zonos controller injected!")};Zonos.injectScript=function(e){var n=e.cdnType,t=e.isModule,o=e.theRestUrl;var r=_a.getZonosUrl(n);var i="".concat(r,"/").concat(o);var a=function(){var e=document.querySelector('script[src="'.concat(i,'"]'));return!!e};if(a()){log('Zonos script "'.concat(i,'" already exists in the document'),"warn");return}var s=document.head||document.body;var c=document.createElement("script");if(!!t){c.type="module"}else{c.noModule=true}c.src=i;c.crossOrigin="anonymous";c.onerror=function(){logError("Failed to load ".concat(c.src));var e=getNextFallbackUrl(n);if(!e){return}_a.injectScript({cdnType:e,isModule:t,theRestUrl:o})};s.appendChild(c)};Zonos.getZonosUrl=function(e){var n=function(){switch(e){case"jsdelivr":return JS_DELIVR_ZONOS_URL;case"unpkg":return UNPKG_ZONOS_URL;case"cdnjs":return CDNJS_ZONOS_URL;case"vercel":return ZONOS_URL}};if(_a.isNpm){var t=getZonosQaUrl();return t||n()}return n()};Zonos.injectZonosCdn=function(){_a.injectScript({cdnType:MAIN_LOAD_CDN_TYPE,isModule:true,theRestUrl:"dist/zonos-elements/zonos-elements.esm.js"});_a.injectScript({cdnType:MAIN_LOAD_CDN_TYPE,isModule:false,theRestUrl:"dist/zonos-elements/zonos-elements.js"});log("Zonos cdn script injected!")};Zonos.injectStylesheet=function(e){var n=e.cdnType,t=e.theRestUrl;var o=_a.getZonosUrl(n);var r=document.head||document.body;var i=document.createElement("link");i.rel="preconnect";i.href="".concat(ZONOS_URL,"/");r.appendChild(i);var a=document.createElement("link");a.rel="stylesheet";a.href="".concat(o,"/").concat(t);a.onerror=function(){logError("Failed to load ".concat(a.href));var e=getNextFallbackUrl(n);if(!e){return}_a.injectStylesheet({cdnType:e,theRestUrl:t})};r.appendChild(a)};Zonos.injectZonosCss=function(){var e=function(){return!!document.querySelector('link[rel="stylesheet"][href*="/dist/zonos-elements/zonos-elements.css"]')};if(e()){log("Zonos style links already injected","warn");return}_a.injectStylesheet({cdnType:MAIN_LOAD_CDN_TYPE,theRestUrl:"dist/zonos-elements/zonos-elements.css"});log("Zonos style css injected!")};Zonos.injectFonts=function(){var e=function(){var e=document.fonts.check("1em Inter");if(e){log("Inter font already loaded","warn");return}var n=document.querySelectorAll('link[rel="stylesheet"][href^="'.concat(GOOGLE_FONT_URL,'"]'));for(var t=0;t<n.length;t++){var o=n[t];if(!o){continue}if(GOOGLE_FONT_REGEX.test(o.href)){continue}return o}return null};if(e()){log("Inter font already injected","warn");return}var n=document.head||document.body;var t=document.createElement("link");t.rel="preconnect";t.href=GOOGLE_FONT_URL;n.appendChild(t);var o=document.createElement("link");o.rel="stylesheet";o.href="".concat(GOOGLE_FONT_URL,"/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap");n.appendChild(o);log("Zonos font injected!")};Zonos.setupGoogleFont=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.setupGoogleFont(e))};Zonos.injectSupportGoogleFont=function(e){var n;log("[FONT] injecting ".concat(e));var t=(n=e.match(/family=(.*?):/))===null||n===void 0?void 0:n[1];var o=document.head||document.body;if(!document.querySelector('link[rel="preconnect"][href^="'.concat(GOOGLE_FONT_URL,'"]'))){var r=document.createElement("link");r.rel="preconnect";r.href=GOOGLE_FONT_URL;o.appendChild(r)}if(document.querySelector('link[rel="stylesheet"][href="'.concat(e,'"]'))){log("[FONT] ".concat(t," font already injected"),"warn");return}var i=document.createElement("link");i.rel="stylesheet";i.href=e;o.appendChild(i);log("[FONT] ".concat(t," font injected!"))};var checkoutSessionMutableAttributeKeys=["ZONOS_FORM_TYPE_USING","APP_VERSION","APP_VERSION_NPM_INTEGRATION","LEGACY_CHECKOUT_FACADE"];var checkoutSessionImmutableAttributeKeys=["ORDER_DUPLICATION_CONSENT","WITH_ABANDONED_CART_TOKEN"];var checkoutSessionAttributeKeys=__spreadArray(__spreadArray([],checkoutSessionMutableAttributeKeys,true),checkoutSessionImmutableAttributeKeys,true);export{Zonos,checkoutSessionAttributeKeys,checkoutSessionImmutableAttributeKeys,checkoutSessionMutableAttributeKeys};
|
|
1
|
+
var __awaiter=this&&this.__awaiter||function(e,n,t,o){function r(e){return e instanceof t?e:new t((function(n){n(e)}))}return new(t||(t=Promise))((function(t,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o["throw"](e))}catch(e){i(e)}}function c(e){e.done?t(e.value):r(e.value).then(a,s)}c((o=o.apply(e,n||[])).next())}))};var __generator=this&&this.__generator||function(e,n){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},o,r,i,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(e){return function(n){return c([e,n])}}function c(s){if(o)throw new TypeError("Generator is already executing.");while(a&&(a=0,s[0]&&(t=0)),t)try{if(o=1,r&&(i=s[0]&2?r["return"]:s[0]?r["throw"]||((i=r["return"])&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;if(r=0,i)s=[s[0]&2,i.value];switch(s[0]){case 0:case 1:i=s;break;case 4:t.label++;return{value:s[1],done:false};case 5:t.label++;r=s[1];s=[0];continue;case 7:s=t.ops.pop();t.trys.pop();continue;default:if(!(i=t.trys,i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1];i=s;break}if(i&&t.label<i[2]){t.label=i[2];t.ops.push(s);break}if(i[2])t.ops.pop();t.trys.pop();continue}s=n.call(e,t)}catch(e){s=[6,e];r=0}finally{o=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};var __spreadArray=this&&this.__spreadArray||function(e,n,t){if(t||arguments.length===2)for(var o=0,r=n.length,i;o<r;o++){if(i||!(o in n)){if(!i)i=Array.prototype.slice.call(n,0,o);i[o]=n[o]}}return e.concat(i||Array.prototype.slice.call(n))};import{c as createCustomEvent}from"./createCustomEvent-58159025.js";import{g as getGenericSettingsOverride,I as IframeService}from"./getGenericSettingsOverride-0bc3e118.js";import{g as getIsTestMode,a as getIsStagingMode,l as log,h as handleFetch,b as logError}from"./handleFetch-99218189.js";import{g as getAbandonedCartRenewTokenValue,_ as _getIsValidCartId,c as checkoutHiddenBtnSelector,a as checkoutHiddenInternationalBtnSelector}from"./CheckoutConfig-724d7bae.js";export{c as checkoutHiddenBtnSelector,a as checkoutHiddenInternationalBtnSelector,d as domesticRedirectedBtnSelector}from"./CheckoutConfig-724d7bae.js";export{a as availableTestKeys}from"./VarianceTest-fef2d958.js";export{c as countryRequireTaxId,e as euCountryCodes,s as shipToTaxIdLabels}from"./TaxId-50d72254.js";var checkIfLoadVersionDomain=function(e){var n=e.loadScriptSrc;if(!n){return{currentLoadScriptUrl:"",isForceLoadVersionDomain:false,isWhiteListed:false}}var t=["dev.elements.zonos.com","dev.assets-checkout.zonos.com",".js.zonos.com","zonos-elements-test-git","zonos-elements-git"];var o=["qa.js.zonos.com"];var r=new URL(n).origin;var i=t.some((function(e){return r.includes(e)}));var a=o.some((function(e){return r.includes(e)}));return{currentLoadScriptUrl:r,isForceLoadVersionDomain:a,isWhiteListed:i}};var fallbackList=["jsdelivr","cdnjs","unpkg","vercel"];var MAIN_LOAD_CDN_TYPE="jsdelivr";var getNextFallbackUrl=function(e){var n=fallbackList.indexOf(e);var t=fallbackList[n+1];return t||null};var getWithTestPublicCredential=function(){return __awaiter(void 0,void 0,void 0,(function(){var e,n,t,o,r,i;return __generator(this,(function(a){switch(a.label){case 0:e=getIsTestMode();n=getIsStagingMode();if(!e&&!n||!window.Zonos.zonosApiKey){return[2,null]}log("[ZONOS - loadZonos] Attempt test public credential","info");if(!!window.Zonos.zonosApiKey.includes("credential_test")){log("[ZONOS - loadZonos] Test mode is enabled but the API key is already a test key","info");return[2,null]}return[4,handleFetch("/api/get-test-public-credential")];case 1:t=a.sent(),o=t.errors,r=t.json;if(o.length||!r){logError("[ZONOS - loadZonos] Failed to get test public credential. Keep using production key",o);return[2,null]}i=r.publicCredential;if(!i){logError("[ZONOS - loadZonos] No test public key credential. Keep using production key");return[2,null]}log("[ZONOS - loadZonos] Retrieve new test public token ".concat(i),"info");return[2,i]}}))}))};var extractZonosQaUrl=function(e){if(!e){return null}var n=new URL(e).searchParams;var t=n.get("zonosQaUrl");if(!t){return null}var o=/[^a-zA-Z0-9-_]+/.test(t);if(!!o){return null}return t};var getZonosQaUrl=function(){var e=window&&window.location.href.includes("forceLoadCdn");if(typeof window==="undefined"||e){return null}var n=extractZonosQaUrl(window.location.href);var t="https://v1.3.218.js.zonos.com";if(!n&&(t.includes("test.")||t.includes("test-"))){return t}if(!n&&["dev.demo.elements.zonos.com","dev.checkout.elements.zonos.com"].includes(window.location.hostname)){return"https://dev.elements.zonos.com"}if(!n){return null}if(n==="dev-elements"){return"https://dev.elements.zonos.com"}var o="preview.js.zonos.com";var r="https://".concat(n,".").concat(o);log("[ZONOS-WARNING] using '".concat(r,"' for loading elements script"),"warn");void fetch(r).then((function(){window.sessionStorage.removeItem("zonos--checkout-session-id");window.sessionStorage.removeItem("zonos--client-secret")})).catch((function(){alert("[ZONOS-WARNING] '".concat(r,"' IS NO LONGER AVAILABLE. REMOVING zonosQaUrl PARAM AND RELOADING THE PAGE"));var e=new URLSearchParams(window.location.search);e.delete("zonosQaUrl");var n=window.location.pathname;var t="".concat(n,"?").concat(e.toString());window.history.replaceState(window.history.state,"",t);window.location.reload();return null}));return r};var V3_URL="https://js.stripe.com/v3";var V3_URL_REGEX=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var EXISTING_SCRIPT_MESSAGE="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used";var zonosStripeFindScript=function(){var e=document.querySelectorAll('script[src^="'.concat(V3_URL,'"]'));for(var n=0;n<e.length;n++){var t=e[n];if(!t){continue}if(!V3_URL_REGEX.test(t.src)){continue}return t}return null};var stripePromise$1=null;var injectScript=function(e){var n=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"";var t=document.createElement("script");t.src="".concat(V3_URL).concat(n);var o=document.head||document.body;if(!o){logError("Expected document.body not to be null. Stripe.js requires a <body> element.");return null}o.appendChild(t);return t};var zonosStripeLoadScript=function(e){if(stripePromise$1!==null){return stripePromise$1}stripePromise$1=new Promise((function(n,t){if(typeof window==="undefined"||typeof document==="undefined"){n(null);return}if(window.Stripe&&e){console.warn(EXISTING_SCRIPT_MESSAGE)}if(window.Stripe){n(window.Stripe);return}try{var o=zonosStripeFindScript();if(o&&e){console.warn(EXISTING_SCRIPT_MESSAGE)}else if(!o){o=injectScript(e)}o===null||o===void 0?void 0:o.addEventListener("load",(function(){if(window.Stripe){n(window.Stripe)}else{t(new Error("Stripe.js not available"))}}));o===null||o===void 0?void 0:o.addEventListener("error",(function(){t(new Error("Failed to load Stripe.js"))}))}catch(e){t(e);return}}));return stripePromise$1};var registerWrapper=function(e,n){if(!e||!e._registerWrapper){return}e._registerWrapper({name:"stripe-js",startTime:n})};var initStripe=function(e,n,t){if(e===null){return null}var o=e.apply(undefined,n);registerWrapper(o,t);return o};var stripePromise=Promise.resolve().then((function(){return zonosStripeLoadScript(null)}));var loadCalled=false;stripePromise.catch((function(e){if(!loadCalled){console.warn(e)}}));var zonosLoadStripe=function(){var e=[];for(var n=0;n<arguments.length;n++){e[n]=arguments[n]}return __awaiter(void 0,void 0,void 0,(function(){var n;return __generator(this,(function(t){loadCalled=true;n=Date.now();return[2,stripePromise.then((function(t){return initStripe(t,e,n)}))]}))}))};var TEMP_CART_ID_QUERY_PARAM="tempCartUUID";var getCartIdFromQueryParam=function(){var e=new URLSearchParams(window.location.search);var n=e.get(TEMP_CART_ID_QUERY_PARAM);return n};var getCartInfoById=function(e){return __awaiter(void 0,[e],void 0,(function(e){var n,t,o,r,i,a,s,c,u;var d=e.cartId,l=e.retries;return __generator(this,(function(e){switch(e.label){case 0:n=getIsTestMode();t=getGenericSettingsOverride();o=getAbandonedCartRenewTokenValue()||undefined;r=new URLSearchParams;if(t.overrideShouldEnabledCustomAddress){r.set("overrideShouldEnabledCustomAddress",t.overrideShouldEnabledCustomAddress)}return[4,handleFetch("/api/zonos-elements/get-cart?".concat(r.toString()),{body:{isTestMode:n,renewCartExpirationToken:o,tempCartUUID:d},headers:{"Content-Type":"application/json"},method:"POST"})];case 1:i=e.sent(),a=i.errors,s=i.json,c=i.zonosMode;u=!s||a.length;if(!(u&&l))return[3,3];log("[ZONOS - loadZonos] temp cart not ready, retrying in 1 second","info",{retries:l});return[4,new Promise((function(e){return setTimeout(e,500)}))];case 2:e.sent();return[2,getCartInfoById({cartId:d,retries:l-1})];case 3:if(u){return[2,null]}return[2,Object.assign(Object.assign({},s),{zonosMode:c})]}}))}))};var setupCartDataWithSettings=function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t,o,r;return __generator(this,(function(i){switch(i.label){case 0:n=_getIsValidCartId(e),t=n.isDgsCartId,o=n.isLegacyCartId;if(!o&&!t){logError("[ZONOS - loadZonos] invalid cart id");return[2,null]}return[4,getCartInfoById({cartId:e,retries:5})];case 1:r=i.sent();log("[ZONOS - loadZonos] getting temp cart data","info",r);if(!r){logError("[ZONOS - loadZonos] Error getting temp cart data, stop checkout process.");return[2,null]}window.Zonos.storeId=r.cartData.storeId;window.Zonos.zonosApiKey=r.cartData.credentialToken;window.Zonos.zonosMode=r.zonosMode;return[2,{cartData:r.cartData,settings:r.settings,storeFavicon:r.storeFaviconUrl,storeId:r.cartData.storeId,storeLogo:r.storeLogoUrl,zonosApiKey:r.cartData.credentialToken}]}}))}))};var _a;var zonosLoadUrl=function(){if(typeof document==="undefined"){return null}var e=document.querySelector('script[src*="/zonos.js"]');var n=checkIfLoadVersionDomain({loadScriptSrc:e===null||e===void 0?void 0:e.src}),t=n.currentLoadScriptUrl,o=n.isWhiteListed;if(o){return t}return null}();var ZONOS_URL="https://v1.3.218.js.zonos.com";var JS_DELIVR_ZONOS_URL=zonosLoadUrl||"https://cdn.jsdelivr.net/npm/@zonos/elements@1.3.218";var UNPKG_ZONOS_URL="https://unpkg.com/@zonos/elements@1.3.218";var CDNJS_ZONOS_URL="https://cdnjs.cloudflare.com/ajax/libs/zonos-elements/1.3.218";var GOOGLE_FONT_URL="https://fonts.googleapis.com";var GOOGLE_FONT_REGEX=/^https:\/\/fonts\.googleapis\.com/;var Zonos=function(){function e(){}return e}();_a=Zonos;Zonos.doneInit=false;Zonos.cartSettings=null;Zonos.debug=typeof window!=="undefined"&&!!window.location.search.match(/\?.*(&*)zonosDebug=1/);Zonos.zonosConversionTest=typeof window!=="undefined"&&!!window.location.search.match(/\?.*(&*)zonosConversionTest/);Zonos._paypalMockResponse=null;Zonos.iframeLogType=typeof window!=="undefined"?new URLSearchParams(window.location.search).get("iframeLogType"):null;Zonos.isBigCommerce=false;Zonos.releaseDate="1749830895070";Zonos.isLegacyCheckout=false;Zonos.domain=typeof window!=="undefined"?window.location!=window.parent.location&&document.referrer||document.location.hostname:"";Zonos.showBaseForeign=typeof window!=="undefined"&&window.location.search.includes("zonosShowBaseForeign");Zonos.overrideUseCustomAddressForm=false;Zonos.isNpm=true;Zonos.zonosQaUrl=null;Zonos.zonosQaUrlApi=null;Zonos.trackEventLogs=[];Zonos.version="v".concat("1.3.218");Zonos.modeAlerted=false;Zonos.cartData=null;Zonos.paypal=null;Zonos.zonosMode=null;Zonos.IframeService=IframeService;Zonos.getCurrentTimestamp=function(){return(new Date).getTime()};Zonos.zonosController=null;Zonos.loadTimeApiInfoList=[];Zonos.logIntervalId=null;Zonos.init=function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t,o,r,i,a,s,c,u,d,l,f,v,m,_;return __generator(this,(function(p){switch(p.label){case 0:n=e.appearance,t=e.checkoutSettings,o=e.currencyConverter,r=e.helloSettings,i=e.onCountryChange,a=e.overrideCurrencyFormat,s=e.storeId,c=e.zonosApiKey;_a.cartId=getCartIdFromQueryParam();if(_a.doneInit){return[2]}log("====== ZONOS DEBUG MODE: on (".concat(_a.version,") ======"));_a.zonosApiKey=c;_a.storeId=s;if(!_a.isNpm)return[3,4];log("====== ZONOS LOADING FROM NPM ======");u=getZonosQaUrl();if(u&&!window.isZonosPreview){log('====== RE-INJECT "zonos.js" FROM PRVIEW: '.concat(u," ======"),"info");d=document.createElement("script");d.src="".concat(u,"/dist/scripts/zonos.js");document.head.appendChild(d);d.addEventListener("load",(function(){window.Zonos.isNpm=_a.isNpm;window.Zonos.isBigCommerce=_a.isBigCommerce;window.Zonos.isLegacyCheckout=_a.isLegacyCheckout;void window.Zonos.init(e)}));d.addEventListener("error",(function(){alert('[ZONOS - loadZonos] Failed to load "loadZonos.js" from zonosQaUrl: '.concat(u))}));window.isZonosPreview=true;return[2]}if(!c&&!_a.cartId){logError("Zonos API key is required unless `tempCartUUID` is provided in url query params.");return[2]}if(!(!_a.cartData&&_a.cartId))return[3,2];log("Initialize cart data");return[4,setupCartDataWithSettings(_a.cartId)];case 1:l=p.sent();if(!l){logError("Failed to get cart data");return[2]}_a.cartData=l.cartData;_a.zonosApiKey=l.zonosApiKey;_a.cartSettings=l.settings;p.label=2;case 2:return[4,getWithTestPublicCredential()];case 3:f=p.sent();if(f){_a.zonosApiKey=f}p.label=4;case 4:v=new URL(window.location.href).searchParams.get("payment_intent_client_secret")||sessionStorage.getItem("zonos--client-secret");m=_a.cartId&&_a.cartData||!!v;if(m){log("Cart data or stripe client secret is available, inject hidden button and trigger checkout");_=document.createElement("button");_.style.display="none";_.id="".concat(checkoutHiddenBtnSelector);document.body.appendChild(_)}log("init zonos");_a.restoreNativeBrowserFunctions();_a.injectCustomScriptForHostedCheckout();_a.injectZonosCdn();_a.injectZonosCss();_a.injectFonts();_a.injectCheckoutInternationalButton();_a.injectController({config:{appearance:n,checkoutSettings:t,currencyConverter:o,helloSettings:r,onCountryChange:i,overrideCurrencyFormat:a}});_a.doneInit=true;return[2]}}))}))};Zonos.injectCheckoutInternationalButton=function(){if(!document.querySelector("#".concat(checkoutHiddenInternationalBtnSelector))){var e=document.createElement("button");e.id=checkoutHiddenInternationalBtnSelector;e.style.display="none";document.body.appendChild(e)}};Zonos.injectCustomScriptForHostedCheckout=function(){var e=_a.cartData;var n=(e===null||e===void 0?void 0:e.metadata)||[];var t=n.find((function(e){return e.key==="customHeaderScript"}));var o=n.find((function(e){return e.key==="customFooterScript"}));if(!window.Zonos.isLegacyCheckout||!t&&!o){log("Skip injecting custom script for hosted checkout","info",{footerScript:o,headerScript:t,isLegacyCheckout:window.Zonos.isLegacyCheckout});return}if(t){log("Injecting custom header script");var r=document.createElement("script");r.textContent=t.value;document.head.appendChild(r)}if(o){log("Injecting custom footer script");var r=document.createElement("script");r.textContent=o.value;document.body.appendChild(r)}};Zonos.displayCurrency=function(){var e=document.querySelector("zonos-hello");if(e){void e.displayCurrency()}};Zonos.triggerCheckoutInternational=function(){return __awaiter(void 0,void 0,void 0,(function(){var e;return __generator(this,(function(n){e=document.querySelector("#".concat(checkoutHiddenInternationalBtnSelector));setTimeout((function(){if(e){e.dispatchEvent(createCustomEvent("click"))}}),10);return[2]}))}))};Zonos.openHelloDialog=function(e){var n=document.querySelector("zonos-hello");if(n){void n.openHelloDialog(e!==null&&e!==void 0?e:true)}};Zonos.showNotification=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.showNotification(e))};Zonos.updateOrganizationName=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.updateOrganizationName(e))};Zonos.disablePlaceOrderButtons=function(e){var n=e.autoEnable,t=n===void 0?true:n,o=e.config,r=e.disable,i=e.placeOrderButtonSelector;var a;if((a=o.checkoutSettings)===null||a===void 0?void 0:a.disablePlaceOrderButtonActivation){return}if(i){var s=document.querySelectorAll(i);var c=function(e){var n=e.target;if(n.getAttribute("disabled")){e.preventDefault();e.stopPropagation()}};s.forEach((function(e){var n=e.getAttribute("data-zonos-checkout-attached");if(n){return}if(r){e.setAttribute("disabled","true");e.addEventListener("click",c)}else{e.removeAttribute("disabled");e.removeEventListener("click",c)}}));if(t&&r){setTimeout((function(){s.forEach((function(e){e.removeAttribute("disabled");e.removeEventListener("click",c)}))}),5e3)}}};Zonos.restoreNativeBrowserFunctions=function(){var e;var n=new URL(window.location.href).searchParams.get("useMerchantPolyfill")==="1";if(n){return}var t="zonos---native-browser";var o=document.querySelector("iframe#".concat(t));if(!o){o=document.createElement("iframe");o.id=t;o.style.display="none";o.style.opacity="0";o.style.position="absolute";o.style.top="-9999px";o.style.left="-9999px";o.style.width="1px";o.style.height="1px";o.style.border="none";o.style.overflow="hidden";o.style.visibility="hidden";document.body.appendChild(o)}var r=((e=o.contentWindow)===null||e===void 0?void 0:e.window.Array.from)||Array.from;Array.from=r;document.body.removeChild(o)};Zonos.injectController=function(e){var n=e.config;var t,o;if(document.querySelector("zonos-controller")){return}if((t=n.checkoutSettings)===null||t===void 0?void 0:t.placeOrderButtonSelector){var r=n.checkoutSettings.placeOrderButtonSelector;_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:r});var i=new MutationObserver((function(){_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:r})}));i.observe(document.body,{childList:true,subtree:true})}if((o=n.checkoutSettings)===null||o===void 0?void 0:o.alwaysTriggerInternationalCheckoutSelector){var a=n.checkoutSettings.alwaysTriggerInternationalCheckoutSelector;_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:a});var i=new MutationObserver((function(){_a.disablePlaceOrderButtons({config:n,disable:true,placeOrderButtonSelector:a})}));i.observe(document.body,{childList:true,subtree:true})}var s=document.createElement("zonos-controller");s.config=n;s.zonosApiKey=_a.zonosApiKey||"";s.addEventListener("stripeInitEvent",(function(e){return __awaiter(void 0,void 0,void 0,(function(){var n,t;return __generator(this,(function(o){switch(o.label){case 0:n=e.detail;log("loading Stripe");return[4,zonosLoadStripe(n.publishableKey)];case 1:t=o.sent();if(!t){logError("API seems to be invalid or missing. Failed to load Stripe");return[2]}window.Zonos.stripe=t;void s.initCheckoutElement(t);return[2]}}))}))}));document.body.appendChild(s);_a.zonosController=s;log("Zonos controller injected!")};Zonos.injectScript=function(e){var n=e.cdnType,t=e.isModule,o=e.theRestUrl;var r=_a.getZonosUrl(n);var i="".concat(r,"/").concat(o);var a=function(){var e=document.querySelector('script[src="'.concat(i,'"]'));return!!e};if(a()){log('Zonos script "'.concat(i,'" already exists in the document'),"warn");return}var s=document.head||document.body;var c=document.createElement("script");if(!!t){c.type="module"}else{c.noModule=true}c.src=i;c.crossOrigin="anonymous";c.onerror=function(){logError("Failed to load ".concat(c.src));var e=getNextFallbackUrl(n);if(!e){return}_a.injectScript({cdnType:e,isModule:t,theRestUrl:o})};s.appendChild(c)};Zonos.getZonosUrl=function(e){var n=function(){switch(e){case"jsdelivr":return JS_DELIVR_ZONOS_URL;case"unpkg":return UNPKG_ZONOS_URL;case"cdnjs":return CDNJS_ZONOS_URL;case"vercel":return ZONOS_URL}};if(_a.isNpm){var t=getZonosQaUrl();return t||n()}return n()};Zonos.injectZonosCdn=function(){_a.injectScript({cdnType:MAIN_LOAD_CDN_TYPE,isModule:true,theRestUrl:"dist/zonos-elements/zonos-elements.esm.js"});_a.injectScript({cdnType:MAIN_LOAD_CDN_TYPE,isModule:false,theRestUrl:"dist/zonos-elements/zonos-elements.js"});log("Zonos cdn script injected!")};Zonos.injectStylesheet=function(e){var n=e.cdnType,t=e.theRestUrl;var o=_a.getZonosUrl(n);var r=document.head||document.body;var i=document.createElement("link");i.rel="preconnect";i.href="".concat(ZONOS_URL,"/");r.appendChild(i);var a=document.createElement("link");a.rel="stylesheet";a.href="".concat(o,"/").concat(t);a.onerror=function(){logError("Failed to load ".concat(a.href));var e=getNextFallbackUrl(n);if(!e){return}_a.injectStylesheet({cdnType:e,theRestUrl:t})};r.appendChild(a)};Zonos.injectZonosCss=function(){var e=function(){return!!document.querySelector('link[rel="stylesheet"][href*="/dist/zonos-elements/zonos-elements.css"]')};if(e()){log("Zonos style links already injected","warn");return}_a.injectStylesheet({cdnType:MAIN_LOAD_CDN_TYPE,theRestUrl:"dist/zonos-elements/zonos-elements.css"});log("Zonos style css injected!")};Zonos.injectFonts=function(){var e=function(){var e=document.fonts.check("1em Inter");if(e){log("Inter font already loaded","warn");return}var n=document.querySelectorAll('link[rel="stylesheet"][href^="'.concat(GOOGLE_FONT_URL,'"]'));for(var t=0;t<n.length;t++){var o=n[t];if(!o){continue}if(GOOGLE_FONT_REGEX.test(o.href)){continue}return o}return null};if(e()){log("Inter font already injected","warn");return}var n=document.head||document.body;var t=document.createElement("link");t.rel="preconnect";t.href=GOOGLE_FONT_URL;n.appendChild(t);var o=document.createElement("link");o.rel="stylesheet";o.href="".concat(GOOGLE_FONT_URL,"/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap");n.appendChild(o);log("Zonos font injected!")};Zonos.setupGoogleFont=function(e){var n;void((n=_a.zonosController)===null||n===void 0?void 0:n.setupGoogleFont(e))};Zonos.injectSupportGoogleFont=function(e){var n;log("[FONT] injecting ".concat(e));var t=(n=e.match(/family=(.*?):/))===null||n===void 0?void 0:n[1];var o=document.head||document.body;if(!document.querySelector('link[rel="preconnect"][href^="'.concat(GOOGLE_FONT_URL,'"]'))){var r=document.createElement("link");r.rel="preconnect";r.href=GOOGLE_FONT_URL;o.appendChild(r)}if(document.querySelector('link[rel="stylesheet"][href="'.concat(e,'"]'))){log("[FONT] ".concat(t," font already injected"),"warn");return}var i=document.createElement("link");i.rel="stylesheet";i.href=e;o.appendChild(i);log("[FONT] ".concat(t," font injected!"))};var checkoutSessionMutableAttributeKeys=["ZONOS_FORM_TYPE_USING","APP_VERSION","APP_VERSION_NPM_INTEGRATION","LEGACY_CHECKOUT_FACADE"];var checkoutSessionImmutableAttributeKeys=["ORDER_DUPLICATION_CONSENT","WITH_ABANDONED_CART_TOKEN"];var checkoutSessionAttributeKeys=__spreadArray(__spreadArray([],checkoutSessionMutableAttributeKeys,true),checkoutSessionImmutableAttributeKeys,true);export{Zonos,checkoutSessionAttributeKeys,checkoutSessionImmutableAttributeKeys,checkoutSessionMutableAttributeKeys};
|