@zonos/elements 1.3.201 → 1.3.202

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 (309) hide show
  1. package/dist/cjs/VarianceTest-0cb1e118.js +12 -0
  2. package/dist/cjs/cart-637ba3d0.js +1943 -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-0eceff03.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} +99 -80
  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 +2 -1
  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 +15 -16
  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 +12 -0
  85. package/dist/collection/types/index.js +1 -0
  86. package/dist/esm/VarianceTest-fef2d958.js +10 -0
  87. package/dist/esm/cart-b7c15b61.js +1907 -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-932fd3dd.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} +48 -30
  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-b7c15b61.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-932fd3dd.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 +839 -765
  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 +0 -1
  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 +163 -0
  186. package/dist/types/types/generated/graphql.internal.types.ts +199 -0
  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/assets/RemoveIcon.svg +1 -1
  190. package/dist/zonos-elements/index.esm.js +1 -1
  191. package/dist/zonos-elements/{p-609c32a3.system.entry.js → p-01987cb2.system.entry.js} +1 -1
  192. package/dist/zonos-elements/p-04a01cb1.js +1 -0
  193. package/dist/zonos-elements/p-04b43dd5.entry.js +1 -0
  194. package/dist/zonos-elements/p-0f77d087.system.entry.js +1 -0
  195. package/dist/zonos-elements/{p-7831b52c.system.entry.js → p-1dcdb65f.system.entry.js} +1 -1
  196. package/dist/zonos-elements/p-26a634a5.system.entry.js +1 -0
  197. package/dist/zonos-elements/p-27987298.system.entry.js +1 -0
  198. package/dist/zonos-elements/p-2af2eb6f.system.entry.js +1 -0
  199. package/dist/zonos-elements/p-2b8f787a.entry.js +1 -0
  200. package/dist/zonos-elements/p-30cfa524.entry.js +1 -0
  201. package/dist/zonos-elements/p-32320d9a.system.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-452070af.system.entry.js +1 -0
  205. package/dist/zonos-elements/p-45ebc788.entry.js +1 -0
  206. package/dist/zonos-elements/p-4c81112f.entry.js +1 -0
  207. package/dist/zonos-elements/p-4efa8187.js +1 -0
  208. package/dist/zonos-elements/p-5170bc41.entry.js +1 -0
  209. package/dist/zonos-elements/p-5a2dd041.system.js +1 -0
  210. package/dist/zonos-elements/p-5c74e5c9.system.entry.js +1 -0
  211. package/dist/zonos-elements/p-5d0f7364.system.js +1 -0
  212. package/dist/zonos-elements/p-6a52a2bc.system.entry.js +1 -0
  213. package/dist/zonos-elements/p-715d0f59.system.entry.js +1 -0
  214. package/dist/zonos-elements/{p-b8d87932.js → p-72f37935.js} +1 -1
  215. package/dist/zonos-elements/p-7ae5cd60.entry.js +1 -0
  216. package/dist/zonos-elements/p-80bbd9c0.system.entry.js +1 -0
  217. package/dist/zonos-elements/p-851c642e.system.entry.js +1 -0
  218. package/dist/zonos-elements/{p-4300d944.entry.js → p-8d870d4c.entry.js} +1 -1
  219. package/dist/zonos-elements/p-98b65387.entry.js +1 -0
  220. package/dist/zonos-elements/p-9af5e93a.entry.js +1 -0
  221. package/dist/zonos-elements/p-aa1193bc.entry.js +1 -0
  222. package/dist/zonos-elements/{p-5de59662.js → p-aae60057.js} +2 -2
  223. package/dist/zonos-elements/p-ab176281.system.entry.js +1 -0
  224. package/dist/zonos-elements/p-b52aba52.entry.js +1 -0
  225. package/dist/zonos-elements/p-bc220d35.system.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-bec2a3ce.entry.js +1 -0
  229. package/dist/zonos-elements/p-c291bac1.entry.js +1 -0
  230. package/dist/zonos-elements/p-c3d2422e.entry.js +1 -0
  231. package/dist/zonos-elements/{p-f28eb1dd.system.js → p-c50b3100.system.js} +1 -1
  232. package/dist/zonos-elements/p-c58acd4c.system.entry.js +1 -0
  233. package/dist/zonos-elements/p-c5fcbc92.system.entry.js +1 -0
  234. package/dist/zonos-elements/p-c767242b.entry.js +1 -0
  235. package/dist/zonos-elements/p-c9aa902e.system.entry.js +1 -0
  236. package/dist/zonos-elements/p-cb823c4d.system.js +1 -0
  237. package/dist/zonos-elements/{p-7d5d89f2.system.js → p-d2466fbd.system.js} +2 -2
  238. package/dist/zonos-elements/{p-d422ad1d.system.js → p-d42dfd32.system.js} +1 -1
  239. package/dist/zonos-elements/p-d46349d3.system.entry.js +1 -0
  240. package/dist/zonos-elements/p-d60ca44b.system.entry.js +1 -0
  241. package/dist/zonos-elements/{p-b2241919.entry.js → p-d6a10007.entry.js} +1 -1
  242. package/dist/zonos-elements/p-db025dfc.system.entry.js +1 -0
  243. package/dist/zonos-elements/p-db3968a2.js +1 -0
  244. package/dist/zonos-elements/p-dcd6acd4.system.entry.js +1 -0
  245. package/dist/zonos-elements/p-dd1cfa74.entry.js +1 -0
  246. package/dist/zonos-elements/p-df4c46a6.entry.js +1 -0
  247. package/dist/zonos-elements/{p-4593324c.js → p-e26c9e83.js} +1 -1
  248. package/dist/zonos-elements/p-e68d5219.entry.js +1 -0
  249. package/dist/zonos-elements/p-ea6d87a1.system.js +1 -1
  250. package/dist/zonos-elements/p-ef3e05e5.system.js +1 -0
  251. package/dist/zonos-elements/p-f255e822.js +1 -0
  252. package/dist/zonos-elements/p-f655ec36.entry.js +1 -0
  253. package/dist/zonos-elements/{p-e91b244c.entry.js → p-f891d470.entry.js} +1 -1
  254. package/dist/zonos-elements/p-f8d0d488.system.entry.js +1 -0
  255. package/dist/zonos-elements/{p-240ee490.system.entry.js → p-fbe36bc8.system.entry.js} +1 -1
  256. package/dist/zonos-elements/p-fcc2e712.entry.js +1 -0
  257. package/dist/zonos-elements/zonos-elements.esm.js +1 -1
  258. package/package.json +1 -1
  259. package/dist/esm-es5/cart-f79c8021.js +0 -1
  260. package/dist/esm-es5/zonos-cart-items_13.entry.js +0 -1
  261. package/dist/esm-es5/zonosStore-cdabc848.js +0 -1
  262. package/dist/zonos-elements/p-0302a254.entry.js +0 -1
  263. package/dist/zonos-elements/p-06ed3582.system.js +0 -1
  264. package/dist/zonos-elements/p-147ca395.entry.js +0 -1
  265. package/dist/zonos-elements/p-1998d8b3.entry.js +0 -1
  266. package/dist/zonos-elements/p-1eddec23.entry.js +0 -1
  267. package/dist/zonos-elements/p-20030bf5.system.js +0 -1
  268. package/dist/zonos-elements/p-24a2e899.system.entry.js +0 -1
  269. package/dist/zonos-elements/p-264f46a5.entry.js +0 -1
  270. package/dist/zonos-elements/p-2882b9f4.entry.js +0 -1
  271. package/dist/zonos-elements/p-2c915112.system.entry.js +0 -1
  272. package/dist/zonos-elements/p-327aebf5.entry.js +0 -1
  273. package/dist/zonos-elements/p-33488109.system.entry.js +0 -1
  274. package/dist/zonos-elements/p-337fab4e.js +0 -1
  275. package/dist/zonos-elements/p-3ddecaa4.system.entry.js +0 -1
  276. package/dist/zonos-elements/p-48f70043.system.entry.js +0 -1
  277. package/dist/zonos-elements/p-49a31b14.system.entry.js +0 -1
  278. package/dist/zonos-elements/p-4cd867d5.js +0 -1
  279. package/dist/zonos-elements/p-55711b80.system.entry.js +0 -1
  280. package/dist/zonos-elements/p-578bf5d7.entry.js +0 -1
  281. package/dist/zonos-elements/p-5c061a35.entry.js +0 -1
  282. package/dist/zonos-elements/p-6096c1c5.entry.js +0 -1
  283. package/dist/zonos-elements/p-65a8f19d.entry.js +0 -1
  284. package/dist/zonos-elements/p-6adc6e27.entry.js +0 -1
  285. package/dist/zonos-elements/p-6cd9b6a1.system.entry.js +0 -1
  286. package/dist/zonos-elements/p-79070ee6.entry.js +0 -1
  287. package/dist/zonos-elements/p-7bb9c330.entry.js +0 -1
  288. package/dist/zonos-elements/p-82aa4f9f.system.entry.js +0 -1
  289. package/dist/zonos-elements/p-8540f3e2.system.entry.js +0 -1
  290. package/dist/zonos-elements/p-8a9d4605.system.entry.js +0 -1
  291. package/dist/zonos-elements/p-932bed54.system.entry.js +0 -1
  292. package/dist/zonos-elements/p-94e3e50d.system.entry.js +0 -1
  293. package/dist/zonos-elements/p-9f6dd86a.entry.js +0 -1
  294. package/dist/zonos-elements/p-a64ab131.system.entry.js +0 -1
  295. package/dist/zonos-elements/p-aac95779.system.entry.js +0 -1
  296. package/dist/zonos-elements/p-ad3c5358.entry.js +0 -1
  297. package/dist/zonos-elements/p-af6af82e.system.js +0 -1
  298. package/dist/zonos-elements/p-b66b3306.system.entry.js +0 -1
  299. package/dist/zonos-elements/p-b6afcf3f.system.entry.js +0 -1
  300. package/dist/zonos-elements/p-b8d91f99.entry.js +0 -1
  301. package/dist/zonos-elements/p-c770044a.system.entry.js +0 -1
  302. package/dist/zonos-elements/p-d4842d10.system.entry.js +0 -1
  303. package/dist/zonos-elements/p-d6c3aec8.system.entry.js +0 -1
  304. package/dist/zonos-elements/p-daf73a4c.system.js +0 -1
  305. package/dist/zonos-elements/p-de388ea0.entry.js +0 -1
  306. package/dist/zonos-elements/p-e14d89de.entry.js +0 -1
  307. package/dist/zonos-elements/p-f6e587bb.entry.js +0 -1
  308. package/dist/zonos-elements/p-f818bdf5.entry.js +0 -1
  309. package/dist/zonos-elements/p-fce6bffe.system.entry.js +0 -1
@@ -1,7 +1,69 @@
1
- import { c as createStore, z as zonosStore } from './zonosStore-cdabc848.js';
2
- import { h as handleFetch, b as logError, l as log, f as fallbackApiList, g as getIsTestMode, a as getIsStagingMode, s as sendErrorLog, d as allLogs, j as jsonParse } from './handleFetch-621e45bc.js';
3
- import { i as isDarkColor } from './isDarkColor-4c7b2ffc.js';
4
- import { g as getBorderRadius } from './getBorderRadius-413e97eb.js';
1
+ import { c as createStore, z as zonosStore } from './zonosStore-d10a829f.js';
2
+ import { l as log, j as jsonParse, h as handleFetch, b as logError } from './handleFetch-621e45bc.js';
3
+ import { a as availableTestKeys } from './VarianceTest-fef2d958.js';
4
+
5
+ /**
6
+ * Check if the response contains at least one available test key that we support
7
+ */
8
+ const hasAtLeastOneAvailableTestKey = (rawResponse) => {
9
+ const hasAvailableTestKey = !!rawResponse.find(item => item.testKey in availableTestKeys);
10
+ if (!hasAvailableTestKey) {
11
+ log('No available test key found in response', 'info', {
12
+ response: rawResponse,
13
+ });
14
+ }
15
+ return !!rawResponse.find(item => item.testKey in availableTestKeys);
16
+ };
17
+
18
+ /**
19
+ * Filter the response to only include test keys and variants key that we support
20
+ */
21
+ const filterValidTests = (testKeys) => {
22
+ // Type guard the response to ensure it matches the expected structure
23
+ if (!hasAtLeastOneAvailableTestKey(testKeys)) {
24
+ return [];
25
+ }
26
+ // Filter the response to only include test keys that we support
27
+ return testKeys
28
+ .filter(item => {
29
+ var _a;
30
+ const isTestKeyValidButNoSelectedVariantKey = availableTestKeys[item.testKey] && !item.selectedVariantKey;
31
+ const validTestKeyWithSelectedVariantKey = item.selectedVariantKey &&
32
+ !!((_a = availableTestKeys[item.testKey]) === null || _a === void 0 ? void 0 : _a['availableVariants'].includes(item.selectedVariantKey));
33
+ return (isTestKeyValidButNoSelectedVariantKey ||
34
+ validTestKeyWithSelectedVariantKey);
35
+ })
36
+ .map(item => (Object.assign(Object.assign({}, item), { expiresAt: item.expiresAt || Date.now() + VARIANT_TEST_KEY_EXPIRATION, selectedVariantKey: item.selectedVariantKey || null })));
37
+ };
38
+
39
+ /**
40
+ * Expiration time for variant test keys in milliseconds
41
+ * @default 1 day
42
+ */
43
+ const VARIANT_TEST_KEY_EXPIRATION = 60 * 60 * 24 * 1000;
44
+ const { onChange: storageStoreOnChange, state: storageStore } = createStore({
45
+ checkoutSessionId: sessionStorage.getItem('zonos--checkout-session-id'),
46
+ enabledVariantTestKeys: jsonParse(localStorage.getItem('zonos--enabled-variant-test-keys')),
47
+ });
48
+ storageStoreOnChange('enabledVariantTestKeys', () => {
49
+ var _a;
50
+ // This should be set in localStorage so we don't have multiple tests for the same user in short period of time
51
+ if (!((_a = storageStore.enabledVariantTestKeys) === null || _a === void 0 ? void 0 : _a.length)) {
52
+ localStorage.removeItem('zonos--enabled-variant-test-keys');
53
+ return;
54
+ }
55
+ localStorage.setItem('zonos--enabled-variant-test-keys', JSON.stringify(storageStore.enabledVariantTestKeys));
56
+ });
57
+ storageStoreOnChange('checkoutSessionId', () => {
58
+ if (!storageStore.checkoutSessionId) {
59
+ sessionStorage.removeItem('zonos--checkout-session-id');
60
+ return;
61
+ }
62
+ sessionStorage.setItem('zonos--checkout-session-id', storageStore.checkoutSessionId);
63
+ });
64
+ const storageStoreSetEnabledVariantTestKeys = (testKeys) => {
65
+ storageStore.enabledVariantTestKeys = filterValidTests(testKeys);
66
+ };
5
67
 
6
68
  const stringsArabic = {
7
69
  ' (Duties due at door)': {
@@ -13518,7 +13580,7 @@ const setZCountryUrlParam = (selectedCountryCode) => {
13518
13580
  }
13519
13581
  };
13520
13582
 
13521
- const { dispose: localizationDispose, onChange: localizationStoreOnUpdate, state: localizationStore, } = createStore({
13583
+ const { dispose: localizationDispose, onChange: localizationStoreOnChange, state: localizationStore, } = createStore({
13522
13584
  countryLandedCost: null,
13523
13585
  customMessages: [],
13524
13586
  exchangeRate: null,
@@ -13699,12 +13761,12 @@ const initHelloCountryList = (allCountries) => {
13699
13761
  }, {});
13700
13762
  };
13701
13763
  const updateCheckoutSessionLanguage = async () => {
13702
- if (!cartStore.checkoutSessionId) {
13764
+ if (!storageStore.checkoutSessionId) {
13703
13765
  return null;
13704
13766
  }
13705
13767
  const { errors, json } = await handleFetch('/api/zonos-elements/update-checkout-session-metadata', {
13706
13768
  body: {
13707
- id: cartStore.checkoutSessionId,
13769
+ id: storageStore.checkoutSessionId,
13708
13770
  metadata: [
13709
13771
  {
13710
13772
  key: 'language',
@@ -13761,1903 +13823,4 @@ const initLocalizationStore = async () => {
13761
13823
  localizationStore.localizationLoaded = true;
13762
13824
  };
13763
13825
 
13764
- /**
13765
- * Extract value from translated object
13766
- */
13767
- const getTranslatedAddress = ({ currentAddress, translatedAddress, }) => {
13768
- var _a, _b, _c, _d, _e, _f;
13769
- const { city, country, line1, line2, postal_code, state } = currentAddress.value.address;
13770
- const name = currentAddress.value.name ||
13771
- [currentAddress.value.firstName, currentAddress.value.lastName].join(' ');
13772
- return {
13773
- city: ((_a = translatedAddress.city) === null || _a === void 0 ? void 0 : _a[city]) || city,
13774
- country: country,
13775
- line1: ((_b = translatedAddress.line1) === null || _b === void 0 ? void 0 : _b[line1]) || line1,
13776
- line2: ((_c = translatedAddress.line2) === null || _c === void 0 ? void 0 : _c[line2 || '']) || line2 || '',
13777
- name: ((_d = translatedAddress.name) === null || _d === void 0 ? void 0 : _d[name]) || name,
13778
- phone: currentAddress.value.phone || '',
13779
- postal_code: ((_e = translatedAddress.postal_code) === null || _e === void 0 ? void 0 : _e[postal_code]) || postal_code,
13780
- state: ((_f = translatedAddress.state) === null || _f === void 0 ? void 0 : _f[state]) || state,
13781
- };
13782
- };
13783
- /**
13784
- * Similar to prepCalculateLandedCost except it only uses cart ID
13785
- */
13786
- const prepCartCalculateLandedCost = (cartId) => {
13787
- var _a;
13788
- const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
13789
- // maybe we don't need email now for prefetch the landed cost
13790
- const stripeLinkData = stripeStore.stripeLinkEventData;
13791
- const stripeAddressData = stripeStore.stripeAddressEventData;
13792
- const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
13793
- ? stripeStore.stripeAddressEventData
13794
- : stripeStore.stripeBillingAddressEventData;
13795
- if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
13796
- throw new Error('Missing stripe address data');
13797
- }
13798
- // Attempt to get translated address if available
13799
- const translatedShippingAddress = getTranslatedAddress({
13800
- currentAddress: stripeAddressData,
13801
- translatedAddress: stripeStore.translatedAddress.address,
13802
- });
13803
- const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
13804
- const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
13805
- const translatedBillingAddress = getTranslatedAddress({
13806
- currentAddress: stripeBillingAddressData,
13807
- translatedAddress: stripeStore.translatedAddress.address,
13808
- });
13809
- const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
13810
- const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
13811
- return {
13812
- billingAddress: {
13813
- addressLine1: translatedBillingAddress.line1,
13814
- addressLine2: translatedBillingAddress.line2 || '',
13815
- city: translatedBillingAddress.city,
13816
- country: translatedBillingAddress.country,
13817
- postalCode: translatedBillingAddress.postal_code,
13818
- state: translatedBillingAddress.state,
13819
- },
13820
- billingContact: {
13821
- // firstName and lastName should be valid now since stripe only mark
13822
- // the address as complete when both fields are filled.
13823
- firstName: billingFirstName,
13824
- lastName: billingLastName,
13825
- phone: translatedBillingAddress.phone,
13826
- },
13827
- // Use the first item's currency code
13828
- cartCurrencyCode: (_a = cartStore.items[0]) === null || _a === void 0 ? void 0 : _a.currencyCode,
13829
- cartId,
13830
- checkoutSessionId: cartStore.checkoutSessionId || '',
13831
- contact: {
13832
- companyName: stripeStore.companyName,
13833
- email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
13834
- // firstName and lastName should be valid now since stripe only mark
13835
- // the address as complete when both fields are filled.
13836
- firstName: shippingFirstName,
13837
- lastName: shippingLastName,
13838
- phone: translatedShippingAddress.phone,
13839
- },
13840
- isTest: !!isE2ETest,
13841
- landedCostAdjustments: cartStore.promoCode
13842
- ? [
13843
- {
13844
- amount: 0,
13845
- productId: null,
13846
- promoCode: cartStore.promoCode,
13847
- sku: null,
13848
- type: 'PROMO_CODE',
13849
- },
13850
- ]
13851
- : [],
13852
- shipToTaxId: stripeStore.taxId,
13853
- shippingAddress: {
13854
- addressLine1: translatedShippingAddress.line1,
13855
- addressLine2: translatedShippingAddress.line2,
13856
- city: translatedShippingAddress.city,
13857
- country: translatedShippingAddress.country,
13858
- postalCode: translatedShippingAddress.postal_code,
13859
- state: translatedShippingAddress.state,
13860
- },
13861
- };
13862
- };
13863
- const prepCalculateLandedCost = () => {
13864
- const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
13865
- // maybe we don't need email now for prefetch the landed cost
13866
- const stripeLinkData = stripeStore.stripeLinkEventData;
13867
- const stripeAddressData = stripeStore.stripeAddressEventData;
13868
- const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
13869
- ? stripeStore.stripeAddressEventData
13870
- : stripeStore.stripeBillingAddressEventData;
13871
- log({ stripeAddressData, stripeBillingAddressData }, 'info');
13872
- if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
13873
- throw new Error('Missing stripe address data');
13874
- }
13875
- // Attempt to get translated address if available
13876
- const translatedShippingAddress = getTranslatedAddress({
13877
- currentAddress: stripeAddressData,
13878
- translatedAddress: stripeStore.translatedAddress.address,
13879
- });
13880
- const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
13881
- const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
13882
- const translatedBillingAddress = getTranslatedAddress({
13883
- currentAddress: stripeBillingAddressData,
13884
- translatedAddress: stripeStore.translatedAddress.address,
13885
- });
13886
- const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
13887
- const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
13888
- const convertedCartAdjuments = cartStore.adjustments.map(adjustment => ({
13889
- amount: adjustment.amount,
13890
- name: adjustment.description || null,
13891
- productId: adjustment.productId,
13892
- sku: adjustment.sku,
13893
- type: adjustment.type,
13894
- }));
13895
- const adjustments = cartStore.promoCode
13896
- ? [
13897
- {
13898
- amount: 0,
13899
- productId: null,
13900
- promoCode: cartStore.promoCode,
13901
- sku: null,
13902
- type: 'PROMO_CODE',
13903
- },
13904
- ...convertedCartAdjuments,
13905
- ]
13906
- : convertedCartAdjuments;
13907
- return {
13908
- billingAddress: {
13909
- addressLine1: translatedBillingAddress.line1,
13910
- addressLine2: translatedBillingAddress.line2 || '',
13911
- city: translatedBillingAddress.city,
13912
- country: translatedBillingAddress.country,
13913
- postalCode: translatedBillingAddress.postal_code,
13914
- state: translatedBillingAddress.state,
13915
- },
13916
- billingContact: {
13917
- // firstName and lastName should be valid now since stripe only mark
13918
- // the address as complete when both fields are filled.
13919
- firstName: billingFirstName,
13920
- lastName: billingLastName,
13921
- phone: translatedBillingAddress.phone,
13922
- },
13923
- checkoutSessionId: cartStore.checkoutSessionId || '',
13924
- contact: {
13925
- companyName: stripeStore.companyName,
13926
- email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
13927
- // firstName and lastName should be valid now since stripe only mark
13928
- // the address as complete when both fields are filled.
13929
- firstName: shippingFirstName,
13930
- lastName: shippingLastName,
13931
- phone: translatedShippingAddress.phone,
13932
- },
13933
- isTest: isE2ETest,
13934
- items: cartStore.items,
13935
- landedCostAdjustments: adjustments,
13936
- shipToTaxId: stripeStore.taxId,
13937
- shippingAddress: {
13938
- addressLine1: translatedShippingAddress.line1,
13939
- addressLine2: translatedShippingAddress.line2,
13940
- city: translatedShippingAddress.city,
13941
- country: translatedShippingAddress.country,
13942
- postalCode: translatedShippingAddress.postal_code,
13943
- state: translatedShippingAddress.state,
13944
- },
13945
- };
13946
- };
13947
-
13948
- const triggerBuildLandedCost = async (buildLandedCost) => {
13949
- var _a, _b, _c, _d, _e;
13950
- const data = prepCalculateLandedCost();
13951
- const landedCost = await buildLandedCost({
13952
- billingAddress: data.billingAddress,
13953
- billingContact: data.billingContact,
13954
- checkoutSessionId: data.checkoutSessionId,
13955
- contact: data.contact,
13956
- landedCostAdjustments: data.landedCostAdjustments,
13957
- // zonosApiKey should always be available
13958
- publicCredential: window.Zonos.zonosApiKey || '',
13959
- shippingAddress: data.shippingAddress,
13960
- zonosApiRoute: fallbackApiList['vercel'],
13961
- });
13962
- if (!landedCost ||
13963
- // Only show errors if there are no rate back (checkoutSessionWorkflow) and there are errors
13964
- (!((_a = landedCost.checkoutSessionWorkflow) === null || _a === void 0 ? void 0 : _a.length) && ((_b = landedCost.errors) === null || _b === void 0 ? void 0 : _b.length))) {
13965
- 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'}`);
13966
- }
13967
- // Validate the landed cost object to make sure the returned value from buildLandedCost has a valid schema
13968
- const { errors, json } = await handleFetch('/api/zonos-elements/validate-landed-cost', {
13969
- body: landedCost,
13970
- headers: {
13971
- 'Content-Type': 'application/json',
13972
- },
13973
- method: 'POST',
13974
- });
13975
- if (!json || errors.length) {
13976
- throw new Error(`Invalid landed cost object: ${((_e = errors.find(Boolean)) === null || _e === void 0 ? void 0 : _e.message) || 'Unknown error'}`);
13977
- }
13978
- return landedCost;
13979
- };
13980
-
13981
- const calculateLandedCost = async (abortController) => {
13982
- var _a;
13983
- // If buildLandedCost callback is supplied, use that instead of our regular request to '/calculate-landed-cost'
13984
- const buildLandedCost = zonosStore.checkoutSettings.buildLandedCost;
13985
- if (buildLandedCost) {
13986
- const json = await triggerBuildLandedCost(buildLandedCost);
13987
- return json;
13988
- }
13989
- // request to get landed cost info
13990
- const { errors, json } = await handleFetch('/api/zonos-elements/calculate-landed-cost', {
13991
- body: prepCalculateLandedCost(),
13992
- method: 'POST',
13993
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
13994
- });
13995
- if (errors.length || !json) {
13996
- const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
13997
- if (isAbortedRequest) {
13998
- throw new Error('The landed cost calculation request was aborted to initiate a new one.');
13999
- }
14000
- // We want to show any successful quotes even if there are errors
14001
- errors.forEach(error => {
14002
- // eslint-disable-next-line no-console
14003
- console.warn(`Error calculating landed cost: ${error.message}`);
14004
- });
14005
- if (!json) {
14006
- throw new Error('Failed to calculate landed cost');
14007
- }
14008
- return json;
14009
- }
14010
- return json;
14011
- };
14012
-
14013
- const cartCalculateLandedCost = async ({ abortController, cartId, }) => {
14014
- var _a;
14015
- // request to get landed cost info
14016
- const { errors, json } = await handleFetch('/api/zonos-elements/cart-calculate-landed-cost', {
14017
- body: prepCartCalculateLandedCost(cartId),
14018
- method: 'POST',
14019
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
14020
- });
14021
- if (errors.length || !json) {
14022
- const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
14023
- const errorMessage = isAbortedRequest
14024
- ? 'The landed cost calculation request was aborted to initiate a new one.'
14025
- : 'Failed to calculate landed cost';
14026
- throw new Error(errorMessage);
14027
- }
14028
- return json;
14029
- };
14030
-
14031
- var __rest = (undefined && undefined.__rest) || function (s, e) {
14032
- var t = {};
14033
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14034
- t[p] = s[p];
14035
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
14036
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
14037
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
14038
- t[p[i]] = s[p[i]];
14039
- }
14040
- return t;
14041
- };
14042
- const calculateLandedCostNormalized = async (abortController) => {
14043
- const cartId = window.Zonos.cartId;
14044
- // Calculate landed cost as usual if no cartId is available
14045
- if (!cartId) {
14046
- const landedCostResult = await calculateLandedCost(abortController);
14047
- return landedCostResult;
14048
- }
14049
- // Calculate landed cost using cartId
14050
- const _a = await cartCalculateLandedCost({
14051
- abortController,
14052
- cartId,
14053
- }), { cartWorkflow } = _a, rest = __rest(_a, ["cartWorkflow"]);
14054
- return Object.assign(Object.assign({}, rest), { itemCreateWorkflow: cartWorkflow.items });
14055
- };
14056
-
14057
- const trackConversionEvent = async ({ checkoutSessionId, eventName, metadata, }) => {
14058
- var _a, _b;
14059
- const eventCreated = Date.now();
14060
- const trackLogMetadata = [...window.Zonos.trackEventLogs];
14061
- window.Zonos.trackEventLogs.push({
14062
- checkoutSessionId,
14063
- eventCreated,
14064
- eventName,
14065
- });
14066
- const isDevelopment =
14067
- // 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)
14068
- (window.location.href.includes('zonos.com') &&
14069
- !window.location.href.includes('checkout.zonos.com')) ||
14070
- !!((_a = window.Zonos) === null || _a === void 0 ? void 0 : _a.zonosQaUrl) ||
14071
- !!((_b = window.Zonos) === null || _b === void 0 ? void 0 : _b.debug);
14072
- const isTest = getIsTestMode() || getIsStagingMode();
14073
- if ((isTest || isDevelopment) &&
14074
- // if found, it means we want to test the conversion event in development site, or test mode and staging mode
14075
- !window.Zonos.zonosConversionTest) {
14076
- return;
14077
- }
14078
- const countryCode = localizationStore.selectedCountryCode;
14079
- const organizationId = zonosStore.organizationId;
14080
- if (!checkoutSessionId) {
14081
- void sendErrorLog({
14082
- endpoint: 'trackConversionEventMetric',
14083
- errors: [`Event "${eventName}" - No checkout session id found`],
14084
- metadata: {
14085
- allLogs,
14086
- checkoutSessionId,
14087
- eventName,
14088
- metadata,
14089
- organizationId,
14090
- trackEventLogs: trackLogMetadata,
14091
- },
14092
- });
14093
- // checkoutSessionId is required for tracking conversion events to work properly
14094
- return;
14095
- }
14096
- if (!organizationId) {
14097
- void sendErrorLog({
14098
- endpoint: 'trackConversionEventMetric',
14099
- errors: [`Event "${eventName}" - No organization id found`],
14100
- metadata: {
14101
- allLogs,
14102
- checkoutSessionId,
14103
- eventName,
14104
- metadata,
14105
- organizationId,
14106
- trackEventLogs: trackLogMetadata,
14107
- },
14108
- });
14109
- }
14110
- const body = {
14111
- checkoutSessionId,
14112
- countryCode,
14113
- eventCreated,
14114
- eventName,
14115
- metadata: Object.assign(Object.assign({}, metadata), { trackEventLogs: trackLogMetadata }),
14116
- organizationId,
14117
- };
14118
- await handleFetch('/api/zonos-elements/track-conversion-event', {
14119
- body,
14120
- method: 'POST',
14121
- });
14122
- };
14123
-
14124
- /**
14125
- * This function generates an object that contains the fields of an address that have invalid characters.
14126
- *
14127
- * @param {Object} params - The parameters for the function.
14128
- * @param {Address | null} params.address - The address to check for invalid characters.
14129
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.invalidAdddressList - The list of address fields that contain invalid characters.
14130
- *
14131
- * @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.
14132
- */
14133
- const getExcludeAddressFieldsObject = ({ address, invalidAdddressList, }) => {
14134
- if (!address) {
14135
- return;
14136
- }
14137
- // if there are no invalid characters, return an empty object
14138
- if (!invalidAdddressList) {
14139
- return;
14140
- }
14141
- const excludeFields = {};
14142
- if (invalidAdddressList.city) {
14143
- excludeFields.city = address.city;
14144
- }
14145
- if (invalidAdddressList.line1) {
14146
- excludeFields.line1 = address.line1;
14147
- }
14148
- if (invalidAdddressList.line2) {
14149
- excludeFields.line2 = address.line2;
14150
- }
14151
- if (invalidAdddressList.postal_code) {
14152
- excludeFields.postal_code = address.postal_code;
14153
- }
14154
- if (invalidAdddressList.state) {
14155
- excludeFields.state = address.state;
14156
- }
14157
- if (invalidAdddressList.name) {
14158
- excludeFields.name = address.name;
14159
- }
14160
- // return null if there are no fields to exclude
14161
- return Object.keys(excludeFields).length ? excludeFields : undefined;
14162
- };
14163
- /**
14164
- * 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.
14165
- * 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.
14166
- * If the conditions are not met, it returns null.
14167
- *
14168
- * @param {Object} params - The parameters for the function.
14169
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
14170
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
14171
- * @param {StripeAddressEventData} params.stripeAddressEventData - The Stripe event data for the address.
14172
- * @param {StripeAddressEventData} params.stripeBillingAddressEventData - The Stripe event data for the billing address.
14173
- * @param {boolean} params.stripeShippingSameAsBilling - A flag indicating whether the shipping address is the same as the billing address.
14174
- *
14175
- * @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.
14176
- */
14177
- const buildTranslateRequest = ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, stripeAddressEventData, stripeBillingAddressEventData, stripeShippingSameAsBilling, }) => {
14178
- var _a, _b, _c, _d;
14179
- const isStripeAddressReady = !!(stripeAddressEventData === null || stripeAddressEventData === void 0 ? void 0 : stripeAddressEventData.complete);
14180
- const isStripeBillingAddressReady = stripeShippingSameAsBilling
14181
- ? isStripeAddressReady
14182
- : !!(stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.complete);
14183
- // only translate if both address and billing address are ready
14184
- if (!isStripeAddressReady || !isStripeBillingAddressReady) {
14185
- return null;
14186
- }
14187
- // only translate if there are invalid characters
14188
- if (!addressInvalidCharactersList && !billingAddressInvalidCharactersList) {
14189
- return null;
14190
- }
14191
- const stripeAddressValue = stripeAddressEventData.value;
14192
- const stripeBillingAddressValue = (stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.value) || null;
14193
- // Returns undefined if the name is Latin so it won't be included in the request body
14194
- const firstName = stripeAddressValue.firstName || ((_a = stripeAddressValue.name) === null || _a === void 0 ? void 0 : _a.split(' ')[0]);
14195
- const lastName = stripeAddressValue.lastName || ((_b = stripeAddressValue.name) === null || _b === void 0 ? void 0 : _b.split(' ')[1]);
14196
- const name = `${firstName} ${lastName}`;
14197
- const billingFirstName = stripeAddressValue.firstName ||
14198
- ((_c = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _c === void 0 ? void 0 : _c.split(' ')[0]);
14199
- const billingLastName = stripeAddressValue.lastName ||
14200
- ((_d = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _d === void 0 ? void 0 : _d.split(' ')[1]);
14201
- const billingName = billingFirstName && billingLastName
14202
- ? `${billingFirstName} ${billingLastName}`
14203
- : '';
14204
- const address = stripeAddressValue.address;
14205
- const billingAddress = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.address;
14206
- return {
14207
- address: getExcludeAddressFieldsObject({
14208
- address: Object.assign(Object.assign({}, address), { name }),
14209
- invalidAdddressList: addressInvalidCharactersList,
14210
- }),
14211
- // only include billing address if it's different from the shipping address
14212
- billingAddress: !stripeShippingSameAsBilling
14213
- ? getExcludeAddressFieldsObject({
14214
- address: billingAddress
14215
- ? Object.assign(Object.assign({}, billingAddress), { name: billingName }) : null,
14216
- invalidAdddressList: billingAddressInvalidCharactersList,
14217
- })
14218
- : undefined,
14219
- destinationCountry: address.country,
14220
- };
14221
- };
14222
-
14223
- /**
14224
- * Sorts service levels with lower cost first
14225
- */
14226
- const sortServiceLevelOptionsByAmount = (serviceLevels) => {
14227
- const sortedServiceLevels = serviceLevels.sort((a, b) => {
14228
- return a.amount - b.amount;
14229
- });
14230
- return sortedServiceLevels;
14231
- };
14232
-
14233
- const getCheckoutSession = async () => {
14234
- if (!cartStore.checkoutSessionId) {
14235
- return {
14236
- errors: [{ message: 'No checkout session id found' }],
14237
- json: null,
14238
- };
14239
- }
14240
- const searchParams = new URLSearchParams();
14241
- searchParams.set('checkoutSessionId', cartStore.checkoutSessionId);
14242
- const { errors, json } = await handleFetch(`/api/zonos-elements/get-checkout-session?${searchParams.toString()}`);
14243
- return { errors, json };
14244
- };
14245
-
14246
- /**
14247
- * Validate checkout session before confirming payment
14248
- */
14249
- const validateCheckoutSession = async () => {
14250
- var _a;
14251
- // get checkout session info
14252
- const { errors, json } = await getCheckoutSession();
14253
- if (errors.length || !json) {
14254
- logError('Failed to retrieve checkout session info before confirming payment ', errors);
14255
- void sendErrorLog({
14256
- endpoint: 'validateCheckoutSession',
14257
- errors: errors.map(error => error.message),
14258
- metadata: { allLogs },
14259
- });
14260
- return {
14261
- errorMessage: translate('Unable to retrieve the checkout session at the moment. Please try again or contact our support team.'),
14262
- valid: false,
14263
- };
14264
- }
14265
- // Make sure landed cost is found in the checkout session
14266
- if (!((_a = json.checkoutSession.landedCost) === null || _a === void 0 ? void 0 : _a.id)) {
14267
- logError('Landed cost is not found in the checkout session before confirming payment.');
14268
- void sendErrorLog({
14269
- endpoint: 'validateCheckoutSession',
14270
- errors: ['No landed cost found before confirming payment'],
14271
- metadata: { allLogs },
14272
- });
14273
- return {
14274
- errorMessage: translate('No shipment rating selected. Please go back to the "Shipping" step and select a shipment rating to proceed.'),
14275
- valid: false,
14276
- };
14277
- }
14278
- return { errorMessage: '', valid: true };
14279
- };
14280
-
14281
- const addressRuleStyle = ({ theme, }) => {
14282
- const defaultStyle = {
14283
- '.AccordionItem': {
14284
- color: 'var(--colorText)',
14285
- },
14286
- '.AccordionItem--selected': {
14287
- color: 'var(--colorText)',
14288
- },
14289
- '.Action': {
14290
- color: 'var(--colorText)',
14291
- },
14292
- '.Input': {
14293
- boxShadow: 'none',
14294
- fontSize: zonosStore.appearance.fontSizeInputValue
14295
- ? `${zonosStore.appearance.fontSizeInputValue}px`
14296
- : undefined,
14297
- // need to reset everything and the paddingTop to default, otherwise the paddingTop will not be updated.
14298
- padding: '0',
14299
- paddingBottom: '8px',
14300
- paddingLeft: '16px',
14301
- paddingRight: '8px',
14302
- // any value here will be add up to the default paddingTop (20px).
14303
- paddingTop: '6px',
14304
- },
14305
- '.Label--resting': {
14306
- fontSize: zonosStore.appearance.fontSizeInputLabel
14307
- ? `${zonosStore.appearance.fontSizeInputLabel}px`
14308
- : undefined,
14309
- },
14310
- '.PickerItem--highlight': {
14311
- boxShadow: '0 0 0 2px var(--colorBackground)',
14312
- },
14313
- '.PickerItem--highlight:hover': {
14314
- backgroundColor: 'var(--colorBackground)',
14315
- boxShadow: 'none',
14316
- },
14317
- '.PickerItem--new': {
14318
- color: 'var(--colorText)',
14319
- },
14320
- '.Tab--selected': {
14321
- borderStyle: 'solid',
14322
- borderWidth: '1px',
14323
- },
14324
- };
14325
- switch (theme) {
14326
- case 'DARK': {
14327
- 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' }) });
14328
- }
14329
- default:
14330
- return defaultStyle;
14331
- }
14332
- };
14333
-
14334
- const defaultVariable = ({ borderStyle, theme, }) => {
14335
- switch (theme) {
14336
- case 'DARK':
14337
- return {
14338
- borderRadius: getBorderRadius({ overrideBorderStyle: borderStyle }),
14339
- colorBackground: '#101117',
14340
- colorBackgroundText: '#C5C6CA',
14341
- colorText: '#C5C6CA',
14342
- colorTextPlaceholder: '#C5C6CA',
14343
- };
14344
- default:
14345
- return {
14346
- borderRadius: getBorderRadius({ overrideBorderStyle: borderStyle }),
14347
- iconMenuColor: 'var(--colorText)',
14348
- iconMenuHoverColor: 'var(--colorText)',
14349
- };
14350
- }
14351
- };
14352
-
14353
- const { onChange: onChange$1, reset: reset$1, state: stripeStore, } = createStore(() => ({
14354
- checkoutSettlementCurrency: 'USD',
14355
- clientSecret: sessionStorage.getItem('zonos--client-secret') || '',
14356
- companyName: '',
14357
- customAddressErrors: {
14358
- city: '',
14359
- firstName: '',
14360
- lastName: '',
14361
- line1: '',
14362
- phone: '',
14363
- postalCode: '',
14364
- showError: false,
14365
- state: '',
14366
- },
14367
- customBillingAddressErrors: {
14368
- city: '',
14369
- firstName: '',
14370
- lastName: '',
14371
- line1: '',
14372
- phone: '',
14373
- postalCode: '',
14374
- showError: false,
14375
- state: '',
14376
- },
14377
- customErrorMessage: null,
14378
- customerProfile: null,
14379
- fetchingLandedCostAbortController: null,
14380
- hasPaymentError: false,
14381
- isFetchingLandedCost: false,
14382
- isFetchingSession: false,
14383
- shouldInventoryRefund: false,
14384
- shouldRenderPayInUsdButton: false,
14385
- /**
14386
- * Default to skip payment intent, only create payment intent when "skipPaymentIntent" in url's query params is set "0"
14387
- * @default true
14388
- */
14389
- skipPaymentIntent: new URLSearchParams(window.location.search).get('skipPaymentIntent') === '0'
14390
- ? false
14391
- : true,
14392
- stripe: null,
14393
- stripeAddressElement: null,
14394
- stripeAddressEventData: null,
14395
- stripeAddressUsedWhenFetchingLC: null,
14396
- stripeAddressUsedWhenValidatingAddress: null,
14397
- stripeBillingAddressElement: null,
14398
- stripeBillingAddressEventData: null,
14399
- stripeBillingAddressUsedWhenFetchingLC: null,
14400
- stripeBillingAddressUsedWhenValidatingAddress: null,
14401
- stripeCustomerSessionClientSecret: null,
14402
- stripeElements: null,
14403
- stripeElementsForBillingAddress: null,
14404
- stripeElementsOptions: null,
14405
- stripeLinkElement: null,
14406
- stripeLinkEventData: null,
14407
- stripeLinkUsedWhenFetchingLC: null,
14408
- stripePaymentElement: null,
14409
- stripePaymentEventData: null,
14410
- stripeShippingSameAsBilling: true,
14411
- taxId: '',
14412
- taxIdUsedWhenFetchingLC: '',
14413
- translatedAddress: {
14414
- address: {},
14415
- billingAddress: {},
14416
- firstName: {},
14417
- lastName: {},
14418
- name: {},
14419
- },
14420
- }));
14421
- const getStripeOptions = ({ clientSecret, overrideBorderRadius, overridePrimaryColor, overrideSecondaryColor, overrideTheme, paypalEnabled, }) => {
14422
- const primaryColor = overridePrimaryColor || zonosStore.appearance.colorPrimary;
14423
- const secondaryColor = overrideSecondaryColor || zonosStore.appearance.colorSecondary;
14424
- const themeBasedColor = primaryColor && isDarkColor(primaryColor) ? 'night' : 'flat';
14425
- // if overrideTheme is provided, use it. Otherwise, use theme based on primary color
14426
- const theme = overrideTheme === 'DARK' ? 'night' : 'flat';
14427
- const paypalPaymentType = paypalEnabled ? ['external_paypal'] : [];
14428
- return {
14429
- appearance: {
14430
- labels: 'floating',
14431
- rules: Object.assign({}, addressRuleStyle({ theme: overrideTheme || 'LIGHT' })),
14432
- // get contrast theme color base on primary color
14433
- theme: overrideTheme ? theme : themeBasedColor,
14434
- variables: Object.assign(Object.assign({}, defaultVariable({
14435
- borderStyle: overrideBorderRadius,
14436
- theme: 'LIGHT',
14437
- })), {
14438
- // use the button background color for input glow color
14439
- colorPrimary: secondaryColor }),
14440
- },
14441
- // 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
14442
- clientSecret: clientSecret || undefined,
14443
- customerSessionClientSecret: stripeStore.stripeCustomerSessionClientSecret || undefined,
14444
- externalPaymentMethodTypes: [...paypalPaymentType],
14445
- locale: localizationStore.selectedLocale,
14446
- };
14447
- };
14448
- const stripeStoreCleanupDomesticShippingSession = () => {
14449
- window.sessionStorage.removeItem('zonos--bigcommerce-domestic-checkout-shipping');
14450
- };
14451
- // Save shipping address to session storage
14452
- const stripeStoreSaveDomesticShippingSession = (props) => {
14453
- window.sessionStorage.setItem('zonos--bigcommerce-domestic-checkout-shipping', JSON.stringify(props));
14454
- };
14455
- const stripeStoreGetDomesticShippingSession = () => {
14456
- const session = window.sessionStorage.getItem('zonos--bigcommerce-domestic-checkout-shipping');
14457
- return jsonParse(session);
14458
- };
14459
- const initStripeElements = async (props) => {
14460
- var _a, _b;
14461
- const clientSecret = stripeStore.clientSecret;
14462
- if (!stripeStore.stripe) {
14463
- log('Skip. Stripe is not initialized');
14464
- return;
14465
- }
14466
- const stripeOptions = getStripeOptions({
14467
- clientSecret,
14468
- overrideBorderRadius: props === null || props === void 0 ? void 0 : props.overrideBorderRadius,
14469
- overridePrimaryColor: props === null || props === void 0 ? void 0 : props.overridePrimaryColor,
14470
- overrideSecondaryColor: props === null || props === void 0 ? void 0 : props.overrideSecondaryColor,
14471
- overrideTheme: props === null || props === void 0 ? void 0 : props.overrideTheme,
14472
- paypalEnabled: props === null || props === void 0 ? void 0 : props.paypalEnabled,
14473
- });
14474
- // compare with the previous options to see if we need to update
14475
- const isSameOptions = JSON.stringify(stripeOptions) ===
14476
- JSON.stringify(stripeStore.stripeElementsOptions);
14477
- if (!stripeStore.stripeElements ||
14478
- !stripeStore.stripeElementsForBillingAddress) {
14479
- // init stripe elements if it doesn't exist
14480
- stripeStore.stripeElements = (_a = stripeStore.stripe) === null || _a === void 0 ? void 0 : _a.elements(stripeOptions);
14481
- // save stripe elements options for later comparison
14482
- stripeStore.stripeElementsOptions = stripeOptions;
14483
- log('Stripe elements initialized');
14484
- // init stripe elements for billing address
14485
- stripeStore.stripeElementsForBillingAddress =
14486
- (_b = stripeStore.stripe) === null || _b === void 0 ? void 0 : _b.elements(stripeOptions);
14487
- log('Stripe elements for billing address initialized');
14488
- return;
14489
- }
14490
- if (!isSameOptions) {
14491
- // update elements with new option if it already exists
14492
- stripeStore.stripeElements.update(stripeOptions);
14493
- // update elements for stripe billing address
14494
- stripeStore.stripeElementsForBillingAddress.update(stripeOptions);
14495
- // save stripe elements options for later comparison
14496
- stripeStore.stripeElementsOptions = stripeOptions;
14497
- void stripeStore.stripeElements.fetchUpdates();
14498
- }
14499
- log('Stripe elements updated');
14500
- };
14501
- const stripeStoreReset = () => {
14502
- // clean clientSecret so that we can start the new one.
14503
- sessionStorage.removeItem('zonos--client-secret');
14504
- // cleanup stripe elements
14505
- reset$1();
14506
- // set stripe back to window.Zonos.stripe
14507
- stripeStore.stripe = window.Zonos.stripe;
14508
- };
14509
- const checkIsAddressOutdatedForValidation = () => {
14510
- var _a, _b, _c, _d;
14511
- 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);
14512
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
14513
- JSON.stringify((_c = stripeStore.stripeBillingAddressEventData) === null || _c === void 0 ? void 0 : _c.value) !==
14514
- JSON.stringify((_d = stripeStore.stripeBillingAddressUsedWhenValidatingAddress) === null || _d === void 0 ? void 0 : _d.value);
14515
- return isAddressDataDirty || isBillingAddressDataDirty;
14516
- };
14517
- const checkIsAddressOutdatedForLCPrefetch = () => {
14518
- var _a, _b, _c, _d, _e, _f;
14519
- const isLinkDataDirty = JSON.stringify((_a = stripeStore.stripeLinkUsedWhenFetchingLC) === null || _a === void 0 ? void 0 : _a.value) !==
14520
- JSON.stringify((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.value);
14521
- const isAddressDataDirty = JSON.stringify((_c = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _c === void 0 ? void 0 : _c.value) !==
14522
- JSON.stringify((_d = stripeStore.stripeAddressEventData) === null || _d === void 0 ? void 0 : _d.value);
14523
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
14524
- JSON.stringify((_e = stripeStore.stripeBillingAddressEventData) === null || _e === void 0 ? void 0 : _e.value) !==
14525
- JSON.stringify((_f = stripeStore.stripeBillingAddressUsedWhenFetchingLC) === null || _f === void 0 ? void 0 : _f.value);
14526
- return isLinkDataDirty || isAddressDataDirty || isBillingAddressDataDirty;
14527
- };
14528
- /**
14529
- * Check if the address and email info used when fetching landed cost with the current email and address info are different
14530
- * Purpose is to resend the request if the info used when fetching landed cost is different from the current info
14531
- */
14532
- const isPrefetchInfoOutdated = () => {
14533
- var _a;
14534
- // Mark the landed cost is outdated since the item total amount has changed (items total didn't match with the cart subtotal)
14535
- const isTotalAmountChanged = cartStore.landedCostData &&
14536
- ((_a = cartStore.landedCostData.find(Boolean)) === null || _a === void 0 ? void 0 : _a.subtotals.items) !==
14537
- cartStore.subtotal;
14538
- const isAddressOutdated = checkIsAddressOutdatedForLCPrefetch();
14539
- // Auto prefetch landed cost if tax id is updated
14540
- const isTaxIdDirty = stripeStore.taxIdUsedWhenFetchingLC !== stripeStore.taxId;
14541
- return (
14542
- // if landed cost data is not available, we need to fetch it
14543
- !cartStore.landedCostData ||
14544
- isAddressOutdated ||
14545
- isTotalAmountChanged ||
14546
- isTaxIdDirty);
14547
- };
14548
- const stripeCalculateLandedCost = async () => {
14549
- var _a;
14550
- const abortController = new AbortController();
14551
- stripeStore.fetchingLandedCostAbortController = abortController;
14552
- // Reset cart items to non-restricted state and restricted item list
14553
- cartStoreResetCartItems();
14554
- const { checkoutSessionWorkflow, errors, itemCreateWorkflow, landedCostCalculateWorkflow, partyCreateWorkflow, shipmentRatingCalculateWorkflow, } = await calculateLandedCostNormalized(abortController);
14555
- // update the error message with customized error message that rule is applying to and disabled shippment rating if there is any
14556
- cartStore.customQuotingError =
14557
- ((_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;
14558
- cartStore.shippingData = sortServiceLevelOptionsByAmount((shipmentRatingCalculateWorkflow === null || shipmentRatingCalculateWorkflow === void 0 ? void 0 : shipmentRatingCalculateWorkflow.filter(Boolean)) || []);
14559
- // check and update cart items with restrictions
14560
- cartStoreCheckItemRestrictions(itemCreateWorkflow);
14561
- // reset abort controller after we are done
14562
- stripeStore.fetchingLandedCostAbortController = null;
14563
- cartStore.partiesData = (partyCreateWorkflow === null || partyCreateWorkflow === void 0 ? void 0 : partyCreateWorkflow.filter(Boolean)) || [];
14564
- // update cart store with landed cost info
14565
- cartStore.landedCostData =
14566
- (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.map(checkoutSession => {
14567
- const foundLandedCost = landedCostCalculateWorkflow === null || landedCostCalculateWorkflow === void 0 ? void 0 : landedCostCalculateWorkflow.find(item => (item === null || item === void 0 ? void 0 : item.id) === checkoutSession.landedCostId);
14568
- if (!foundLandedCost) {
14569
- return null;
14570
- }
14571
- return Object.assign(Object.assign({}, checkoutSession), { landedCost: foundLandedCost });
14572
- }).filter(Boolean)) || [];
14573
- // Send event when we get the quote back after the customer clicked "Continue to shipping"
14574
- const checkoutSessionId = cartStore.checkoutSessionId;
14575
- if (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.length) {
14576
- void trackConversionEvent({
14577
- checkoutSessionId,
14578
- eventName: 'checkout_quoteReceived',
14579
- });
14580
- }
14581
- // update adjustmentTotal
14582
- // highlight promocode input error if promocode is applied but no adjustment applied in landed cost
14583
- const isInvalidPromoCode = cartStore.promoCodeApplied &&
14584
- !cartStore.landedCostData.find(item => {
14585
- var _a;
14586
- return (_a = item.landedCost.appliedAdjustments) === null || _a === void 0 ? void 0 : _a.find(_item => _item.type === 'PROMO_CODE');
14587
- });
14588
- cartStore.promoCodeError = isInvalidPromoCode;
14589
- // When promocode is valid, set promoCode to session storage so if user close the modal, we can still reapply for them
14590
- if (!isInvalidPromoCode) {
14591
- sessionStorage.setItem('promoCode', cartStore.promoCode);
14592
- }
14593
- };
14594
- const stripeStorePrefetchLandedCost = async (params) => {
14595
- var _a, _b, _c, _d, _e, _f, _g, _h;
14596
- const retries = (params === null || params === void 0 ? void 0 : params.retries) || 0;
14597
- const applyingPromocode = !!(params === null || params === void 0 ? void 0 : params.applyingPromocode);
14598
- const stripeAddressReady = !!((_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.complete);
14599
- const stripeLinkReady = !!((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.complete);
14600
- const stripeBillingAddressReady = stripeStore.stripeShippingSameAsBilling
14601
- ? !!((_c = stripeStore.stripeLinkEventData) === null || _c === void 0 ? void 0 : _c.complete)
14602
- : !!((_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.complete);
14603
- const shouldRefetch = isPrefetchInfoOutdated();
14604
- if (shouldRefetch) {
14605
- // if the info used when fetching landed cost is different from the current info, abort the previous request
14606
- (_e = stripeStore.fetchingLandedCostAbortController) === null || _e === void 0 ? void 0 : _e.abort();
14607
- stripeStore.fetchingLandedCostAbortController = null;
14608
- }
14609
- // Do not fetch if we are not ready or data is not outdated
14610
- if ((!shouldRefetch && !applyingPromocode) ||
14611
- !stripeAddressReady ||
14612
- !stripeLinkReady ||
14613
- !stripeBillingAddressReady) {
14614
- return;
14615
- }
14616
- // 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)
14617
- if (retries) {
14618
- stripeStore.isFetchingLandedCost = false;
14619
- setTimeout(() => {
14620
- stripeStore.isFetchingLandedCost = true;
14621
- }, 300);
14622
- }
14623
- else {
14624
- stripeStore.isFetchingLandedCost = true;
14625
- }
14626
- if (stripeStore.stripeAddressEventData) {
14627
- stripeStore.stripeAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeAddressEventData);
14628
- }
14629
- if (stripeStore.stripeBillingAddressEventData) {
14630
- stripeStore.stripeBillingAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeBillingAddressEventData);
14631
- }
14632
- if (stripeStore.stripeLinkEventData) {
14633
- stripeStore.stripeLinkUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeLinkEventData);
14634
- }
14635
- stripeStore.taxIdUsedWhenFetchingLC = stripeStore.taxId;
14636
- try {
14637
- // Reset cart items to non-restricted state and restricted item list
14638
- cartStoreResetCartItems();
14639
- // fetch and apply landed cost
14640
- await stripeCalculateLandedCost();
14641
- // This is the cheapest service level since we already sorted them after fetching landed cost
14642
- const cheapestServiceLevel = (_f = cartStore.shippingData) === null || _f === void 0 ? void 0 : _f.find(Boolean);
14643
- // Landed cost that matches with service level
14644
- 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));
14645
- // apply new subtotal and total, this is mainly to show items in the presentment currency
14646
- const subtotals = !!matchLandedCost ? matchLandedCost.subtotals : null;
14647
- if (subtotals) {
14648
- // prefetch landed cost will not update shipping and taxes since we haven't selected shipping method yet
14649
- cartStoreApplySubtotals({
14650
- method: (matchLandedCost === null || matchLandedCost === void 0 ? void 0 : matchLandedCost.landedCost.method) || 'DDP',
14651
- subtotals,
14652
- });
14653
- }
14654
- }
14655
- catch (err) {
14656
- // default to empty array if we failed to fetch landed cost, so we can show the error message
14657
- cartStore.landedCostData = [];
14658
- cartStore.shippingData = [];
14659
- const excludeErrors = [
14660
- 'The landed cost calculation request was aborted to initiate a new one.',
14661
- ];
14662
- if (err instanceof Error &&
14663
- err.message &&
14664
- !excludeErrors.includes(err.message)) {
14665
- if (retries < 1) {
14666
- // retry fetching landed cost one more time
14667
- await stripeStorePrefetchLandedCost(Object.assign(Object.assign({}, params), { retries: (retries || 0) + 1 }));
14668
- return;
14669
- }
14670
- const shipToAddress = (_h = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _h === void 0 ? void 0 : _h.value;
14671
- void sendErrorLog({
14672
- endpoint: `Failed to fetch landed cost (${retries} retries)`,
14673
- errors: [err.message],
14674
- metadata: {
14675
- cartId: window.Zonos.cartId,
14676
- shipToAddress,
14677
- },
14678
- });
14679
- }
14680
- logError(err);
14681
- }
14682
- stripeStore.isFetchingLandedCost = false;
14683
- };
14684
- const stripeStoreApplyPromoCode = async () => {
14685
- var _a, _b;
14686
- await stripeStorePrefetchLandedCost({
14687
- applyingPromocode: true,
14688
- });
14689
- // Go back to shipping step if we are in payment step so user can reselect shipping method
14690
- if (cartStore.step === 'payment') {
14691
- cartStorePreviousStep();
14692
- }
14693
- // This is the cheapest service level since we already sorted them after fetching landed cost
14694
- const cheapestServiceLevel = (_a = cartStore.shippingData) === null || _a === void 0 ? void 0 : _a.find(Boolean);
14695
- // Landed cost that matches with service level
14696
- 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));
14697
- if (!cheapestServiceLevel || !matchLandedCost) {
14698
- return;
14699
- }
14700
- await cartStoreUpdateSelectedShippingOption(cheapestServiceLevel, matchLandedCost.landedCostId);
14701
- };
14702
- const stripeStoreResetPromoCode = () => {
14703
- cartStore.promoCode = '';
14704
- sessionStorage.removeItem('promoCode');
14705
- // reset promocode error state
14706
- cartStore.promoCodeError = false;
14707
- cartStore.promoCodeApplied = false;
14708
- };
14709
- const stripeStoreRemovePromoCode = async () => {
14710
- // Go back to shipping step if we are in payment step so user can reselect shipping method
14711
- if (cartStore.step === 'payment') {
14712
- cartStorePreviousStep();
14713
- }
14714
- stripeStoreResetPromoCode();
14715
- await stripeStoreApplyPromoCode();
14716
- };
14717
- const stripeStoreMessageBasedOnStatus = (status) => {
14718
- let messages = [];
14719
- let isError = true;
14720
- // Inspect the PaymentIntent `status` to indicate the status of the payment
14721
- // to your customer.
14722
- //
14723
- // Some payment methods will [immediately succeed or fail][0] upon
14724
- // confirmation, while others will first enter a `processing` state.
14725
- //
14726
- // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
14727
- switch (status) {
14728
- case 'succeeded': {
14729
- messages = [
14730
- 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.'),
14731
- '',
14732
- 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."),
14733
- ];
14734
- isError = false;
14735
- break;
14736
- }
14737
- case 'requires_capture':
14738
- case 'processing': {
14739
- messages = [
14740
- translate("Payment processing. We'll update you when payment is received."),
14741
- ];
14742
- isError = false;
14743
- break;
14744
- }
14745
- case 'requires_payment_method': {
14746
- messages = [
14747
- translate('Payment failed. Please try another payment method.'),
14748
- ];
14749
- break;
14750
- }
14751
- case 'requires_action': {
14752
- isError = false;
14753
- messages = [
14754
- translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'),
14755
- ];
14756
- }
14757
- default: {
14758
- messages = [translate('Something went wrong.')];
14759
- break;
14760
- }
14761
- }
14762
- return {
14763
- isError,
14764
- messages,
14765
- };
14766
- };
14767
- /**
14768
- * Handle inventory check and returns error message if the callback provided.
14769
- */
14770
- const stripeStoreHandleInventoryCheck = async () => {
14771
- var _a, _b;
14772
- const { onInventoryCheck } = zonosStore.checkoutSettings;
14773
- 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);
14774
- // default inventory check is only available for legacy checkout and store has referenceId in metadata
14775
- if (window.Zonos.isLegacyCheckout &&
14776
- window.Zonos.cartData &&
14777
- hasReferenceId) {
14778
- const { errors, json } = await handleFetch('/api/zonos-elements/legacy/inventory-check', {
14779
- body: {
14780
- cartData: window.Zonos.cartData,
14781
- },
14782
- method: 'POST',
14783
- });
14784
- if (errors.length || !json) {
14785
- logError('Error occurs when handling inventory refund', 'warn', JSON.stringify(errors));
14786
- return null;
14787
- }
14788
- // Proceed if the item is available
14789
- if (!json.available || json.status === 204) {
14790
- return translate("The item you're looking for is currently unavailable in our inventory. Please check back later or contact support for assistance with availability.");
14791
- }
14792
- if (json.available || json.status === 200) {
14793
- stripeStore.shouldInventoryRefund = true;
14794
- return null;
14795
- }
14796
- return null;
14797
- }
14798
- if (typeof onInventoryCheck !== 'function') {
14799
- return null;
14800
- }
14801
- try {
14802
- const message = await onInventoryCheck({ items: cartStore.items });
14803
- return message;
14804
- }
14805
- catch (err) {
14806
- const message = err instanceof Error ? err.message : 'Unknown error';
14807
- void sendErrorLog({
14808
- endpoint: 'onInventoryCheck',
14809
- errors: [`cartId: ${window.Zonos.cartId} - ${message}`],
14810
- metadata: {
14811
- cartId: window.Zonos.cartId,
14812
- href: window.location.href,
14813
- items: cartStore.items,
14814
- },
14815
- });
14816
- throw err;
14817
- }
14818
- };
14819
- /**
14820
- * Handle inventory check and returns error message if the callback provided.
14821
- */
14822
- const stripeStoreHandleInventoryRefund = async () => {
14823
- var _a, _b;
14824
- 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);
14825
- // inventory refund is only available for legacy checkout and store has referenceId in metadata
14826
- if (!window.Zonos.isLegacyCheckout ||
14827
- !window.Zonos.cartData ||
14828
- !hasReferenceId) {
14829
- return;
14830
- }
14831
- // handle inventory check on legacy checkout
14832
- await handleFetch('/api/zonos-elements/legacy/inventory-refund', {
14833
- body: {
14834
- cartData: window.Zonos.cartData,
14835
- },
14836
- method: 'POST',
14837
- });
14838
- };
14839
- const stripeStoreRetrievePayment = async ({ clientSecret: _clientSecret, storybookForceStatus, }) => {
14840
- if (storybookForceStatus) {
14841
- // return status right away if we are in storybook mode
14842
- const { isError, messages } = stripeStoreMessageBasedOnStatus(storybookForceStatus);
14843
- return { error: isError, messages };
14844
- }
14845
- const clientSecret = _clientSecret || stripeStore.clientSecret;
14846
- if (!stripeStore.stripe || !clientSecret) {
14847
- logError('Failed to retrieve payment intent. Stripe is not initialized');
14848
- return { error: true, message: [translate('Something went wrong.')] };
14849
- }
14850
- const { paymentIntent } = await stripeStore.stripe.retrievePaymentIntent(clientSecret);
14851
- const status = paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status;
14852
- const { isError, messages } = stripeStoreMessageBasedOnStatus(status);
14853
- return {
14854
- error: isError,
14855
- messages,
14856
- paymentIntentId: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.id,
14857
- paymentMethod: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.payment_method,
14858
- status,
14859
- };
14860
- };
14861
- const stripeStoreConfirmPayment = async () => {
14862
- var _a, _b;
14863
- const stripePaymentReady = !!((_a = stripeStore.stripePaymentEventData) === null || _a === void 0 ? void 0 : _a.complete);
14864
- const stripeElements = stripeStore.stripeElements;
14865
- const stripe = stripeStore.stripe;
14866
- const stripeClientSecret = stripeStore.clientSecret;
14867
- stripeStore.customErrorMessage = null;
14868
- if (!((_b = cartStore.selectedLandedCost) === null || _b === void 0 ? void 0 : _b.landedCost.id)) {
14869
- throw new Error('Attempted to confirm the payment when no landed cost is found in store');
14870
- }
14871
- // Check if the checkout session is valid before proceeding
14872
- const checkoutSessionStatus = await validateCheckoutSession();
14873
- if (!checkoutSessionStatus.valid) {
14874
- stripeStore.customErrorMessage = checkoutSessionStatus.errorMessage;
14875
- throw new Error(checkoutSessionStatus.errorMessage);
14876
- }
14877
- const checkoutSessionId = cartStore.checkoutSessionId;
14878
- if (stripe &&
14879
- stripeElements &&
14880
- stripePaymentReady &&
14881
- stripeClientSecret &&
14882
- checkoutSessionId) {
14883
- const buildUrl = new URL(window.location.href);
14884
- buildUrl.searchParams.set('payment_intent_client_secret', stripeClientSecret);
14885
- buildUrl.searchParams.set('zonosCheckoutSessionId', checkoutSessionId);
14886
- void trackConversionEvent({
14887
- checkoutSessionId,
14888
- eventName: 'checkout_paymentInfoCompleted',
14889
- });
14890
- const { error, paymentIntent } = await stripe.confirmPayment({
14891
- confirmParams: {
14892
- return_url: buildUrl.toString(),
14893
- },
14894
- elements: stripeElements,
14895
- redirect: 'if_required',
14896
- });
14897
- log('Payment intent confirmed', 'info', { error, paymentIntent });
14898
- if ((paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status) === 'requires_action') {
14899
- throw new Error(translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'));
14900
- }
14901
- if (error) {
14902
- if (error.type === 'card_error' || error.type === 'validation_error') {
14903
- throw new Error(error.message);
14904
- }
14905
- if (error.type === 'invalid_request_error') {
14906
- if (error.code === 'payment_intent_unexpected_state') {
14907
- // PaymentIntent was canceled or expired, or status is `require_capture`.
14908
- // don't throw error here because we will reset the checkout session last step
14909
- return;
14910
- }
14911
- }
14912
- throw new Error('An unexpected error occurred.');
14913
- }
14914
- if (paymentIntent.status === 'requires_payment_method') {
14915
- // Failed to confirm payment, allows user to try another payment method
14916
- throw new Error(translate('Payment failed. Please try another payment method.'));
14917
- }
14918
- }
14919
- };
14920
- const getCheckoutSessionBody = () => {
14921
- var _a;
14922
- const total = cartStore.items.reduce((amount, item) => amount + item.amount * item.quantity, 0);
14923
- const body = {
14924
- adjustmentsAmount: cartStore.adjustments.reduce((prev, adj) => prev + adj.amount, 0),
14925
- cartId: window.Zonos.cartId,
14926
- currency: ((_a = cartStore.items.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode) || '',
14927
- customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
14928
- itemsAmount: total,
14929
- metadata: [
14930
- {
14931
- key: 'language',
14932
- value: localizationStore.selectedLocale,
14933
- },
14934
- {
14935
- key: 'appVersion',
14936
- value: window.Zonos.version,
14937
- },
14938
- {
14939
- key: 'appVersionNpmIntegration',
14940
- value: window.Zonos.isNpm ? '1' : '0',
14941
- },
14942
- {
14943
- key: 'legacyCheckoutFacade',
14944
- value: window.Zonos.isLegacyCheckout ? '1' : '0',
14945
- },
14946
- ],
14947
- presentmentCountryCode: localizationStore.selectedCountryCode,
14948
- skipPaymentIntent: stripeStore.skipPaymentIntent,
14949
- };
14950
- return body;
14951
- };
14952
- const stripeStoreGetPaymentIntent = async () => {
14953
- var _a;
14954
- if (!cartStore.checkoutSessionId) {
14955
- // We want to log the error anytime we fail to create a checkout session
14956
- void sendErrorLog({
14957
- endpoint: 'Error creating payment intent',
14958
- errors: ['No checkout session id found when retrieving payment intent'],
14959
- metadata: {
14960
- allLogs,
14961
- cartId: window.Zonos.cartId,
14962
- },
14963
- });
14964
- cartStoreUpdateToErrorState({
14965
- messages: [
14966
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
14967
- ],
14968
- title: translate('Error creating Checkout'),
14969
- });
14970
- return;
14971
- }
14972
- const { errors, json } = await handleFetch('/api/zonos-elements/create-payment-intent', {
14973
- body: {
14974
- checkoutSessionId: cartStore.checkoutSessionId,
14975
- },
14976
- method: 'POST',
14977
- });
14978
- const clientSecret = (_a = json === null || json === void 0 ? void 0 : json.checkoutSessionPaymentIntentCreate) === null || _a === void 0 ? void 0 : _a.clientSecret;
14979
- if (errors.length || !clientSecret) {
14980
- logError('Error occurs when getting payment intent', JSON.stringify(errors, null, 2));
14981
- // We want to log the error anytime we fail to create a payment intent
14982
- void sendErrorLog({
14983
- endpoint: 'Error creating payment intent',
14984
- errors: errors.map(error => error.message),
14985
- metadata: {
14986
- allLogs,
14987
- cartId: window.Zonos.cartId,
14988
- checkoutSessionId: cartStore.checkoutSessionId,
14989
- clientSecret,
14990
- },
14991
- });
14992
- cartStoreUpdateToErrorState({
14993
- messages: [
14994
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
14995
- ],
14996
- title: translate('Error creating Checkout'),
14997
- });
14998
- return;
14999
- }
15000
- // update cart store checkout session with updated from checkout session payment intent creation call so the checkout session and payment intent are in sync
15001
- cartStoreSetCheckoutSession(json.checkoutSessionPaymentIntentCreate);
15002
- };
15003
- /**
15004
- * Init checkout session
15005
- * @returns {boolean} whether or not the checkout session is successfully created
15006
- */
15007
- const stripeStoreInitCheckoutSession = async () => {
15008
- var _a, _b;
15009
- if (!localizationStore.targetCurrency) {
15010
- logError(`Failed to create checkout session - missing localizationStore.targetCurrency`);
15011
- return false;
15012
- }
15013
- stripeStore.isFetchingSession = true;
15014
- const body = getCheckoutSessionBody();
15015
- log('Checkout session body', 'info', body);
15016
- const { errors, json } = await handleFetch('/api/zonos-elements/create-checkout-session', {
15017
- body,
15018
- method: 'POST',
15019
- });
15020
- stripeStore.isFetchingSession = false;
15021
- if (errors.length || !json) {
15022
- const messages = (_a = errors.find(error => error.message)) === null || _a === void 0 ? void 0 : _a.message;
15023
- // check if the error is related to expired cart and thow error so we can show error message accordingly
15024
- if (messages.some(message => message.message === 'Cart is expired.')) {
15025
- throw new Error('Cart is expired.');
15026
- }
15027
- logError('Error occurred when creating checkout session', JSON.stringify(errors, null, 2));
15028
- return false;
15029
- }
15030
- const result = json.checkoutSessionCreate;
15031
- // update cart store with updated information
15032
- cartStoreSetCheckoutSession(result);
15033
- cartStoreApplySubtotals({
15034
- method: ((_b = result.landedCost) === null || _b === void 0 ? void 0 : _b.method) || 'DDP',
15035
- subtotals: result.subtotals,
15036
- });
15037
- log('Exchange rate updated for cart items (checkout session create)', 'info', cartStore.exchangeRate);
15038
- log('done-init-checkout-session');
15039
- return true;
15040
- };
15041
- const stripeStoreUpdateCheckoutSessionBaseCurrency = async () => {
15042
- const checkoutSessionId = cartStore.checkoutSessionId;
15043
- // Checkout session id should be available at this point
15044
- if (!checkoutSessionId) {
15045
- logError('Failed to update checkout session base currency');
15046
- return false;
15047
- }
15048
- // Only update checkout session currency if setting is enabled
15049
- if (zonosStore.checkoutSettings.allowedSettlementCurrencies === 'LOCAL') {
15050
- log('allowedSettlementCurrencies: "LOCAL". Skip updating checkout session base currency');
15051
- return true;
15052
- }
15053
- const { json } = await handleFetch('/api/zonos-elements/update-checkout-session-base-currency', {
15054
- body: {
15055
- checkoutSessionId,
15056
- currencyCode: stripeStore.checkoutSettlementCurrency,
15057
- },
15058
- method: 'POST',
15059
- });
15060
- const settlementCurrencyCode = json === null || json === void 0 ? void 0 : json.checkoutSessionBaseCurrencyUpdate.subtotals.presentmentCurrencyCode;
15061
- // S
15062
- if (!json ||
15063
- settlementCurrencyCode !== stripeStore.checkoutSettlementCurrency) {
15064
- logError('Failed to update checkout session base currency');
15065
- return false;
15066
- }
15067
- log(`Updated checkout session to settlement currency "${settlementCurrencyCode}".`);
15068
- return true;
15069
- };
15070
- /**
15071
- * Update checkout session. Use for updating amount with landed cost id, or update session when cart items change
15072
- */
15073
- const stripeStoreUpdateCheckoutSession = async ({ adjustmentsAmount, cartId, currency, id, itemsAmount, landedCostId, presentmentCountryCode, }) => {
15074
- // No need to set loading state here because this function will be called under the hood to update
15075
- // landed cost id for the section.
15076
- const { errors, json } = await handleFetch('/api/zonos-elements/update-checkout-session', {
15077
- body: {
15078
- adjustmentsAmount,
15079
- cartId,
15080
- currency,
15081
- customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
15082
- id,
15083
- itemsAmount,
15084
- landedCostId,
15085
- metadata: [
15086
- {
15087
- key: 'language',
15088
- value: localizationStore.selectedLocale,
15089
- },
15090
- {
15091
- key: 'appVersion',
15092
- value: window.Zonos.version,
15093
- },
15094
- {
15095
- key: 'appVersionNpmIntegration',
15096
- value: window.Zonos.isNpm ? '1' : '0',
15097
- },
15098
- {
15099
- key: 'legacyCheckoutFacade',
15100
- value: window.Zonos.isLegacyCheckout ? '1' : '0',
15101
- },
15102
- ],
15103
- presentmentCountryCode,
15104
- skipPaymentIntent: stripeStore.skipPaymentIntent,
15105
- },
15106
- method: 'POST',
15107
- });
15108
- if (errors.length || !json) {
15109
- logError('Error occurs when updating checkout session', JSON.stringify(errors, null, 2));
15110
- return { errors, json };
15111
- }
15112
- return { errors: [], json };
15113
- };
15114
- /**
15115
- * This function builds a translated address object from the current address and the translated address result.
15116
- * 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.
15117
- * 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.
15118
- *
15119
- * @param {Object} params - The parameters for the function.
15120
- * @param {Address} params.currentAddress - The current address information.
15121
- * @param {Address} params.translatedAddressResult - The translated address result.
15122
- *
15123
- * @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.
15124
- */
15125
- const buildTranslatedAddress = ({ currentAddress, translatedAddressResult, }) => {
15126
- const translatedAddress = {};
15127
- if (!translatedAddressResult) {
15128
- return translatedAddress;
15129
- }
15130
- const { city, line1, line2, name, postal_code, state } = translatedAddressResult;
15131
- // If we have translated address, add it to the translated address object
15132
- if (currentAddress.city && city) {
15133
- translatedAddress.city = {
15134
- [currentAddress.city]: city,
15135
- };
15136
- }
15137
- if (currentAddress.line1 && line1) {
15138
- translatedAddress.line1 = {
15139
- [currentAddress.line1]: line1,
15140
- };
15141
- }
15142
- if (currentAddress.line2 && line2) {
15143
- translatedAddress.line2 = {
15144
- [currentAddress.line2]: line2,
15145
- };
15146
- }
15147
- if (currentAddress.postal_code && postal_code) {
15148
- translatedAddress.postal_code = {
15149
- [currentAddress.postal_code]: postal_code,
15150
- };
15151
- }
15152
- if (currentAddress.state && state) {
15153
- translatedAddress.state = {
15154
- [currentAddress.state]: state,
15155
- };
15156
- }
15157
- if (currentAddress.name && name) {
15158
- translatedAddress.name = {
15159
- [currentAddress.name]: name,
15160
- };
15161
- }
15162
- return translatedAddress;
15163
- };
15164
- /**
15165
- * This function translates an address to Latin characters using the Zonos API.
15166
- * 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.
15167
- * If the address is not outdated, it returns without making the API call.
15168
- * 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.
15169
- * 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.
15170
- *
15171
- * @param {Object} params - The parameters for the function.
15172
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
15173
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
15174
- */
15175
- const stripeStoreTranslateAddressToLatin = async ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, }) => {
15176
- var _a, _b, _c, _d;
15177
- const requestBody = buildTranslateRequest({
15178
- addressInvalidCharactersList,
15179
- billingAddressInvalidCharactersList,
15180
- stripeAddressEventData: stripeStore.stripeAddressEventData,
15181
- stripeBillingAddressEventData: stripeStore.stripeBillingAddressEventData,
15182
- stripeShippingSameAsBilling: stripeStore.stripeShippingSameAsBilling,
15183
- });
15184
- if (!requestBody) {
15185
- // reset translated address if we don't have any address to translate
15186
- stripeStore.translatedAddress = {
15187
- address: {},
15188
- billingAddress: {},
15189
- };
15190
- return;
15191
- }
15192
- // only translate address if the address is out of date
15193
- const isAddressOutdated = checkIsAddressOutdatedForValidation();
15194
- if (!isAddressOutdated) {
15195
- return;
15196
- }
15197
- const { errors, json } = await handleFetch('/api/zonos-elements/validate-address', {
15198
- body: requestBody,
15199
- method: 'POST',
15200
- });
15201
- if (errors.length || !json) {
15202
- logError('Error occurs when translating address to latin', JSON.stringify(errors, null, 2));
15203
- // reset translated address if we Failed to translate and let user manually fix it
15204
- stripeStore.translatedAddress = {
15205
- address: {},
15206
- billingAddress: {},
15207
- };
15208
- return;
15209
- }
15210
- // Set current address to the store so we can compare it later to determine if we need to re-translate the address
15211
- stripeStore.stripeAddressUsedWhenValidatingAddress =
15212
- stripeStore.stripeAddressEventData;
15213
- stripeStore.stripeBillingAddressUsedWhenValidatingAddress =
15214
- stripeStore.stripeBillingAddressEventData;
15215
- const address = (_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.value.address;
15216
- const billingAddress = (_b = stripeStore.stripeBillingAddressEventData) === null || _b === void 0 ? void 0 : _b.value.address;
15217
- // Set the translated address to the store so we can populate it to the address element for user to update
15218
- stripeStore.translatedAddress = {
15219
- address: address
15220
- ? buildTranslatedAddress({
15221
- currentAddress: Object.assign(Object.assign({}, address), { name: (_c = stripeStore.stripeAddressEventData) === null || _c === void 0 ? void 0 : _c.value.name }),
15222
- translatedAddressResult: json.address || null,
15223
- })
15224
- : {},
15225
- billingAddress: !stripeStore.stripeShippingSameAsBilling
15226
- ? buildTranslatedAddress({
15227
- currentAddress: Object.assign(Object.assign({}, billingAddress), { name: (_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.value.name }),
15228
- translatedAddressResult: json.billingAddress || null,
15229
- })
15230
- : {},
15231
- };
15232
- };
15233
- onChange$1('clientSecret', clientSecret => {
15234
- // update stripe elements when client secret changes
15235
- if (clientSecret && stripeStore.stripe) {
15236
- sessionStorage.setItem('zonos--client-secret', clientSecret);
15237
- }
15238
- if (!clientSecret) {
15239
- sessionStorage.removeItem('zonos--client-secret');
15240
- }
15241
- });
15242
-
15243
- const { onChange, reset, state: cartStore, } = createStore(() => ({
15244
- adjustmentTotal: 0,
15245
- adjustments: [],
15246
- checkoutSession: null,
15247
- checkoutSessionId: sessionStorage.getItem('zonos--checkout-session-id') || null,
15248
- checkoutSessionTimeoutShow: false,
15249
- checkoutTimeoutInterval: null,
15250
- currency: 'USD',
15251
- customQuotingError: null,
15252
- customerAuthenticationToken: null,
15253
- displayBaseCurrency: false,
15254
- dutiesTaxesFees: null,
15255
- dutiesTaxesFeesEstimate: null,
15256
- error: null,
15257
- exchangeRate: null,
15258
- externalConfirmationPageURL: null,
15259
- inventoryCheckErrorMessage: null,
15260
- isSelectedShippingAboveDeminimis: false,
15261
- isSelectedShippingGuarantee: false,
15262
- isStagingMode: getIsStagingMode(),
15263
- items: [],
15264
- landedCostData: null,
15265
- landedCostMethod: 'DDP',
15266
- partiesData: [],
15267
- promoCode: sessionStorage.getItem('promoCode') || '',
15268
- // When user clicked applied button, save promocode into session storage for later use. So if session has promocode, applied button is clicked
15269
- promoCodeApplied: !!sessionStorage.getItem('promoCode'),
15270
- promoCodeError: false,
15271
- restrictedItems: [],
15272
- selectedLandedCost: null,
15273
- selectedShippingOption: null,
15274
- selectedShippingOptionExpectedDate: '',
15275
- selectedShippingOptionTransitTime: '',
15276
- shipping: 0,
15277
- shippingData: null,
15278
- shouldHideDiscountInput: false,
15279
- step: 'customer-info',
15280
- subtotal: 0,
15281
- tabItems: {
15282
- 'customer-info': {
15283
- index: 1,
15284
- isDone: false,
15285
- label: 'Customer',
15286
- value: 'customer-info',
15287
- },
15288
- shipping: {
15289
- index: 2,
15290
- isDone: false,
15291
- label: 'Shipping',
15292
- value: 'shipping',
15293
- },
15294
- // eslint-disable-next-line sort-keys/sort-keys-fix
15295
- payment: {
15296
- index: 3,
15297
- isDone: false,
15298
- label: 'Payment',
15299
- value: 'payment',
15300
- },
15301
- },
15302
- total: 0,
15303
- }));
15304
- const getTransitUnit = (type) => {
15305
- switch (type) {
15306
- case 'DAYS':
15307
- return translate('days');
15308
- case 'WEEKS':
15309
- return translate('weeks');
15310
- case 'BUSINESS_DAYS':
15311
- default:
15312
- return translate('business days');
15313
- }
15314
- };
15315
- /**
15316
- * Format shipping transit info to be displayed on UI
15317
- * @returns
15318
- * - expectedDate: Thursday, Aug 12
15319
- * - maxTransit: 5
15320
- * - minTransit: 3
15321
- */
15322
- const cartStoreGetShippingTransitInfo = (item) => {
15323
- var _a;
15324
- const transitTime = (_a = item.shippingProfile) === null || _a === void 0 ? void 0 : _a.transitTime;
15325
- // Don't care about falsy 0 values because this is international shipping and 0 days is not feasible
15326
- 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)) {
15327
- return null;
15328
- }
15329
- return {
15330
- maxTransit: transitTime.max,
15331
- minTransit: transitTime.min,
15332
- unit: getTransitUnit(transitTime.type),
15333
- };
15334
- };
15335
- const getMatchItem = ({ item1, item2, }) => {
15336
- if (!item1 || !item2) {
15337
- return false;
15338
- }
15339
- return ((item2.sku && item1.sku && item1.sku === item2.sku) ||
15340
- (item2.description &&
15341
- item1.description &&
15342
- item1.description === item2.description) ||
15343
- (item1.name && item2.name && item1.name === item2.name));
15344
- };
15345
- /**
15346
- * Check and set restricted items in cart
15347
- */
15348
- const cartStoreCheckItemRestrictions = (itemsWorkflow) => {
15349
- log('Checking item restrictions');
15350
- const mappedRestrictedItems = itemsWorkflow
15351
- .map(item => {
15352
- if (!item.restriction) {
15353
- return null;
15354
- }
15355
- const { restriction } = item;
15356
- const matchedItem = cartStore.items.find(x => getMatchItem({ item1: x, item2: item }));
15357
- return Object.assign(Object.assign({ matchedItem }, item), { restriction });
15358
- })
15359
- .filter(Boolean);
15360
- cartStore.restrictedItems = mappedRestrictedItems;
15361
- // remove items that are restricted from cart
15362
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: !!mappedRestrictedItems.find(x => getMatchItem({ item1: x, item2: item })) })));
15363
- return {
15364
- cartItems: cartStore.items,
15365
- restrictedItems: mappedRestrictedItems,
15366
- };
15367
- };
15368
- const cartStoreReset = () => {
15369
- sessionStorage.removeItem('zonos--checkout-session-id');
15370
- // reset cart store
15371
- reset();
15372
- };
15373
- const cartStoreUpdateToErrorState = ({ messages, title, }) => {
15374
- cartStoreReset();
15375
- stripeStoreReset();
15376
- cartStore.step = 'error';
15377
- cartStore.error = {
15378
- messages,
15379
- title,
15380
- };
15381
- };
15382
- const cartStoreApplySubtotals = ({ dutiesTaxesFeesEstimate, method, subtotals, }) => {
15383
- // update exchange rate so we can use it to display cart items
15384
- cartStore.exchangeRate = subtotals.exchangeRate;
15385
- cartStore.adjustmentTotal = subtotals.adjustments;
15386
- cartStore.dutiesTaxesFees =
15387
- method === 'DAP' ? null : subtotals.landedCostTotal;
15388
- cartStore.subtotal = subtotals.items;
15389
- cartStore.total = subtotals.total;
15390
- cartStore.currency = subtotals.presentmentCurrencyCode;
15391
- cartStore.dutiesTaxesFeesEstimate = dutiesTaxesFeesEstimate || null;
15392
- };
15393
- /**
15394
- * Detect if there are any items in cart that are not restricted and have positive amount, exclude negative amount items
15395
- */
15396
- const cartStoreHasOneEligibleItem = () => {
15397
- // filter all items with positive amount
15398
- const checkItems = cartStore.items.filter(item => item.amount > 0);
15399
- // only check restricted status for items with positive amount
15400
- // if there is no item restricted found => all items are restricted
15401
- return !!checkItems.find(item => !item.isRestricted);
15402
- };
15403
- const cartStoreSetCheckoutSession = (checkoutSession) => {
15404
- var _a, _b, _c, _d, _e;
15405
- // update stripe store with updated information
15406
- stripeStore.clientSecret = checkoutSession.clientSecret;
15407
- stripeStore.stripeCustomerSessionClientSecret =
15408
- checkoutSession.customerSessionClientSecret;
15409
- stripeStore.customerProfile = checkoutSession.customerProfile;
15410
- cartStore.checkoutSession = checkoutSession;
15411
- if (!checkoutSession.id) {
15412
- // Log error to track down the issue
15413
- void sendErrorLog({
15414
- endpoint: 'cartStoreSetCheckoutSession',
15415
- errors: ['Missing checkout session id in checkout session'],
15416
- metadata: {
15417
- allLogs,
15418
- checkoutSession,
15419
- },
15420
- });
15421
- }
15422
- // Only update checkout session id if it's not empty
15423
- if (checkoutSession.id) {
15424
- cartStore.checkoutSessionId = checkoutSession.id;
15425
- }
15426
- // Check if there is a redirect URL in the metadata to override
15427
- 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) ||
15428
- (
15429
- // Sometimes externalConfirmationPageURL is not in checkoutSession create/update, check if there is a redirect URL in the cart metadata to override
15430
- (_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) ||
15431
- null;
15432
- if (externalConfirmationPageURL) {
15433
- log(`Found externalConfirmationPageURL: ${externalConfirmationPageURL}`);
15434
- cartStore.externalConfirmationPageURL = externalConfirmationPageURL;
15435
- }
15436
- };
15437
- const cartStoreReCalculateTotal = async ({ adjustmentsAmount, cartId, currency, dutiesTaxesFeesEstimate, itemsAmount, landedCostId, shouldInitSessionOnFailure, }) => {
15438
- var _a;
15439
- if (landedCostId && cartStore.selectedLandedCost) {
15440
- // update cart total right away if we have landed cost id to avoid order total flickering
15441
- const subtotals = cartStore.selectedLandedCost.subtotals;
15442
- cartStoreApplySubtotals({
15443
- dutiesTaxesFeesEstimate,
15444
- method: cartStore.landedCostMethod,
15445
- subtotals,
15446
- });
15447
- log('Exchange rate updated for cart items (landed cost subtotal)', 'info', cartStore.exchangeRate);
15448
- }
15449
- // update checkout session
15450
- if (!cartStore.checkoutSessionId) {
15451
- log('Could not update cart total without checkout session id', 'info');
15452
- return false;
15453
- }
15454
- const { errors, json } = await stripeStoreUpdateCheckoutSession({
15455
- adjustmentsAmount,
15456
- cartId,
15457
- currency,
15458
- id: cartStore.checkoutSessionId,
15459
- itemsAmount,
15460
- landedCostId,
15461
- presentmentCountryCode: localizationStore.selectedCountryCode,
15462
- });
15463
- if (errors.length > 0 || !json) {
15464
- logError('Error occurs when updating checkout session.');
15465
- if (shouldInitSessionOnFailure) {
15466
- log('Initiating checkout session on failure', 'info');
15467
- const success = await stripeStoreInitCheckoutSession();
15468
- log(`stripeStoreInitCheckoutSession: ${success}`);
15469
- if (!success) {
15470
- cartStoreUpdateToErrorState({
15471
- messages: [
15472
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
15473
- ],
15474
- title: translate('Error creating Checkout'),
15475
- });
15476
- return false;
15477
- }
15478
- return true;
15479
- }
15480
- return false;
15481
- }
15482
- if (!landedCostId) {
15483
- // This is when we first open the checkout modal and we just want to get info from the old cart session.
15484
- // use subtotals from checkout session to update cart total
15485
- cartStoreApplySubtotals({
15486
- method: ((_a = json.checkoutSessionUpdate.landedCost) === null || _a === void 0 ? void 0 : _a.method) || 'DDP',
15487
- subtotals: json.checkoutSessionUpdate.subtotals,
15488
- });
15489
- log('Exchange rate updated for cart items (checkout session update)', 'info', cartStore.exchangeRate);
15490
- }
15491
- cartStoreSetCheckoutSession(json.checkoutSessionUpdate);
15492
- return true;
15493
- };
15494
- const cartStoreUpdateSelectedShippingOption = async (selectedShippingOption, landedCostId) => {
15495
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
15496
- cartStore.selectedShippingOption = selectedShippingOption;
15497
- // update shipping transit info
15498
- const transitData = cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);
15499
- if (transitData) {
15500
- const { maxTransit, minTransit, unit } = transitData;
15501
- cartStore.selectedShippingOptionTransitTime = `${minTransit}-${maxTransit} ${unit}`;
15502
- }
15503
- else {
15504
- cartStore.selectedShippingOptionTransitTime = '';
15505
- }
15506
- const selectedLandedCost = (_a = cartStore.landedCostData) === null || _a === void 0 ? void 0 : _a.find(x => x.landedCostId === landedCostId);
15507
- // save selected landed cost for later use
15508
- cartStore.selectedLandedCost = selectedLandedCost || null;
15509
- if (!selectedLandedCost) {
15510
- // do nothing if we can't find landed cost for selected shipping option
15511
- return false;
15512
- }
15513
- // If the quote is DAP, then convert manually.
15514
- const landedCostAmount = ((_b = selectedLandedCost.landedCost.amountSubtotals) === null || _b === void 0 ? void 0 : _b.landedCostTotal) || 0;
15515
- // Convert using checkout presentment exchange rate
15516
- const exchangeRate = selectedLandedCost.subtotals.exchangeRate.rate;
15517
- const dutiesTaxesFeesEstimate = landedCostAmount * exchangeRate;
15518
- if (dutiesTaxesFeesEstimate) {
15519
- log(`DAP quote, using estimate: ${dutiesTaxesFeesEstimate}`, 'info');
15520
- }
15521
- cartStore.landedCostMethod = selectedLandedCost.landedCost.method || 'DDP';
15522
- // update shipping value and dutiesTaxFees on selectedShippingOption change
15523
- cartStore.shipping = selectedLandedCost.subtotals.shipping;
15524
- // update deminimis status
15525
- const isGuarantee = ((_c = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _c === void 0 ? void 0 : _c.landedCostGuaranteeCode) === 'ZONOS';
15526
- // one item in deminimis with type of duty and tax has threshold value is "ABOVE"
15527
- 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'));
15528
- cartStore.isSelectedShippingAboveDeminimis = isAboveDeminimis;
15529
- cartStore.isSelectedShippingGuarantee = isGuarantee;
15530
- // update session with selected landed cost
15531
- const updateCalculateStatus = await cartStoreReCalculateTotal({
15532
- adjustmentsAmount: cartStore.adjustmentTotal,
15533
- cartId: window.Zonos.cartId,
15534
- dutiesTaxesFeesEstimate: dutiesTaxesFeesEstimate,
15535
- landedCostId: (_f = selectedLandedCost.landedCost) === null || _f === void 0 ? void 0 : _f.id,
15536
- });
15537
- // update conditionally render pay in USD button
15538
- const firstItem = (_g = cartStore.items.find(Boolean)) === null || _g === void 0 ? void 0 : _g.currencyCode;
15539
- // Stripe address event data should be available at this point
15540
- const shipToCountry = ((_h = stripeStore.stripeAddressEventData) === null || _h === void 0 ? void 0 : _h.value.address.country) || 'US';
15541
- // 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
15542
- stripeStore.shouldRenderPayInUsdButton =
15543
- firstItem === 'USD' &&
15544
- zonosStore.checkoutSettings.allowedSettlementCurrencies ===
15545
- 'LOCAL_AND_USD' &&
15546
- ((_j = cartStore.checkoutSession) === null || _j === void 0 ? void 0 : _j.subtotals.presentmentCurrencyCode) !== 'USD' &&
15547
- !!((_l = (_k = zonosStore.genericSettings) === null || _k === void 0 ? void 0 : _k.usdSettlementCountryEnabled) === null || _l === void 0 ? void 0 : _l.includes(shipToCountry));
15548
- return updateCalculateStatus;
15549
- };
15550
- onChange('checkoutSessionId', () => {
15551
- log('checkoutSessionId changed', 'info', cartStore.checkoutSessionId);
15552
- if (!cartStore.checkoutSessionId) {
15553
- sessionStorage.removeItem('zonos--checkout-session-id');
15554
- return;
15555
- }
15556
- sessionStorage.setItem('zonos--checkout-session-id', cartStore.checkoutSessionId);
15557
- });
15558
- const cartStoreStartCheckoutInterval = ({ isPreview, sessionTimeout, }) => {
15559
- // do nothing if in preview mode
15560
- if (isPreview) {
15561
- return;
15562
- }
15563
- const timeoutQuery = new URLSearchParams(window.location.search).get('zonosCheckoutTimeout');
15564
- const timeout =
15565
- // timeout query is mainly for testing purpose
15566
- timeoutQuery && !isNaN(parseInt(timeoutQuery, 10))
15567
- ? parseInt(timeoutQuery, 10)
15568
- : sessionTimeout;
15569
- log(`==START CHECKOUT TIMEOUT - ${timeout}==`);
15570
- cartStore.checkoutTimeoutInterval = setTimeout(() => {
15571
- cartStore.checkoutSessionTimeoutShow = true;
15572
- }, timeout);
15573
- };
15574
- const cartStoreClearCheckoutInterval = () => {
15575
- if (cartStore.checkoutTimeoutInterval) {
15576
- clearTimeout(cartStore.checkoutTimeoutInterval);
15577
- cartStore.checkoutTimeoutInterval = null;
15578
- }
15579
- };
15580
- const getCartItemToUse = (items) => items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
15581
- const cartStoreResetCartItems = () => {
15582
- // mark all items as not restricted
15583
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
15584
- cartStore.restrictedItems = [];
15585
- };
15586
- const cartStoreUpdateItems = async ({ adjustments, cartItems, }) => {
15587
- var _a;
15588
- // Update adjustments and items
15589
- cartStore.adjustments = adjustments;
15590
- cartStore.items = getCartItemToUse(cartItems);
15591
- const currency = (_a = cartItems.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode;
15592
- const total = cartItems.reduce((amt, item) => {
15593
- return amt + item.amount * item.quantity;
15594
- }, 0);
15595
- const adjustmentTotal = adjustments.reduce((amt, adjustment) => amt + adjustment.amount, 0);
15596
- if (!currency || !total) {
15597
- // do nothing if we can't get currency or total
15598
- return;
15599
- }
15600
- cartStore.currency = currency;
15601
- // set loading state here because this is the first load checkout session when we already have checkout session id stored
15602
- stripeStore.isFetchingSession = true;
15603
- await cartStoreReCalculateTotal({
15604
- adjustmentsAmount: adjustmentTotal,
15605
- cartId: window.Zonos.cartId,
15606
- currency: currency,
15607
- dutiesTaxesFeesEstimate: 0,
15608
- itemsAmount: total,
15609
- // attempt to init session on failure to update checkout session
15610
- shouldInitSessionOnFailure: true,
15611
- });
15612
- stripeStore.isFetchingSession = false;
15613
- };
15614
- const cartStoreResetSelectedShippingOption = () => {
15615
- cartStore.selectedShippingOption = null;
15616
- cartStore.isSelectedShippingAboveDeminimis = false;
15617
- cartStore.isSelectedShippingGuarantee = false;
15618
- cartStore.selectedShippingOptionTransitTime = '';
15619
- cartStore.dutiesTaxesFees = 0;
15620
- cartStore.dutiesTaxesFeesEstimate = 0;
15621
- cartStore.shipping = 0;
15622
- // reset total to subtotal
15623
- cartStore.total = cartStore.subtotal;
15624
- };
15625
- const cartStorePreviousStep = () => {
15626
- if (cartStore.step === 'shipping') {
15627
- cartStore.step = 'customer-info';
15628
- // set shipping step to done
15629
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
15630
- }
15631
- else if (cartStore.step === 'payment') {
15632
- cartStore.step = 'shipping';
15633
- // set shipping step to done
15634
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
15635
- }
15636
- else if (cartStore.step === 'finish') {
15637
- cartStore.step = 'payment';
15638
- // set shipping step to done
15639
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { payment: Object.assign(Object.assign({}, cartStore.tabItems.payment), { isDone: false }) });
15640
- }
15641
- };
15642
- const cartStoreNextStep = () => {
15643
- if (cartStore.step === 'customer-info') {
15644
- cartStore.step = 'shipping';
15645
- // set customer-info step to done
15646
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems['customer-info']), { isDone: true }) });
15647
- }
15648
- else if (cartStore.step === 'shipping') {
15649
- cartStore.step = 'payment';
15650
- // set shipping step to done
15651
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: true }) });
15652
- }
15653
- else if (cartStore.step === 'payment') {
15654
- cartStore.step = 'finish';
15655
- }
15656
- };
15657
- const cartStoreResetTabItems = () => {
15658
- cartStore.step = 'customer-info';
15659
- 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 }) });
15660
- cartStoreResetSelectedShippingOption();
15661
- };
15662
-
15663
- export { stripeStoreConfirmPayment as A, stripeStoreHandleInventoryRefund as B, stripeStoreReset as C, localizationStoreOnUpdate as D, currencyFormat as E, validateCheckoutSession as F, isValidSelector as G, initLocalizationStore as H, setZCountryUrlParam as I, currencyDisplay as J, currencyConvertAndFormat as K, currencyConvert as L, cartStoreHasOneEligibleItem as M, stripeStoreApplyPromoCode as N, stripeStoreRemovePromoCode as O, stripeStoreResetPromoCode as P, stripeStoreMessageBasedOnStatus as Q, stripeStoreTranslateAddressToLatin as R, cartStoreUpdateSelectedShippingOption as S, cartStoreGetShippingTransitInfo as T, sortServiceLevelOptionsByAmount as U, getFallbackDefaultCountryCode as V, localizationStoreUpdateSelectedLocale as W, localizationStoreUpdateSelectedCountryCode as a, stripeStoreCleanupDomesticShippingSession as b, stripeStoreSaveDomesticShippingSession as c, stripeStoreRetrievePayment as d, cartStore as e, stripeStore as f, cartStoreUpdateItems as g, cartStoreReset as h, initStripeElements as i, cartStoreResetTabItems as j, cartStoreClearCheckoutInterval as k, localizationStore as l, stripeStoreInitCheckoutSession as m, stripeStoreGetPaymentIntent as n, cartStoreStartCheckoutInterval as o, getCheckoutSessionBody as p, cartStoreUpdateToErrorState as q, translate as r, stripeStoreGetDomesticShippingSession as s, trackConversionEvent as t, getZCountryUrlParam as u, cartStoreSetCheckoutSession as v, stripeStorePrefetchLandedCost as w, cartStoreNextStep as x, stripeStoreUpdateCheckoutSessionBaseCurrency as y, stripeStoreHandleInventoryCheck as z };
13826
+ export { VARIANT_TEST_KEY_EXPIRATION as V, localizationStoreUpdateSelectedCountryCode as a, storageStoreSetEnabledVariantTestKeys as b, localizationStoreOnChange as c, currencyFormat as d, initLocalizationStore as e, filterValidTests as f, getZCountryUrlParam as g, setZCountryUrlParam as h, isValidSelector as i, currencyDisplay as j, currencyConvertAndFormat as k, localizationStore as l, currencyConvert as m, storageStoreOnChange as n, getFallbackDefaultCountryCode as o, localizationStoreUpdateSelectedLocale as p, storageStore as s, translate as t };