@rechargeapps/storefront-client 0.0.17 → 0.1.0

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 (41) hide show
  1. package/README.md +7 -0
  2. package/dist/cjs/api/auth.js +29 -0
  3. package/dist/cjs/api/auth.js.map +1 -0
  4. package/dist/cjs/api/bundle.js +6 -10
  5. package/dist/cjs/api/bundle.js.map +1 -1
  6. package/dist/cjs/api/cdn.js +6 -12
  7. package/dist/cjs/api/cdn.js.map +1 -1
  8. package/dist/cjs/api/subscription.js +12 -0
  9. package/dist/cjs/api/subscription.js.map +1 -0
  10. package/dist/cjs/constants/api.js +4 -0
  11. package/dist/cjs/constants/api.js.map +1 -1
  12. package/dist/cjs/index.js +5 -0
  13. package/dist/cjs/index.js.map +1 -1
  14. package/dist/cjs/utils/init.js +25 -3
  15. package/dist/cjs/utils/init.js.map +1 -1
  16. package/dist/cjs/utils/options.js +2 -1
  17. package/dist/cjs/utils/options.js.map +1 -1
  18. package/dist/cjs/utils/request.js +37 -0
  19. package/dist/cjs/utils/request.js.map +1 -1
  20. package/dist/esm/api/auth.js +20 -0
  21. package/dist/esm/api/auth.js.map +1 -0
  22. package/dist/esm/api/bundle.js +7 -11
  23. package/dist/esm/api/bundle.js.map +1 -1
  24. package/dist/esm/api/cdn.js +7 -13
  25. package/dist/esm/api/cdn.js.map +1 -1
  26. package/dist/esm/api/subscription.js +8 -0
  27. package/dist/esm/api/subscription.js.map +1 -0
  28. package/dist/esm/constants/api.js +3 -1
  29. package/dist/esm/constants/api.js.map +1 -1
  30. package/dist/esm/index.js +2 -0
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/utils/init.js +25 -3
  33. package/dist/esm/utils/init.js.map +1 -1
  34. package/dist/esm/utils/options.js +2 -1
  35. package/dist/esm/utils/options.js.map +1 -1
  36. package/dist/esm/utils/request.js +34 -1
  37. package/dist/esm/utils/request.js.map +1 -1
  38. package/dist/index.d.ts +88 -5
  39. package/dist/umd/recharge-storefront-client.min.js +8 -8
  40. package/dist/umd/recharge-storefront-client.min.js.map +1 -1
  41. package/package.json +6 -4
package/README.md CHANGED
@@ -45,3 +45,10 @@ recharge.init({ storeIdentifier: 'storeIdentifier' });
45
45
 
46
46
  - `recharge.bundle.getBundleId(bundle)`
47
47
  - `recharge.bundle.validate(bundle)`
48
+
49
+ ## Testing with Shopify App Proxy
50
+
51
+ - Build UMD locally
52
+ - run `npx http-server ./packages/storefront/client/dist`
53
+ - login to storefront
54
+ - run script from `test.html` in the dev tools
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var Cookies = require('js-cookie');
6
+ var request = require('../utils/request.js');
7
+
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
+
10
+ var Cookies__default = /*#__PURE__*/_interopDefaultLegacy(Cookies);
11
+
12
+ const login = async () => {
13
+ const response = await request.shopifyAppProxyRequest("get", "/logged_in_customer_poc");
14
+ if (response.api_token) {
15
+ const expires = new Date();
16
+ expires.setHours(expires.getHours() + 1);
17
+ Cookies__default["default"].set("recharge-session", response.api_token, { expires });
18
+ } else {
19
+ Cookies__default["default"].remove("recharge-session");
20
+ }
21
+ return !!response.api_token;
22
+ };
23
+ const logout = () => {
24
+ Cookies__default["default"].remove("recharge-session");
25
+ };
26
+
27
+ exports.login = login;
28
+ exports.logout = logout;
29
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import Cookies from 'js-cookie';\nimport { shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse } from '../types/auth';\n\nexport const login = async (): Promise<boolean> => {\n const response = await shopifyAppProxyRequest<LoginResponse | Partial<LoginResponse>>(\n 'get',\n '/logged_in_customer_poc'\n );\n\n if (response.api_token) {\n const expires = new Date();\n expires.setHours(expires.getHours() + 1);\n Cookies.set('recharge-session', response.api_token, { expires });\n } else {\n Cookies.remove('recharge-session');\n }\n\n return !!response.api_token;\n};\n\nexport const logout = (): void => {\n Cookies.remove('recharge-session');\n};\n"],"names":["shopifyAppProxyRequest","Cookies"],"mappings":";;;;;;;;;;;AAEY,MAAC,KAAK,GAAG,YAAY;AACjC,EAAE,MAAM,QAAQ,GAAG,MAAMA,8BAAsB,CAAC,KAAK,EAAE,yBAAyB,CAAC,CAAC;AAClF,EAAE,IAAI,QAAQ,CAAC,SAAS,EAAE;AAC1B,IAAI,MAAM,OAAO,GAAG,IAAI,IAAI,EAAE,CAAC;AAC/B,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;AAC7C,IAAIC,2BAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,QAAQ,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACrE,GAAG,MAAM;AACT,IAAIA,2BAAO,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACvC,GAAG;AACH,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC9B,EAAE;AACU,MAAC,MAAM,GAAG,MAAM;AAC5B,EAAEA,2BAAO,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrC;;;;;"}
@@ -7,14 +7,13 @@ var request = require('../utils/request.js');
7
7
  var options = require('../utils/options.js');
8
8
  var cdn = require('./cdn.js');
9
9
 
10
- const STORE_FRONT_MANAGER_URL = "/tools/recurring/bundling-storefront-manager";
10
+ const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
11
11
  function getTimestampSecondsFromClient() {
12
12
  return Math.ceil(Date.now() / 1e3);
13
13
  }
14
- async function getTimestampSecondsFromServer(request2) {
15
- const url = `${STORE_FRONT_MANAGER_URL}/t`;
14
+ async function getTimestampSecondsFromServer() {
16
15
  try {
17
- const { timestamp } = await request2("get", url, {
16
+ const { timestamp } = await request.shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t`, {
18
17
  headers: { "X-Recharge-App": "storefront-client" }
19
18
  });
20
19
  return timestamp;
@@ -29,7 +28,7 @@ const getBundleId = async (bundle) => {
29
28
  if (!isValid) {
30
29
  throw new Error("Bundle selection is invalid.");
31
30
  }
32
- const timestampSeconds = await getTimestampSecondsFromServer(request.request);
31
+ const timestampSeconds = await getTimestampSecondsFromServer();
33
32
  const bundleData = bundlingData.toLineItemProperty({
34
33
  variantId: bundle.externalVariantId,
35
34
  version: timestampSeconds,
@@ -44,15 +43,12 @@ const getBundleId = async (bundle) => {
44
43
  })
45
44
  });
46
45
  try {
47
- const STORE_FRONT_BUNDLE_URL = `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`;
48
- const payload = await request.request("post", STORE_FRONT_BUNDLE_URL, {
46
+ const payload = await request.shopifyAppProxyRequest("post", `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`, {
49
47
  data: {
50
48
  bundle: bundleData
51
49
  },
52
50
  headers: {
53
- "Content-Type": "application/json",
54
- Origin: `https://${opts.storeIdentifier}`,
55
- "X-Recharge-App": "storefront-client"
51
+ Origin: `https://${opts.storeIdentifier}`
56
52
  }
57
53
  });
58
54
  if (!payload.id || payload.code !== 200) {
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { toLineItemProperty } from '@recharge-packages/bundling-data';\nimport { Request, Bundle } from '../types';\nimport { request } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getBundleSettings } from './cdn';\n\nconst STORE_FRONT_MANAGER_URL = '/tools/recurring/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(request: Request): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n const url = `${STORE_FRONT_MANAGER_URL}/t`;\n\n try {\n const { timestamp } = await request<{ timestamp: number }>('get', url, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport const getBundleId = async (bundle: Bundle): Promise<string> => {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (!isValid) {\n throw new Error('Bundle selection is invalid.');\n }\n const timestampSeconds = await getTimestampSecondsFromServer(request);\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const STORE_FRONT_BUNDLE_URL = `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`;\n const payload = await request<{ id: string; code: number; message: string }>('post', STORE_FRONT_BUNDLE_URL, {\n data: {\n bundle: bundleData,\n },\n headers: {\n 'Content-Type': 'application/json',\n Origin: `https://${opts.storeIdentifier}`,\n 'X-Recharge-App': 'storefront-client',\n },\n });\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n};\n\nexport const validateBundle = async (bundle: Bundle): Promise<boolean> => {\n try {\n const bundleSettings = await getBundleSettings(bundle.externalProductId);\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n return !!bundle && !!bundleSettings;\n } catch (e) {\n console.error('Error fetching bundle settings');\n return false;\n }\n};\n"],"names":["getOptions","request","toLineItemProperty","getBundleSettings"],"mappings":";;;;;;;;;AAIA,MAAM,uBAAuB,GAAG,8CAA8C,CAAC;AAC/E,SAAS,6BAA6B,GAAG;AACz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I,CAAC,CAAC,cAAc,CAAC;AACxC,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { toLineItemProperty } from '@recharge-packages/bundling-data';\nimport { Bundle } from '../types';\nimport { shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getBundleSettings } from './cdn';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport const getBundleId = async (bundle: Bundle): Promise<string> => {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (!isValid) {\n throw new Error('Bundle selection is invalid.');\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n};\n\nexport const validateBundle = async (bundle: Bundle): Promise<boolean> => {\n try {\n const bundleSettings = await getBundleSettings(bundle.externalProductId);\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n return !!bundle && !!bundleSettings;\n } catch (e) {\n console.error('Error fetching bundle settings');\n return false;\n }\n};\n"],"names":["shopifyAppProxyRequest","getOptions","toLineItemProperty","getBundleSettings"],"mappings":";;;;;;;;;AAIA,MAAM,uBAAuB,GAAG,8BAA8B,CAAC;AAC/D,SAAS,6BAA6B,GAAG;AACzC,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC;AACrC,CAAC;AACD,eAAe,6BAA6B,GAAG;AAC/C,EAAE,IAAI;AACN,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,MAAMA,8BAAsB,CAAC,KAAK,EAAE,CAAC,EAAE,uBAAuB,CAAC,EAAE,CAAC,EAAE;AAC9F,MAAM,OAAO,EAAE,EAAE,gBAAgB,EAAE,mBAAmB,EAAE;AACxD,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,SAAS,CAAC;AACrB,GAAG,CAAC,OAAO,EAAE,EAAE;AACf,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAClE,IAAI,OAAO,6BAA6B,EAAE,CAAC;AAC3C,GAAG;AACH,CAAC;AACW,MAAC,WAAW,GAAG,OAAO,MAAM,KAAK;AAC7C,EAAE,MAAM,IAAI,GAAGC,kBAAU,EAAE,CAAC;AAC5B,EAAE,MAAM,OAAO,GAAG,MAAM,c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AO,OAAO,CAAC,EAAE,CAAC;AACtB,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,2BAA2B,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AACvD,GAAG;AACH,EAAE;AACU,MAAC,cAAc,GAAG,OAAO,MAAM,KAAK;AAChD,EAAE,IAAI;AACN,IAAI,MAAM,cAAc,GAAG,MAAMG,qBAAiB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;AAC7E,IAAI,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,cAAc,CAAC;AACxC,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;;;;;"}
@@ -2,10 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var api = require('../constants/api.js');
6
5
  var cdn = require('../mappers/cdn.js');
7
6
  var request = require('../utils/request.js');
8
- var options = require('../utils/options.js');
9
7
 
10
8
  const CDN_VERSION = "2020-12";
11
9
  const DEFAULT_STORE_SETTINGS = {
@@ -18,33 +16,29 @@ const DEFAULT_STORE_SETTINGS = {
18
16
  }
19
17
  };
20
18
  const promiseCache = /* @__PURE__ */ new Map();
21
- function cacheRequest(cacheKey, request2) {
19
+ function cacheRequest(cacheKey, request) {
22
20
  if (!promiseCache.has(cacheKey)) {
23
- promiseCache.set(cacheKey, request2());
21
+ promiseCache.set(cacheKey, request());
24
22
  }
25
23
  return promiseCache.get(cacheKey);
26
24
  }
27
25
  const getProduct = async (externalProductId) => {
28
- const opts = options.getOptions();
29
- const { product } = await cacheRequest(`product.${externalProductId}`, () => request.request("get", `${api.RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/product/${CDN_VERSION}/${externalProductId}.json`));
26
+ const { product } = await cacheRequest(`product.${externalProductId}`, () => request.cdnRequest("get", `/product/${CDN_VERSION}/${externalProductId}.json`));
30
27
  return cdn.productMapper(product);
31
28
  };
32
29
  const getStoreSettings = async () => {
33
- const opts = options.getOptions();
34
- const storeSettings = await cacheRequest("storeSettings", () => request.request("get", `${api.RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/store_settings.json`).catch(() => {
30
+ const storeSettings = await cacheRequest("storeSettings", () => request.cdnRequest("get", `/${CDN_VERSION}/store_settings.json`).catch(() => {
35
31
  return DEFAULT_STORE_SETTINGS;
36
32
  }));
37
33
  return storeSettings;
38
34
  };
39
35
  const getWidgetSettings = async () => {
40
- const opts = options.getOptions();
41
- const { widget_settings } = await cacheRequest("widgetSettings", () => request.request("get", `${api.RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/widget_settings.json`));
36
+ const { widget_settings } = await cacheRequest("widgetSettings", () => request.cdnRequest("get", `/${CDN_VERSION}/widget_settings.json`));
42
37
  const widgetSettings = cdn.widgetSettingsMapper(widget_settings);
43
38
  return widgetSettings;
44
39
  };
45
40
  const getProductsAndSettings = async () => {
46
- const opts = options.getOptions();
47
- const { products, widget_settings, store_settings, meta } = await cacheRequest("productsAndSettings", () => request.request("get", `${api.RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/product/${CDN_VERSION}/products.json`));
41
+ const { products, widget_settings, store_settings, meta } = await cacheRequest("productsAndSettings", () => request.cdnRequest("get", `/product/${CDN_VERSION}/products.json`));
48
42
  if ((meta == null ? void 0 : meta.status) === "error") {
49
43
  return Promise.reject(meta.message);
50
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cdn.js","sources":["../../../src/api/cdn.ts"],"sourcesContent":["import { RECHARGE_CDN_URL } from '../constants/api';\nimport {\n CDNWidgetSettings,\n CDNStoreSettings,\n CDNWidgetSettingsResource,\n CDNProductsAndSettings,\n CDNProductResource,\n CDNProduct,\n CDNProductAndSettings,\n CDNProductsAndSettingsResource,\n CDNBundleSettings,\n CDNProductKeyObject,\n} from '../types';\nimport { productArrayMapper, productMapper, widgetSettingsMapper } from '../mappers/cdn';\nimport { request } from '../utils/request';\nimport { getOptions } from '../utils/options';\n\nconst CDN_VERSION = '2020-12';\n\n// Default store settings if none are provided from the cdn\nconst DEFAULT_STORE_SETTINGS: CDNStoreSettings = {\n store_currency: {\n currency_code: 'USD',\n currency_symbol: '$',\n decimal_separator: '.',\n thousands_separator: ',',\n currency_symbol_location: 'left',\n },\n};\n\nconst promiseCache = new Map();\n\n// This will cache the request and use the same promise anywhere we call this function. This will never make multiple calls and always return the first request\nfunction cacheRequest<T>(cacheKey: string, request: () => T): T {\n if (!promiseCache.has(cacheKey)) {\n promiseCache.set(cacheKey, request());\n }\n return promiseCache.get(cacheKey);\n}\n\nexport const getProduct = async (externalProductId: string | number): Promise<CDNProduct> => {\n const opts = getOptions();\n const { product } = await cacheRequest(`product.${externalProductId}`, () =>\n request<CDNProductResource>(\n 'get',\n `${RECHARGE_CDN_URL(opts.environment)}/store/${\n opts.storeIdentifier\n }/product/${CDN_VERSION}/${externalProductId}.json`\n )\n );\n\n return productMapper(product);\n};\n\nexport const getStoreSettings = async (): Promise<CDNStoreSettings> => {\n const opts = getOptions();\n const storeSettings = await cacheRequest('storeSettings', () =>\n request<CDNStoreSettings>(\n 'get',\n `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/store_settings.json`\n ).catch(() => {\n return DEFAULT_STORE_SETTINGS;\n })\n );\n return storeSettings;\n};\n\nexport const getWidgetSettings = async (): Promise<CDNWidgetSettings> => {\n const opts = getOptions();\n const { widget_settings } = await cacheRequest('widgetSettings', () =>\n request<CDNWidgetSettingsResource>(\n 'get',\n `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/widget_settings.json`\n )\n );\n\n const widgetSettings = widgetSettingsMapper(widget_settings);\n\n return widgetSettings;\n};\n\nexport const getProductsAndSettings = async (): Promise<CDNProductsAndSettings> => {\n const opts = getOptions();\n const { products, widget_settings, store_settings, meta } = await cacheRequest('productsAndSettings', () =>\n request<CDNProductsAndSettingsResource>(\n 'get',\n `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/product/${CDN_VERSION}/products.json`\n )\n );\n\n if (meta?.status === 'error') {\n return Promise.reject(meta.message);\n }\n\n return {\n products: productArrayMapper(products),\n widget_settings: widgetSettingsMapper(widget_settings),\n store_settings,\n };\n};\n\nexport const getProducts = async (): Promise<CDNProductKeyObject[]> => {\n const { products } = await getProductsAndSettings();\n return products;\n};\n\nexport const getProductAndSettings = async (externalProductId: string | number): Promise<CDNProductAndSettings> => {\n const [product, store_settings, widget_settings] = await Promise.all([\n getProduct(externalProductId),\n getStoreSettings(),\n getWidgetSettings(),\n ]);\n\n return {\n product,\n store_settings,\n widget_settings,\n storeSettings: store_settings,\n widgetSettings: widget_settings,\n };\n};\n\nexport const getBundleSettings = async (\n externalProductId: string | number\n): Promise<CDNBundleSettings | null | undefined> => {\n const { bundle_product } = await getProduct(externalProductId);\n\n return bundle_product;\n};\n\nexport const resetCache = () => Array.from(promiseCache.keys()).forEach(key => promiseCache.delete(key));\n"],"names":["getOptions","request","RECHARGE_CDN_URL","productMapper","widgetSettingsMapper","productArrayMapper"],"mappings":";;;;;;;;;AAIA,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,sBAAsB,GAAG;AAC/B,EAAE,cAAc,EAAE;AAClB,IAAI,aAAa,EAAE,KAAK;AACxB,IAAI,eAAe,EAAE,GAAG;AACxB,IAAI,iBAAiB,EAAE,GAAG;AAC1B,IAAI,mBAAmB,EAAE,GAAG;AAC5B,IAAI,wBAAwB,EAAE,MAAM;AACpC,GAAG;AACH,CAAC,CAAC;AACF,MAAM,YAAY,mBAAmB,IAAI,GAAG,EAAE,CAAC;AAC/C,SAAS,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE;AAC1C,EAAE,IAAI,CAA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,OAAO,iBAAiB,KAAK;AAClE,EAAE,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,eAAe,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;AACvE,IAAI,UAAU,CAAC,iBAAiB,CAAC;AACjC,IAAI,gBAAgB,EAAE;AACtB,IAAI,iBAAiB,EAAE;AACvB,GAAG,CAAC,CAAC;AACL,EAAE,OAAO;AACT,IAAI,OAAO;AACX,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,aAAa,EAAE,cAAc;AACjC,IAAI,cAAc,EAAE,eAAe;AACnC,GAAG,CAAC;AACJ,EAAE;AACU,MAAC,iBAAiB,GAAG,OAAO,iBAAiB,KAAK;AAC9D,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACjE,EAAE,OAAO,cAAc,CAAC;AACxB,EAAE;AACU,MAAC,UAAU,GAAG,MAAM,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,KAAK,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC;;;;;;;;;;;"}
1
+ {"version":3,"file":"cdn.js","sources":["../../../src/api/cdn.ts"],"sourcesContent":["import {\n CDNWidgetSettings,\n CDNStoreSettings,\n CDNWidgetSettingsResource,\n CDNProductsAndSettings,\n CDNProductResource,\n CDNProduct,\n CDNProductAndSettings,\n CDNProductsAndSettingsResource,\n CDNBundleSettings,\n CDNProductKeyObject,\n} from '../types';\nimport { productArrayMapper, productMapper, widgetSettingsMapper } from '../mappers/cdn';\nimport { cdnRequest } from '../utils/request';\n\nconst CDN_VERSION = '2020-12';\n\n// Default store settings if none are provided from the cdn\nconst DEFAULT_STORE_SETTINGS: CDNStoreSettings = {\n store_currency: {\n currency_code: 'USD',\n currency_symbol: '$',\n decimal_separator: '.',\n thousands_separator: ',',\n currency_symbol_location: 'left',\n },\n};\n\nconst promiseCache = new Map();\n\n// This will cache the request and use the same promise anywhere we call this function. This will never make multiple calls and always return the first request\nfunction cacheRequest<T>(cacheKey: string, request: () => T): T {\n if (!promiseCache.has(cacheKey)) {\n promiseCache.set(cacheKey, request());\n }\n return promiseCache.get(cacheKey);\n}\n\nexport const getProduct = async (externalProductId: string | number): Promise<CDNProduct> => {\n const { product } = await cacheRequest(`product.${externalProductId}`, () =>\n cdnRequest<CDNProductResource>('get', `/product/${CDN_VERSION}/${externalProductId}.json`)\n );\n\n return productMapper(product);\n};\n\nexport const getStoreSettings = async (): Promise<CDNStoreSettings> => {\n const storeSettings = await cacheRequest('storeSettings', () =>\n cdnRequest<CDNStoreSettings>('get', `/${CDN_VERSION}/store_settings.json`).catch(() => {\n return DEFAULT_STORE_SETTINGS;\n })\n );\n return storeSettings;\n};\n\nexport const getWidgetSettings = async (): Promise<CDNWidgetSettings> => {\n const { widget_settings } = await cacheRequest('widgetSettings', () =>\n cdnRequest<CDNWidgetSettingsResource>('get', `/${CDN_VERSION}/widget_settings.json`)\n );\n\n const widgetSettings = widgetSettingsMapper(widget_settings);\n\n return widgetSettings;\n};\n\nexport const getProductsAndSettings = async (): Promise<CDNProductsAndSettings> => {\n const { products, widget_settings, store_settings, meta } = await cacheRequest('productsAndSettings', () =>\n cdnRequest<CDNProductsAndSettingsResource>('get', `/product/${CDN_VERSION}/products.json`)\n );\n\n if (meta?.status === 'error') {\n return Promise.reject(meta.message);\n }\n\n return {\n products: productArrayMapper(products),\n widget_settings: widgetSettingsMapper(widget_settings),\n store_settings,\n };\n};\n\nexport const getProducts = async (): Promise<CDNProductKeyObject[]> => {\n const { products } = await getProductsAndSettings();\n return products;\n};\n\nexport const getProductAndSettings = async (externalProductId: string | number): Promise<CDNProductAndSettings> => {\n const [product, store_settings, widget_settings] = await Promise.all([\n getProduct(externalProductId),\n getStoreSettings(),\n getWidgetSettings(),\n ]);\n\n return {\n product,\n store_settings,\n widget_settings,\n storeSettings: store_settings,\n widgetSettings: widget_settings,\n };\n};\n\nexport const getBundleSettings = async (\n externalProductId: string | number\n): Promise<CDNBundleSettings | null | undefined> => {\n const { bundle_product } = await getProduct(externalProductId);\n\n return bundle_product;\n};\n\nexport const resetCache = () => Array.from(promiseCache.keys()).forEach(key => promiseCache.delete(key));\n"],"names":["cdnRequest","productMapper","widgetSettingsMapper","productArrayMapper"],"mappings":";;;;;;;AAEA,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,sBAAsB,GAAG;AAC/B,EAAE,cAAc,EAAE;AAClB,IAAI,aAAa,EAAE,KAAK;AACxB,IAAI,eAAe,EAAE,GAAG;AACxB,IAAI,iBAAiB,EAAE,GAAG;AAC1B,IAAI,mBAAmB,EAAE,GAAG;AAC5B,IAAI,wBAAwB,EAAE,MAAM;AACpC,GAAG;AACH,CAAC,CAAC;AACF,MAAM,YAAY,mBAAmB,IAAI,GAAG,EAAE,CAAC;AAC/C,SAAS,YAAY,CAAC,QAAQ,EAAE,OAAO,EAAE;AACzC,EAAE,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;AACnC,IAAI,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;AAC1C,GAAG;AACH,EAAE,OAAO,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACpC,CAAC;AACW,MAAC,UAAU,GAAG,OAAO,iBAAiB,KAAK;AACvD,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,YAAY,CAAC,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC,EAAE,MAAMA,kBAAU,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,EAAE,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACvJ,EAAE,OAAOC,iBAAa,CAAC,OAAO,CAAC,CAAC;AAChC,EAAE;AACU,MAAC,gBAAgB,GAAG,YAAY;AAC5C,EAAE,MAAM,aAAa,GAAG,MAAM,YA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C;AACtD,EAAE,OAAO,QAAQ,CAAC;AAClB,EAAE;AACU,MAAC,qBAAqB,GAAG,OAAO,iBAAiB,KAAK;AAClE,EAAE,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,eAAe,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;AACvE,IAAI,UAAU,CAAC,iBAAiB,CAAC;AACjC,IAAI,gBAAgB,EAAE;AACtB,IAAI,iBAAiB,EAAE;AACvB,GAAG,CAAC,CAAC;AACL,EAAE,OAAO;AACT,IAAI,OAAO;AACX,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,aAAa,EAAE,cAAc;AACjC,IAAI,cAAc,EAAE,eAAe;AACnC,GAAG,CAAC;AACJ,EAAE;AACU,MAAC,iBAAiB,GAAG,OAAO,iBAAiB,KAAK;AAC9D,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,UAAU,CAAC,iBAAiB,CAAC,CAAC;AACjE,EAAE,OAAO,cAAc,CAAC;AACxB,EAAE;AACU,MAAC,UAAU,GAAG,MAAM,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,KAAK,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC;;;;;;;;;;;"}
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var request = require('../utils/request.js');
6
+
7
+ const listSubscriptions = (query) => {
8
+ return request.rechargeApiRequest("get", `/subscriptions`, { query });
9
+ };
10
+
11
+ exports.listSubscriptions = listSubscriptions;
12
+ //# sourceMappingURL=subscription.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription.js","sources":["../../../src/api/subscription.ts"],"sourcesContent":["import { rechargeApiRequest } from '../utils/request';\nimport { CustomerSubscriptionResponse, SubscriptionListParams } from '../types/subscription';\n\nexport const listSubscriptions = (query?: SubscriptionListParams): Promise<CustomerSubscriptionResponse> => {\n return rechargeApiRequest<CustomerSubscriptionResponse>('get', `/subscriptions`, { query });\n};\n"],"names":["rechargeApiRequest"],"mappings":";;;;;;AACY,MAAC,iBAAiB,GAAG,CAAC,KAAK,KAAK;AAC5C,EAAE,OAAOA,0BAAkB,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAChE;;;;"}
@@ -2,7 +2,11 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ const RECHARGE_API_URL = (environment) => environment === "stage" ? "https://api.stage.rechargeapps.com" : "https://api.rechargeapps.com";
5
6
  const RECHARGE_CDN_URL = (environment) => environment === "stage" ? "https://static.stage.rechargecdn.com" : "https://static.rechargecdn.com";
7
+ const SHOPIFY_APP_PROXY_URL = "/tools/recurring";
6
8
 
9
+ exports.RECHARGE_API_URL = RECHARGE_API_URL;
7
10
  exports.RECHARGE_CDN_URL = RECHARGE_CDN_URL;
11
+ exports.SHOPIFY_APP_PROXY_URL = SHOPIFY_APP_PROXY_URL;
8
12
  //# sourceMappingURL=api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sources":["../../../src/constants/api.ts"],"sourcesContent":["export const RECHARGE_API_URL = (environment: 'stage' | 'prod'): string =>\n environment === 'stage' ? 'https://api.stage.rechargeapps.com' : 'https://api.rechargeapps.com';\nexport const RECHARGE_CDN_URL = (environment: 'stage' | 'prod'): string =>\n environment === 'stage' ? 'https://static.stage.rechargecdn.com' : 'https://static.rechargecdn.com';\n"],"names":[],"mappings":";;;;AACY,MAAC,gBAAgB,GAAG,CAAC,WAAW,KAAK,WAAW,KAAK,OAAO,GAAG,sCAAsC,GAAG;;;;"}
1
+ {"version":3,"file":"api.js","sources":["../../../src/constants/api.ts"],"sourcesContent":["export const RECHARGE_API_URL = (environment: 'stage' | 'prod'): string =>\n environment === 'stage' ? 'https://api.stage.rechargeapps.com' : 'https://api.rechargeapps.com';\nexport const RECHARGE_CDN_URL = (environment: 'stage' | 'prod'): string =>\n environment === 'stage' ? 'https://static.stage.rechargecdn.com' : 'https://static.rechargecdn.com';\nexport const RECHARGE_HOSTED_DOMAIN = '.admin.rechargeapps.com';\nexport const SHOPIFY_EMBEDDED_DOMAIN = '.myshopify.com';\nexport const SHOPIFY_APP_PROXY_URL = '/tools/recurring';\n"],"names":[],"mappings":";;;;AAAY,MAAC,gBAAgB,GAAG,CAAC,WAAW,KAAK,WAAW,KAAK,OAAO,GAAG,oCAAoC,GAAG,+BAA+B;AACrI,MAAC,gBAAgB,GAAG,CAAC,WAAW,KAAK,WAAW,KAAK,OAAO,GAAG,sCAAsC,GAAG,iCAAiC;AAGzI,MAAC,qBAAqB,GAAG;;;;;;"}
package/dist/cjs/index.js CHANGED
@@ -2,12 +2,16 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var auth = require('./api/auth.js');
5
6
  var cdn = require('./api/cdn.js');
6
7
  var bundle = require('./api/bundle.js');
8
+ var subscription = require('./api/subscription.js');
7
9
  var init = require('./utils/init.js');
8
10
 
9
11
 
10
12
 
13
+ exports.login = auth.login;
14
+ exports.logout = auth.logout;
11
15
  exports.getBundleSettings = cdn.getBundleSettings;
12
16
  exports.getProduct = cdn.getProduct;
13
17
  exports.getProductAndSettings = cdn.getProductAndSettings;
@@ -18,6 +22,7 @@ exports.getWidgetSettings = cdn.getWidgetSettings;
18
22
  exports.resetCache = cdn.resetCache;
19
23
  exports.getBundleId = bundle.getBundleId;
20
24
  exports.validateBundle = bundle.validateBundle;
25
+ exports.listSubscriptions = subscription.listSubscriptions;
21
26
  exports.api = init.api;
22
27
  exports.initRecharge = init.initRecharge;
23
28
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -20,10 +20,32 @@ const api = {
20
20
  return request.request("delete", url, requestOptions);
21
21
  }
22
22
  };
23
- function initRecharge(opt) {
23
+ function getStoreIdentifier(storeIdentifier) {
24
+ var _a, _b;
25
+ if (storeIdentifier) {
26
+ return storeIdentifier;
27
+ }
28
+ if ((_a = window == null ? void 0 : window.Shopify) == null ? void 0 : _a.shop) {
29
+ return window.Shopify.shop;
30
+ }
31
+ let domain = window == null ? void 0 : window.domain;
32
+ if (!domain) {
33
+ const subdomain = (_b = location == null ? void 0 : location.href.match(/(?:http[s]*:\/\/)*(.*?)\.(?=admin\.rechargeapps\.com)/i)) == null ? void 0 : _b[1].replace(/-sp$/, "");
34
+ if (subdomain) {
35
+ domain = `${subdomain}.myshopify.com`;
36
+ }
37
+ }
38
+ if (domain) {
39
+ return domain;
40
+ }
41
+ throw new Error(`No storeIdentifier was passed into init.`);
42
+ }
43
+ function initRecharge(opt = {}) {
44
+ const hiddenOpts = opt;
24
45
  options.setOptions({
25
- storeIdentifier: opt.storeIdentifier,
26
- environment: opt.environment ? opt.environment : "prod"
46
+ storeIdentifier: getStoreIdentifier(opt.storeIdentifier),
47
+ environment: hiddenOpts.environment ? hiddenOpts.environment : "prod",
48
+ apiKey: hiddenOpts.apiKey ? hiddenOpts.apiKey : ""
27
49
  });
28
50
  cdn.resetCache();
29
51
  }
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\nexport interface InitOptions extends Omit<StorefrontOptions, 'environment'> {\n /** This is only for internal use. Sets the environment where data is fetched from. */\n environment?: StorefrontOptions['environment'];\n}\n\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\nexport function initRecharge(opt: InitOptions) {\n setOptions({\n storeIdentifier: opt.storeIdentifier,\n environment: opt.environment ? opt.environment : 'prod',\n });\n\n // When init is called again, reset the cache to make sure we don't have the old cache around\n resetCache();\n}\n"],"names":["request","setOptions","resetCache"],"mappings":";;;;;;;;AAGY,MAAC,GAAG,GAAG;AACnB,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc,EAAE;AAC3B,IAAI,OAAOA,eAAO,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC;AAC/C,GAAG;AACH,EAAE,IAAI,CAAC,GAAG,EAAE,cAAc,EAAE;AAC5B,IAAI,OAAOA,eAAO,CAAC,MAAM,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC;AAChD,GAAG;AACH,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc,EAAE;AAC3B,IAAI,OAAOA,eAAO,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC;AAC/C,GAAG;AACH,EAAE,MAAM,CAAC,GAAG,EAAE,cAAc,EAAE;AAC9B,IAAI,OAAOA,eAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,cAAc,CAAC,CAAC;AAClD,GAAG;AACH,EAAE;AACK,SAAS,YAAY,CAAC,GAAG,EAAE;AAClC,EAAEC,kBAAU,CAAC;AACb,IAAI,eAAe,EAAE,GAAG,CAAC,eAAe;AACxC,IAAI,WAAW,EAAE,GAAG,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,GAAG,MAAM;AAC3D,GAAG,CAAC,CAAC;AACL,EAAEC,cAAU,EAAE,CAAC;AACf;;;;;"}
1
+ {"version":3,"file":"init.js","sources":["../../../src/utils/init.ts"],"sourcesContent":["import { resetCache } from '../api/cdn';\nimport { StorefrontOptions, CRUDRequestOptions, GetRequestOptions } from '../types';\nimport { setOptions } from './options';\nimport { request } from './request';\n\n// This omits all of our 'hidden' variables. These can still be passed in, but won't have types generated for them\nexport type InitOptions = Omit<Partial<StorefrontOptions>, 'environment' | 'apiKey'>;\n\nexport const api = {\n get<T>(url: string, requestOptions?: GetRequestOptions): Promise<T> {\n return request<T>('get', url, requestOptions);\n },\n post<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('post', url, requestOptions);\n },\n put<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('put', url, requestOptions);\n },\n delete<T>(url: string, requestOptions?: CRUDRequestOptions): Promise<T> {\n return request<T>('delete', url, requestOptions);\n },\n};\n\n/**\n * Uses passed in storeIdentifier, but if it's not passed in will try to infer it.\n * Currently it will only infer if we are in the context of a Shopify store. This will not infer headless or hosted yet.\n */\nfunction getStoreIdentifier(storeIdentifier?: string): string {\n if (storeIdentifier) {\n return storeIdentifier;\n }\n\n // Infer's when on Shopify store (non headless)\n if (window?.Shopify?.shop) {\n return window.Shopify.shop;\n }\n\n // Domain exists on hosted themes. If it doesn't for some reason, get the subdomain and create the identifier\n let domain = window?.domain;\n if (!domain) {\n const subdomain = location?.href\n .match(/(?:http[s]*:\\/\\/)*(.*?)\\.(?=admin\\.rechargeapps\\.com)/i)?.[1]\n .replace(/-sp$/, '');\n if (subdomain) {\n domain = `${subdomain}.myshopify.com`;\n }\n }\n\n // Infer's when on Recharge hosted\n if (domain) {\n return domain;\n }\n\n throw new Error(`No storeIdentifier was passed into init.`);\n}\n\nexport function initRecharge(opt: InitOptions = {}) {\n const hiddenOpts = opt as StorefrontOptions;\n setOptions({\n storeIdentifier: getStoreIdentifier(opt.storeIdentifier),\n environment: hiddenOpts.environment ? hiddenOpts.environment : 'prod',\n apiKey: hiddenOpts.apiKey ? hiddenOpts.apiKey : '',\n });\n\n // When init is called again, reset the cache to make sure we don't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AAQ,CAAC,IAAI,CAAC,KAAK,CAAC,wDAAwD,CAAC,KAAK,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AACpL,IAAI,IAAI,SAAS,EAAE;AACnB,MAAM,MAAM,GAAG,CAAC,EAAE,SAAS,CAAC,cAAc,CAAC,CAAC;AAC5C,KAAK;AACL,GAAG;AACH,EAAE,IAAI,MAAM,EAAE;AACd,IAAI,OAAO,MAAM,CAAC;AAClB,GAAG;AACH,EAAE,MAAM,IAAI,KAAK,CAAC,CAAC,wCAAwC,CAAC,CAAC,CAAC;AAC9D,CAAC;AACM,SAAS,YAAY,CAAC,GAAG,GAAG,EAAE,EAAE;AACvC,EAAE,MAAM,UAAU,GAAG,GAAG,CAAC;AACzB,EAAEC,kBAAU,CAAC;AACb,IAAI,eAAe,EAAE,kBAAkB,CAAC,GAAG,CAAC,eAAe,CAAC;AAC5D,IAAI,WAAW,EAAE,UAAU,CAAC,WAAW,GAAG,UAAU,CAAC,WAAW,GAAG,MAAM;AACzE,IAAI,MAAM,EAAE,UAAU,CAAC,MAAM,GAAG,UAAU,CAAC,MAAM,GAAG,EAAE;AACtD,GAAG,CAAC,CAAC;AACL,EAAEC,cAAU,EAAE,CAAC;AACf;;;;;"}
@@ -4,7 +4,8 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  let options = {
6
6
  storeIdentifier: "",
7
- environment: "prod"
7
+ environment: "prod",
8
+ apiKey: ""
8
9
  };
9
10
  function setOptions(opts) {
10
11
  options = opts;
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","sources":["../../../src/utils/options.ts"],"sourcesContent":["import { StorefrontOptions } from '../types';\n\nlet options: StorefrontOptions = {\n storeIdentifier: '',\n environment: 'prod',\n};\n\nexport function setOptions(opts: StorefrontOptions) {\n options = opts;\n}\n\nexport function getOptions() {\n return options;\n}\n"],"names":[],"mappings":";;;;AAAA,IAAI,OAAO,GAAG;AACd,EAAE,eAAe,EAAE,EAAE;AACrB,EAAE,WAAW,EAAE,MAAM;AACrB,CAAC,CAAC;AACK,SAAS,UAAU,CAAC,IAAI,EAAE;AACjC,EAAE,OAAO,GAAG,IAAI,CAAC;AACjB,CAAC;AACM,SAAS,UAAU,GAAG;AAC7B,EAAE,OAAO,OAAO,CAAC;AACjB;;;;;"}
1
+ {"version":3,"file":"options.js","sources":["../../../src/utils/options.ts"],"sourcesContent":["import { StorefrontOptions } from '../types';\n\nlet options: StorefrontOptions = {\n storeIdentifier: '',\n environment: 'prod',\n apiKey: '',\n};\n\nexport function setOptions(opts: StorefrontOptions) {\n options = opts;\n}\n\nexport function getOptions() {\n return options;\n}\n"],"names":[],"mappings":";;;;AAAA,IAAI,OAAO,GAAG;AACd,EAAE,eAAe,EAAE,EAAE;AACrB,EAAE,WAAW,EAAE,MAAM;AACrB,EAAE,MAAM,EAAE,EAAE;AACZ,CAAC,CAAC;AACK,SAAS,UAAU,CAAC,IAAI,EAAE;AACjC,EAAE,OAAO,GAAG,IAAI,CAAC;AACjB,CAAC;AACM,SAAS,UAAU,GAAG;AAC7B,EAAE,OAAO,OAAO,CAAC;AACjB;;;;;"}
@@ -3,12 +3,16 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  require('isomorphic-fetch');
6
+ var Cookies = require('js-cookie');
6
7
  var qs = require('qs');
7
8
  var trimStart = require('lodash/trimStart');
8
9
  var trimEnd = require('lodash/trimEnd');
10
+ var options = require('./options.js');
11
+ var api = require('../constants/api.js');
9
12
 
10
13
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
14
 
15
+ var Cookies__default = /*#__PURE__*/_interopDefaultLegacy(Cookies);
12
16
  var trimStart__default = /*#__PURE__*/_interopDefaultLegacy(trimStart);
13
17
  var trimEnd__default = /*#__PURE__*/_interopDefaultLegacy(trimEnd);
14
18
 
@@ -35,6 +39,36 @@ function stringifyQuery(str) {
35
39
  arrayFormat: "comma"
36
40
  });
37
41
  }
42
+ async function cdnRequest(method, url, requestOptions = {}) {
43
+ const opts = options.getOptions();
44
+ return request(method, `${api.RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);
45
+ }
46
+ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}) {
47
+ var _a;
48
+ const opts = options.getOptions();
49
+ const token = (_a = Cookies__default["default"].get("recharge-session")) != null ? _a : opts.apiKey;
50
+ if (!token) {
51
+ throw new Error("No API Key or token found.");
52
+ }
53
+ const rechargeBaseUrl = api.RECHARGE_API_URL(opts.environment);
54
+ const reqHeaders = __spreadValues({
55
+ "Content-Type": "application/json",
56
+ "X-Recharge-Access-Token": token,
57
+ "X-Recharge-Version": "2021-11",
58
+ "X-Recharge-App": "storefront-client"
59
+ }, headers ? headers : {});
60
+ const localQuery = __spreadValues({
61
+ shop_url: opts.storeIdentifier
62
+ }, query);
63
+ return request(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });
64
+ }
65
+ async function shopifyAppProxyRequest(method, url, { id, query, data, headers } = {}) {
66
+ const reqHeaders = __spreadValues({
67
+ "Content-Type": "application/json",
68
+ "X-Recharge-App": "storefront-client"
69
+ }, headers ? headers : {});
70
+ return request(method, `${api.SHOPIFY_APP_PROXY_URL}${url}`, { id, query, data, headers: reqHeaders });
71
+ }
38
72
  async function request(method, url, { id, query, data, headers } = {}) {
39
73
  let reqUrl = url;
40
74
  if (id) {
@@ -69,5 +103,8 @@ async function request(method, url, { id, query, data, headers } = {}) {
69
103
  return result;
70
104
  }
71
105
 
106
+ exports.cdnRequest = cdnRequest;
107
+ exports.rechargeApiRequest = rechargeApiRequest;
72
108
  exports.request = request;
109
+ exports.shopifyAppProxyRequest = shopifyAppProxyRequest;
73
110
  //# sourceMappingURL=request.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport { stringify } from 'qs';\nimport trimStart from 'lodash/trimStart';\nimport trimEnd from 'lodash/trimEnd';\n\nimport { Method, RequestHeaders, RequestOptions } from '../types';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url;\n\n if (id) {\n reqUrl = [trimEnd(url), trimStart(id as string)].join('/');\n }\n\n let reqBody;\n if (method === 'get') {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n } else {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n // 'Content-Type': 'application/json',\n // 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n mode: 'cors',\n });\n\n const result = await response.json();\n\n if (!response.ok) {\n if (result && result.error) {\n throw new Error(`${response.status}: ${result.error}`);\n } else {\n throw new Error('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["stringify","trimEnd","trimStart"],"mappings":";;;;;;;;;;;;;;AAAA,IAAI,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC;AACtC,IAAI,mBAAmB,GAAG,MAAM,CAAC,qBAAqB,CAAC;AACvD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,oBAAoB,CAAC;AACzD,IAAI,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,KAAK,GAAG,IAAI,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,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,CAAC;AAC7D,KAAK,MAAM;AACX,MAAM,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;AAC9E,KAAK;AACL,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import 'isomorphic-fetch';\n\nimport Cookies from 'js-cookie';\nimport { stringify } from 'qs';\nimport trimStart from 'lodash/trimStart';\nimport trimEnd from 'lodash/trimEnd';\n\nimport { Method, RequestHeaders, RequestOptions } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\n\nfunction stringifyQuery(str: unknown): string {\n return stringify(str, {\n encode: false,\n indices: false,\n arrayFormat: 'comma',\n });\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const opts = getOptions();\n const token = Cookies.get('recharge-session') ?? opts.apiKey;\n if (!token) {\n throw new Error('No API Key or token found.');\n }\n const rechargeBaseUrl = RECHARGE_API_URL(opts.environment);\n const reqHeaders: RequestHeaders = {\n 'Content-Type': 'application/json',\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const localQuery = {\n shop_url: opts.storeIdentifier,\n ...(query as any),\n };\n\n return request(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const reqHeaders: RequestHeaders = {\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, { id, query, data, headers: reqHeaders });\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url;\n\n if (id) {\n reqUrl = [trimEnd(url), trimStart(id as string)].join('/');\n }\n\n let reqBody;\n if (method === 'get') {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n } else {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n // 'Content-Type': 'application/json',\n // 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n mode: 'cors',\n });\n\n const result = await response.json();\n\n if (!response.ok) {\n if (result && result.error) {\n throw new Error(`${response.status}: ${result.error}`);\n } else {\n throw new Error('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["stringify","getOptions","RECHARGE_CDN_URL","Cookies","RECHARGE_API_URL","SHOPIFY_APP_PROXY_URL","trimEnd","trimStart"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,IAAI,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC;AACtC,IAAI,mBAAmB,GAAG,MAAM,CAAC,qBAAqB,CAAC;AACvD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC;AACnD,IAAI,YAAY,GAAG,MAAM,CAAC,SAAS,CAAC,oBAAoB,CAAC;AACzD,IAAI,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,KAAK,GAAG,IAAI,GAAG,GAAG,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI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ACnC,GAAG;AACH,EAAE,MAAM,UAAU,GAAG,cAAc,CAAC;AACpC,IAAI,MAAM,EAAE,kBAAkB;AAC9B,GAAG,EAAE,OAAO,GAAG,OAAO,GAAG,EAAE,CAAC,CAAC;AAC7B,EAAE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,MAAM,EAAE;AACvC,IAAI,MAAM;AACV,IAAI,OAAO,EAAE,UAAU;AACvB,IAAI,IAAI,EAAE,OAAO;AACjB,IAAI,IAAI,EAAE,MAAM;AAChB,GAAG,CAAC,CAAC;AACL,EAAE,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;AACvC,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;AACpB,IAAI,IAAI,MAAM,IAAI,MAAM,CAAC,KAAK,EAAE;AAChC,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC7D,KAAK,MAAM;AACX,MAAM,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;AAC9E,KAAK;AACL,GAAG;AACH,EAAE,OAAO,MAAM,CAAC;AAChB;;;;;;;"}
@@ -0,0 +1,20 @@
1
+ import Cookies from 'js-cookie';
2
+ import { shopifyAppProxyRequest } from '../utils/request.js';
3
+
4
+ const login = async () => {
5
+ const response = await shopifyAppProxyRequest("get", "/logged_in_customer_poc");
6
+ if (response.api_token) {
7
+ const expires = new Date();
8
+ expires.setHours(expires.getHours() + 1);
9
+ Cookies.set("recharge-session", response.api_token, { expires });
10
+ } else {
11
+ Cookies.remove("recharge-session");
12
+ }
13
+ return !!response.api_token;
14
+ };
15
+ const logout = () => {
16
+ Cookies.remove("recharge-session");
17
+ };
18
+
19
+ export { login, logout };
20
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import Cookies from 'js-cookie';\nimport { shopifyAppProxyRequest } from '../utils/request';\nimport { LoginResponse } from '../types/auth';\n\nexport const login = async (): Promise<boolean> => {\n const response = await shopifyAppProxyRequest<LoginResponse | Partial<LoginResponse>>(\n 'get',\n '/logged_in_customer_poc'\n );\n\n if (response.api_token) {\n const expires = new Date();\n expires.setHours(expires.getHours() + 1);\n Cookies.set('recharge-session', response.api_token, { expires });\n } else {\n Cookies.remove('recharge-session');\n }\n\n return !!response.api_token;\n};\n\nexport const logout = (): void => {\n Cookies.remove('recharge-session');\n};\n"],"names":[],"mappings":";;;AAEY,MAAC,KAAK,GAAG,YAAY;AACjC,EAAE,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,KAAK,EAAE,yBAAyB,CAAC,CAAC;AAClF,EAAE,IAAI,QAAQ,CAAC,SAAS,EAAE;AAC1B,IAAI,MAAM,OAAO,GAAG,IAAI,IAAI,EAAE,CAAC;AAC/B,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;AAC7C,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,QAAQ,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACrE,GAAG,MAAM;AACT,IAAI,OAAO,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACvC,GAAG;AACH,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC;AAC9B,EAAE;AACU,MAAC,MAAM,GAAG,MAAM;AAC5B,EAAE,OAAO,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;AACrC;;;;"}
@@ -1,16 +1,15 @@
1
1
  import { toLineItemProperty } from '@recharge-packages/bundling-data';
2
- import { request } from '../utils/request.js';
2
+ import { shopifyAppProxyRequest } from '../utils/request.js';
3
3
  import { getOptions } from '../utils/options.js';
4
4
  import { getBundleSettings } from './cdn.js';
5
5
 
6
- const STORE_FRONT_MANAGER_URL = "/tools/recurring/bundling-storefront-manager";
6
+ const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
7
7
  function getTimestampSecondsFromClient() {
8
8
  return Math.ceil(Date.now() / 1e3);
9
9
  }
10
- async function getTimestampSecondsFromServer(request2) {
11
- const url = `${STORE_FRONT_MANAGER_URL}/t`;
10
+ async function getTimestampSecondsFromServer() {
12
11
  try {
13
- const { timestamp } = await request2("get", url, {
12
+ const { timestamp } = await shopifyAppProxyRequest("get", `${STORE_FRONT_MANAGER_URL}/t`, {
14
13
  headers: { "X-Recharge-App": "storefront-client" }
15
14
  });
16
15
  return timestamp;
@@ -25,7 +24,7 @@ const getBundleId = async (bundle) => {
25
24
  if (!isValid) {
26
25
  throw new Error("Bundle selection is invalid.");
27
26
  }
28
- const timestampSeconds = await getTimestampSecondsFromServer(request);
27
+ const timestampSeconds = await getTimestampSecondsFromServer();
29
28
  const bundleData = toLineItemProperty({
30
29
  variantId: bundle.externalVariantId,
31
30
  version: timestampSeconds,
@@ -40,15 +39,12 @@ const getBundleId = async (bundle) => {
40
39
  })
41
40
  });
42
41
  try {
43
- const STORE_FRONT_BUNDLE_URL = `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`;
44
- const payload = await request("post", STORE_FRONT_BUNDLE_URL, {
42
+ const payload = await shopifyAppProxyRequest("post", `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`, {
45
43
  data: {
46
44
  bundle: bundleData
47
45
  },
48
46
  headers: {
49
- "Content-Type": "application/json",
50
- Origin: `https://${opts.storeIdentifier}`,
51
- "X-Recharge-App": "storefront-client"
47
+ Origin: `https://${opts.storeIdentifier}`
52
48
  }
53
49
  });
54
50
  if (!payload.id || payload.code !== 200) {
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { toLineItemProperty } from '@recharge-packages/bundling-data';\nimport { Request, Bundle } from '../types';\nimport { request } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getBundleSettings } from './cdn';\n\nconst STORE_FRONT_MANAGER_URL = '/tools/recurring/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(request: Request): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n const url = `${STORE_FRONT_MANAGER_URL}/t`;\n\n try {\n const { timestamp } = await request<{ timestamp: number }>('get', url, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport const getBundleId = async (bundle: Bundle): Promise<string> => {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (!isValid) {\n throw new Error('Bundle selection is invalid.');\n }\n const timestampSeconds = await getTimestampSecondsFromServer(request);\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const STORE_FRONT_BUNDLE_URL = `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`;\n const payload = await request<{ id: string; code: number; message: string }>('post', STORE_FRONT_BUNDLE_URL, {\n data: {\n bundle: bundleData,\n },\n headers: {\n 'Content-Type': 'application/json',\n Origin: `https://${opts.storeIdentifier}`,\n 'X-Recharge-App': 'storefront-client',\n },\n });\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n};\n\nexport const validateBundle = async (bundle: Bundle): Promise<boolean> => {\n try {\n const bundleSettings = await getBundleSettings(bundle.externalProductId);\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n return !!bundle && !!bundleSettings;\n } catch (e) {\n console.error('Error fetching bundle settings');\n return false;\n }\n};\n"],"names":[],"mappings":";;;;;AAIA,MAAM,uBAAuB,GAAG,8CAA8C,CAAC;AAC/E,SAAS,6BAA6B,GAAG;AACzC,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC;AACrC,CAAC;AACD,eAAe,6BAA6B,CAAC,QAAQ,EAAE;AACvD,EAAE,MAAM,GAAG,GAAG,CAAC,EAAE,uBAAuB,CAAC,EAAE,CAAC,CAAC;AAC7C,EAAE,IAAI;AACN,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,QAAQ,CAAC,KAAK,EAAE,GAAG,EAAE;AACrD,MAAM,OAAO,EAAE,EAAE,gBAAgB,EAAE,mBAAmB,EAAE;AACxD,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,SAAS,CAAC;AACrB,GAAG,CAAC,OAAO,EAAE,EAAE;AACf,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAClE,IAAI,OAAO,6BAA6B,EAAE,CAAC;AAC3C,GAAG;AACH,CAAC;AACW,MAAC,WAAW,GAAG,OAAO,MAAM,KAAK;AAC7C,EAAE,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;AAC5B,EAAE,MAAM,OAAO,GAAG,MAAM,cAAc,CAAC,MAAM,CAAC,CAAC;AAC/C,EAAE,IAAI,CAAC,OAAO,EAAE;AAChB,IAAI,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;AACpD,GAAG;AACH,EAAE,MAAM,gBAAgB,GAAG,MAAM,6BAA6B,CAAC,OAAO,CAAC,CAAC;AACxE,EAAE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAC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,CAAC,CAAC,CAAC,CAAC;AACvD,GAAG;AACH,EAAE;AACU,MAAC,cAAc,GAAG,OAAO,MAAM,KAAK;AAChD,EAAE,IAAI;AACN,IAAI,MAAM,cAAc,GAAG,MAAM,iBAAiB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;AAC7E,IAAI,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,cAAc,CAAC;AACxC,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { toLineItemProperty } from '@recharge-packages/bundling-data';\nimport { Bundle } from '../types';\nimport { shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getBundleSettings } from './cdn';\n\nconst STORE_FRONT_MANAGER_URL = '/bundling-storefront-manager';\n\nfunction getTimestampSecondsFromClient(): number {\n /**\n * Get the current unix epoch in seconds from the client-side.\n */\n return Math.ceil(Date.now() / 1000);\n}\n\nasync function getTimestampSecondsFromServer(): Promise<number> {\n /**\n * Get the unix epoch from the server instead of using it directly from the\n * client. This must reduce even more the number of invalid Bundles.\n */\n try {\n const { timestamp } = await shopifyAppProxyRequest<{ timestamp: number }>('get', `${STORE_FRONT_MANAGER_URL}/t`, {\n headers: { 'X-Recharge-App': 'storefront-client' },\n });\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport const getBundleId = async (bundle: Bundle): Promise<string> => {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (!isValid) {\n throw new Error('Bundle selection is invalid.');\n }\n const timestampSeconds = await getTimestampSecondsFromServer();\n const bundleData = toLineItemProperty({\n variantId: bundle.externalVariantId,\n version: timestampSeconds,\n items: bundle.selections.map(item => {\n return {\n collectionId: item.collectionId,\n productId: item.externalProductId,\n variantId: item.externalVariantId,\n quantity: item.quantity,\n sku: '',\n };\n }),\n });\n\n try {\n const payload = await shopifyAppProxyRequest<{ id: string; code: number; message: string }>(\n 'post',\n `${STORE_FRONT_MANAGER_URL}/api/v1/bundles`,\n {\n data: {\n bundle: bundleData,\n },\n headers: {\n Origin: `https://${opts.storeIdentifier}`,\n },\n }\n );\n\n if (!payload.id || payload.code !== 200) {\n throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);\n }\n\n return payload.id;\n } catch (e) {\n // Handle NetworkError exceptions\n throw new Error(`2: failed generating rb_id ${e}`);\n }\n};\n\nexport const validateBundle = async (bundle: Bundle): Promise<boolean> => {\n try {\n const bundleSettings = await getBundleSettings(bundle.externalProductId);\n // once we implement this function, we can make it raise an exception\n // we could also have a local store relative to this function so we don't have to pass bundleProduct\n return !!bundle && !!bundleSettings;\n } catch (e) {\n console.error('Error fetching bundle settings');\n return false;\n }\n};\n"],"names":[],"mappings":";;;;;AAIA,MAAM,uBAAuB,GAAG,8BAA8B,CAAC;AAC/D,SAAS,6BAA6B,GAAG;AACzC,EAAE,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC;AACrC,CAAC;AACD,eAAe,6BAA6B,GAAG;AAC/C,EAAE,IAAI;AACN,IAAI,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,sBAAsB,CAAC,KAAK,EAAE,CAAC,EAAE,uBAAuB,CAAC,EAAE,CAAC,EAAE;AAC9F,MAAM,OAAO,EAAE,EAAE,gBAAgB,EAAE,mBAAmB,EAAE;AACxD,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,SAAS,CAAC;AACrB,GAAG,CAAC,OAAO,EAAE,EAAE;AACf,IAAI,OAAO,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,EAAE,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAClE,IAAI,O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O,CAAC,IAAI,KAAK,GAAG,EAAE;AAC7C,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,4BAA4B,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAChF,KAAK;AACL,IAAI,OAAO,OAAO,CAAC,EAAE,CAAC;AACtB,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,2BAA2B,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AACvD,GAAG;AACH,EAAE;AACU,MAAC,cAAc,GAAG,OAAO,MAAM,KAAK;AAChD,EAAE,IAAI;AACN,IAAI,MAAM,cAAc,GAAG,MAAM,iBAAiB,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;AAC7E,IAAI,OAAO,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,cAAc,CAAC;AACxC,GAAG,CAAC,OAAO,CAAC,EAAE;AACd,IAAI,OAAO,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,IAAI,OAAO,KAAK,CAAC;AACjB,GAAG;AACH;;;;"}
@@ -1,7 +1,5 @@
1
- import { RECHARGE_CDN_URL } from '../constants/api.js';
2
1
  import { productMapper, widgetSettingsMapper, productArrayMapper } from '../mappers/cdn.js';
3
- import { request } from '../utils/request.js';
4
- import { getOptions } from '../utils/options.js';
2
+ import { cdnRequest } from '../utils/request.js';
5
3
 
6
4
  const CDN_VERSION = "2020-12";
7
5
  const DEFAULT_STORE_SETTINGS = {
@@ -14,33 +12,29 @@ const DEFAULT_STORE_SETTINGS = {
14
12
  }
15
13
  };
16
14
  const promiseCache = /* @__PURE__ */ new Map();
17
- function cacheRequest(cacheKey, request2) {
15
+ function cacheRequest(cacheKey, request) {
18
16
  if (!promiseCache.has(cacheKey)) {
19
- promiseCache.set(cacheKey, request2());
17
+ promiseCache.set(cacheKey, request());
20
18
  }
21
19
  return promiseCache.get(cacheKey);
22
20
  }
23
21
  const getProduct = async (externalProductId) => {
24
- const opts = getOptions();
25
- const { product } = await cacheRequest(`product.${externalProductId}`, () => request("get", `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/product/${CDN_VERSION}/${externalProductId}.json`));
22
+ const { product } = await cacheRequest(`product.${externalProductId}`, () => cdnRequest("get", `/product/${CDN_VERSION}/${externalProductId}.json`));
26
23
  return productMapper(product);
27
24
  };
28
25
  const getStoreSettings = async () => {
29
- const opts = getOptions();
30
- const storeSettings = await cacheRequest("storeSettings", () => request("get", `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/store_settings.json`).catch(() => {
26
+ const storeSettings = await cacheRequest("storeSettings", () => cdnRequest("get", `/${CDN_VERSION}/store_settings.json`).catch(() => {
31
27
  return DEFAULT_STORE_SETTINGS;
32
28
  }));
33
29
  return storeSettings;
34
30
  };
35
31
  const getWidgetSettings = async () => {
36
- const opts = getOptions();
37
- const { widget_settings } = await cacheRequest("widgetSettings", () => request("get", `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/${CDN_VERSION}/widget_settings.json`));
32
+ const { widget_settings } = await cacheRequest("widgetSettings", () => cdnRequest("get", `/${CDN_VERSION}/widget_settings.json`));
38
33
  const widgetSettings = widgetSettingsMapper(widget_settings);
39
34
  return widgetSettings;
40
35
  };
41
36
  const getProductsAndSettings = async () => {
42
- const opts = getOptions();
43
- const { products, widget_settings, store_settings, meta } = await cacheRequest("productsAndSettings", () => request("get", `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}/product/${CDN_VERSION}/products.json`));
37
+ const { products, widget_settings, store_settings, meta } = await cacheRequest("productsAndSettings", () => cdnRequest("get", `/product/${CDN_VERSION}/products.json`));
44
38
  if ((meta == null ? void 0 : meta.status) === "error") {
45
39
  return Promise.reject(meta.message);
46
40
  }