@zonos/elements 1.3.201 → 1.3.203

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.
Files changed (308) hide show
  1. package/dist/cjs/VarianceTest-0cb1e118.js +12 -0
  2. package/dist/cjs/cart-0d91ad0b.js +1955 -0
  3. package/dist/cjs/{debounce-d393fafe.js → debounce-94e1b7ff.js} +1 -1
  4. package/dist/cjs/{getBorderRadius-3d0a563e.js → getBorderRadius-8d3b1049.js} +1 -1
  5. package/dist/cjs/index.cjs.js +10 -8
  6. package/dist/cjs/{isDarkColor-92a10a85.js → isDarkColor-bcf49625.js} +1 -1
  7. package/dist/cjs/loader.cjs.js +1 -1
  8. package/dist/cjs/{cart-e73cde62.js → localization-2f17c95f.js} +74 -1941
  9. package/dist/cjs/{paypal-39bbbd1a.js → paypal-9953115b.js} +10 -9
  10. package/dist/cjs/zonos-address_11.cjs.entry.js +98 -72
  11. package/dist/cjs/zonos-badge.cjs.entry.js +2 -1
  12. package/dist/cjs/zonos-banner.cjs.entry.js +2 -1
  13. package/dist/cjs/zonos-button_3.cjs.entry.js +4 -3
  14. package/dist/cjs/zonos-card.cjs.entry.js +3 -2
  15. package/dist/cjs/{zonos-cart-items_13.cjs.entry.js → zonos-cart-items_14.cjs.entry.js} +105 -82
  16. package/dist/cjs/zonos-checkout.cjs.entry.js +395 -50
  17. package/dist/cjs/zonos-collapse.cjs.entry.js +2 -1
  18. package/dist/cjs/zonos-component.cjs.entry.js +1 -1
  19. package/dist/cjs/zonos-controller.cjs.entry.js +13 -11
  20. package/dist/cjs/zonos-country-flag.cjs.entry.js +4 -5
  21. package/dist/cjs/zonos-country-select_4.cjs.entry.js +13 -13
  22. package/dist/cjs/zonos-elements.cjs.js +1 -1
  23. package/dist/cjs/zonos-empty-state-payment_4.cjs.entry.js +10 -8
  24. package/dist/cjs/zonos-hello-dialog.cjs.entry.js +41 -42
  25. package/dist/cjs/zonos-hello.cjs.entry.js +30 -31
  26. package/dist/cjs/zonos-input.cjs.entry.js +3 -2
  27. package/dist/cjs/zonos-language-select_2.cjs.entry.js +8 -9
  28. package/dist/cjs/zonos-logo.cjs.entry.js +4 -3
  29. package/dist/cjs/zonos-shipping-rich-radio.cjs.entry.js +3 -2
  30. package/dist/cjs/zonos-stripe-input.cjs.entry.js +8 -7
  31. package/dist/cjs/zonos-text.cjs.entry.js +2 -1
  32. package/dist/cjs/zonos-toggle.cjs.entry.js +4 -3
  33. package/dist/cjs/zonos-tooltip.cjs.entry.js +2 -2
  34. package/dist/cjs/zonos-v-stack.cjs.entry.js +4 -3
  35. package/dist/cjs/{zonosStore-c466b127.js → zonosStore-9264749e.js} +15 -5
  36. package/dist/collection/collection-manifest.json +1 -0
  37. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.js +18 -17
  38. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout.js +235 -15
  39. package/dist/collection/components/checkout/zonos-checkout/zonos-customer-info/zonos-customer-info.js +3 -3
  40. package/dist/collection/components/checkout/zonos-checkout/zonos-shipping/zonos-shipping.js +9 -4
  41. package/dist/collection/components/common/zonos-loading-overlay/zonos-loading-overlay.css +62 -0
  42. package/dist/collection/components/common/zonos-loading-overlay/zonos-loading-overlay.js +90 -0
  43. package/dist/collection/components/common/zonos-logo/zonos-logo.js +2 -2
  44. package/dist/collection/components/common/zonos-rest-state/zonos-rest-state.js +3 -3
  45. package/dist/collection/components/common/zonos-select-dialog-header/zonos-select-dialog-header.js +2 -2
  46. package/dist/collection/components/common/zonos-stripe-input/zonos-stripe-input.js +4 -4
  47. package/dist/collection/components/common/zonos-stripe-phone-input/zonos-stripe-phone-input.js +5 -5
  48. package/dist/collection/components/common/zonos-stripe-select/zonos-stripe-select.js +5 -5
  49. package/dist/collection/components/common/zonos-toggle/zonos-toggle.js +2 -2
  50. package/dist/collection/components/common/zonos-tooltip/zonos-tooltip.js +2 -2
  51. package/dist/collection/components/common/zonos-v-stack/zonos-v-stack.js +2 -2
  52. package/dist/collection/components/common/zonos-virtual-scroll/zonos-virtual-scroll.js +2 -2
  53. package/dist/collection/components/component-template/zonos-component/zonos-component.js +1 -1
  54. package/dist/collection/components/hello/zonos-hello-dialog/zonos-hello-dialog-footer/zonos-hello-dialog-footer.js +2 -2
  55. package/dist/collection/components/hello/zonos-hello-dialog/zonos-hello-dialog.js +4 -4
  56. package/dist/collection/components/main/zonos-controller.js +3 -3
  57. package/dist/collection/components/paypal/zonos-paypal-payment.js +1 -1
  58. package/dist/collection/components/store/checkout/cart.js +28 -18
  59. package/dist/collection/components/store/checkout/paypal.js +2 -1
  60. package/dist/collection/components/store/checkout/stripe.js +16 -11
  61. package/dist/collection/components/store/hello/localization.js +5 -5
  62. package/dist/collection/components/store/storageStore.js +32 -0
  63. package/dist/collection/components/store/zonosStore.js +12 -6
  64. package/dist/collection/components/stripe/zonos-address/zonos-address.js +18 -6
  65. package/dist/collection/components/stripe/zonos-custom-address/zonos-address-suggestions/zonos-address-suggestions.js +2 -2
  66. package/dist/collection/components/stripe/zonos-custom-address/zonos-custom-address.js +19 -7
  67. package/dist/collection/components/stripe/zonos-payment/zonos-payment.js +3 -3
  68. package/dist/collection/components/utils/api/getCheckoutSession.js +3 -3
  69. package/dist/collection/components/utils/api/placeTestOrder.js +2 -1
  70. package/dist/collection/components/utils/api/prepCalculateLandedCost.js +3 -2
  71. package/dist/collection/components/utils/api/selectVarianceTest.js +20 -0
  72. package/dist/collection/components/utils/buildCartUrl.js +44 -0
  73. package/dist/collection/components/utils/getLegacyQueryParams.js +42 -0
  74. package/dist/collection/components/utils/varianceTest/filterExpiredTests.js +6 -0
  75. package/dist/collection/components/utils/varianceTest/filterValidTests.js +23 -0
  76. package/dist/collection/components/utils/varianceTest/getSelectedTestVariant.js +6 -0
  77. package/dist/collection/components/utils/varianceTest/hasAtLeastOneAvailableTestKey.js +14 -0
  78. package/dist/collection/components/utils/varianceTest/isInAvailableTestKey.js +4 -0
  79. package/dist/collection/components/utils/varianceTest/isTestEnabled.js +4 -0
  80. package/dist/collection/components/utils/varianceTest/isTestKeysAllVariantSelected.js +6 -0
  81. package/dist/collection/components/utils/varianceTest/mergeTest.js +13 -0
  82. package/dist/collection/scripts/_getZonosQaUrl.js +2 -2
  83. package/dist/collection/types/checkout/api/VarianceTest.js +8 -0
  84. package/dist/collection/types/generated/graphql.internal.types.js +26 -7
  85. package/dist/collection/types/index.js +1 -0
  86. package/dist/esm/VarianceTest-fef2d958.js +10 -0
  87. package/dist/esm/cart-db61eb95.js +1918 -0
  88. package/dist/esm/{debounce-a2121722.js → debounce-3a9f27a0.js} +1 -1
  89. package/dist/esm/{getBorderRadius-413e97eb.js → getBorderRadius-78b28b4d.js} +1 -1
  90. package/dist/esm/index.js +9 -8
  91. package/dist/esm/{isDarkColor-4c7b2ffc.js → isDarkColor-31dd7dff.js} +1 -1
  92. package/dist/esm/loader.js +1 -1
  93. package/dist/esm/{cart-f79c8021.js → localization-bf7224aa.js} +70 -1907
  94. package/dist/esm/{paypal-6d4667d1.js → paypal-2e0ffb07.js} +5 -4
  95. package/dist/esm/zonos-address_11.entry.js +54 -28
  96. package/dist/esm/zonos-badge.entry.js +2 -1
  97. package/dist/esm/zonos-banner.entry.js +2 -1
  98. package/dist/esm/zonos-button_3.entry.js +4 -3
  99. package/dist/esm/zonos-card.entry.js +3 -2
  100. package/dist/esm/{zonos-cart-items_13.entry.js → zonos-cart-items_14.entry.js} +54 -32
  101. package/dist/esm/zonos-checkout.entry.js +363 -18
  102. package/dist/esm/zonos-collapse.entry.js +2 -1
  103. package/dist/esm/zonos-component.entry.js +1 -1
  104. package/dist/esm/zonos-controller.entry.js +8 -6
  105. package/dist/esm/zonos-country-flag.entry.js +3 -4
  106. package/dist/esm/zonos-country-select_4.entry.js +8 -8
  107. package/dist/esm/zonos-elements.js +1 -1
  108. package/dist/esm/zonos-empty-state-payment_4.entry.js +10 -8
  109. package/dist/esm/zonos-hello-dialog.entry.js +7 -8
  110. package/dist/esm/zonos-hello.entry.js +4 -5
  111. package/dist/esm/zonos-input.entry.js +3 -2
  112. package/dist/esm/zonos-language-select_2.entry.js +5 -6
  113. package/dist/esm/zonos-logo.entry.js +4 -3
  114. package/dist/esm/zonos-shipping-rich-radio.entry.js +3 -2
  115. package/dist/esm/zonos-stripe-input.entry.js +8 -7
  116. package/dist/esm/zonos-text.entry.js +2 -1
  117. package/dist/esm/zonos-toggle.entry.js +4 -3
  118. package/dist/esm/zonos-tooltip.entry.js +2 -2
  119. package/dist/esm/zonos-v-stack.entry.js +4 -3
  120. package/dist/esm/{zonosStore-cdabc848.js → zonosStore-d10a829f.js} +15 -5
  121. package/dist/esm-es5/VarianceTest-fef2d958.js +1 -0
  122. package/dist/esm-es5/cart-db61eb95.js +1 -0
  123. package/dist/esm-es5/{debounce-a2121722.js → debounce-3a9f27a0.js} +1 -1
  124. package/dist/esm-es5/{getBorderRadius-413e97eb.js → getBorderRadius-78b28b4d.js} +1 -1
  125. package/dist/esm-es5/index.js +1 -1
  126. package/dist/esm-es5/{isDarkColor-4c7b2ffc.js → isDarkColor-31dd7dff.js} +1 -1
  127. package/dist/esm-es5/loader.js +1 -1
  128. package/dist/esm-es5/localization-bf7224aa.js +1 -0
  129. package/dist/esm-es5/{paypal-6d4667d1.js → paypal-2e0ffb07.js} +2 -2
  130. package/dist/esm-es5/zonos-address_11.entry.js +1 -1
  131. package/dist/esm-es5/zonos-badge.entry.js +1 -1
  132. package/dist/esm-es5/zonos-banner.entry.js +1 -1
  133. package/dist/esm-es5/zonos-button_3.entry.js +1 -1
  134. package/dist/esm-es5/zonos-card.entry.js +1 -1
  135. package/dist/esm-es5/zonos-cart-items_14.entry.js +1 -0
  136. package/dist/esm-es5/zonos-checkout.entry.js +1 -1
  137. package/dist/esm-es5/zonos-collapse.entry.js +1 -1
  138. package/dist/esm-es5/zonos-component.entry.js +1 -1
  139. package/dist/esm-es5/zonos-controller.entry.js +1 -1
  140. package/dist/esm-es5/zonos-country-flag.entry.js +1 -1
  141. package/dist/esm-es5/zonos-country-select_4.entry.js +1 -1
  142. package/dist/esm-es5/zonos-elements.js +1 -1
  143. package/dist/esm-es5/zonos-empty-state-payment_4.entry.js +1 -1
  144. package/dist/esm-es5/zonos-hello-dialog.entry.js +1 -1
  145. package/dist/esm-es5/zonos-hello.entry.js +1 -1
  146. package/dist/esm-es5/zonos-input.entry.js +1 -1
  147. package/dist/esm-es5/zonos-language-select_2.entry.js +1 -1
  148. package/dist/esm-es5/zonos-logo.entry.js +1 -1
  149. package/dist/esm-es5/zonos-shipping-rich-radio.entry.js +1 -1
  150. package/dist/esm-es5/zonos-stripe-input.entry.js +1 -1
  151. package/dist/esm-es5/zonos-text.entry.js +1 -1
  152. package/dist/esm-es5/zonos-toggle.entry.js +1 -1
  153. package/dist/esm-es5/zonos-tooltip.entry.js +1 -1
  154. package/dist/esm-es5/zonos-v-stack.entry.js +1 -1
  155. package/dist/esm-es5/zonosStore-d10a829f.js +1 -0
  156. package/dist/scripts/index.d.ts +844 -766
  157. package/dist/scripts/index.js +1 -1
  158. package/dist/scripts/loadZonos.js +1 -1
  159. package/dist/scripts/zonos.js +1 -1
  160. package/dist/types/components/checkout/zonos-checkout/zonos-checkout.d.ts +16 -0
  161. package/dist/types/components/common/zonos-loading-overlay/zonos-loading-overlay.d.ts +16 -0
  162. package/dist/types/components/store/checkout/cart.d.ts +5 -2
  163. package/dist/types/components/store/checkout/stripe.d.ts +2 -2
  164. package/dist/types/components/store/hello/localization.d.ts +2 -2
  165. package/dist/types/components/store/storageStore.d.ts +13 -0
  166. package/dist/types/components/store/zonosStore.d.ts +7 -2
  167. package/dist/types/components/stripe/zonos-address/zonos-address.d.ts +2 -0
  168. package/dist/types/components/stripe/zonos-custom-address/zonos-custom-address.d.ts +2 -0
  169. package/dist/types/components/utils/api/selectVarianceTest.d.ts +6 -0
  170. package/dist/types/components/utils/buildCartUrl.d.ts +10 -0
  171. package/dist/types/components/utils/getLegacyQueryParams.d.ts +2 -0
  172. package/dist/types/components/utils/varianceTest/filterExpiredTests.d.ts +2 -0
  173. package/dist/types/components/utils/varianceTest/filterValidTests.d.ts +9 -0
  174. package/dist/types/components/utils/varianceTest/getSelectedTestVariant.d.ts +2 -0
  175. package/dist/types/components/utils/varianceTest/hasAtLeastOneAvailableTestKey.d.ts +8 -0
  176. package/dist/types/components/utils/varianceTest/isInAvailableTestKey.d.ts +2 -0
  177. package/dist/types/components/utils/varianceTest/isTestEnabled.d.ts +2 -0
  178. package/dist/types/components/utils/varianceTest/isTestKeysAllVariantSelected.d.ts +9 -0
  179. package/dist/types/components/utils/varianceTest/mergeTest.d.ts +5 -0
  180. package/dist/types/components.d.ts +51 -0
  181. package/dist/types/scripts/cart/_setupCartDataWithSettings.d.ts +7 -0
  182. package/dist/types/types/checkout/CheckoutConfig.d.ts +13 -1
  183. package/dist/types/types/checkout/api/CheckoutSession.d.ts +7 -0
  184. package/dist/types/types/checkout/api/VarianceTest.d.ts +30 -0
  185. package/dist/types/types/generated/graphql.internal.types.d.ts +206 -22
  186. package/dist/types/types/generated/graphql.internal.types.ts +235 -19
  187. package/dist/types/types/index.d.ts +1 -0
  188. package/dist/types/types/utils/ZonosSettings.d.ts +7 -6
  189. package/dist/zonos-elements/index.esm.js +1 -1
  190. package/dist/zonos-elements/{p-609c32a3.system.entry.js → p-01987cb2.system.entry.js} +1 -1
  191. package/dist/zonos-elements/p-04a01cb1.js +1 -0
  192. package/dist/zonos-elements/p-04b43dd5.entry.js +1 -0
  193. package/dist/zonos-elements/{p-7d5d89f2.system.js → p-0693422b.system.js} +2 -2
  194. package/dist/zonos-elements/p-06f25f75.entry.js +1 -0
  195. package/dist/zonos-elements/p-0c62cfb3.entry.js +1 -0
  196. package/dist/zonos-elements/{p-7831b52c.system.entry.js → p-1dcdb65f.system.entry.js} +1 -1
  197. package/dist/zonos-elements/p-25970cb8.system.entry.js +1 -0
  198. package/dist/zonos-elements/p-26a634a5.system.entry.js +1 -0
  199. package/dist/zonos-elements/p-27987298.system.entry.js +1 -0
  200. package/dist/zonos-elements/p-2bb8ca7d.system.entry.js +1 -0
  201. package/dist/zonos-elements/p-2f70d0eb.entry.js +1 -0
  202. package/dist/zonos-elements/p-3284f459.system.entry.js +1 -0
  203. package/dist/zonos-elements/{p-13796f98.js → p-3d82a352.js} +1 -1
  204. package/dist/zonos-elements/p-411b8e10.entry.js +1 -0
  205. package/dist/zonos-elements/p-452070af.system.entry.js +1 -0
  206. package/dist/zonos-elements/p-45ebc788.entry.js +1 -0
  207. package/dist/zonos-elements/p-4c81112f.entry.js +1 -0
  208. package/dist/zonos-elements/p-4efa8187.js +1 -0
  209. package/dist/zonos-elements/p-5170bc41.entry.js +1 -0
  210. package/dist/zonos-elements/p-54cdc47f.system.entry.js +1 -0
  211. package/dist/zonos-elements/p-5a2dd041.system.js +1 -0
  212. package/dist/zonos-elements/p-5c74e5c9.system.entry.js +1 -0
  213. package/dist/zonos-elements/p-5d0f7364.system.js +1 -0
  214. package/dist/zonos-elements/p-6b6a9dd6.system.js +1 -0
  215. package/dist/zonos-elements/p-715d0f59.system.entry.js +1 -0
  216. package/dist/zonos-elements/{p-b8d87932.js → p-72f37935.js} +1 -1
  217. package/dist/zonos-elements/p-7ae5cd60.entry.js +1 -0
  218. package/dist/zonos-elements/p-7cd09f1f.system.js +1 -0
  219. package/dist/zonos-elements/p-80bbd9c0.system.entry.js +1 -0
  220. package/dist/zonos-elements/p-851c642e.system.entry.js +1 -0
  221. package/dist/zonos-elements/{p-4300d944.entry.js → p-8d870d4c.entry.js} +1 -1
  222. package/dist/zonos-elements/p-9af5e93a.entry.js +1 -0
  223. package/dist/zonos-elements/{p-5de59662.js → p-a9307caa.js} +2 -2
  224. package/dist/zonos-elements/p-aa1193bc.entry.js +1 -0
  225. package/dist/zonos-elements/p-ab176281.system.entry.js +1 -0
  226. package/dist/zonos-elements/p-bc8bda92.entry.js +1 -0
  227. package/dist/zonos-elements/p-be5afc91.system.entry.js +1 -0
  228. package/dist/zonos-elements/p-c291bac1.entry.js +1 -0
  229. package/dist/zonos-elements/p-c3d2422e.entry.js +1 -0
  230. package/dist/zonos-elements/{p-f28eb1dd.system.js → p-c50b3100.system.js} +1 -1
  231. package/dist/zonos-elements/p-c5fcbc92.system.entry.js +1 -0
  232. package/dist/zonos-elements/p-c767242b.entry.js +1 -0
  233. package/dist/zonos-elements/p-c9aa902e.system.entry.js +1 -0
  234. package/dist/zonos-elements/p-cb823c4d.system.js +1 -0
  235. package/dist/zonos-elements/p-cdd3087f.system.entry.js +1 -0
  236. package/dist/zonos-elements/p-d2165441.system.entry.js +1 -0
  237. package/dist/zonos-elements/{p-d422ad1d.system.js → p-d42dfd32.system.js} +1 -1
  238. package/dist/zonos-elements/p-d46349d3.system.entry.js +1 -0
  239. package/dist/zonos-elements/{p-b2241919.entry.js → p-d6a10007.entry.js} +1 -1
  240. package/dist/zonos-elements/p-d99d9e00.js +1 -0
  241. package/dist/zonos-elements/p-db025dfc.system.entry.js +1 -0
  242. package/dist/zonos-elements/p-dcd6acd4.system.entry.js +1 -0
  243. package/dist/zonos-elements/p-dd1cfa74.entry.js +1 -0
  244. package/dist/zonos-elements/p-df4c46a6.entry.js +1 -0
  245. package/dist/zonos-elements/p-dfd1ba1d.entry.js +1 -0
  246. package/dist/zonos-elements/{p-4593324c.js → p-e26c9e83.js} +1 -1
  247. package/dist/zonos-elements/p-e68d5219.entry.js +1 -0
  248. package/dist/zonos-elements/p-ea6d87a1.system.js +1 -1
  249. package/dist/zonos-elements/p-ef3e05e5.system.js +1 -0
  250. package/dist/zonos-elements/p-f255e822.js +1 -0
  251. package/dist/zonos-elements/p-f655ec36.entry.js +1 -0
  252. package/dist/zonos-elements/{p-e91b244c.entry.js → p-f891d470.entry.js} +1 -1
  253. package/dist/zonos-elements/p-f8d0d488.system.entry.js +1 -0
  254. package/dist/zonos-elements/{p-240ee490.system.entry.js → p-fbe36bc8.system.entry.js} +1 -1
  255. package/dist/zonos-elements/p-fcc2e712.entry.js +1 -0
  256. package/dist/zonos-elements/zonos-elements.esm.js +1 -1
  257. package/package.json +1 -1
  258. package/dist/esm-es5/cart-f79c8021.js +0 -1
  259. package/dist/esm-es5/zonos-cart-items_13.entry.js +0 -1
  260. package/dist/esm-es5/zonosStore-cdabc848.js +0 -1
  261. package/dist/zonos-elements/p-0302a254.entry.js +0 -1
  262. package/dist/zonos-elements/p-06ed3582.system.js +0 -1
  263. package/dist/zonos-elements/p-147ca395.entry.js +0 -1
  264. package/dist/zonos-elements/p-1998d8b3.entry.js +0 -1
  265. package/dist/zonos-elements/p-1eddec23.entry.js +0 -1
  266. package/dist/zonos-elements/p-20030bf5.system.js +0 -1
  267. package/dist/zonos-elements/p-24a2e899.system.entry.js +0 -1
  268. package/dist/zonos-elements/p-264f46a5.entry.js +0 -1
  269. package/dist/zonos-elements/p-2882b9f4.entry.js +0 -1
  270. package/dist/zonos-elements/p-2c915112.system.entry.js +0 -1
  271. package/dist/zonos-elements/p-327aebf5.entry.js +0 -1
  272. package/dist/zonos-elements/p-33488109.system.entry.js +0 -1
  273. package/dist/zonos-elements/p-337fab4e.js +0 -1
  274. package/dist/zonos-elements/p-3ddecaa4.system.entry.js +0 -1
  275. package/dist/zonos-elements/p-48f70043.system.entry.js +0 -1
  276. package/dist/zonos-elements/p-49a31b14.system.entry.js +0 -1
  277. package/dist/zonos-elements/p-4cd867d5.js +0 -1
  278. package/dist/zonos-elements/p-55711b80.system.entry.js +0 -1
  279. package/dist/zonos-elements/p-578bf5d7.entry.js +0 -1
  280. package/dist/zonos-elements/p-5c061a35.entry.js +0 -1
  281. package/dist/zonos-elements/p-6096c1c5.entry.js +0 -1
  282. package/dist/zonos-elements/p-65a8f19d.entry.js +0 -1
  283. package/dist/zonos-elements/p-6adc6e27.entry.js +0 -1
  284. package/dist/zonos-elements/p-6cd9b6a1.system.entry.js +0 -1
  285. package/dist/zonos-elements/p-79070ee6.entry.js +0 -1
  286. package/dist/zonos-elements/p-7bb9c330.entry.js +0 -1
  287. package/dist/zonos-elements/p-82aa4f9f.system.entry.js +0 -1
  288. package/dist/zonos-elements/p-8540f3e2.system.entry.js +0 -1
  289. package/dist/zonos-elements/p-8a9d4605.system.entry.js +0 -1
  290. package/dist/zonos-elements/p-932bed54.system.entry.js +0 -1
  291. package/dist/zonos-elements/p-94e3e50d.system.entry.js +0 -1
  292. package/dist/zonos-elements/p-9f6dd86a.entry.js +0 -1
  293. package/dist/zonos-elements/p-a64ab131.system.entry.js +0 -1
  294. package/dist/zonos-elements/p-aac95779.system.entry.js +0 -1
  295. package/dist/zonos-elements/p-ad3c5358.entry.js +0 -1
  296. package/dist/zonos-elements/p-af6af82e.system.js +0 -1
  297. package/dist/zonos-elements/p-b66b3306.system.entry.js +0 -1
  298. package/dist/zonos-elements/p-b6afcf3f.system.entry.js +0 -1
  299. package/dist/zonos-elements/p-b8d91f99.entry.js +0 -1
  300. package/dist/zonos-elements/p-c770044a.system.entry.js +0 -1
  301. package/dist/zonos-elements/p-d4842d10.system.entry.js +0 -1
  302. package/dist/zonos-elements/p-d6c3aec8.system.entry.js +0 -1
  303. package/dist/zonos-elements/p-daf73a4c.system.js +0 -1
  304. package/dist/zonos-elements/p-de388ea0.entry.js +0 -1
  305. package/dist/zonos-elements/p-e14d89de.entry.js +0 -1
  306. package/dist/zonos-elements/p-f6e587bb.entry.js +0 -1
  307. package/dist/zonos-elements/p-f818bdf5.entry.js +0 -1
  308. package/dist/zonos-elements/p-fce6bffe.system.entry.js +0 -1
@@ -0,0 +1,1955 @@
1
+ 'use strict';
2
+
3
+ const zonosStore = require('./zonosStore-9264749e.js');
4
+ const localization = require('./localization-2f17c95f.js');
5
+ const handleFetch = require('./handleFetch-969d05d8.js');
6
+ const isDarkColor = require('./isDarkColor-bcf49625.js');
7
+ const getBorderRadius = require('./getBorderRadius-8d3b1049.js');
8
+
9
+ /**
10
+ * Extract value from translated object
11
+ */
12
+ const getTranslatedAddress = ({ currentAddress, translatedAddress, }) => {
13
+ var _a, _b, _c, _d, _e, _f;
14
+ const { city, country, line1, line2, postal_code, state } = currentAddress.value.address;
15
+ const name = currentAddress.value.name ||
16
+ [currentAddress.value.firstName, currentAddress.value.lastName].join(' ');
17
+ return {
18
+ city: ((_a = translatedAddress.city) === null || _a === void 0 ? void 0 : _a[city]) || city,
19
+ country: country,
20
+ line1: ((_b = translatedAddress.line1) === null || _b === void 0 ? void 0 : _b[line1]) || line1,
21
+ line2: ((_c = translatedAddress.line2) === null || _c === void 0 ? void 0 : _c[line2 || '']) || line2 || '',
22
+ name: ((_d = translatedAddress.name) === null || _d === void 0 ? void 0 : _d[name]) || name,
23
+ phone: currentAddress.value.phone || '',
24
+ postal_code: ((_e = translatedAddress.postal_code) === null || _e === void 0 ? void 0 : _e[postal_code]) || postal_code,
25
+ state: ((_f = translatedAddress.state) === null || _f === void 0 ? void 0 : _f[state]) || state,
26
+ };
27
+ };
28
+ /**
29
+ * Similar to prepCalculateLandedCost except it only uses cart ID
30
+ */
31
+ const prepCartCalculateLandedCost = (cartId) => {
32
+ var _a;
33
+ const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
34
+ // maybe we don't need email now for prefetch the landed cost
35
+ const stripeLinkData = stripeStore.stripeLinkEventData;
36
+ const stripeAddressData = stripeStore.stripeAddressEventData;
37
+ const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
38
+ ? stripeStore.stripeAddressEventData
39
+ : stripeStore.stripeBillingAddressEventData;
40
+ if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
41
+ throw new Error('Missing stripe address data');
42
+ }
43
+ // Attempt to get translated address if available
44
+ const translatedShippingAddress = getTranslatedAddress({
45
+ currentAddress: stripeAddressData,
46
+ translatedAddress: stripeStore.translatedAddress.address,
47
+ });
48
+ const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
49
+ const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
50
+ const translatedBillingAddress = getTranslatedAddress({
51
+ currentAddress: stripeBillingAddressData,
52
+ translatedAddress: stripeStore.translatedAddress.address,
53
+ });
54
+ const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
55
+ const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
56
+ return {
57
+ billingAddress: {
58
+ addressLine1: translatedBillingAddress.line1,
59
+ addressLine2: translatedBillingAddress.line2 || '',
60
+ city: translatedBillingAddress.city,
61
+ country: translatedBillingAddress.country,
62
+ postalCode: translatedBillingAddress.postal_code,
63
+ state: translatedBillingAddress.state,
64
+ },
65
+ billingContact: {
66
+ // firstName and lastName should be valid now since stripe only mark
67
+ // the address as complete when both fields are filled.
68
+ firstName: billingFirstName,
69
+ lastName: billingLastName,
70
+ phone: translatedBillingAddress.phone,
71
+ },
72
+ // Use the first item's currency code
73
+ cartCurrencyCode: (_a = cartStore.items[0]) === null || _a === void 0 ? void 0 : _a.currencyCode,
74
+ cartId,
75
+ checkoutSessionId: localization.storageStore.checkoutSessionId || '',
76
+ contact: {
77
+ companyName: stripeStore.companyName,
78
+ email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
79
+ // firstName and lastName should be valid now since stripe only mark
80
+ // the address as complete when both fields are filled.
81
+ firstName: shippingFirstName,
82
+ lastName: shippingLastName,
83
+ phone: translatedShippingAddress.phone,
84
+ },
85
+ isTest: !!isE2ETest,
86
+ landedCostAdjustments: cartStore.promoCode
87
+ ? [
88
+ {
89
+ amount: 0,
90
+ productId: null,
91
+ promoCode: cartStore.promoCode,
92
+ sku: null,
93
+ type: 'PROMO_CODE',
94
+ },
95
+ ]
96
+ : [],
97
+ shipToTaxId: stripeStore.taxId,
98
+ shippingAddress: {
99
+ addressLine1: translatedShippingAddress.line1,
100
+ addressLine2: translatedShippingAddress.line2,
101
+ city: translatedShippingAddress.city,
102
+ country: translatedShippingAddress.country,
103
+ postalCode: translatedShippingAddress.postal_code,
104
+ state: translatedShippingAddress.state,
105
+ },
106
+ };
107
+ };
108
+ const prepCalculateLandedCost = () => {
109
+ const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
110
+ // maybe we don't need email now for prefetch the landed cost
111
+ const stripeLinkData = stripeStore.stripeLinkEventData;
112
+ const stripeAddressData = stripeStore.stripeAddressEventData;
113
+ const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
114
+ ? stripeStore.stripeAddressEventData
115
+ : stripeStore.stripeBillingAddressEventData;
116
+ handleFetch.log({ stripeAddressData, stripeBillingAddressData }, 'info');
117
+ if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
118
+ throw new Error('Missing stripe address data');
119
+ }
120
+ // Attempt to get translated address if available
121
+ const translatedShippingAddress = getTranslatedAddress({
122
+ currentAddress: stripeAddressData,
123
+ translatedAddress: stripeStore.translatedAddress.address,
124
+ });
125
+ const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
126
+ const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
127
+ const translatedBillingAddress = getTranslatedAddress({
128
+ currentAddress: stripeBillingAddressData,
129
+ translatedAddress: stripeStore.translatedAddress.address,
130
+ });
131
+ const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
132
+ const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
133
+ const convertedCartAdjuments = cartStore.adjustments.map(adjustment => ({
134
+ amount: adjustment.amount,
135
+ name: adjustment.description || null,
136
+ productId: adjustment.productId,
137
+ sku: adjustment.sku,
138
+ type: adjustment.type,
139
+ }));
140
+ const adjustments = cartStore.promoCode
141
+ ? [
142
+ {
143
+ amount: 0,
144
+ productId: null,
145
+ promoCode: cartStore.promoCode,
146
+ sku: null,
147
+ type: 'PROMO_CODE',
148
+ },
149
+ ...convertedCartAdjuments,
150
+ ]
151
+ : convertedCartAdjuments;
152
+ return {
153
+ billingAddress: {
154
+ addressLine1: translatedBillingAddress.line1,
155
+ addressLine2: translatedBillingAddress.line2 || '',
156
+ city: translatedBillingAddress.city,
157
+ country: translatedBillingAddress.country,
158
+ postalCode: translatedBillingAddress.postal_code,
159
+ state: translatedBillingAddress.state,
160
+ },
161
+ billingContact: {
162
+ // firstName and lastName should be valid now since stripe only mark
163
+ // the address as complete when both fields are filled.
164
+ firstName: billingFirstName,
165
+ lastName: billingLastName,
166
+ phone: translatedBillingAddress.phone,
167
+ },
168
+ checkoutSessionId: localization.storageStore.checkoutSessionId || '',
169
+ contact: {
170
+ companyName: stripeStore.companyName,
171
+ email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
172
+ // firstName and lastName should be valid now since stripe only mark
173
+ // the address as complete when both fields are filled.
174
+ firstName: shippingFirstName,
175
+ lastName: shippingLastName,
176
+ phone: translatedShippingAddress.phone,
177
+ },
178
+ isTest: isE2ETest,
179
+ items: cartStore.items,
180
+ landedCostAdjustments: adjustments,
181
+ shipToTaxId: stripeStore.taxId,
182
+ shippingAddress: {
183
+ addressLine1: translatedShippingAddress.line1,
184
+ addressLine2: translatedShippingAddress.line2,
185
+ city: translatedShippingAddress.city,
186
+ country: translatedShippingAddress.country,
187
+ postalCode: translatedShippingAddress.postal_code,
188
+ state: translatedShippingAddress.state,
189
+ },
190
+ };
191
+ };
192
+
193
+ const triggerBuildLandedCost = async (buildLandedCost) => {
194
+ var _a, _b, _c, _d, _e;
195
+ const data = prepCalculateLandedCost();
196
+ const landedCost = await buildLandedCost({
197
+ billingAddress: data.billingAddress,
198
+ billingContact: data.billingContact,
199
+ checkoutSessionId: data.checkoutSessionId,
200
+ contact: data.contact,
201
+ landedCostAdjustments: data.landedCostAdjustments,
202
+ // zonosApiKey should always be available
203
+ publicCredential: window.Zonos.zonosApiKey || '',
204
+ shippingAddress: data.shippingAddress,
205
+ zonosApiRoute: handleFetch.fallbackApiList['vercel'],
206
+ });
207
+ if (!landedCost ||
208
+ // Only show errors if there are no rate back (checkoutSessionWorkflow) and there are errors
209
+ (!((_a = landedCost.checkoutSessionWorkflow) === null || _a === void 0 ? void 0 : _a.length) && ((_b = landedCost.errors) === null || _b === void 0 ? void 0 : _b.length))) {
210
+ throw new Error(`Failed to build landed cost: ${((_d = (_c = landedCost === null || landedCost === void 0 ? void 0 : landedCost.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message) || 'Unknown error'}`);
211
+ }
212
+ // Validate the landed cost object to make sure the returned value from buildLandedCost has a valid schema
213
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/validate-landed-cost', {
214
+ body: landedCost,
215
+ headers: {
216
+ 'Content-Type': 'application/json',
217
+ },
218
+ method: 'POST',
219
+ });
220
+ if (!json || errors.length) {
221
+ throw new Error(`Invalid landed cost object: ${((_e = errors.find(Boolean)) === null || _e === void 0 ? void 0 : _e.message) || 'Unknown error'}`);
222
+ }
223
+ return landedCost;
224
+ };
225
+
226
+ const calculateLandedCost = async (abortController) => {
227
+ var _a;
228
+ // If buildLandedCost callback is supplied, use that instead of our regular request to '/calculate-landed-cost'
229
+ const buildLandedCost = zonosStore.zonosStore.checkoutSettings.buildLandedCost;
230
+ if (buildLandedCost) {
231
+ const json = await triggerBuildLandedCost(buildLandedCost);
232
+ return json;
233
+ }
234
+ // request to get landed cost info
235
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/calculate-landed-cost', {
236
+ body: prepCalculateLandedCost(),
237
+ method: 'POST',
238
+ signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
239
+ });
240
+ if (errors.length || !json) {
241
+ const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
242
+ if (isAbortedRequest) {
243
+ throw new Error('The landed cost calculation request was aborted to initiate a new one.');
244
+ }
245
+ // We want to show any successful quotes even if there are errors
246
+ errors.forEach(error => {
247
+ // eslint-disable-next-line no-console
248
+ console.warn(`Error calculating landed cost: ${error.message}`);
249
+ });
250
+ if (!json) {
251
+ throw new Error('Failed to calculate landed cost');
252
+ }
253
+ return json;
254
+ }
255
+ return json;
256
+ };
257
+
258
+ const cartCalculateLandedCost = async ({ abortController, cartId, }) => {
259
+ var _a;
260
+ // request to get landed cost info
261
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/cart-calculate-landed-cost', {
262
+ body: prepCartCalculateLandedCost(cartId),
263
+ method: 'POST',
264
+ signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
265
+ });
266
+ if (errors.length || !json) {
267
+ const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
268
+ const errorMessage = isAbortedRequest
269
+ ? 'The landed cost calculation request was aborted to initiate a new one.'
270
+ : 'Failed to calculate landed cost';
271
+ throw new Error(errorMessage);
272
+ }
273
+ return json;
274
+ };
275
+
276
+ var __rest = (undefined && undefined.__rest) || function (s, e) {
277
+ var t = {};
278
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
279
+ t[p] = s[p];
280
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
281
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
282
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
283
+ t[p[i]] = s[p[i]];
284
+ }
285
+ return t;
286
+ };
287
+ const calculateLandedCostNormalized = async (abortController) => {
288
+ const cartId = window.Zonos.cartId;
289
+ // Calculate landed cost as usual if no cartId is available
290
+ if (!cartId) {
291
+ const landedCostResult = await calculateLandedCost(abortController);
292
+ return landedCostResult;
293
+ }
294
+ // Calculate landed cost using cartId
295
+ const _a = await cartCalculateLandedCost({
296
+ abortController,
297
+ cartId,
298
+ }), { cartWorkflow } = _a, rest = __rest(_a, ["cartWorkflow"]);
299
+ return Object.assign(Object.assign({}, rest), { itemCreateWorkflow: cartWorkflow.items });
300
+ };
301
+
302
+ const trackConversionEvent = async ({ checkoutSessionId, eventName, metadata, }) => {
303
+ var _a, _b;
304
+ const eventCreated = Date.now();
305
+ const trackLogMetadata = [...window.Zonos.trackEventLogs];
306
+ window.Zonos.trackEventLogs.push({
307
+ checkoutSessionId,
308
+ eventCreated,
309
+ eventName,
310
+ });
311
+ const isDevelopment =
312
+ // if the url includes zonos.com and not hosted checkout (checkout.zonos.com), it means we are on the development site (dashboard, preview zonos domain or main zonos.com)
313
+ (window.location.href.includes('zonos.com') &&
314
+ !window.location.href.includes('checkout.zonos.com')) ||
315
+ !!((_a = window.Zonos) === null || _a === void 0 ? void 0 : _a.zonosQaUrl) ||
316
+ !!((_b = window.Zonos) === null || _b === void 0 ? void 0 : _b.debug);
317
+ const isTest = handleFetch.getIsTestMode() || handleFetch.getIsStagingMode();
318
+ if ((isTest || isDevelopment) &&
319
+ // if found, it means we want to test the conversion event in development site, or test mode and staging mode
320
+ !window.Zonos.zonosConversionTest) {
321
+ return;
322
+ }
323
+ const countryCode = localization.localizationStore.selectedCountryCode;
324
+ const organizationId = zonosStore.zonosStore.organizationId;
325
+ if (!checkoutSessionId) {
326
+ void handleFetch.sendErrorLog({
327
+ endpoint: 'trackConversionEventMetric',
328
+ errors: [`Event "${eventName}" - No checkout session id found`],
329
+ metadata: {
330
+ allLogs: handleFetch.allLogs,
331
+ checkoutSessionId,
332
+ eventName,
333
+ metadata,
334
+ organizationId,
335
+ trackEventLogs: trackLogMetadata,
336
+ },
337
+ });
338
+ // checkoutSessionId is required for tracking conversion events to work properly
339
+ return;
340
+ }
341
+ if (!organizationId) {
342
+ void handleFetch.sendErrorLog({
343
+ endpoint: 'trackConversionEventMetric',
344
+ errors: [`Event "${eventName}" - No organization id found`],
345
+ metadata: {
346
+ allLogs: handleFetch.allLogs,
347
+ checkoutSessionId,
348
+ eventName,
349
+ metadata,
350
+ organizationId,
351
+ trackEventLogs: trackLogMetadata,
352
+ },
353
+ });
354
+ }
355
+ const body = {
356
+ checkoutSessionId,
357
+ countryCode,
358
+ eventCreated,
359
+ eventName,
360
+ metadata: Object.assign(Object.assign({}, metadata), { trackEventLogs: trackLogMetadata }),
361
+ organizationId,
362
+ };
363
+ await handleFetch.handleFetch('/api/zonos-elements/track-conversion-event', {
364
+ body,
365
+ method: 'POST',
366
+ });
367
+ };
368
+
369
+ /**
370
+ * This function generates an object that contains the fields of an address that have invalid characters.
371
+ *
372
+ * @param {Object} params - The parameters for the function.
373
+ * @param {Address | null} params.address - The address to check for invalid characters.
374
+ * @param {ReturnType<typeof containsNonLatinChars> | null} params.invalidAdddressList - The list of address fields that contain invalid characters.
375
+ *
376
+ * @returns {Partial<Address> | undefined} - An object that contains the fields of the address that have invalid characters. If no fields have invalid characters, the function returns undefined.
377
+ */
378
+ const getExcludeAddressFieldsObject = ({ address, invalidAdddressList, }) => {
379
+ if (!address) {
380
+ return;
381
+ }
382
+ // if there are no invalid characters, return an empty object
383
+ if (!invalidAdddressList) {
384
+ return;
385
+ }
386
+ const excludeFields = {};
387
+ if (invalidAdddressList.city) {
388
+ excludeFields.city = address.city;
389
+ }
390
+ if (invalidAdddressList.line1) {
391
+ excludeFields.line1 = address.line1;
392
+ }
393
+ if (invalidAdddressList.line2) {
394
+ excludeFields.line2 = address.line2;
395
+ }
396
+ if (invalidAdddressList.postal_code) {
397
+ excludeFields.postal_code = address.postal_code;
398
+ }
399
+ if (invalidAdddressList.state) {
400
+ excludeFields.state = address.state;
401
+ }
402
+ if (invalidAdddressList.name) {
403
+ excludeFields.name = address.name;
404
+ }
405
+ // return null if there are no fields to exclude
406
+ return Object.keys(excludeFields).length ? excludeFields : undefined;
407
+ };
408
+ /**
409
+ * This function builds the request body for validating an address. It checks if the address and billing address are ready and if they contain any invalid characters.
410
+ * If there are non-latin character to translate, returns an object with the address fields that have invalid characters, the destination country, and the first and last name.
411
+ * If the conditions are not met, it returns null.
412
+ *
413
+ * @param {Object} params - The parameters for the function.
414
+ * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
415
+ * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
416
+ * @param {StripeAddressEventData} params.stripeAddressEventData - The Stripe event data for the address.
417
+ * @param {StripeAddressEventData} params.stripeBillingAddressEventData - The Stripe event data for the billing address.
418
+ * @param {boolean} params.stripeShippingSameAsBilling - A flag indicating whether the shipping address is the same as the billing address.
419
+ *
420
+ * @returns {ValidateAddressRequest | null} - An object that contains the address fields that have invalid characters, the destination country, and the first and last name. If the conditions are not met, the function returns null.
421
+ */
422
+ const buildTranslateRequest = ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, stripeAddressEventData, stripeBillingAddressEventData, stripeShippingSameAsBilling, }) => {
423
+ var _a, _b, _c, _d;
424
+ const isStripeAddressReady = !!(stripeAddressEventData === null || stripeAddressEventData === void 0 ? void 0 : stripeAddressEventData.complete);
425
+ const isStripeBillingAddressReady = stripeShippingSameAsBilling
426
+ ? isStripeAddressReady
427
+ : !!(stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.complete);
428
+ // only translate if both address and billing address are ready
429
+ if (!isStripeAddressReady || !isStripeBillingAddressReady) {
430
+ return null;
431
+ }
432
+ // only translate if there are invalid characters
433
+ if (!addressInvalidCharactersList && !billingAddressInvalidCharactersList) {
434
+ return null;
435
+ }
436
+ const stripeAddressValue = stripeAddressEventData.value;
437
+ const stripeBillingAddressValue = (stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.value) || null;
438
+ // Returns undefined if the name is Latin so it won't be included in the request body
439
+ const firstName = stripeAddressValue.firstName || ((_a = stripeAddressValue.name) === null || _a === void 0 ? void 0 : _a.split(' ')[0]);
440
+ const lastName = stripeAddressValue.lastName || ((_b = stripeAddressValue.name) === null || _b === void 0 ? void 0 : _b.split(' ')[1]);
441
+ const name = `${firstName} ${lastName}`;
442
+ const billingFirstName = stripeAddressValue.firstName ||
443
+ ((_c = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _c === void 0 ? void 0 : _c.split(' ')[0]);
444
+ const billingLastName = stripeAddressValue.lastName ||
445
+ ((_d = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _d === void 0 ? void 0 : _d.split(' ')[1]);
446
+ const billingName = billingFirstName && billingLastName
447
+ ? `${billingFirstName} ${billingLastName}`
448
+ : '';
449
+ const address = stripeAddressValue.address;
450
+ const billingAddress = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.address;
451
+ return {
452
+ address: getExcludeAddressFieldsObject({
453
+ address: Object.assign(Object.assign({}, address), { name }),
454
+ invalidAdddressList: addressInvalidCharactersList,
455
+ }),
456
+ // only include billing address if it's different from the shipping address
457
+ billingAddress: !stripeShippingSameAsBilling
458
+ ? getExcludeAddressFieldsObject({
459
+ address: billingAddress
460
+ ? Object.assign(Object.assign({}, billingAddress), { name: billingName }) : null,
461
+ invalidAdddressList: billingAddressInvalidCharactersList,
462
+ })
463
+ : undefined,
464
+ destinationCountry: address.country,
465
+ };
466
+ };
467
+
468
+ /**
469
+ * Sorts service levels with lower cost first
470
+ */
471
+ const sortServiceLevelOptionsByAmount = (serviceLevels) => {
472
+ const sortedServiceLevels = serviceLevels.sort((a, b) => {
473
+ return a.amount - b.amount;
474
+ });
475
+ return sortedServiceLevels;
476
+ };
477
+
478
+ const getCheckoutSession = async () => {
479
+ if (!localization.storageStore.checkoutSessionId) {
480
+ return {
481
+ errors: [{ message: 'No checkout session id found' }],
482
+ json: null,
483
+ };
484
+ }
485
+ const searchParams = new URLSearchParams();
486
+ searchParams.set('checkoutSessionId', localization.storageStore.checkoutSessionId);
487
+ const { errors, json } = await handleFetch.handleFetch(`/api/zonos-elements/get-checkout-session?${searchParams.toString()}`);
488
+ return { errors, json };
489
+ };
490
+
491
+ /**
492
+ * Validate checkout session before confirming payment
493
+ */
494
+ const validateCheckoutSession = async () => {
495
+ var _a;
496
+ // get checkout session info
497
+ const { errors, json } = await getCheckoutSession();
498
+ if (errors.length || !json) {
499
+ handleFetch.logError('Failed to retrieve checkout session info before confirming payment ', errors);
500
+ void handleFetch.sendErrorLog({
501
+ endpoint: 'validateCheckoutSession',
502
+ errors: errors.map(error => error.message),
503
+ metadata: { allLogs: handleFetch.allLogs },
504
+ });
505
+ return {
506
+ errorMessage: localization.translate('Unable to retrieve the checkout session at the moment. Please try again or contact our support team.'),
507
+ valid: false,
508
+ };
509
+ }
510
+ // Make sure landed cost is found in the checkout session
511
+ if (!((_a = json.checkoutSession.landedCost) === null || _a === void 0 ? void 0 : _a.id)) {
512
+ handleFetch.logError('Landed cost is not found in the checkout session before confirming payment.');
513
+ void handleFetch.sendErrorLog({
514
+ endpoint: 'validateCheckoutSession',
515
+ errors: ['No landed cost found before confirming payment'],
516
+ metadata: { allLogs: handleFetch.allLogs },
517
+ });
518
+ return {
519
+ errorMessage: localization.translate('No shipment rating selected. Please go back to the "Shipping" step and select a shipment rating to proceed.'),
520
+ valid: false,
521
+ };
522
+ }
523
+ return { errorMessage: '', valid: true };
524
+ };
525
+
526
+ const addressRuleStyle = ({ theme, }) => {
527
+ const defaultStyle = {
528
+ '.AccordionItem': {
529
+ color: 'var(--colorText)',
530
+ },
531
+ '.AccordionItem--selected': {
532
+ color: 'var(--colorText)',
533
+ },
534
+ '.Action': {
535
+ color: 'var(--colorText)',
536
+ },
537
+ '.Input': {
538
+ boxShadow: 'none',
539
+ fontSize: zonosStore.zonosStore.appearance.fontSizeInputValue
540
+ ? `${zonosStore.zonosStore.appearance.fontSizeInputValue}px`
541
+ : undefined,
542
+ // need to reset everything and the paddingTop to default, otherwise the paddingTop will not be updated.
543
+ padding: '0',
544
+ paddingBottom: '8px',
545
+ paddingLeft: '16px',
546
+ paddingRight: '8px',
547
+ // any value here will be add up to the default paddingTop (20px).
548
+ paddingTop: '6px',
549
+ },
550
+ '.Label--resting': {
551
+ fontSize: zonosStore.zonosStore.appearance.fontSizeInputLabel
552
+ ? `${zonosStore.zonosStore.appearance.fontSizeInputLabel}px`
553
+ : undefined,
554
+ },
555
+ '.PickerItem--highlight': {
556
+ boxShadow: '0 0 0 2px var(--colorBackground)',
557
+ },
558
+ '.PickerItem--highlight:hover': {
559
+ backgroundColor: 'var(--colorBackground)',
560
+ boxShadow: 'none',
561
+ },
562
+ '.PickerItem--new': {
563
+ color: 'var(--colorText)',
564
+ },
565
+ '.Tab--selected': {
566
+ borderStyle: 'solid',
567
+ borderWidth: '1px',
568
+ },
569
+ };
570
+ switch (theme) {
571
+ case 'DARK': {
572
+ return Object.assign(Object.assign({}, defaultStyle), { '.Action': Object.assign(Object.assign({}, defaultStyle['.Action']), { color: 'white' }), '.PickerItem--new': Object.assign(Object.assign({}, defaultStyle['.PickerItem--new']), { color: 'white' }) });
573
+ }
574
+ default:
575
+ return defaultStyle;
576
+ }
577
+ };
578
+
579
+ const defaultVariable = ({ borderStyle, theme, }) => {
580
+ switch (theme) {
581
+ case 'DARK':
582
+ return {
583
+ borderRadius: getBorderRadius.getBorderRadius({ overrideBorderStyle: borderStyle }),
584
+ colorBackground: '#101117',
585
+ colorBackgroundText: '#C5C6CA',
586
+ colorText: '#C5C6CA',
587
+ colorTextPlaceholder: '#C5C6CA',
588
+ };
589
+ default:
590
+ return {
591
+ borderRadius: getBorderRadius.getBorderRadius({ overrideBorderStyle: borderStyle }),
592
+ iconMenuColor: 'var(--colorText)',
593
+ iconMenuHoverColor: 'var(--colorText)',
594
+ };
595
+ }
596
+ };
597
+
598
+ const { onChange: stripeStoreOnChange, reset: reset$1, state: stripeStore, } = zonosStore.createStore(() => ({
599
+ checkoutSettlementCurrency: 'USD',
600
+ clientSecret: sessionStorage.getItem('zonos--client-secret') || '',
601
+ companyName: '',
602
+ customAddressErrors: {
603
+ city: '',
604
+ firstName: '',
605
+ lastName: '',
606
+ line1: '',
607
+ phone: '',
608
+ postalCode: '',
609
+ showError: false,
610
+ state: '',
611
+ },
612
+ customBillingAddressErrors: {
613
+ city: '',
614
+ firstName: '',
615
+ lastName: '',
616
+ line1: '',
617
+ phone: '',
618
+ postalCode: '',
619
+ showError: false,
620
+ state: '',
621
+ },
622
+ customErrorMessage: null,
623
+ customerProfile: null,
624
+ fetchingLandedCostAbortController: null,
625
+ hasPaymentError: false,
626
+ isFetchingLandedCost: false,
627
+ isFetchingSession: false,
628
+ shouldInventoryRefund: false,
629
+ shouldRenderPayInUsdButton: false,
630
+ /**
631
+ * Default to skip payment intent, only create payment intent when "skipPaymentIntent" in url's query params is set "0"
632
+ * @default true
633
+ */
634
+ skipPaymentIntent: new URLSearchParams(window.location.search).get('skipPaymentIntent') === '0'
635
+ ? false
636
+ : true,
637
+ stripe: null,
638
+ stripeAddressElement: null,
639
+ stripeAddressEventData: null,
640
+ stripeAddressUsedWhenFetchingLC: null,
641
+ stripeAddressUsedWhenValidatingAddress: null,
642
+ stripeBillingAddressElement: null,
643
+ stripeBillingAddressEventData: null,
644
+ stripeBillingAddressUsedWhenFetchingLC: null,
645
+ stripeBillingAddressUsedWhenValidatingAddress: null,
646
+ stripeCustomerSessionClientSecret: null,
647
+ stripeElements: null,
648
+ stripeElementsForBillingAddress: null,
649
+ stripeElementsOptions: null,
650
+ stripeLinkElement: null,
651
+ stripeLinkEventData: null,
652
+ stripeLinkUsedWhenFetchingLC: null,
653
+ stripePaymentElement: null,
654
+ stripePaymentEventData: null,
655
+ stripeShippingSameAsBilling: true,
656
+ taxId: '',
657
+ taxIdUsedWhenFetchingLC: '',
658
+ translatedAddress: {
659
+ address: {},
660
+ billingAddress: {},
661
+ firstName: {},
662
+ lastName: {},
663
+ name: {},
664
+ },
665
+ }));
666
+ const getStripeOptions = ({ clientSecret, overrideBorderRadius, overridePrimaryColor, overrideSecondaryColor, overrideTheme, paypalEnabled, }) => {
667
+ const primaryColor = overridePrimaryColor || zonosStore.zonosStore.appearance.colorPrimary;
668
+ const secondaryColor = overrideSecondaryColor || zonosStore.zonosStore.appearance.colorSecondary;
669
+ const themeBasedColor = primaryColor && isDarkColor.isDarkColor(primaryColor) ? 'night' : 'flat';
670
+ // if overrideTheme is provided, use it. Otherwise, use theme based on primary color
671
+ const theme = overrideTheme === 'DARK' ? 'night' : 'flat';
672
+ const paypalPaymentType = paypalEnabled ? ['external_paypal'] : [];
673
+ return {
674
+ appearance: {
675
+ labels: 'floating',
676
+ rules: Object.assign({}, addressRuleStyle({ theme: overrideTheme || 'LIGHT' })),
677
+ // get contrast theme color base on primary color
678
+ theme: overrideTheme ? theme : themeBasedColor,
679
+ variables: Object.assign(Object.assign({}, defaultVariable({
680
+ borderStyle: overrideBorderRadius,
681
+ theme: 'LIGHT',
682
+ })), {
683
+ // use the button background color for input glow color
684
+ colorPrimary: secondaryColor }),
685
+ },
686
+ // Client secret can be undefined since we will load other elements that doesn't require client secret first, then load client secret and render one that requires it later
687
+ clientSecret: clientSecret || undefined,
688
+ customerSessionClientSecret: stripeStore.stripeCustomerSessionClientSecret || undefined,
689
+ externalPaymentMethodTypes: [...paypalPaymentType],
690
+ locale: localization.localizationStore.selectedLocale,
691
+ };
692
+ };
693
+ const stripeStoreCleanupDomesticShippingSession = () => {
694
+ window.sessionStorage.removeItem('zonos--bigcommerce-domestic-checkout-shipping');
695
+ };
696
+ // Save shipping address to session storage
697
+ const stripeStoreSaveDomesticShippingSession = (props) => {
698
+ window.sessionStorage.setItem('zonos--bigcommerce-domestic-checkout-shipping', JSON.stringify(props));
699
+ };
700
+ const stripeStoreGetDomesticShippingSession = () => {
701
+ const session = window.sessionStorage.getItem('zonos--bigcommerce-domestic-checkout-shipping');
702
+ return handleFetch.jsonParse(session);
703
+ };
704
+ const initStripeElements = async (props) => {
705
+ var _a, _b;
706
+ const clientSecret = stripeStore.clientSecret;
707
+ if (!stripeStore.stripe) {
708
+ handleFetch.log('Skip. Stripe is not initialized');
709
+ return;
710
+ }
711
+ const stripeOptions = getStripeOptions({
712
+ clientSecret,
713
+ overrideBorderRadius: props === null || props === void 0 ? void 0 : props.overrideBorderRadius,
714
+ overridePrimaryColor: props === null || props === void 0 ? void 0 : props.overridePrimaryColor,
715
+ overrideSecondaryColor: props === null || props === void 0 ? void 0 : props.overrideSecondaryColor,
716
+ overrideTheme: props === null || props === void 0 ? void 0 : props.overrideTheme,
717
+ paypalEnabled: props === null || props === void 0 ? void 0 : props.paypalEnabled,
718
+ });
719
+ // compare with the previous options to see if we need to update
720
+ const isSameOptions = JSON.stringify(stripeOptions) ===
721
+ JSON.stringify(stripeStore.stripeElementsOptions);
722
+ if (!stripeStore.stripeElements ||
723
+ !stripeStore.stripeElementsForBillingAddress) {
724
+ // init stripe elements if it doesn't exist
725
+ stripeStore.stripeElements = (_a = stripeStore.stripe) === null || _a === void 0 ? void 0 : _a.elements(stripeOptions);
726
+ // save stripe elements options for later comparison
727
+ stripeStore.stripeElementsOptions = stripeOptions;
728
+ handleFetch.log('Stripe elements initialized');
729
+ // init stripe elements for billing address
730
+ stripeStore.stripeElementsForBillingAddress =
731
+ (_b = stripeStore.stripe) === null || _b === void 0 ? void 0 : _b.elements(stripeOptions);
732
+ handleFetch.log('Stripe elements for billing address initialized');
733
+ return;
734
+ }
735
+ if (!isSameOptions) {
736
+ // update elements with new option if it already exists
737
+ stripeStore.stripeElements.update(stripeOptions);
738
+ // update elements for stripe billing address
739
+ stripeStore.stripeElementsForBillingAddress.update(stripeOptions);
740
+ // save stripe elements options for later comparison
741
+ stripeStore.stripeElementsOptions = stripeOptions;
742
+ void stripeStore.stripeElements.fetchUpdates();
743
+ }
744
+ handleFetch.log('Stripe elements updated');
745
+ };
746
+ const stripeStoreReset = () => {
747
+ // clean clientSecret so that we can start the new one.
748
+ sessionStorage.removeItem('zonos--client-secret');
749
+ // cleanup stripe elements
750
+ reset$1();
751
+ // set stripe back to window.Zonos.stripe
752
+ stripeStore.stripe = window.Zonos.stripe;
753
+ };
754
+ const checkIsAddressOutdatedForValidation = () => {
755
+ var _a, _b, _c, _d;
756
+ const isAddressDataDirty = JSON.stringify((_a = stripeStore.stripeAddressUsedWhenValidatingAddress) === null || _a === void 0 ? void 0 : _a.value) !== JSON.stringify((_b = stripeStore.stripeAddressEventData) === null || _b === void 0 ? void 0 : _b.value);
757
+ const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
758
+ JSON.stringify((_c = stripeStore.stripeBillingAddressEventData) === null || _c === void 0 ? void 0 : _c.value) !==
759
+ JSON.stringify((_d = stripeStore.stripeBillingAddressUsedWhenValidatingAddress) === null || _d === void 0 ? void 0 : _d.value);
760
+ return isAddressDataDirty || isBillingAddressDataDirty;
761
+ };
762
+ const checkIsAddressOutdatedForLCPrefetch = () => {
763
+ var _a, _b, _c, _d, _e, _f;
764
+ const isLinkDataDirty = JSON.stringify((_a = stripeStore.stripeLinkUsedWhenFetchingLC) === null || _a === void 0 ? void 0 : _a.value) !==
765
+ JSON.stringify((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.value);
766
+ const isAddressDataDirty = JSON.stringify((_c = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _c === void 0 ? void 0 : _c.value) !==
767
+ JSON.stringify((_d = stripeStore.stripeAddressEventData) === null || _d === void 0 ? void 0 : _d.value);
768
+ const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
769
+ JSON.stringify((_e = stripeStore.stripeBillingAddressEventData) === null || _e === void 0 ? void 0 : _e.value) !==
770
+ JSON.stringify((_f = stripeStore.stripeBillingAddressUsedWhenFetchingLC) === null || _f === void 0 ? void 0 : _f.value);
771
+ return isLinkDataDirty || isAddressDataDirty || isBillingAddressDataDirty;
772
+ };
773
+ /**
774
+ * Check if the address and email info used when fetching landed cost with the current email and address info are different
775
+ * Purpose is to resend the request if the info used when fetching landed cost is different from the current info
776
+ */
777
+ const isPrefetchInfoOutdated = () => {
778
+ var _a;
779
+ // Mark the landed cost is outdated since the item total amount has changed (items total didn't match with the cart subtotal)
780
+ const isTotalAmountChanged = cartStore.landedCostData &&
781
+ ((_a = cartStore.landedCostData.find(Boolean)) === null || _a === void 0 ? void 0 : _a.subtotals.items) !==
782
+ cartStore.subtotal;
783
+ const isAddressOutdated = checkIsAddressOutdatedForLCPrefetch();
784
+ // Auto prefetch landed cost if tax id is updated
785
+ const isTaxIdDirty = stripeStore.taxIdUsedWhenFetchingLC !== stripeStore.taxId;
786
+ return (
787
+ // if landed cost data is not available, we need to fetch it
788
+ !cartStore.landedCostData ||
789
+ isAddressOutdated ||
790
+ isTotalAmountChanged ||
791
+ isTaxIdDirty);
792
+ };
793
+ const stripeCalculateLandedCost = async () => {
794
+ var _a;
795
+ const abortController = new AbortController();
796
+ stripeStore.fetchingLandedCostAbortController = abortController;
797
+ // Reset cart items to non-restricted state and restricted item list
798
+ cartStoreResetCartItems();
799
+ const { checkoutSessionWorkflow, errors, itemCreateWorkflow, landedCostCalculateWorkflow, partyCreateWorkflow, shipmentRatingCalculateWorkflow, } = await calculateLandedCostNormalized(abortController);
800
+ // update the error message with customized error message that rule is applying to and disabled shippment rating if there is any
801
+ cartStore.customQuotingError =
802
+ ((_a = errors === null || errors === void 0 ? void 0 : errors.find(error => { var _a; return ((_a = error.extensions) === null || _a === void 0 ? void 0 : _a.ruleMessageType) === 'CUSTOM'; })) === null || _a === void 0 ? void 0 : _a.message) || null;
803
+ cartStore.shippingData = sortServiceLevelOptionsByAmount((shipmentRatingCalculateWorkflow === null || shipmentRatingCalculateWorkflow === void 0 ? void 0 : shipmentRatingCalculateWorkflow.filter(Boolean)) || []);
804
+ // check and update cart items with restrictions
805
+ cartStoreCheckItemRestrictions(itemCreateWorkflow);
806
+ // reset abort controller after we are done
807
+ stripeStore.fetchingLandedCostAbortController = null;
808
+ cartStore.partiesData = (partyCreateWorkflow === null || partyCreateWorkflow === void 0 ? void 0 : partyCreateWorkflow.filter(Boolean)) || [];
809
+ // update cart store with landed cost info
810
+ cartStore.landedCostData =
811
+ (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.map(checkoutSession => {
812
+ const foundLandedCost = landedCostCalculateWorkflow === null || landedCostCalculateWorkflow === void 0 ? void 0 : landedCostCalculateWorkflow.find(item => (item === null || item === void 0 ? void 0 : item.id) === checkoutSession.landedCostId);
813
+ if (!foundLandedCost) {
814
+ return null;
815
+ }
816
+ return Object.assign(Object.assign({}, checkoutSession), { landedCost: foundLandedCost });
817
+ }).filter(Boolean)) || [];
818
+ // Send event when we get the quote back after the customer clicked "Continue to shipping"
819
+ const checkoutSessionId = localization.storageStore.checkoutSessionId;
820
+ if (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.length) {
821
+ void trackConversionEvent({
822
+ checkoutSessionId,
823
+ eventName: 'checkout_quoteReceived',
824
+ });
825
+ }
826
+ // update adjustmentTotal
827
+ // highlight promocode input error if promocode is applied but no adjustment applied in landed cost
828
+ const isInvalidPromoCode = cartStore.promoCodeApplied &&
829
+ !cartStore.landedCostData.find(item => {
830
+ var _a;
831
+ return (_a = item.landedCost.appliedAdjustments) === null || _a === void 0 ? void 0 : _a.find(_item => _item.type === 'PROMO_CODE');
832
+ });
833
+ cartStore.promoCodeError = isInvalidPromoCode;
834
+ // When promocode is valid, set promoCode to session storage so if user close the modal, we can still reapply for them
835
+ if (!isInvalidPromoCode) {
836
+ sessionStorage.setItem('zonos--promo-code', cartStore.promoCode);
837
+ }
838
+ };
839
+ const stripeStorePrefetchLandedCost = async (params) => {
840
+ var _a, _b, _c, _d, _e, _f, _g, _h;
841
+ const retries = (params === null || params === void 0 ? void 0 : params.retries) || 0;
842
+ const applyingPromocode = !!(params === null || params === void 0 ? void 0 : params.applyingPromocode);
843
+ const stripeAddressReady = !!((_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.complete);
844
+ const stripeLinkReady = !!((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.complete);
845
+ const stripeBillingAddressReady = stripeStore.stripeShippingSameAsBilling
846
+ ? !!((_c = stripeStore.stripeLinkEventData) === null || _c === void 0 ? void 0 : _c.complete)
847
+ : !!((_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.complete);
848
+ const shouldRefetch = isPrefetchInfoOutdated();
849
+ if (shouldRefetch) {
850
+ // if the info used when fetching landed cost is different from the current info, abort the previous request
851
+ (_e = stripeStore.fetchingLandedCostAbortController) === null || _e === void 0 ? void 0 : _e.abort();
852
+ stripeStore.fetchingLandedCostAbortController = null;
853
+ }
854
+ // Do not fetch if we are not ready or data is not outdated
855
+ if ((!shouldRefetch && !applyingPromocode) ||
856
+ !stripeAddressReady ||
857
+ !stripeLinkReady ||
858
+ !stripeBillingAddressReady) {
859
+ return;
860
+ }
861
+ // If there is retries, stop loading for a moment and then showing the spinner again (this is just so customer can see that checkout is doing something and not stuck)
862
+ if (retries) {
863
+ stripeStore.isFetchingLandedCost = false;
864
+ setTimeout(() => {
865
+ stripeStore.isFetchingLandedCost = true;
866
+ }, 300);
867
+ }
868
+ else {
869
+ stripeStore.isFetchingLandedCost = true;
870
+ }
871
+ if (stripeStore.stripeAddressEventData) {
872
+ stripeStore.stripeAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeAddressEventData);
873
+ }
874
+ if (stripeStore.stripeBillingAddressEventData) {
875
+ stripeStore.stripeBillingAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeBillingAddressEventData);
876
+ }
877
+ if (stripeStore.stripeLinkEventData) {
878
+ stripeStore.stripeLinkUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeLinkEventData);
879
+ }
880
+ stripeStore.taxIdUsedWhenFetchingLC = stripeStore.taxId;
881
+ try {
882
+ // Reset cart items to non-restricted state and restricted item list
883
+ cartStoreResetCartItems();
884
+ // fetch and apply landed cost
885
+ await stripeCalculateLandedCost();
886
+ // This is the cheapest service level since we already sorted them after fetching landed cost
887
+ const cheapestServiceLevel = (_f = cartStore.shippingData) === null || _f === void 0 ? void 0 : _f.find(Boolean);
888
+ // Landed cost that matches with service level
889
+ const matchLandedCost = (_g = cartStore.landedCostData) === null || _g === void 0 ? void 0 : _g.find(x => x.landedCost.shipmentRating.id === (cheapestServiceLevel === null || cheapestServiceLevel === void 0 ? void 0 : cheapestServiceLevel.id));
890
+ // apply new subtotal and total, this is mainly to show items in the presentment currency
891
+ const subtotals = !!matchLandedCost ? matchLandedCost.subtotals : null;
892
+ if (subtotals) {
893
+ // prefetch landed cost will not update shipping and taxes since we haven't selected shipping method yet
894
+ cartStoreApplySubtotals({
895
+ method: (matchLandedCost === null || matchLandedCost === void 0 ? void 0 : matchLandedCost.landedCost.method) || 'DDP',
896
+ subtotals,
897
+ });
898
+ }
899
+ }
900
+ catch (err) {
901
+ // default to empty array if we failed to fetch landed cost, so we can show the error message
902
+ cartStore.landedCostData = [];
903
+ cartStore.shippingData = [];
904
+ const excludeErrors = [
905
+ 'The landed cost calculation request was aborted to initiate a new one.',
906
+ ];
907
+ if (err instanceof Error &&
908
+ err.message &&
909
+ !excludeErrors.includes(err.message)) {
910
+ if (retries < 1) {
911
+ // retry fetching landed cost one more time
912
+ await stripeStorePrefetchLandedCost(Object.assign(Object.assign({}, params), { retries: (retries || 0) + 1 }));
913
+ return;
914
+ }
915
+ const shipToAddress = (_h = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _h === void 0 ? void 0 : _h.value;
916
+ void handleFetch.sendErrorLog({
917
+ endpoint: `Failed to fetch landed cost (${retries} retries)`,
918
+ errors: [err.message],
919
+ metadata: {
920
+ cartId: window.Zonos.cartId,
921
+ shipToAddress,
922
+ },
923
+ });
924
+ }
925
+ handleFetch.logError(err);
926
+ }
927
+ stripeStore.isFetchingLandedCost = false;
928
+ };
929
+ const stripeStoreApplyPromoCode = async () => {
930
+ var _a, _b;
931
+ await stripeStorePrefetchLandedCost({
932
+ applyingPromocode: true,
933
+ });
934
+ // Go back to shipping step if we are in payment step so user can reselect shipping method
935
+ if (cartStore.step === 'payment') {
936
+ cartStorePreviousStep();
937
+ }
938
+ // This is the cheapest service level since we already sorted them after fetching landed cost
939
+ const cheapestServiceLevel = (_a = cartStore.shippingData) === null || _a === void 0 ? void 0 : _a.find(Boolean);
940
+ // Landed cost that matches with service level
941
+ const matchLandedCost = (_b = cartStore.landedCostData) === null || _b === void 0 ? void 0 : _b.find(x => x.landedCost.id === (cheapestServiceLevel === null || cheapestServiceLevel === void 0 ? void 0 : cheapestServiceLevel.id));
942
+ if (!cheapestServiceLevel || !matchLandedCost) {
943
+ return;
944
+ }
945
+ await cartStoreUpdateSelectedShippingOption(cheapestServiceLevel, matchLandedCost.landedCostId);
946
+ };
947
+ const stripeStoreResetPromoCode = () => {
948
+ cartStore.promoCode = '';
949
+ sessionStorage.removeItem('zonos--promo-code');
950
+ // reset promocode error state
951
+ cartStore.promoCodeError = false;
952
+ cartStore.promoCodeApplied = false;
953
+ };
954
+ const stripeStoreRemovePromoCode = async () => {
955
+ // Go back to shipping step if we are in payment step so user can reselect shipping method
956
+ if (cartStore.step === 'payment') {
957
+ cartStorePreviousStep();
958
+ }
959
+ stripeStoreResetPromoCode();
960
+ await stripeStoreApplyPromoCode();
961
+ };
962
+ const stripeStoreMessageBasedOnStatus = (status) => {
963
+ let messages = [];
964
+ let isError = true;
965
+ // Inspect the PaymentIntent `status` to indicate the status of the payment
966
+ // to your customer.
967
+ //
968
+ // Some payment methods will [immediately succeed or fail][0] upon
969
+ // confirmation, while others will first enter a `processing` state.
970
+ //
971
+ // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
972
+ switch (status) {
973
+ case 'succeeded': {
974
+ messages = [
975
+ localization.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.'),
976
+ '',
977
+ localization.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."),
978
+ ];
979
+ isError = false;
980
+ break;
981
+ }
982
+ case 'requires_capture':
983
+ case 'processing': {
984
+ messages = [
985
+ localization.translate("Payment processing. We'll update you when payment is received."),
986
+ ];
987
+ isError = false;
988
+ break;
989
+ }
990
+ case 'requires_payment_method': {
991
+ messages = [
992
+ localization.translate('Payment failed. Please try another payment method.'),
993
+ ];
994
+ break;
995
+ }
996
+ case 'requires_action': {
997
+ isError = false;
998
+ messages = [
999
+ localization.translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'),
1000
+ ];
1001
+ }
1002
+ default: {
1003
+ messages = [localization.translate('Something went wrong.')];
1004
+ break;
1005
+ }
1006
+ }
1007
+ return {
1008
+ isError,
1009
+ messages,
1010
+ };
1011
+ };
1012
+ /**
1013
+ * Handle inventory check and returns error message if the callback provided.
1014
+ */
1015
+ const stripeStoreHandleInventoryCheck = async () => {
1016
+ var _a, _b;
1017
+ const { onInventoryCheck } = zonosStore.zonosStore.checkoutSettings;
1018
+ const hasReferenceId = !!((_b = (_a = window.Zonos.cartData) === null || _a === void 0 ? void 0 : _a.metadata.find(meta => meta.key === 'referenceId')) === null || _b === void 0 ? void 0 : _b.value);
1019
+ // default inventory check is only available for legacy checkout and store has referenceId in metadata
1020
+ if (window.Zonos.isLegacyCheckout &&
1021
+ window.Zonos.cartData &&
1022
+ hasReferenceId) {
1023
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/legacy/inventory-check', {
1024
+ body: {
1025
+ cartData: window.Zonos.cartData,
1026
+ },
1027
+ method: 'POST',
1028
+ });
1029
+ if (errors.length || !json) {
1030
+ handleFetch.logError('Error occurs when handling inventory refund', 'warn', JSON.stringify(errors));
1031
+ return null;
1032
+ }
1033
+ // Proceed if the item is available
1034
+ if (!json.available || json.status === 204) {
1035
+ return localization.translate("The item you're looking for is currently unavailable in our inventory. Please check back later or contact support for assistance with availability.");
1036
+ }
1037
+ if (json.available || json.status === 200) {
1038
+ stripeStore.shouldInventoryRefund = true;
1039
+ return null;
1040
+ }
1041
+ return null;
1042
+ }
1043
+ if (typeof onInventoryCheck !== 'function') {
1044
+ return null;
1045
+ }
1046
+ try {
1047
+ const message = await onInventoryCheck({ items: cartStore.items });
1048
+ return message;
1049
+ }
1050
+ catch (err) {
1051
+ const message = err instanceof Error ? err.message : 'Unknown error';
1052
+ void handleFetch.sendErrorLog({
1053
+ endpoint: 'onInventoryCheck',
1054
+ errors: [`cartId: ${window.Zonos.cartId} - ${message}`],
1055
+ metadata: {
1056
+ cartId: window.Zonos.cartId,
1057
+ href: window.location.href,
1058
+ items: cartStore.items,
1059
+ },
1060
+ });
1061
+ throw err;
1062
+ }
1063
+ };
1064
+ /**
1065
+ * Handle inventory check and returns error message if the callback provided.
1066
+ */
1067
+ const stripeStoreHandleInventoryRefund = async () => {
1068
+ var _a, _b;
1069
+ const hasReferenceId = !!((_b = (_a = window.Zonos.cartData) === null || _a === void 0 ? void 0 : _a.metadata.find(meta => meta.key === 'referenceId')) === null || _b === void 0 ? void 0 : _b.value);
1070
+ // inventory refund is only available for legacy checkout and store has referenceId in metadata
1071
+ if (!window.Zonos.isLegacyCheckout ||
1072
+ !window.Zonos.cartData ||
1073
+ !hasReferenceId) {
1074
+ return;
1075
+ }
1076
+ // handle inventory check on legacy checkout
1077
+ await handleFetch.handleFetch('/api/zonos-elements/legacy/inventory-refund', {
1078
+ body: {
1079
+ cartData: window.Zonos.cartData,
1080
+ },
1081
+ method: 'POST',
1082
+ });
1083
+ };
1084
+ const stripeStoreRetrievePayment = async ({ clientSecret: _clientSecret, storybookForceStatus, }) => {
1085
+ if (storybookForceStatus) {
1086
+ // return status right away if we are in storybook mode
1087
+ const { isError, messages } = stripeStoreMessageBasedOnStatus(storybookForceStatus);
1088
+ return { error: isError, messages };
1089
+ }
1090
+ const clientSecret = _clientSecret || stripeStore.clientSecret;
1091
+ if (!stripeStore.stripe || !clientSecret) {
1092
+ handleFetch.logError('Failed to retrieve payment intent. Stripe is not initialized');
1093
+ return { error: true, message: [localization.translate('Something went wrong.')] };
1094
+ }
1095
+ const { paymentIntent } = await stripeStore.stripe.retrievePaymentIntent(clientSecret);
1096
+ const status = paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status;
1097
+ const { isError, messages } = stripeStoreMessageBasedOnStatus(status);
1098
+ return {
1099
+ error: isError,
1100
+ messages,
1101
+ paymentIntentId: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.id,
1102
+ paymentMethod: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.payment_method,
1103
+ status,
1104
+ };
1105
+ };
1106
+ const stripeStoreConfirmPayment = async () => {
1107
+ var _a, _b;
1108
+ const stripePaymentReady = !!((_a = stripeStore.stripePaymentEventData) === null || _a === void 0 ? void 0 : _a.complete);
1109
+ const stripeElements = stripeStore.stripeElements;
1110
+ const stripe = stripeStore.stripe;
1111
+ const stripeClientSecret = stripeStore.clientSecret;
1112
+ stripeStore.customErrorMessage = null;
1113
+ if (!((_b = cartStore.selectedLandedCost) === null || _b === void 0 ? void 0 : _b.landedCost.id)) {
1114
+ throw new Error('Attempted to confirm the payment when no landed cost is found in store');
1115
+ }
1116
+ // Check if the checkout session is valid before proceeding
1117
+ const checkoutSessionStatus = await validateCheckoutSession();
1118
+ if (!checkoutSessionStatus.valid) {
1119
+ stripeStore.customErrorMessage = checkoutSessionStatus.errorMessage;
1120
+ throw new Error(checkoutSessionStatus.errorMessage);
1121
+ }
1122
+ const checkoutSessionId = localization.storageStore.checkoutSessionId;
1123
+ if (stripe &&
1124
+ stripeElements &&
1125
+ stripePaymentReady &&
1126
+ stripeClientSecret &&
1127
+ checkoutSessionId) {
1128
+ const buildUrl = new URL(window.location.href);
1129
+ buildUrl.searchParams.set('payment_intent_client_secret', stripeClientSecret);
1130
+ buildUrl.searchParams.set('zonosCheckoutSessionId', checkoutSessionId);
1131
+ void trackConversionEvent({
1132
+ checkoutSessionId,
1133
+ eventName: 'checkout_paymentInfoCompleted',
1134
+ });
1135
+ const { error, paymentIntent } = await stripe.confirmPayment({
1136
+ confirmParams: {
1137
+ return_url: buildUrl.toString(),
1138
+ },
1139
+ elements: stripeElements,
1140
+ redirect: 'if_required',
1141
+ });
1142
+ handleFetch.log('Payment intent confirmed', 'info', { error, paymentIntent });
1143
+ if ((paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status) === 'requires_action') {
1144
+ throw new Error(localization.translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'));
1145
+ }
1146
+ if (error) {
1147
+ if (error.type === 'card_error' || error.type === 'validation_error') {
1148
+ throw new Error(error.message);
1149
+ }
1150
+ if (error.type === 'invalid_request_error') {
1151
+ if (error.code === 'payment_intent_unexpected_state') {
1152
+ // PaymentIntent was canceled or expired, or status is `require_capture`.
1153
+ // don't throw error here because we will reset the checkout session last step
1154
+ return;
1155
+ }
1156
+ }
1157
+ throw new Error('An unexpected error occurred.');
1158
+ }
1159
+ if (paymentIntent.status === 'requires_payment_method') {
1160
+ // Failed to confirm payment, allows user to try another payment method
1161
+ throw new Error(localization.translate('Payment failed. Please try another payment method.'));
1162
+ }
1163
+ }
1164
+ };
1165
+ const getCheckoutSessionBody = () => {
1166
+ var _a;
1167
+ const total = cartStore.items.reduce((amount, item) => amount + item.amount * item.quantity, 0);
1168
+ const varianceTestInput = localization.storageStore.enabledVariantTestKeys || [];
1169
+ const body = {
1170
+ adjustmentsAmount: cartStore.adjustments.reduce((prev, adj) => prev + adj.amount, 0),
1171
+ cartId: window.Zonos.cartId,
1172
+ currency: ((_a = cartStore.items.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode) || '',
1173
+ customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
1174
+ itemsAmount: total,
1175
+ metadata: [
1176
+ {
1177
+ key: 'language',
1178
+ value: localization.localizationStore.selectedLocale,
1179
+ },
1180
+ {
1181
+ key: 'appVersion',
1182
+ value: window.Zonos.version,
1183
+ },
1184
+ {
1185
+ key: 'appVersionNpmIntegration',
1186
+ value: window.Zonos.isNpm ? '1' : '0',
1187
+ },
1188
+ {
1189
+ key: 'legacyCheckoutFacade',
1190
+ value: window.Zonos.isLegacyCheckout ? '1' : '0',
1191
+ },
1192
+ ],
1193
+ presentmentCountryCode: localization.localizationStore.selectedCountryCode,
1194
+ skipPaymentIntent: stripeStore.skipPaymentIntent,
1195
+ varianceTestInput,
1196
+ };
1197
+ return body;
1198
+ };
1199
+ const stripeStoreGetPaymentIntent = async () => {
1200
+ var _a;
1201
+ if (!localization.storageStore.checkoutSessionId) {
1202
+ // We want to log the error anytime we fail to create a checkout session
1203
+ void handleFetch.sendErrorLog({
1204
+ endpoint: 'Error creating payment intent',
1205
+ errors: ['No checkout session id found when retrieving payment intent'],
1206
+ metadata: {
1207
+ allLogs: handleFetch.allLogs,
1208
+ cartId: window.Zonos.cartId,
1209
+ },
1210
+ });
1211
+ cartStoreUpdateToErrorState({
1212
+ messages: [
1213
+ localization.translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
1214
+ ],
1215
+ title: localization.translate('Error creating Checkout'),
1216
+ });
1217
+ return;
1218
+ }
1219
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/create-payment-intent', {
1220
+ body: {
1221
+ checkoutSessionId: localization.storageStore.checkoutSessionId,
1222
+ },
1223
+ method: 'POST',
1224
+ });
1225
+ const clientSecret = (_a = json === null || json === void 0 ? void 0 : json.checkoutSessionPaymentIntentCreate) === null || _a === void 0 ? void 0 : _a.clientSecret;
1226
+ if (errors.length || !clientSecret) {
1227
+ handleFetch.logError('Error occurs when getting payment intent', JSON.stringify(errors, null, 2));
1228
+ // We want to log the error anytime we fail to create a payment intent
1229
+ void handleFetch.sendErrorLog({
1230
+ endpoint: 'Error creating payment intent',
1231
+ errors: errors.map(error => error.message),
1232
+ metadata: {
1233
+ allLogs: handleFetch.allLogs,
1234
+ cartId: window.Zonos.cartId,
1235
+ checkoutSessionId: localization.storageStore.checkoutSessionId,
1236
+ clientSecret,
1237
+ },
1238
+ });
1239
+ cartStoreUpdateToErrorState({
1240
+ messages: [
1241
+ localization.translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
1242
+ ],
1243
+ title: localization.translate('Error creating Checkout'),
1244
+ });
1245
+ return;
1246
+ }
1247
+ // update cart store checkout session with updated from checkout session payment intent creation call so the checkout session and payment intent are in sync
1248
+ cartStoreSetCheckoutSession(json.checkoutSessionPaymentIntentCreate);
1249
+ };
1250
+ /**
1251
+ * Init checkout session
1252
+ * @returns {boolean} whether or not the checkout session is successfully created
1253
+ */
1254
+ const stripeStoreInitCheckoutSession = async () => {
1255
+ var _a, _b;
1256
+ if (!localization.localizationStore.targetCurrency) {
1257
+ handleFetch.logError(`Failed to create checkout session - missing localizationStore.targetCurrency`);
1258
+ return false;
1259
+ }
1260
+ stripeStore.isFetchingSession = true;
1261
+ const body = getCheckoutSessionBody();
1262
+ handleFetch.log('Checkout session body', 'info', body);
1263
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/create-checkout-session', {
1264
+ body,
1265
+ method: 'POST',
1266
+ });
1267
+ stripeStore.isFetchingSession = false;
1268
+ if (errors.length || !json) {
1269
+ const messages = (_a = errors.find(error => error.message)) === null || _a === void 0 ? void 0 : _a.message;
1270
+ // check if the error is related to expired cart and thow error so we can show error message accordingly
1271
+ if (messages.some(message => message.message === 'Cart is expired.')) {
1272
+ throw new Error('Cart is expired.');
1273
+ }
1274
+ handleFetch.logError('Error occurred when creating checkout session', JSON.stringify(errors, null, 2));
1275
+ return false;
1276
+ }
1277
+ const result = json.checkoutSessionCreate;
1278
+ // update cart store with updated information
1279
+ cartStoreSetCheckoutSession(result);
1280
+ cartStoreApplySubtotals({
1281
+ method: ((_b = result.landedCost) === null || _b === void 0 ? void 0 : _b.method) || 'DDP',
1282
+ subtotals: result.subtotals,
1283
+ });
1284
+ handleFetch.log('Exchange rate updated for cart items (checkout session create)', 'info', cartStore.exchangeRate);
1285
+ handleFetch.log('done-init-checkout-session');
1286
+ return true;
1287
+ };
1288
+ const stripeStoreUpdateCheckoutSessionBaseCurrency = async () => {
1289
+ const checkoutSessionId = localization.storageStore.checkoutSessionId;
1290
+ // Checkout session id should be available at this point
1291
+ if (!checkoutSessionId) {
1292
+ handleFetch.logError('Failed to update checkout session base currency');
1293
+ return false;
1294
+ }
1295
+ // Only update checkout session currency if setting is enabled
1296
+ if (zonosStore.zonosStore.checkoutSettings.allowedSettlementCurrencies === 'LOCAL') {
1297
+ handleFetch.log('allowedSettlementCurrencies: "LOCAL". Skip updating checkout session base currency');
1298
+ return true;
1299
+ }
1300
+ const { json } = await handleFetch.handleFetch('/api/zonos-elements/update-checkout-session-base-currency', {
1301
+ body: {
1302
+ checkoutSessionId,
1303
+ currencyCode: stripeStore.checkoutSettlementCurrency,
1304
+ },
1305
+ method: 'POST',
1306
+ });
1307
+ const settlementCurrencyCode = json === null || json === void 0 ? void 0 : json.checkoutSessionBaseCurrencyUpdate.subtotals.presentmentCurrencyCode;
1308
+ // S
1309
+ if (!json ||
1310
+ settlementCurrencyCode !== stripeStore.checkoutSettlementCurrency) {
1311
+ handleFetch.logError('Failed to update checkout session base currency');
1312
+ return false;
1313
+ }
1314
+ handleFetch.log(`Updated checkout session to settlement currency "${settlementCurrencyCode}".`);
1315
+ return true;
1316
+ };
1317
+ /**
1318
+ * Update checkout session. Use for updating amount with landed cost id, or update session when cart items change
1319
+ */
1320
+ const stripeStoreUpdateCheckoutSession = async ({ adjustmentsAmount, cartId, currency, id, itemsAmount, landedCostId, presentmentCountryCode, }) => {
1321
+ const varianceTestInput = localization.storageStore.enabledVariantTestKeys || [];
1322
+ // No need to set loading state here because this function will be called under the hood to update
1323
+ // landed cost id for the section.
1324
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/update-checkout-session', {
1325
+ body: {
1326
+ adjustmentsAmount,
1327
+ cartId,
1328
+ currency,
1329
+ customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
1330
+ id,
1331
+ itemsAmount,
1332
+ landedCostId,
1333
+ metadata: [
1334
+ {
1335
+ key: 'language',
1336
+ value: localization.localizationStore.selectedLocale,
1337
+ },
1338
+ {
1339
+ key: 'appVersion',
1340
+ value: window.Zonos.version,
1341
+ },
1342
+ {
1343
+ key: 'appVersionNpmIntegration',
1344
+ value: window.Zonos.isNpm ? '1' : '0',
1345
+ },
1346
+ {
1347
+ key: 'legacyCheckoutFacade',
1348
+ value: window.Zonos.isLegacyCheckout ? '1' : '0',
1349
+ },
1350
+ ],
1351
+ presentmentCountryCode,
1352
+ skipPaymentIntent: stripeStore.skipPaymentIntent,
1353
+ varianceTestInput,
1354
+ },
1355
+ method: 'POST',
1356
+ });
1357
+ if (errors.length || !json) {
1358
+ handleFetch.logError('Error occurs when updating checkout session', JSON.stringify(errors, null, 2));
1359
+ return { errors, json };
1360
+ }
1361
+ return { errors: [], json };
1362
+ };
1363
+ /**
1364
+ * This function builds a translated address object from the current address and the translated address result.
1365
+ * It checks each field in the current address and if it exists in the translated address result, it adds it to the translated address object.
1366
+ * The key of each field in the translated address object is the current address's field value and the value is the corresponding translated address's field value.
1367
+ *
1368
+ * @param {Object} params - The parameters for the function.
1369
+ * @param {Address} params.currentAddress - The current address information.
1370
+ * @param {Address} params.translatedAddressResult - The translated address result.
1371
+ *
1372
+ * @returns {TranslatedAddress} - An object containing the translated address. Each field is an object with the current address's field value as the key and the translated address's field value as the value.
1373
+ */
1374
+ const buildTranslatedAddress = ({ currentAddress, translatedAddressResult, }) => {
1375
+ const translatedAddress = {};
1376
+ if (!translatedAddressResult) {
1377
+ return translatedAddress;
1378
+ }
1379
+ const { city, line1, line2, name, postal_code, state } = translatedAddressResult;
1380
+ // If we have translated address, add it to the translated address object
1381
+ if (currentAddress.city && city) {
1382
+ translatedAddress.city = {
1383
+ [currentAddress.city]: city,
1384
+ };
1385
+ }
1386
+ if (currentAddress.line1 && line1) {
1387
+ translatedAddress.line1 = {
1388
+ [currentAddress.line1]: line1,
1389
+ };
1390
+ }
1391
+ if (currentAddress.line2 && line2) {
1392
+ translatedAddress.line2 = {
1393
+ [currentAddress.line2]: line2,
1394
+ };
1395
+ }
1396
+ if (currentAddress.postal_code && postal_code) {
1397
+ translatedAddress.postal_code = {
1398
+ [currentAddress.postal_code]: postal_code,
1399
+ };
1400
+ }
1401
+ if (currentAddress.state && state) {
1402
+ translatedAddress.state = {
1403
+ [currentAddress.state]: state,
1404
+ };
1405
+ }
1406
+ if (currentAddress.name && name) {
1407
+ translatedAddress.name = {
1408
+ [currentAddress.name]: name,
1409
+ };
1410
+ }
1411
+ return translatedAddress;
1412
+ };
1413
+ /**
1414
+ * This function translates an address to Latin characters using the Zonos API.
1415
+ * It first builds the request body for the API call. If there's no request body, it resets the translated address in the store and returns.
1416
+ * If the address is not outdated, it returns without making the API call.
1417
+ * It then makes a POST request to the Zonos API to validate and translate the address. If the API call fails, it resets the translated address in the store and returns.
1418
+ * If the API call is successful, it sets the current address and billing address in the store and builds the translated address and billing address from the API response.
1419
+ *
1420
+ * @param {Object} params - The parameters for the function.
1421
+ * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
1422
+ * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
1423
+ */
1424
+ const stripeStoreTranslateAddressToLatin = async ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, }) => {
1425
+ var _a, _b, _c, _d;
1426
+ const requestBody = buildTranslateRequest({
1427
+ addressInvalidCharactersList,
1428
+ billingAddressInvalidCharactersList,
1429
+ stripeAddressEventData: stripeStore.stripeAddressEventData,
1430
+ stripeBillingAddressEventData: stripeStore.stripeBillingAddressEventData,
1431
+ stripeShippingSameAsBilling: stripeStore.stripeShippingSameAsBilling,
1432
+ });
1433
+ if (!requestBody) {
1434
+ // reset translated address if we don't have any address to translate
1435
+ stripeStore.translatedAddress = {
1436
+ address: {},
1437
+ billingAddress: {},
1438
+ };
1439
+ return;
1440
+ }
1441
+ // only translate address if the address is out of date
1442
+ const isAddressOutdated = checkIsAddressOutdatedForValidation();
1443
+ if (!isAddressOutdated) {
1444
+ return;
1445
+ }
1446
+ const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/validate-address', {
1447
+ body: requestBody,
1448
+ method: 'POST',
1449
+ });
1450
+ if (errors.length || !json) {
1451
+ handleFetch.logError('Error occurs when translating address to latin', JSON.stringify(errors, null, 2));
1452
+ // reset translated address if we Failed to translate and let user manually fix it
1453
+ stripeStore.translatedAddress = {
1454
+ address: {},
1455
+ billingAddress: {},
1456
+ };
1457
+ return;
1458
+ }
1459
+ // Set current address to the store so we can compare it later to determine if we need to re-translate the address
1460
+ stripeStore.stripeAddressUsedWhenValidatingAddress =
1461
+ stripeStore.stripeAddressEventData;
1462
+ stripeStore.stripeBillingAddressUsedWhenValidatingAddress =
1463
+ stripeStore.stripeBillingAddressEventData;
1464
+ const address = (_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.value.address;
1465
+ const billingAddress = (_b = stripeStore.stripeBillingAddressEventData) === null || _b === void 0 ? void 0 : _b.value.address;
1466
+ // Set the translated address to the store so we can populate it to the address element for user to update
1467
+ stripeStore.translatedAddress = {
1468
+ address: address
1469
+ ? buildTranslatedAddress({
1470
+ currentAddress: Object.assign(Object.assign({}, address), { name: (_c = stripeStore.stripeAddressEventData) === null || _c === void 0 ? void 0 : _c.value.name }),
1471
+ translatedAddressResult: json.address || null,
1472
+ })
1473
+ : {},
1474
+ billingAddress: !stripeStore.stripeShippingSameAsBilling
1475
+ ? buildTranslatedAddress({
1476
+ currentAddress: Object.assign(Object.assign({}, billingAddress), { name: (_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.value.name }),
1477
+ translatedAddressResult: json.billingAddress || null,
1478
+ })
1479
+ : {},
1480
+ };
1481
+ };
1482
+ stripeStoreOnChange('clientSecret', clientSecret => {
1483
+ // update stripe elements when client secret changes
1484
+ if (clientSecret && stripeStore.stripe) {
1485
+ sessionStorage.setItem('zonos--client-secret', clientSecret);
1486
+ }
1487
+ if (!clientSecret) {
1488
+ sessionStorage.removeItem('zonos--client-secret');
1489
+ }
1490
+ });
1491
+
1492
+ const { reset, state: cartStore } = zonosStore.createStore(() => ({
1493
+ adjustmentTotal: 0,
1494
+ adjustments: [],
1495
+ checkoutSession: null,
1496
+ checkoutSessionTimeoutShow: false,
1497
+ checkoutTimeoutInterval: null,
1498
+ currency: 'USD',
1499
+ customQuotingError: null,
1500
+ customerAuthenticationToken: null,
1501
+ displayBaseCurrency: false,
1502
+ dutiesTaxesFees: null,
1503
+ dutiesTaxesFeesEstimate: null,
1504
+ error: null,
1505
+ exchangeRate: null,
1506
+ externalConfirmationPageURL: null,
1507
+ inventoryCheckErrorMessage: null,
1508
+ isSelectedShippingAboveDeminimis: false,
1509
+ isSelectedShippingGuarantee: false,
1510
+ isStagingMode: handleFetch.getIsStagingMode(),
1511
+ items: [],
1512
+ landedCostData: null,
1513
+ landedCostMethod: 'DDP',
1514
+ partiesData: [],
1515
+ promoCode: sessionStorage.getItem('zonos--promo-code') || '',
1516
+ // When user clicked applied button, save promocode into session storage for later use. So if session has promocode, applied button is clicked
1517
+ promoCodeApplied: !!sessionStorage.getItem('zonos--promo-code'),
1518
+ promoCodeError: false,
1519
+ restrictedItems: [],
1520
+ selectedLandedCost: null,
1521
+ selectedShippingOption: null,
1522
+ selectedShippingOptionExpectedDate: '',
1523
+ selectedShippingOptionTransitTime: '',
1524
+ shipping: 0,
1525
+ shippingData: null,
1526
+ shouldHideDiscountInput: false,
1527
+ step: 'customer-info',
1528
+ subtotal: 0,
1529
+ tabItems: {
1530
+ 'customer-info': {
1531
+ index: 1,
1532
+ isDone: false,
1533
+ label: 'Customer',
1534
+ value: 'customer-info',
1535
+ },
1536
+ shipping: {
1537
+ index: 2,
1538
+ isDone: false,
1539
+ label: 'Shipping',
1540
+ value: 'shipping',
1541
+ },
1542
+ // eslint-disable-next-line sort-keys/sort-keys-fix
1543
+ payment: {
1544
+ index: 3,
1545
+ isDone: false,
1546
+ label: 'Payment',
1547
+ value: 'payment',
1548
+ },
1549
+ },
1550
+ total: 0,
1551
+ }));
1552
+ const getTransitUnit = (type) => {
1553
+ switch (type) {
1554
+ case 'DAYS':
1555
+ return localization.translate('days');
1556
+ case 'WEEKS':
1557
+ return localization.translate('weeks');
1558
+ case 'BUSINESS_DAYS':
1559
+ default:
1560
+ return localization.translate('business days');
1561
+ }
1562
+ };
1563
+ /**
1564
+ * Format shipping transit info to be displayed on UI
1565
+ * @returns
1566
+ * - expectedDate: Thursday, Aug 12
1567
+ * - maxTransit: 5
1568
+ * - minTransit: 3
1569
+ */
1570
+ const cartStoreGetShippingTransitInfo = (item) => {
1571
+ var _a;
1572
+ const transitTime = (_a = item.shippingProfile) === null || _a === void 0 ? void 0 : _a.transitTime;
1573
+ // Don't care about falsy 0 values because this is international shipping and 0 days is not feasible
1574
+ if (!(transitTime === null || transitTime === void 0 ? void 0 : transitTime.min) || !(transitTime === null || transitTime === void 0 ? void 0 : transitTime.max) || !(transitTime === null || transitTime === void 0 ? void 0 : transitTime.type)) {
1575
+ return null;
1576
+ }
1577
+ return {
1578
+ maxTransit: transitTime.max,
1579
+ minTransit: transitTime.min,
1580
+ unit: getTransitUnit(transitTime.type),
1581
+ };
1582
+ };
1583
+ const getMatchItem = ({ item1, item2, }) => {
1584
+ if (!item1 || !item2) {
1585
+ return false;
1586
+ }
1587
+ return ((item2.sku && item1.sku && item1.sku === item2.sku) ||
1588
+ (item2.description &&
1589
+ item1.description &&
1590
+ item1.description === item2.description) ||
1591
+ (item1.name && item2.name && item1.name === item2.name));
1592
+ };
1593
+ /**
1594
+ * Check and set restricted items in cart
1595
+ */
1596
+ const cartStoreCheckItemRestrictions = (itemsWorkflow) => {
1597
+ handleFetch.log('Checking item restrictions');
1598
+ const mappedRestrictedItems = itemsWorkflow
1599
+ .map(item => {
1600
+ if (!item.restriction) {
1601
+ return null;
1602
+ }
1603
+ const { restriction } = item;
1604
+ const matchedItem = cartStore.items.find(x => getMatchItem({ item1: x, item2: item }));
1605
+ return Object.assign(Object.assign({ matchedItem }, item), { restriction });
1606
+ })
1607
+ .filter(Boolean);
1608
+ cartStore.restrictedItems = mappedRestrictedItems;
1609
+ // remove items that are restricted from cart
1610
+ cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: !!mappedRestrictedItems.find(x => getMatchItem({ item1: x, item2: item })) })));
1611
+ return {
1612
+ cartItems: cartStore.items,
1613
+ restrictedItems: mappedRestrictedItems,
1614
+ };
1615
+ };
1616
+ const cartStoreReset = () => {
1617
+ localization.storageStore.checkoutSessionId = null;
1618
+ // reset cart store
1619
+ reset();
1620
+ };
1621
+ const cartStoreUpdateToErrorState = ({ messages, title, }) => {
1622
+ cartStoreReset();
1623
+ stripeStoreReset();
1624
+ cartStore.step = 'error';
1625
+ cartStore.error = {
1626
+ messages,
1627
+ title,
1628
+ };
1629
+ };
1630
+ const cartStoreApplySubtotals = ({ dutiesTaxesFeesEstimate, method, subtotals, }) => {
1631
+ // update exchange rate so we can use it to display cart items
1632
+ cartStore.exchangeRate = subtotals.exchangeRate;
1633
+ cartStore.adjustmentTotal = subtotals.adjustments;
1634
+ cartStore.dutiesTaxesFees =
1635
+ method === 'DAP' ? null : subtotals.landedCostTotal;
1636
+ cartStore.subtotal = subtotals.items;
1637
+ cartStore.total = subtotals.total;
1638
+ cartStore.currency = subtotals.presentmentCurrencyCode;
1639
+ cartStore.dutiesTaxesFeesEstimate = dutiesTaxesFeesEstimate || null;
1640
+ };
1641
+ /**
1642
+ * Detect if there are any items in cart that are not restricted and have positive amount, exclude negative amount items
1643
+ */
1644
+ const cartStoreHasOneEligibleItem = () => {
1645
+ // filter all items with positive amount
1646
+ const checkItems = cartStore.items.filter(item => item.amount > 0);
1647
+ // only check restricted status for items with positive amount
1648
+ // if there is no item restricted found => all items are restricted
1649
+ return !!checkItems.find(item => !item.isRestricted);
1650
+ };
1651
+ const cartStoreSetCheckoutSession = (checkoutSession) => {
1652
+ var _a, _b, _c, _d, _e;
1653
+ // update stripe store with updated information
1654
+ stripeStore.clientSecret = checkoutSession.clientSecret;
1655
+ stripeStore.stripeCustomerSessionClientSecret =
1656
+ checkoutSession.customerSessionClientSecret;
1657
+ stripeStore.customerProfile = checkoutSession.customerProfile;
1658
+ cartStore.checkoutSession = checkoutSession;
1659
+ if (!checkoutSession.id) {
1660
+ // Log error to track down the issue
1661
+ void handleFetch.sendErrorLog({
1662
+ endpoint: 'cartStoreSetCheckoutSession',
1663
+ errors: ['Missing checkout session id in checkout session'],
1664
+ metadata: {
1665
+ allLogs: handleFetch.allLogs,
1666
+ checkoutSession,
1667
+ },
1668
+ });
1669
+ }
1670
+ // Only update checkout session id if it's not empty
1671
+ if (checkoutSession.id) {
1672
+ localization.storageStore.checkoutSessionId = checkoutSession.id;
1673
+ }
1674
+ // Filter the response to only include test keys that we support and then save it to the session
1675
+ const availableSelectedVariantTestKeys = localization.filterValidTests(checkoutSession.varianceTestResults || []);
1676
+ localization.storageStoreSetEnabledVariantTestKeys(availableSelectedVariantTestKeys);
1677
+ // Check if there is a redirect URL in the metadata to override
1678
+ const externalConfirmationPageURL = ((_c = (_b = (_a = cartStore.checkoutSession) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.find(entry => (entry === null || entry === void 0 ? void 0 : entry.key) === 'externalConfirmationPageURL')) === null || _c === void 0 ? void 0 : _c.value) ||
1679
+ (
1680
+ // Sometimes externalConfirmationPageURL is not in checkoutSession create/update, check if there is a redirect URL in the cart metadata to override
1681
+ (_e = (_d = window.Zonos.cartData) === null || _d === void 0 ? void 0 : _d.metadata.find(entry => (entry === null || entry === void 0 ? void 0 : entry.key) === 'externalConfirmationPageURL')) === null || _e === void 0 ? void 0 : _e.value) ||
1682
+ null;
1683
+ if (externalConfirmationPageURL) {
1684
+ handleFetch.log(`Found externalConfirmationPageURL: ${externalConfirmationPageURL}`);
1685
+ cartStore.externalConfirmationPageURL = externalConfirmationPageURL;
1686
+ }
1687
+ };
1688
+ const cartStoreReCalculateTotal = async ({ adjustmentsAmount, cartId, currency, dutiesTaxesFeesEstimate, itemsAmount, landedCostId, shouldInitSessionOnFailure, }) => {
1689
+ var _a;
1690
+ if (landedCostId && cartStore.selectedLandedCost) {
1691
+ // update cart total right away if we have landed cost id to avoid order total flickering
1692
+ const subtotals = cartStore.selectedLandedCost.subtotals;
1693
+ cartStoreApplySubtotals({
1694
+ dutiesTaxesFeesEstimate,
1695
+ method: cartStore.landedCostMethod,
1696
+ subtotals,
1697
+ });
1698
+ handleFetch.log('Exchange rate updated for cart items (landed cost subtotal)', 'info', cartStore.exchangeRate);
1699
+ }
1700
+ // update checkout session
1701
+ if (!localization.storageStore.checkoutSessionId) {
1702
+ handleFetch.log('Could not update cart total without checkout session id', 'info');
1703
+ return false;
1704
+ }
1705
+ const { errors, json } = await stripeStoreUpdateCheckoutSession({
1706
+ adjustmentsAmount,
1707
+ cartId,
1708
+ currency,
1709
+ id: localization.storageStore.checkoutSessionId,
1710
+ itemsAmount,
1711
+ landedCostId,
1712
+ presentmentCountryCode: localization.localizationStore.selectedCountryCode,
1713
+ varianceTestInput: localization.storageStore.enabledVariantTestKeys || [],
1714
+ });
1715
+ if (errors.length > 0 || !json) {
1716
+ handleFetch.logError('Error occurs when updating checkout session.');
1717
+ if (shouldInitSessionOnFailure) {
1718
+ handleFetch.log('Initiating checkout session on failure', 'info');
1719
+ const success = await stripeStoreInitCheckoutSession();
1720
+ handleFetch.log(`stripeStoreInitCheckoutSession: ${success}`);
1721
+ if (!success) {
1722
+ cartStoreUpdateToErrorState({
1723
+ messages: [
1724
+ localization.translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
1725
+ ],
1726
+ title: localization.translate('Error creating Checkout'),
1727
+ });
1728
+ return false;
1729
+ }
1730
+ return true;
1731
+ }
1732
+ return false;
1733
+ }
1734
+ if (!landedCostId) {
1735
+ // This is when we first open the checkout modal and we just want to get info from the old cart session.
1736
+ // use subtotals from checkout session to update cart total
1737
+ cartStoreApplySubtotals({
1738
+ method: ((_a = json.checkoutSessionUpdate.landedCost) === null || _a === void 0 ? void 0 : _a.method) || 'DDP',
1739
+ subtotals: json.checkoutSessionUpdate.subtotals,
1740
+ });
1741
+ handleFetch.log('Exchange rate updated for cart items (checkout session update)', 'info', cartStore.exchangeRate);
1742
+ }
1743
+ cartStoreSetCheckoutSession(json.checkoutSessionUpdate);
1744
+ return true;
1745
+ };
1746
+ /**
1747
+ * For some service levels, the landed cost that's DAP and we do remittance on behalf of the merchant, these landed cost should be treated as DDP
1748
+ */
1749
+ const cartStoreGetMethod = (landedCost) => {
1750
+ if (landedCost.method === 'DAP' &&
1751
+ landedCost.remittance.length &&
1752
+ landedCost.landedCostGuaranteeCode === 'ZONOS') {
1753
+ return 'DDP';
1754
+ }
1755
+ return landedCost.method;
1756
+ };
1757
+ const cartStoreUpdateSelectedShippingOption = async (selectedShippingOption, landedCostId) => {
1758
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
1759
+ cartStore.selectedShippingOption = selectedShippingOption;
1760
+ // update shipping transit info
1761
+ const transitData = cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);
1762
+ if (transitData) {
1763
+ const { maxTransit, minTransit, unit } = transitData;
1764
+ cartStore.selectedShippingOptionTransitTime = `${minTransit}-${maxTransit} ${unit}`;
1765
+ }
1766
+ else {
1767
+ cartStore.selectedShippingOptionTransitTime = '';
1768
+ }
1769
+ const selectedLandedCost = (_a = cartStore.landedCostData) === null || _a === void 0 ? void 0 : _a.find(x => x.landedCostId === landedCostId);
1770
+ // save selected landed cost for later use
1771
+ cartStore.selectedLandedCost = selectedLandedCost || null;
1772
+ if (!selectedLandedCost) {
1773
+ // do nothing if we can't find landed cost for selected shipping option
1774
+ return false;
1775
+ }
1776
+ // If the quote is DAP, then convert manually.
1777
+ const landedCostAmount = ((_b = selectedLandedCost.landedCost.amountSubtotals) === null || _b === void 0 ? void 0 : _b.landedCostTotal) || 0;
1778
+ // Convert using checkout presentment exchange rate
1779
+ const exchangeRate = selectedLandedCost.subtotals.exchangeRate.rate;
1780
+ const dutiesTaxesFeesEstimate = landedCostAmount * exchangeRate;
1781
+ if (dutiesTaxesFeesEstimate) {
1782
+ handleFetch.log(`DAP quote, using estimate: ${dutiesTaxesFeesEstimate}`, 'info');
1783
+ }
1784
+ cartStore.landedCostMethod = cartStoreGetMethod(selectedLandedCost.landedCost);
1785
+ // update shipping value and dutiesTaxFees on selectedShippingOption change
1786
+ cartStore.shipping = selectedLandedCost.subtotals.shipping;
1787
+ // update deminimis status
1788
+ const isGuarantee = ((_c = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _c === void 0 ? void 0 : _c.landedCostGuaranteeCode) === 'ZONOS';
1789
+ // one item in deminimis with type of duty and tax has threshold value is "ABOVE"
1790
+ const isAboveDeminimis = !!((_e = (_d = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _d === void 0 ? void 0 : _d.deMinimis) === null || _e === void 0 ? void 0 : _e.find(item => ['DUTY', 'TAX'].includes(item.type) && item.threshold === 'ABOVE'));
1791
+ cartStore.isSelectedShippingAboveDeminimis = isAboveDeminimis;
1792
+ cartStore.isSelectedShippingGuarantee = isGuarantee;
1793
+ // update session with selected landed cost
1794
+ const updateCalculateStatus = await cartStoreReCalculateTotal({
1795
+ adjustmentsAmount: cartStore.adjustmentTotal,
1796
+ cartId: window.Zonos.cartId,
1797
+ dutiesTaxesFeesEstimate: dutiesTaxesFeesEstimate,
1798
+ landedCostId: (_f = selectedLandedCost.landedCost) === null || _f === void 0 ? void 0 : _f.id,
1799
+ varianceTestInput: localization.storageStore.enabledVariantTestKeys || [],
1800
+ });
1801
+ // update conditionally render pay in USD button
1802
+ const firstItem = (_g = cartStore.items.find(Boolean)) === null || _g === void 0 ? void 0 : _g.currencyCode;
1803
+ // Stripe address event data should be available at this point
1804
+ const shipToCountry = ((_h = stripeStore.stripeAddressEventData) === null || _h === void 0 ? void 0 : _h.value.address.country) || 'US';
1805
+ // Only show pay in USD button if item's currency is in USD, the setting is enabled and the order presentment currency is not USD, also only in USD settlement ship to country list
1806
+ stripeStore.shouldRenderPayInUsdButton =
1807
+ firstItem === 'USD' &&
1808
+ zonosStore.zonosStore.checkoutSettings.allowedSettlementCurrencies ===
1809
+ 'LOCAL_AND_USD' &&
1810
+ ((_j = cartStore.checkoutSession) === null || _j === void 0 ? void 0 : _j.subtotals.presentmentCurrencyCode) !== 'USD' &&
1811
+ !!((_l = (_k = zonosStore.zonosStore.genericSettings) === null || _k === void 0 ? void 0 : _k.usdSettlementCountryEnabled) === null || _l === void 0 ? void 0 : _l.includes(shipToCountry));
1812
+ return updateCalculateStatus;
1813
+ };
1814
+ const cartStoreStartCheckoutInterval = ({ isPreview, sessionTimeout, }) => {
1815
+ // do nothing if in preview mode
1816
+ if (isPreview) {
1817
+ return;
1818
+ }
1819
+ const timeoutQuery = new URLSearchParams(window.location.search).get('zonosCheckoutTimeout');
1820
+ const timeout =
1821
+ // timeout query is mainly for testing purpose
1822
+ timeoutQuery && !isNaN(parseInt(timeoutQuery, 10))
1823
+ ? parseInt(timeoutQuery, 10)
1824
+ : sessionTimeout;
1825
+ handleFetch.log(`==START CHECKOUT TIMEOUT - ${timeout}==`);
1826
+ cartStore.checkoutTimeoutInterval = setTimeout(() => {
1827
+ cartStore.checkoutSessionTimeoutShow = true;
1828
+ }, timeout);
1829
+ };
1830
+ const cartStoreClearCheckoutInterval = () => {
1831
+ if (cartStore.checkoutTimeoutInterval) {
1832
+ clearTimeout(cartStore.checkoutTimeoutInterval);
1833
+ cartStore.checkoutTimeoutInterval = null;
1834
+ }
1835
+ };
1836
+ const getCartItemToUse = (items) => items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
1837
+ const cartStoreResetCartItems = () => {
1838
+ // mark all items as not restricted
1839
+ cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
1840
+ cartStore.restrictedItems = [];
1841
+ };
1842
+ const cartStoreUpdateItems = async ({ adjustments, cartItems, }) => {
1843
+ var _a;
1844
+ // Update adjustments and items
1845
+ cartStore.adjustments = adjustments;
1846
+ cartStore.items = getCartItemToUse(cartItems);
1847
+ const currency = (_a = cartItems.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode;
1848
+ const total = cartItems.reduce((amt, item) => {
1849
+ return amt + item.amount * item.quantity;
1850
+ }, 0);
1851
+ const adjustmentTotal = adjustments.reduce((amt, adjustment) => amt + adjustment.amount, 0);
1852
+ if (!currency || !total) {
1853
+ // do nothing if we can't get currency or total
1854
+ return;
1855
+ }
1856
+ cartStore.currency = currency;
1857
+ // set loading state here because this is the first load checkout session when we already have checkout session id stored
1858
+ stripeStore.isFetchingSession = true;
1859
+ await cartStoreReCalculateTotal({
1860
+ adjustmentsAmount: adjustmentTotal,
1861
+ cartId: window.Zonos.cartId,
1862
+ currency: currency,
1863
+ dutiesTaxesFeesEstimate: 0,
1864
+ itemsAmount: total,
1865
+ // attempt to init session on failure to update checkout session
1866
+ shouldInitSessionOnFailure: true,
1867
+ varianceTestInput: localization.storageStore.enabledVariantTestKeys || [],
1868
+ });
1869
+ stripeStore.isFetchingSession = false;
1870
+ };
1871
+ const cartStoreResetSelectedShippingOption = () => {
1872
+ cartStore.selectedShippingOption = null;
1873
+ cartStore.isSelectedShippingAboveDeminimis = false;
1874
+ cartStore.isSelectedShippingGuarantee = false;
1875
+ cartStore.selectedShippingOptionTransitTime = '';
1876
+ cartStore.dutiesTaxesFees = 0;
1877
+ cartStore.dutiesTaxesFeesEstimate = 0;
1878
+ cartStore.shipping = 0;
1879
+ // reset total to subtotal
1880
+ cartStore.total = cartStore.subtotal;
1881
+ };
1882
+ const cartStorePreviousStep = () => {
1883
+ if (cartStore.step === 'shipping') {
1884
+ cartStore.step = 'customer-info';
1885
+ // set shipping step to done
1886
+ cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
1887
+ }
1888
+ else if (cartStore.step === 'payment') {
1889
+ cartStore.step = 'shipping';
1890
+ // set shipping step to done
1891
+ cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
1892
+ }
1893
+ else if (cartStore.step === 'finish') {
1894
+ cartStore.step = 'payment';
1895
+ // set shipping step to done
1896
+ cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { payment: Object.assign(Object.assign({}, cartStore.tabItems.payment), { isDone: false }) });
1897
+ }
1898
+ };
1899
+ const cartStoreNextStep = () => {
1900
+ if (cartStore.step === 'customer-info') {
1901
+ cartStore.step = 'shipping';
1902
+ // set customer-info step to done
1903
+ cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems['customer-info']), { isDone: true }) });
1904
+ }
1905
+ else if (cartStore.step === 'shipping') {
1906
+ cartStore.step = 'payment';
1907
+ // set shipping step to done
1908
+ cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: true }) });
1909
+ }
1910
+ else if (cartStore.step === 'payment') {
1911
+ cartStore.step = 'finish';
1912
+ }
1913
+ };
1914
+ const cartStoreResetTabItems = () => {
1915
+ cartStore.step = 'customer-info';
1916
+ 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 }) });
1917
+ cartStoreResetSelectedShippingOption();
1918
+ };
1919
+
1920
+ exports.cartStore = cartStore;
1921
+ exports.cartStoreClearCheckoutInterval = cartStoreClearCheckoutInterval;
1922
+ exports.cartStoreGetMethod = cartStoreGetMethod;
1923
+ exports.cartStoreGetShippingTransitInfo = cartStoreGetShippingTransitInfo;
1924
+ exports.cartStoreHasOneEligibleItem = cartStoreHasOneEligibleItem;
1925
+ exports.cartStoreNextStep = cartStoreNextStep;
1926
+ exports.cartStoreReset = cartStoreReset;
1927
+ exports.cartStoreResetTabItems = cartStoreResetTabItems;
1928
+ exports.cartStoreSetCheckoutSession = cartStoreSetCheckoutSession;
1929
+ exports.cartStoreStartCheckoutInterval = cartStoreStartCheckoutInterval;
1930
+ exports.cartStoreUpdateItems = cartStoreUpdateItems;
1931
+ exports.cartStoreUpdateSelectedShippingOption = cartStoreUpdateSelectedShippingOption;
1932
+ exports.cartStoreUpdateToErrorState = cartStoreUpdateToErrorState;
1933
+ exports.getCheckoutSessionBody = getCheckoutSessionBody;
1934
+ exports.initStripeElements = initStripeElements;
1935
+ exports.sortServiceLevelOptionsByAmount = sortServiceLevelOptionsByAmount;
1936
+ exports.stripeStore = stripeStore;
1937
+ exports.stripeStoreApplyPromoCode = stripeStoreApplyPromoCode;
1938
+ exports.stripeStoreCleanupDomesticShippingSession = stripeStoreCleanupDomesticShippingSession;
1939
+ exports.stripeStoreConfirmPayment = stripeStoreConfirmPayment;
1940
+ exports.stripeStoreGetDomesticShippingSession = stripeStoreGetDomesticShippingSession;
1941
+ exports.stripeStoreGetPaymentIntent = stripeStoreGetPaymentIntent;
1942
+ exports.stripeStoreHandleInventoryCheck = stripeStoreHandleInventoryCheck;
1943
+ exports.stripeStoreHandleInventoryRefund = stripeStoreHandleInventoryRefund;
1944
+ exports.stripeStoreInitCheckoutSession = stripeStoreInitCheckoutSession;
1945
+ exports.stripeStoreMessageBasedOnStatus = stripeStoreMessageBasedOnStatus;
1946
+ exports.stripeStorePrefetchLandedCost = stripeStorePrefetchLandedCost;
1947
+ exports.stripeStoreRemovePromoCode = stripeStoreRemovePromoCode;
1948
+ exports.stripeStoreReset = stripeStoreReset;
1949
+ exports.stripeStoreResetPromoCode = stripeStoreResetPromoCode;
1950
+ exports.stripeStoreRetrievePayment = stripeStoreRetrievePayment;
1951
+ exports.stripeStoreSaveDomesticShippingSession = stripeStoreSaveDomesticShippingSession;
1952
+ exports.stripeStoreTranslateAddressToLatin = stripeStoreTranslateAddressToLatin;
1953
+ exports.stripeStoreUpdateCheckoutSessionBaseCurrency = stripeStoreUpdateCheckoutSessionBaseCurrency;
1954
+ exports.trackConversionEvent = trackConversionEvent;
1955
+ exports.validateCheckoutSession = validateCheckoutSession;