@zonos/elements 1.3.44 → 1.3.46

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 (137) hide show
  1. package/dist/cjs/{cart-89b4f62d.js → cart-7a79bccc.js} +152 -49
  2. package/dist/cjs/{sendErrorLog-a966a8c1.js → createCustomEvent-2fe80338.js} +2 -22
  3. package/dist/cjs/index.cjs.js +12 -8
  4. package/dist/cjs/loader.cjs.js +1 -1
  5. package/dist/cjs/{paypal-1a1882c4.js → paypal-eb07e9f5.js} +3 -3
  6. package/dist/cjs/zonos-address_8.cjs.entry.js +2 -2
  7. package/dist/cjs/zonos-cart-items_12.cjs.entry.js +29 -21
  8. package/dist/cjs/zonos-checkout.cjs.entry.js +11 -11
  9. package/dist/cjs/zonos-controller.cjs.entry.js +6 -6
  10. package/dist/cjs/zonos-country-flag.cjs.entry.js +1 -1
  11. package/dist/cjs/zonos-country-select_4.cjs.entry.js +1 -1
  12. package/dist/cjs/zonos-elements.cjs.js +1 -1
  13. package/dist/cjs/zonos-hello-dialog.cjs.entry.js +1 -1
  14. package/dist/cjs/zonos-hello.cjs.entry.js +2 -3
  15. package/dist/cjs/zonos-language-select_2.cjs.entry.js +1 -1
  16. package/dist/cjs/zonos-notification_3.cjs.entry.js +2 -2
  17. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.css +7 -0
  18. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.js +16 -9
  19. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout.css +4 -0
  20. package/dist/collection/components/common/zonos-dialog/zonos-dialog.css +1 -0
  21. package/dist/collection/components/main/zonos-controller.js +4 -3
  22. package/dist/collection/components/store/checkout/stripe.js +4 -7
  23. package/dist/collection/components/store/hello/localization.js +1 -1
  24. package/dist/collection/components/utils/api/calculateLandedCost.js +1 -2
  25. package/dist/collection/components/utils/api/checkItemRestrictions.js +1 -2
  26. package/dist/collection/components/utils/api/getCountries.js +1 -1
  27. package/dist/collection/components/utils/api/getCountryLandedCost.js +1 -1
  28. package/dist/collection/components/utils/api/getExchangeRate.js +6 -2
  29. package/dist/collection/components/utils/api/getInclusivePricing.js +1 -2
  30. package/dist/collection/components/utils/api/getLocaleMessages.js +7 -2
  31. package/dist/collection/components/utils/api/getLocalization.js +3 -6
  32. package/dist/collection/components/utils/api/getShippingZones.js +1 -2
  33. package/dist/collection/components/utils/api/getZonosSettings.js +1 -2
  34. package/dist/collection/components/utils/api/paypalCaptureOrder.js +1 -1
  35. package/dist/collection/components/utils/api/paypalCreateOrder.js +1 -1
  36. package/dist/collection/components/utils/api/trackConversionEvent.js +1 -2
  37. package/dist/collection/components/utils/api/triggerBuildLandedCost.js +3 -2
  38. package/dist/collection/components/utils/getNextFallbackApi.js +18 -0
  39. package/dist/collection/components/utils/handleFetch.js +75 -21
  40. package/dist/collection/components/utils/logging/sendErrorLog.js +19 -5
  41. package/dist/collection/components/utils/logging/sendLoadScriptLog.js +1 -1
  42. package/dist/collection/environment.js +13 -78
  43. package/dist/collection/scripts/_getZonosQaUrl.js +6 -2
  44. package/dist/collection/utils/formattedCloudflareApiUrl.js +43 -0
  45. package/dist/collection/utils/formattedUrl.js +80 -0
  46. package/dist/collection/utils/generateCloudflareDeployUrl.js +21 -0
  47. package/dist/collection/utils/getGraphQlShortId.js +1 -0
  48. package/dist/esm/{cart-9f40efd7.js → cart-2198741e.js} +153 -51
  49. package/dist/esm/{sendErrorLog-aea606c0.js → createCustomEvent-451d7879.js} +3 -22
  50. package/dist/esm/index.js +12 -8
  51. package/dist/esm/loader.js +1 -1
  52. package/dist/esm/{paypal-f4bb6ce7.js → paypal-2890968d.js} +3 -3
  53. package/dist/esm/zonos-address_8.entry.js +2 -2
  54. package/dist/esm/zonos-cart-items_12.entry.js +21 -13
  55. package/dist/esm/zonos-checkout.entry.js +4 -4
  56. package/dist/esm/zonos-controller.entry.js +6 -6
  57. package/dist/esm/zonos-country-flag.entry.js +1 -1
  58. package/dist/esm/zonos-country-select_4.entry.js +1 -1
  59. package/dist/esm/zonos-elements.js +1 -1
  60. package/dist/esm/zonos-hello-dialog.entry.js +1 -1
  61. package/dist/esm/zonos-hello.entry.js +2 -3
  62. package/dist/esm/zonos-language-select_2.entry.js +1 -1
  63. package/dist/esm/zonos-notification_3.entry.js +2 -2
  64. package/dist/esm-es5/{cart-9f40efd7.js → cart-2198741e.js} +1 -1
  65. package/dist/esm-es5/createCustomEvent-451d7879.js +1 -0
  66. package/dist/esm-es5/index.js +1 -1
  67. package/dist/esm-es5/loader.js +1 -1
  68. package/dist/esm-es5/paypal-2890968d.js +17 -0
  69. package/dist/esm-es5/zonos-address_8.entry.js +1 -1
  70. package/dist/esm-es5/zonos-cart-items_12.entry.js +1 -1
  71. package/dist/esm-es5/zonos-checkout.entry.js +1 -1
  72. package/dist/esm-es5/zonos-controller.entry.js +1 -1
  73. package/dist/esm-es5/zonos-country-flag.entry.js +1 -1
  74. package/dist/esm-es5/zonos-country-select_4.entry.js +1 -1
  75. package/dist/esm-es5/zonos-elements.js +1 -1
  76. package/dist/esm-es5/zonos-hello-dialog.entry.js +1 -1
  77. package/dist/esm-es5/zonos-hello.entry.js +1 -1
  78. package/dist/esm-es5/zonos-language-select_2.entry.js +1 -1
  79. package/dist/esm-es5/zonos-notification_3.entry.js +1 -1
  80. package/dist/scripts/index.d.ts +3 -0
  81. package/dist/scripts/index.js +1 -1
  82. package/dist/scripts/loadZonos.js +1 -1
  83. package/dist/scripts/zonos.js +1 -1
  84. package/dist/types/components/utils/getNextFallbackApi.d.ts +10 -0
  85. package/dist/types/components/utils/handleFetch.d.ts +10 -1
  86. package/dist/types/environment.d.ts +4 -9
  87. package/dist/types/scripts/_getNextFallbackUrl.d.ts +1 -1
  88. package/dist/types/utils/formattedCloudflareApiUrl.d.ts +20 -0
  89. package/dist/types/utils/formattedUrl.d.ts +9 -0
  90. package/dist/types/utils/generateCloudflareDeployUrl.d.ts +10 -0
  91. package/dist/types/utils/getGraphQlShortId.d.ts +1 -0
  92. package/dist/zonos-elements/assets/RemoveIcon.svg +1 -1
  93. package/dist/zonos-elements/index.esm.js +1 -1
  94. package/dist/zonos-elements/p-18f46c3f.entry.js +1 -0
  95. package/dist/zonos-elements/p-2b25ac5e.system.js +1 -0
  96. package/dist/zonos-elements/p-2f24a1f7.system.js +17 -0
  97. package/dist/zonos-elements/p-3b116246.system.entry.js +1 -0
  98. package/dist/zonos-elements/{p-578f42c1.entry.js → p-40e8f3bd.entry.js} +1 -1
  99. package/dist/zonos-elements/p-467cdce8.system.entry.js +1 -0
  100. package/dist/zonos-elements/p-52c2fb9d.entry.js +1 -0
  101. package/dist/zonos-elements/{p-5845029a.system.entry.js → p-65efc406.system.entry.js} +1 -1
  102. package/dist/zonos-elements/{p-8618e185.entry.js → p-6b868590.entry.js} +1 -1
  103. package/dist/zonos-elements/{p-21d07dda.entry.js → p-791d240f.entry.js} +1 -1
  104. package/dist/zonos-elements/{p-acf9a97e.system.entry.js → p-7b9ed9ed.system.entry.js} +1 -1
  105. package/dist/zonos-elements/{p-7b8099ed.js → p-84e5636c.js} +1 -1
  106. package/dist/zonos-elements/{p-8630168f.system.entry.js → p-85b297d3.system.entry.js} +1 -1
  107. package/dist/zonos-elements/p-8b2486b7.system.entry.js +1 -0
  108. package/dist/zonos-elements/{p-aee29731.system.entry.js → p-a28492ca.system.entry.js} +1 -1
  109. package/dist/zonos-elements/{p-43d3cafd.system.js → p-ac01a4fe.system.js} +1 -1
  110. package/dist/zonos-elements/{p-4204ccf9.system.entry.js → p-b066612a.system.entry.js} +1 -1
  111. package/dist/zonos-elements/p-b06704a9.js +17 -0
  112. package/dist/zonos-elements/{p-37c9fdd2.system.entry.js → p-bfe85ef2.system.entry.js} +1 -1
  113. package/dist/zonos-elements/p-c3bb224b.entry.js +1 -0
  114. package/dist/zonos-elements/p-c78dd680.system.js +1 -1
  115. package/dist/zonos-elements/{p-09988f34.entry.js → p-cfbcfd4b.entry.js} +1 -1
  116. package/dist/zonos-elements/{p-c7952400.entry.js → p-e43bbfe1.entry.js} +1 -1
  117. package/dist/zonos-elements/{p-567b457b.entry.js → p-e69e429d.entry.js} +1 -1
  118. package/dist/zonos-elements/p-f12c159e.js +1 -0
  119. package/dist/zonos-elements/p-f9aa9bd8.system.js +1 -0
  120. package/dist/zonos-elements/{p-8bf1af28.entry.js → p-fb6c529a.entry.js} +1 -1
  121. package/dist/zonos-elements/p-ff10609a.system.entry.js +1 -0
  122. package/dist/zonos-elements/zonos-elements.esm.js +1 -1
  123. package/package.json +1 -1
  124. package/dist/esm-es5/paypal-f4bb6ce7.js +0 -17
  125. package/dist/esm-es5/sendErrorLog-aea606c0.js +0 -1
  126. package/dist/zonos-elements/p-0641784b.system.js +0 -1
  127. package/dist/zonos-elements/p-0bfe455c.system.entry.js +0 -1
  128. package/dist/zonos-elements/p-29f4cce5.system.js +0 -17
  129. package/dist/zonos-elements/p-2d01b8e6.system.entry.js +0 -1
  130. package/dist/zonos-elements/p-2e12d178.system.entry.js +0 -1
  131. package/dist/zonos-elements/p-3490d40f.js +0 -17
  132. package/dist/zonos-elements/p-6f759c76.system.js +0 -1
  133. package/dist/zonos-elements/p-744180f1.entry.js +0 -1
  134. package/dist/zonos-elements/p-76291114.entry.js +0 -1
  135. package/dist/zonos-elements/p-9aef3a35.entry.js +0 -1
  136. package/dist/zonos-elements/p-c10099bd.system.entry.js +0 -1
  137. package/dist/zonos-elements/p-d99e58f2.js +0 -1
@@ -0,0 +1,80 @@
1
+ // rollup and ts somehow can't compile this with absolute path
2
+ // eslint-disable-next-line no-relative-import-paths/no-relative-import-paths
3
+ import { generateVercelDeployUrl } from "./generateVercelDeployUrl";
4
+ export const formattedUrl = ({ branchName, inCI: _inCI, inVercel: _inVercel, isVercelPreview: _isVercelPreview, packageVersion: _packageVersion, type = 'full', url, }) => {
5
+ if (!url) {
6
+ // return origin value so t3 can throw error when it's empty
7
+ return url;
8
+ }
9
+ const trimmedUrl = (_url) => _url === null || _url === void 0 ? void 0 : _url.replace('https://', '');
10
+ const domainOnlyUrl = trimmedUrl(url);
11
+ if (!_inCI && !_inVercel) {
12
+ // local host environment, no need to format url
13
+ return `https://${domainOnlyUrl}`;
14
+ }
15
+ const isProdBranch = branchName && ['main'].includes(branchName);
16
+ const isServerless =
17
+ // url: route.js.zonos.com
18
+ domainOnlyUrl.includes('route.js') ||
19
+ // url: zonos-elements-serverless-git-something
20
+ domainOnlyUrl.includes('serverless-git');
21
+ const isTest =
22
+ // url: test.js.zonos.com
23
+ domainOnlyUrl.includes('test.') ||
24
+ // url: zonos-elements-test-git-something
25
+ domainOnlyUrl.includes('test-git') ||
26
+ // url: something.preview.js.zonos.com (this is only applicable on preview deployment of `zonos-elements` and `zonos-elements-test`)
27
+ domainOnlyUrl.includes('preview.js.zonos.com');
28
+ if (isTest && isProdBranch) {
29
+ return `https://${domainOnlyUrl}`;
30
+ }
31
+ // always use vercel url if in vercel env, non-production branch (not qa or main branch) or the domain using is a test url
32
+ if ((_isVercelPreview && !isProdBranch) ||
33
+ isTest ||
34
+ (_inVercel && type === 'vercel-git')) {
35
+ // use vercel branch_url instead of the production url
36
+ if (!branchName) {
37
+ throw new Error('Fail to get vercel commit ref or branch name');
38
+ }
39
+ // get project name based on the `${url}`
40
+ const isStorybook =
41
+ // url: storybook.js.zonos.com
42
+ domainOnlyUrl.includes('storybook.js') ||
43
+ // url: zonos-elements-storybook-git-something
44
+ domainOnlyUrl.includes('storybook-git');
45
+ const projectName = isStorybook
46
+ ? 'zonos-elements-storybook'
47
+ : isServerless
48
+ ? 'zonos-elements-serverless'
49
+ : 'zonos-elements';
50
+ // add -test suffix for test environment
51
+ const fullProjectName = isTest ? `${projectName}-test` : projectName;
52
+ // generate generated deploy url based on the branch name
53
+ const vercelGitBranchSuffix = generateVercelDeployUrl({
54
+ branchName,
55
+ projectName: fullProjectName,
56
+ });
57
+ return `https://${vercelGitBranchSuffix}`;
58
+ }
59
+ // only require package version in production and in CI, so that we still can use dev url (no version prefix).
60
+ if (!_packageVersion && (isProdBranch || _inCI)) {
61
+ throw new Error('package version is required');
62
+ }
63
+ const version = type === 'major' ? `${_packageVersion === null || _packageVersion === void 0 ? void 0 : _packageVersion.split('.')[0]}` : _packageVersion;
64
+ const isVersionedUrl = domainOnlyUrl === null || domainOnlyUrl === void 0 ? void 0 : domainOnlyUrl.startsWith('v');
65
+ const shouldAddVersion = (isProdBranch || _inCI) && !isVersionedUrl;
66
+ /**
67
+ * Trimming the `qa` from the domain url only when we add version prefix
68
+ * @reason We've now introduced alpha versioning for the QA branch deployment.
69
+ * However, we've generated the domain as `v1.2.4-alpha.1.js.zonos.com`, while the
70
+ * current CDN URL env uses `qa.js.zonos.com` on qa branch. This discrepancy causes
71
+ * this function to return an invalid alpha domain (v1.2.4-alpha.1.qa.js.zonos.com).
72
+ */
73
+ const trimmedQaUrl = shouldAddVersion
74
+ ? domainOnlyUrl === null || domainOnlyUrl === void 0 ? void 0 : domainOnlyUrl.replace('qa.js.zonos.com', 'js.zonos.com')
75
+ : domainOnlyUrl;
76
+ // only set version for the url once
77
+ return shouldAddVersion
78
+ ? `https://v${version}.${trimmedQaUrl}`
79
+ : `https://${trimmedQaUrl}`;
80
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Generate a Cloudflare deploy URL based on the branch name and project name
3
+ * @note not including https://
4
+ * @return {url} string
5
+ * @urlExample build-cloudflare-2.zonos-elements.page.dev
6
+ */
7
+ export const generateCloudflareDeployUrl = ({ branchName, projectName, }) => {
8
+ const normalizedProjectName = projectName.toLowerCase().replace(/\s+/g, '-');
9
+ // remove dots and replace non-alphanumeric characters with dashes
10
+ const normalizedBranchName = branchName
11
+ .toLowerCase()
12
+ .replace(/\./g, '-') // Replace periods with hyphens
13
+ .replace(/\//g, '-') // Replace slashes with hyphens
14
+ .replace(/[^a-z0-9-_]/g, '') // Remove any characters that aren't alphanumeric, hyphens, or underscores
15
+ .replace(/-+/g, '-') // Collapse multiple hyphens into a single hyphen
16
+ .replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
17
+ if (!normalizedProjectName || !normalizedBranchName) {
18
+ return null;
19
+ }
20
+ return `${normalizedBranchName}.${normalizedProjectName}.pages.dev`;
21
+ };
@@ -0,0 +1 @@
1
+ export const getGraphQlShortId = (id) => { var _a; return ((_a = id === null || id === void 0 ? void 0 : id.match(/_(.*?)-/)) === null || _a === void 0 ? void 0 : _a[1]) || null; };
@@ -1,5 +1,5 @@
1
1
  import { c as createStore, z as zonosStore } from './zonosStore-8fc9ceb2.js';
2
- import { a as logError, l as log } from './logError-c456c092.js';
2
+ import { l as log, a as logError } from './logError-c456c092.js';
3
3
  import { i as isDarkColor } from './isDarkColor-3119e351.js';
4
4
  import { g as getBorderRadius } from './getBorderRadius-3ba98361.js';
5
5
 
@@ -7171,6 +7171,57 @@ const translate = (...[key, replacement]) => {
7171
7171
  return ((_b = translationStore.translatedChunks[key]) === null || _b === void 0 ? void 0 : _b.value) || key;
7172
7172
  };
7173
7173
 
7174
+ const fallbackApiType = ['vercel', 'cloudflare'];
7175
+ const MAIN_BASE_API_TYPE = fallbackApiType[0];
7176
+ const fallbackApiList = {
7177
+ cloudflare: "https://route.elements.zonos.com",
7178
+ vercel: "https://v1.route.js.zonos.com",
7179
+ };
7180
+ const MAIN_BASE_API = fallbackApiList[MAIN_BASE_API_TYPE];
7181
+ /**
7182
+ * Next available fallback api type
7183
+ */
7184
+ const getNextFallbackApiType = (currentApiType = MAIN_BASE_API_TYPE) => {
7185
+ const currentIndex = fallbackApiType.indexOf(currentApiType);
7186
+ const nextFallbackApiType = fallbackApiType[currentIndex + 1];
7187
+ if (!nextFallbackApiType) {
7188
+ return null;
7189
+ }
7190
+ return nextFallbackApiType;
7191
+ };
7192
+
7193
+ const sendErrorLog = async ({ endpoint, errors, metadata }) => {
7194
+ const userAgentData = 'userAgentData' in window.navigator
7195
+ ? // userAgentData is not yet supported in all browsers
7196
+ window.navigator.userAgentData
7197
+ : null;
7198
+ const errorObject = {
7199
+ endpoint,
7200
+ errors,
7201
+ metadata: Object.assign({ href: window.location.href, userAgent: userAgentData && userAgentData.brands.length > 0
7202
+ ? userAgentData
7203
+ : window.navigator.userAgent }, metadata),
7204
+ };
7205
+ try {
7206
+ // use native fetch because in handleFetch also calls sendErrorLog and it will possibly cause circular dependencies issue
7207
+ void fetch(`${MAIN_BASE_API}/api/zonos-elements/log-error`, {
7208
+ body: JSON.stringify(errorObject),
7209
+ method: 'POST',
7210
+ });
7211
+ }
7212
+ catch (_err) {
7213
+ const nextFallbackApi = getNextFallbackApiType();
7214
+ if (!nextFallbackApi) {
7215
+ return;
7216
+ }
7217
+ // request to the fallback API if the first one fails
7218
+ void fetch(`${fallbackApiList[nextFallbackApi]}/api/zonos-elements/log-error`, {
7219
+ body: JSON.stringify(errorObject),
7220
+ method: 'POST',
7221
+ });
7222
+ }
7223
+ };
7224
+
7174
7225
  var __rest = (undefined && undefined.__rest) || function (s, e) {
7175
7226
  var t = {};
7176
7227
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -7198,14 +7249,36 @@ const getResponseBody = async ({ response, shouldLog = true, shouldThrow = false
7198
7249
  return null;
7199
7250
  }
7200
7251
  };
7201
- const handleRequest = async (url, options) => {
7252
+ const encodeString = (text) => {
7253
+ try {
7254
+ // encode the string, remove the "=" at the end of the encoded string
7255
+ const encodedString = btoa(text).replace(/=/g, '');
7256
+ return encodedString;
7257
+ }
7258
+ catch (error) {
7259
+ // return the reverse string if the encoding failed
7260
+ return text
7261
+ .replace(/[^A-Za-z0-9]/g, '')
7262
+ .split('')
7263
+ .reverse()
7264
+ .join('');
7265
+ }
7266
+ };
7267
+ const handleRequest = async ({ basePathType, options, path, }) => {
7202
7268
  let response;
7269
+ // fallback to the main base API if the passed in base path is not available
7270
+ const baseUrl = fallbackApiList[basePathType] || MAIN_BASE_API_TYPE;
7271
+ const url = baseUrl + path;
7272
+ // adding random encoded token to the url so that the request will be cached differently for each store
7273
+ const modifiedUrl = new URL(url);
7274
+ modifiedUrl.searchParams.set('zToken', encodeString(window.location.hostname));
7203
7275
  try {
7204
- response = await fetch(url, options);
7276
+ response = await fetch(modifiedUrl.toString(), options);
7205
7277
  }
7206
7278
  catch (e) {
7207
7279
  if (e instanceof Error) {
7208
7280
  return {
7281
+ baseUrl,
7209
7282
  errors: [{ message: e.message, type: 'unknown' }],
7210
7283
  json: null,
7211
7284
  response: null,
@@ -7214,6 +7287,7 @@ const handleRequest = async (url, options) => {
7214
7287
  }
7215
7288
  const message = 'Fail to fetch';
7216
7289
  return {
7290
+ baseUrl,
7217
7291
  errors: [{ message, type: 'unknown' }],
7218
7292
  json: null,
7219
7293
  response: null,
@@ -7229,6 +7303,7 @@ const handleRequest = async (url, options) => {
7229
7303
  if (response.ok) {
7230
7304
  const data = await getResponseBody({ response });
7231
7305
  return {
7306
+ baseUrl,
7232
7307
  errors: [],
7233
7308
  json: data,
7234
7309
  response,
@@ -7243,6 +7318,7 @@ const handleRequest = async (url, options) => {
7243
7318
  });
7244
7319
  const message = JSON.stringify(data);
7245
7320
  return {
7321
+ baseUrl,
7246
7322
  errors: [{ message, type: status }],
7247
7323
  json: null,
7248
7324
  response,
@@ -7252,6 +7328,7 @@ const handleRequest = async (url, options) => {
7252
7328
  catch (e) {
7253
7329
  const message = 'Unknown error';
7254
7330
  return {
7331
+ baseUrl,
7255
7332
  errors: [{ message: `${status}: ${message}`, type: status }],
7256
7333
  json: null,
7257
7334
  response: null,
@@ -7259,38 +7336,63 @@ const handleRequest = async (url, options) => {
7259
7336
  };
7260
7337
  }
7261
7338
  };
7262
- function encodeString(text) {
7263
- try {
7264
- // encode the string, remove the "=" at the end of the encoded string
7265
- const encodedString = btoa(text).replace(/=/g, '');
7266
- return encodedString;
7267
- }
7268
- catch (error) {
7269
- // return the reverse string if the encoding failed
7270
- return text
7271
- .replace(/[^A-Za-z0-9]/g, '')
7272
- .split('')
7273
- .reverse()
7274
- .join('');
7339
+ const handleRequestWithFallback = async ({ basePathType, options, path, }) => {
7340
+ const _a = await handleRequest({
7341
+ basePathType,
7342
+ options,
7343
+ path,
7344
+ }), { errors, response } = _a, rest = __rest(_a, ["errors", "response"]);
7345
+ const nextFallbackApiType = getNextFallbackApiType(basePathType);
7346
+ const unknownError = errors.find(({ type }) => type === 'unknown');
7347
+ const shouldCallFallback =
7348
+ // If next fallback is available, and the error is unknown (fail to fetch) or 404
7349
+ nextFallbackApiType && (!!unknownError || (response === null || response === void 0 ? void 0 : response.status) === 404);
7350
+ if (shouldCallFallback) {
7351
+ void sendErrorLog({
7352
+ endpoint: fallbackApiList[basePathType] + path,
7353
+ errors: errors.map(({ message }) => message),
7354
+ metadata: {
7355
+ currentBasePath: basePathType,
7356
+ nextFallbackApiType,
7357
+ status: response === null || response === void 0 ? void 0 : response.status,
7358
+ statusText: response === null || response === void 0 ? void 0 : response.statusText,
7359
+ },
7360
+ });
7361
+ log(`=== "${path}" failed to fetch, trying next fallback ${nextFallbackApiType}`);
7362
+ return handleRequestWithFallback({
7363
+ basePathType: nextFallbackApiType,
7364
+ options,
7365
+ path,
7366
+ });
7275
7367
  }
7276
- }
7277
- const handleFetch = async (url, _opts) => {
7368
+ // No more fallbacks, just return the result
7369
+ return Object.assign({ errors, response }, rest);
7370
+ };
7371
+ /**
7372
+ * Fetch request and will request to fallback API when the first one fails
7373
+ * @param path Path name of the request (e.g. /api/something/com).
7374
+ * @param _opts fetch options
7375
+ */
7376
+ const handleFetch = async (path, _opts) => {
7278
7377
  const opts = __rest(_opts || {}, []);
7279
7378
  const body = opts.body ? JSON.stringify(opts.body) : undefined;
7280
7379
  const method = opts.method || 'GET';
7281
- // adding random encoded token to the url so that the request will be cached differently for each store
7282
- const modifiedUrl = new URL(url);
7283
- modifiedUrl.searchParams.set('zToken', encodeString(window.location.hostname));
7284
7380
  // headers content type
7285
7381
  const headers = Object.assign({ 'Content-Type': 'application/json', 'Zonos-Is-BigCommerce': window.Zonos.isBigCommerce.toString(), 'Zonos-Referer': window.location.hostname, 'Zonos-Version': window.Zonos.version, credentialtoken: window.Zonos.zonosApiKey || 'Empty credential token from zonos-elements' }, opts.headers);
7286
7382
  const options = Object.assign(Object.assign({}, opts), { body: method === 'GET' ? undefined : body, headers,
7287
7383
  method });
7288
- return handleRequest(modifiedUrl.toString(), options);
7384
+ // This is for testing fallback API, set fallback API type to start with
7385
+ const useFallbackApi = new URLSearchParams(window.location.search).get('useFallbackApi');
7386
+ return handleRequestWithFallback({
7387
+ basePathType: useFallbackApi || MAIN_BASE_API_TYPE,
7388
+ options,
7389
+ path,
7390
+ });
7289
7391
  };
7290
7392
 
7291
7393
  const getCountries = async () => {
7292
7394
  try {
7293
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/get-countries`, {
7395
+ const { errors, json } = await handleFetch('/api/zonos-elements/get-countries', {
7294
7396
  method: 'GET',
7295
7397
  });
7296
7398
  if (errors.length || !json) {
@@ -7308,7 +7410,7 @@ const getCountryLandedCost = async (countryCode) => {
7308
7410
  if (!countryCode) {
7309
7411
  return null;
7310
7412
  }
7311
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/country-landed-cost/${countryCode}`;
7413
+ const url = `/api/zonos-elements/country-landed-cost/${countryCode}`;
7312
7414
  const { errors, json } = await handleFetch(url);
7313
7415
  if (errors.length || !json) {
7314
7416
  logError(`Error fetching country landed cost: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
@@ -7337,8 +7439,12 @@ const getExchangeRate = async ({ country, isGuaranteed, sourceCurrency, targetCu
7337
7439
  if (sourceCurrency === targetCurrency && !isGuaranteed) {
7338
7440
  return defaultUsExchangeRate;
7339
7441
  }
7340
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/exchange-rates?sourceCurrency=${sourceCurrency}&targetCurrency=${targetCurrency}&isGuaranteed=${isGuaranteed}&country=${country}`;
7341
- const { errors, json } = await handleFetch(url);
7442
+ const searchParams = new URLSearchParams();
7443
+ searchParams.set('sourceCurrency', sourceCurrency);
7444
+ searchParams.set('targetCurrency', targetCurrency);
7445
+ searchParams.set('isGuaranteed', String(isGuaranteed));
7446
+ searchParams.set('country', country || '');
7447
+ const { errors, json } = await handleFetch(`/api/zonos-elements/exchange-rates?${searchParams.toString()}`);
7342
7448
  if (errors.length || !json) {
7343
7449
  logError(`Error fetching country landed cost: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
7344
7450
  return defaultUsExchangeRate;
@@ -7358,8 +7464,7 @@ const getInclusivePricing = async (countryCode) => {
7358
7464
  if (!countryCode) {
7359
7465
  return null;
7360
7466
  }
7361
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/inclusive-prices/${countryCode}`;
7362
- const { errors, json } = await handleFetch(url);
7467
+ const { errors, json } = await handleFetch(`/api/zonos-elements/inclusive-prices/${countryCode}`);
7363
7468
  if (errors.length || !json) {
7364
7469
  logError(`Error fetching country inclusive price setting: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
7365
7470
  return null;
@@ -7369,8 +7474,13 @@ const getInclusivePricing = async (countryCode) => {
7369
7474
 
7370
7475
  const getLocaleMessages = async ({ countryCode, localeTo, storeId, }) => {
7371
7476
  var _a;
7372
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/locale-messages?countryCode=${countryCode}&storeId=${storeId}&localeTo=${localeTo}`;
7373
- const { errors, json } = await handleFetch(url);
7477
+ const searchParams = new URLSearchParams();
7478
+ searchParams.set('countryCode', countryCode);
7479
+ searchParams.set('storeId', storeId.toString());
7480
+ if (localeTo) {
7481
+ searchParams.set('localeTo', localeTo);
7482
+ }
7483
+ const { errors, json } = await handleFetch(`/api/zonos-elements/locale-messages?${searchParams.toString()}`);
7374
7484
  if (errors.length || !json) {
7375
7485
  logError('Error fetching exchange rate', (_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message);
7376
7486
  return [];
@@ -7390,14 +7500,11 @@ const getLocalization = async () => {
7390
7500
  // load and use country from session storage when zCountry query param is not present
7391
7501
  const countryLoadedSession = window.sessionStorage.getItem('zonos--country');
7392
7502
  const zCountry = getZCountryUrlParam(currentUrl.searchParams) || countryLoadedSession;
7393
- const localizationUrl = new URL(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/localization`);
7503
+ const searchParams = new URLSearchParams();
7394
7504
  if (zCountry) {
7395
- localizationUrl.searchParams.set('zCountry', zCountry);
7505
+ searchParams.set('zCountry', zCountry);
7396
7506
  }
7397
- const fetchUrl = localizationUrl.href;
7398
- const { errors, json } = await handleFetch(fetchUrl, {
7399
- method: 'GET',
7400
- });
7507
+ const { errors, json } = await handleFetch(`/api/zonos-elements/localization?${searchParams.toString()}`);
7401
7508
  if (errors.length || !json) {
7402
7509
  return { country: null, locale: null };
7403
7510
  }
@@ -7413,8 +7520,7 @@ const getLocalization = async () => {
7413
7520
 
7414
7521
  const getShippingZones = async () => {
7415
7522
  var _a, _b;
7416
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/shipping-zones`;
7417
- const { errors, json } = await handleFetch(url);
7523
+ const { errors, json } = await handleFetch('/api/zonos-elements/shipping-zones');
7418
7524
  if (errors.length || !json) {
7419
7525
  logError(`Error fetching shipping zones: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
7420
7526
  return null;
@@ -7821,7 +7927,7 @@ const updateCheckoutSessionLanguage = async () => {
7821
7927
  if (!cartStore.checkoutSessionId) {
7822
7928
  return null;
7823
7929
  }
7824
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/update-checkout-session-metadata`, {
7930
+ const { errors, json } = await handleFetch('/api/zonos-elements/update-checkout-session-metadata', {
7825
7931
  body: {
7826
7932
  id: cartStore.checkoutSessionId,
7827
7933
  metadata: [
@@ -7933,13 +8039,13 @@ const triggerBuildLandedCost = async (buildLandedCost) => {
7933
8039
  checkoutSessionId: data.checkoutSessionId,
7934
8040
  contact: data.contact,
7935
8041
  shippingAddress: data.shippingAddress,
7936
- zonosApiRoute: "https://v1.route.js.zonos.com",
8042
+ zonosApiRoute: MAIN_BASE_API,
7937
8043
  });
7938
8044
  if (!landedCost || ((_a = landedCost.errors) === null || _a === void 0 ? void 0 : _a.length)) {
7939
8045
  throw new Error(`Failed to build landed cost: ${((_c = (_b = landedCost === null || landedCost === void 0 ? void 0 : landedCost.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) || 'Unknown error'}`);
7940
8046
  }
7941
8047
  // Validate the landed cost object to make sure the returned value from buildLandedCost has a valid schema
7942
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/validate-landed-cost`, {
8048
+ const { errors, json } = await handleFetch('/api/zonos-elements/validate-landed-cost', {
7943
8049
  body: landedCost,
7944
8050
  headers: {
7945
8051
  'Content-Type': 'application/json',
@@ -7961,8 +8067,7 @@ const calculateLandedCost = async (abortController) => {
7961
8067
  return json;
7962
8068
  }
7963
8069
  // request to get landed cost info
7964
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/calculate-landed-cost`;
7965
- const { errors, json } = await handleFetch(url, {
8070
+ const { errors, json } = await handleFetch('/api/zonos-elements/calculate-landed-cost', {
7966
8071
  body: prepCalculateLandedCost(),
7967
8072
  method: 'POST',
7968
8073
  signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
@@ -8493,13 +8598,11 @@ const stripeStoreInitCheckoutSession = async () => {
8493
8598
  return false;
8494
8599
  }
8495
8600
  stripeStore.isFetchingSession = true;
8496
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/create-checkout-session`, {
8601
+ const { errors, json } = await handleFetch('/api/zonos-elements/create-checkout-session', {
8497
8602
  body: {
8498
8603
  currency: ((_a = cartStore.items.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode) || '',
8499
8604
  itemsAmount: total,
8500
- metadata: [
8501
- { key: 'language', value: localizationStore.selectedLocale },
8502
- ],
8605
+ metadata: [{ key: 'language', value: localizationStore.selectedLocale }],
8503
8606
  presentmentCountryCode: localizationStore.selectedCountryCode || null,
8504
8607
  },
8505
8608
  method: 'POST',
@@ -8524,7 +8627,7 @@ const stripeStoreInitCheckoutSession = async () => {
8524
8627
  const stripeStoreUpdateCheckoutSession = async ({ currency, id, itemsAmount, landedCostId, presentmentCountryCode, }) => {
8525
8628
  // No need to set loading state here because this function will be called under the hood to update
8526
8629
  // landed cost id for the section.
8527
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/update-checkout-session`, {
8630
+ const { errors, json } = await handleFetch('/api/zonos-elements/update-checkout-session', {
8528
8631
  body: {
8529
8632
  currency,
8530
8633
  id,
@@ -8623,8 +8726,7 @@ const stripeStoreTranslateAddressToLatin = async ({ addressInvalidCharactersList
8623
8726
  if (!isAddressOutdated) {
8624
8727
  return;
8625
8728
  }
8626
- const routeUrl = "https://v1.route.js.zonos.com";
8627
- const { errors, json } = await handleFetch(`${routeUrl}/api/zonos-elements/validate-address`, {
8729
+ const { errors, json } = await handleFetch('/api/zonos-elements/validate-address', {
8628
8730
  body: requestBody,
8629
8731
  method: 'POST',
8630
8732
  });
@@ -8982,4 +9084,4 @@ const cartStoreResetTabItems = () => {
8982
9084
  cartStoreResetSelectedShippingOption();
8983
9085
  };
8984
9086
 
8985
- export { getZCountryUrlParam as A, setZCountryUrlParam as B, currencyDisplay as C, currencyConvertAndFormat as D, currencyConvert as E, currencyFormat as F, cartStoreHasOneEligibleItem as G, stripeStoreRetrievePayment as H, stripeStoreMessageBasedOnStatus as I, stripeStoreTranslateAddressToLatin as J, cartStoreUpdateSelectedShippingOption as K, cartStoreGetShippingTransitInfo as L, localizationStoreUpdateSelectedLocale as M, localizationStoreUpdateSelectedCountryCode as a, stripeStoreCleanupDomesticShippingSession as b, stripeStoreSaveDomesticShippingSession as c, cartStore as d, cartStoreUpdateItems as e, cartStoreReset as f, cartStoreResetTabItems as g, cartStoreClearCheckoutInterval as h, initStripeElements as i, stripeStore as j, stripeStoreInitCheckoutSession as k, localizationStore as l, cartStoreStartCheckoutInterval as m, cartStoreUpdateToErrorState as n, stripeStorePrefetchLandedCost as o, cartStoreNextStep as p, stripeStoreHandleInventoryCheck as q, stripeStoreConfirmPayment as r, stripeStoreGetDomesticShippingSession as s, translate as t, stripeStoreReset as u, localizationStoreOnUpdate as v, handleFetch as w, jsonParse as x, isValidSelector as y, initLocalizationStore as z };
9087
+ export { initLocalizationStore as A, getZCountryUrlParam as B, setZCountryUrlParam as C, currencyDisplay as D, currencyConvertAndFormat as E, currencyConvert as F, currencyFormat as G, cartStoreHasOneEligibleItem as H, stripeStoreRetrievePayment as I, stripeStoreMessageBasedOnStatus as J, stripeStoreTranslateAddressToLatin as K, cartStoreUpdateSelectedShippingOption as L, cartStoreGetShippingTransitInfo as M, localizationStoreUpdateSelectedLocale as N, localizationStoreUpdateSelectedCountryCode as a, stripeStoreCleanupDomesticShippingSession as b, sendErrorLog as c, stripeStoreSaveDomesticShippingSession as d, cartStore as e, cartStoreUpdateItems as f, cartStoreReset as g, cartStoreResetTabItems as h, initStripeElements as i, cartStoreClearCheckoutInterval as j, stripeStore as k, localizationStore as l, stripeStoreInitCheckoutSession as m, cartStoreStartCheckoutInterval as n, cartStoreUpdateToErrorState as o, stripeStorePrefetchLandedCost as p, cartStoreNextStep as q, stripeStoreHandleInventoryCheck as r, stripeStoreGetDomesticShippingSession as s, translate as t, stripeStoreConfirmPayment as u, stripeStoreReset as v, localizationStoreOnUpdate as w, handleFetch as x, jsonParse as y, isValidSelector as z };
@@ -1,4 +1,4 @@
1
- import { w as handleFetch, d as cartStore, l as localizationStore } from './cart-9f40efd7.js';
1
+ import { x as handleFetch, e as cartStore, l as localizationStore } from './cart-2198741e.js';
2
2
  import { z as zonosStore } from './zonosStore-8fc9ceb2.js';
3
3
 
4
4
  const trackConversionEvent = async (eventName, metadata) => {
@@ -13,7 +13,6 @@ const trackConversionEvent = async (eventName, metadata) => {
13
13
  !window.Zonos.zonosConversionTest) {
14
14
  return;
15
15
  }
16
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/track-conversion-event`;
17
16
  const countryCode = localizationStore.selectedCountryCode;
18
17
  const organizationId = zonosStore.organizationId;
19
18
  const checkoutSessionId = cartStore.checkoutSessionId;
@@ -28,7 +27,7 @@ const trackConversionEvent = async (eventName, metadata) => {
28
27
  metadata,
29
28
  organizationId,
30
29
  };
31
- await handleFetch(url, {
30
+ await handleFetch('/api/zonos-elements/track-conversion-event', {
32
31
  body,
33
32
  method: 'POST',
34
33
  });
@@ -46,22 +45,4 @@ const createCustomEvent = (eventName, detail) => {
46
45
  });
47
46
  };
48
47
 
49
- const sendErrorLog = async ({ endpoint, errors, metadata }) => {
50
- const userAgentData = 'userAgentData' in window.navigator
51
- ? // userAgentData is not yet supported in all browsers
52
- window.navigator.userAgentData
53
- : null;
54
- const errorObject = {
55
- endpoint,
56
- errors,
57
- metadata: Object.assign({ href: window.location.href, userAgent: userAgentData && userAgentData.brands.length > 0
58
- ? userAgentData
59
- : window.navigator.userAgent }, metadata),
60
- };
61
- void handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/log-error`, {
62
- body: errorObject,
63
- method: 'POST',
64
- });
65
- };
66
-
67
- export { createCustomEvent as c, getIsTestMode as g, sendErrorLog as s, trackConversionEvent as t };
48
+ export { createCustomEvent as c, getIsTestMode as g, trackConversionEvent as t };
package/dist/esm/index.js CHANGED
@@ -90,13 +90,17 @@ const getZonosQaUrl = () => {
90
90
  return null;
91
91
  }
92
92
  const qaUrl = extractZonosQaUrl(window.location.href);
93
- const cdnUrl = "https://v1.3.44.js.zonos.com";
93
+ const cdnUrl = "https://v1.3.46.js.zonos.com";
94
94
  // when the qaUrl is not set and the built URL is from the test domain, use the test domain for testing
95
- if (!qaUrl && cdnUrl.includes('test.')) {
95
+ if (!qaUrl &&
96
+ (cdnUrl.includes('test.') ||
97
+ // Vercel git domain
98
+ cdnUrl.includes('test-'))) {
96
99
  return cdnUrl;
97
100
  }
98
101
  // when local demo app is running, it needs to use the local dev script unless the qaUrl is set
99
- if (!qaUrl && window.location.hostname === 'dev.demo.elements.zonos.com') {
102
+ if (!qaUrl &&
103
+ ['dev.demo.elements.zonos.com'].includes(window.location.hostname)) {
100
104
  return 'https://dev.elements.zonos.com';
101
105
  }
102
106
  if (!qaUrl) {
@@ -260,10 +264,10 @@ const zonosLoadUrl = (() => {
260
264
  }
261
265
  return null;
262
266
  })();
263
- const ZONOS_URL = "https://v1.3.44.js.zonos.com";
264
- const JS_DELIVR_ZONOS_URL = zonosLoadUrl || "https://cdn.jsdelivr.net/npm/@zonos/elements@1.3.44";
265
- const UNPKG_ZONOS_URL = "https://unpkg.com/@zonos/elements@1.3.44";
266
- const CDNJS_ZONOS_URL = "https://cdnjs.cloudflare.com/ajax/libs/zonos-elements/1.3.44";
267
+ const ZONOS_URL = "https://v1.3.46.js.zonos.com";
268
+ const JS_DELIVR_ZONOS_URL = zonosLoadUrl || "https://cdn.jsdelivr.net/npm/@zonos/elements@1.3.46";
269
+ const UNPKG_ZONOS_URL = "https://unpkg.com/@zonos/elements@1.3.46";
270
+ const CDNJS_ZONOS_URL = "https://cdnjs.cloudflare.com/ajax/libs/zonos-elements/1.3.46";
267
271
  const MAIN_LOAD_CDN_TYPE = 'jsdelivr';
268
272
  const INTER_FONT_URL = 'https://rsms.me';
269
273
  const GOOGLE_FONT_URL = 'https://fonts.googleapis.com';
@@ -284,7 +288,7 @@ Zonos.isBigCommerce = false;
284
288
  */
285
289
  Zonos.isNpm = true;
286
290
  Zonos.zonosQaUrl = null;
287
- Zonos.version = `v${"1.3.44"}`;
291
+ Zonos.version = `v${"1.3.46"}`;
288
292
  Zonos.modeAlerted = false;
289
293
  Zonos.tempCartData = null;
290
294
  Zonos.paypal = null;