@rechargeapps/storefront-client 1.28.0 → 1.28.1

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 (71) hide show
  1. package/dist/cjs/api/address.js +15 -0
  2. package/dist/cjs/api/address.js.map +1 -1
  3. package/dist/cjs/api/auth.js +40 -1
  4. package/dist/cjs/api/auth.js.map +1 -1
  5. package/dist/cjs/api/bundle.js +12 -0
  6. package/dist/cjs/api/bundle.js.map +1 -1
  7. package/dist/cjs/api/cdn.js +3 -0
  8. package/dist/cjs/api/cdn.js.map +1 -1
  9. package/dist/cjs/api/charge.js +24 -0
  10. package/dist/cjs/api/charge.js.map +1 -1
  11. package/dist/cjs/api/collection.js +6 -0
  12. package/dist/cjs/api/collection.js.map +1 -1
  13. package/dist/cjs/api/customer.js +6 -0
  14. package/dist/cjs/api/customer.js.map +1 -1
  15. package/dist/cjs/api/gift.js +3 -0
  16. package/dist/cjs/api/gift.js.map +1 -1
  17. package/dist/cjs/api/membership.js +12 -0
  18. package/dist/cjs/api/membership.js.map +1 -1
  19. package/dist/cjs/api/membershipProgram.js +3 -0
  20. package/dist/cjs/api/membershipProgram.js.map +1 -1
  21. package/dist/cjs/api/metafield.js +6 -0
  22. package/dist/cjs/api/metafield.js.map +1 -1
  23. package/dist/cjs/api/onetime.js +9 -0
  24. package/dist/cjs/api/onetime.js.map +1 -1
  25. package/dist/cjs/api/order.js +3 -0
  26. package/dist/cjs/api/order.js.map +1 -1
  27. package/dist/cjs/api/paymentMethod.js +6 -0
  28. package/dist/cjs/api/paymentMethod.js.map +1 -1
  29. package/dist/cjs/api/plan.js +3 -0
  30. package/dist/cjs/api/plan.js.map +1 -1
  31. package/dist/cjs/api/subscription.js +30 -0
  32. package/dist/cjs/api/subscription.js.map +1 -1
  33. package/dist/cjs/utils/request.js +7 -1
  34. package/dist/cjs/utils/request.js.map +1 -1
  35. package/dist/esm/api/address.js +15 -0
  36. package/dist/esm/api/address.js.map +1 -1
  37. package/dist/esm/api/auth.js +40 -1
  38. package/dist/esm/api/auth.js.map +1 -1
  39. package/dist/esm/api/bundle.js +12 -0
  40. package/dist/esm/api/bundle.js.map +1 -1
  41. package/dist/esm/api/cdn.js +3 -0
  42. package/dist/esm/api/cdn.js.map +1 -1
  43. package/dist/esm/api/charge.js +24 -0
  44. package/dist/esm/api/charge.js.map +1 -1
  45. package/dist/esm/api/collection.js +6 -0
  46. package/dist/esm/api/collection.js.map +1 -1
  47. package/dist/esm/api/customer.js +6 -0
  48. package/dist/esm/api/customer.js.map +1 -1
  49. package/dist/esm/api/gift.js +3 -0
  50. package/dist/esm/api/gift.js.map +1 -1
  51. package/dist/esm/api/membership.js +12 -0
  52. package/dist/esm/api/membership.js.map +1 -1
  53. package/dist/esm/api/membershipProgram.js +3 -0
  54. package/dist/esm/api/membershipProgram.js.map +1 -1
  55. package/dist/esm/api/metafield.js +6 -0
  56. package/dist/esm/api/metafield.js.map +1 -1
  57. package/dist/esm/api/onetime.js +9 -0
  58. package/dist/esm/api/onetime.js.map +1 -1
  59. package/dist/esm/api/order.js +3 -0
  60. package/dist/esm/api/order.js.map +1 -1
  61. package/dist/esm/api/paymentMethod.js +6 -0
  62. package/dist/esm/api/paymentMethod.js.map +1 -1
  63. package/dist/esm/api/plan.js +3 -0
  64. package/dist/esm/api/plan.js.map +1 -1
  65. package/dist/esm/api/subscription.js +30 -0
  66. package/dist/esm/api/subscription.js.map +1 -1
  67. package/dist/esm/utils/request.js +7 -1
  68. package/dist/esm/utils/request.js.map +1 -1
  69. package/dist/index.d.ts +1 -1
  70. package/dist/umd/recharge-client.min.js +13 -13
  71. package/package.json +1 -1
@@ -9,6 +9,9 @@ function listAddresses(session, query) {
9
9
  );
10
10
  }
11
11
  async function getAddress(session, id, options) {
12
+ if (id === void 0 || id === "") {
13
+ throw new Error("ID is required");
14
+ }
12
15
  const { address } = await rechargeApiRequest(
13
16
  "get",
14
17
  `/addresses`,
@@ -30,6 +33,9 @@ async function createAddress(session, createRequest) {
30
33
  return address;
31
34
  }
32
35
  async function updateAddress(session, id, updateRequest, query) {
36
+ if (id === void 0 || id === "") {
37
+ throw new Error("ID is required");
38
+ }
33
39
  const { address } = await rechargeApiRequest(
34
40
  "put",
35
41
  `/addresses`,
@@ -49,9 +55,15 @@ async function applyDiscountToAddress(session, id, discountCode, query) {
49
55
  );
50
56
  }
51
57
  async function removeDiscountsFromAddress(session, id, query) {
58
+ if (id === void 0 || id === "") {
59
+ throw new Error("Id is required");
60
+ }
52
61
  return updateAddress(getInternalSession(session, "removeDiscountsFromAddress"), id, { discounts: [] }, query);
53
62
  }
54
63
  function deleteAddress(session, id) {
64
+ if (id === void 0 || id === "") {
65
+ throw new Error("ID is required");
66
+ }
55
67
  return rechargeApiRequest("delete", `/addresses`, { id }, getInternalSession(session, "deleteAddress"));
56
68
  }
57
69
  async function mergeAddresses(session, mergeRequest) {
@@ -66,6 +78,9 @@ async function mergeAddresses(session, mergeRequest) {
66
78
  return address;
67
79
  }
68
80
  async function skipFutureCharge(session, id, skipRequest) {
81
+ if (id === void 0 || id === "") {
82
+ throw new Error("ID is required");
83
+ }
69
84
  const { charge } = await rechargeApiRequest(
70
85
  "post",
71
86
  `/addresses/${id}/charges/skip`,
@@ -1 +1 @@
1
- {"version":3,"file":"address.js","sources":["../../../src/api/address.ts"],"sourcesContent":["import { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport {\n AddressResponse,\n AddressListParams,\n CreateAddressRequest,\n UpdateAddressRequest,\n AddressListResponse,\n MergeAddressesRequest,\n SkipFutureChargeAddressRequest,\n SkipFutureChargeAddressResponse,\n GetAddressOptions,\n Session,\n UpdateAddressParams,\n} from '../types';\n\n/** Returns all addresses from the store, or addresses for the customer given in the parameter. */\nexport function listAddresses(session: Session, query?: AddressListParams) {\n return rechargeApiRequest<AddressListResponse>(\n 'get',\n `/addresses`,\n { query },\n getInternalSession(session, 'listAddresses')\n );\n}\n\n/** Retrieves address for customer based on specified address id. */\nexport async function getAddress(session: Session, id: string | number, options?: GetAddressOptions) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'get',\n `/addresses`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getAddress')\n );\n return address;\n}\n\n/** Create a new address for a customer. */\nexport async function createAddress(session: Session, createRequest: CreateAddressRequest) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'post',\n `/addresses`,\n { data: { customer_id: session.customerId ? Number(session.customerId) : undefined, ...createRequest } },\n getInternalSession(session, 'createAddress')\n );\n return address;\n}\n\n/** Updates an existing address to match the specified parameters. */\nexport async function updateAddress(\n session: Session,\n id: string | number,\n updateRequest: UpdateAddressRequest,\n query?: UpdateAddressParams\n) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'put',\n `/addresses`,\n { id, data: updateRequest, query },\n getInternalSession(session, 'updateAddress')\n );\n return address;\n}\n\n/** Apply discount code to an address. Addresses are currently limited to a single discount. */\nexport async function applyDiscountToAddress(\n session: Session,\n id: string | number,\n discountCode: string,\n query?: UpdateAddressParams\n) {\n return updateAddress(\n getInternalSession(session, 'applyDiscountToAddress'),\n id,\n {\n discounts: [{ code: discountCode }],\n },\n query\n );\n}\n\n/** Removes all discounts from an address. */\nexport async function removeDiscountsFromAddress(session: Session, id: string | number, query?: UpdateAddressParams) {\n return updateAddress(getInternalSession(session, 'removeDiscountsFromAddress'), id, { discounts: [] }, query);\n}\n\n/** Deletes an address. Only Addresses with no active Subscriptions can be deleted. */\nexport function deleteAddress(session: Session, id: string | number) {\n return rechargeApiRequest<void>('delete', `/addresses`, { id }, getInternalSession(session, 'deleteAddress'));\n}\n\n/**\n * Merges up to 10 source addresses into 1 target address.\n */\nexport async function mergeAddresses(session: Session, mergeRequest: MergeAddressesRequest) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'post',\n `/addresses/merge`,\n {\n data: mergeRequest,\n },\n getInternalSession(session, 'mergeAddresses')\n );\n return address;\n}\n\n/**\n * Skip a Charge in the future for one or multiple Subscriptions associated with the Address.\n */\nexport async function skipFutureCharge(\n session: Session,\n id: string | number,\n skipRequest: SkipFutureChargeAddressRequest\n) {\n const { charge } = await rechargeApiRequest<SkipFutureChargeAddressResponse>(\n 'post',\n `/addresses/${id}/charges/skip`,\n {\n data: skipRequest,\n },\n getInternalSession(session, 'skipFutureCharge')\n );\n return charge;\n}\n"],"names":[],"mappings":";;AAgBgB,SAAA,aAAA,CAAc,SAAkB,KAA2B,EAAA;AACzE,EAAO,OAAA,kBAAA;AAAA,IACL,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA,EAAE,KAAM,EAAA;AAAA,IACR,kBAAA,CAAmB,SAAS,eAAe,CAAA;AAAA,GAC7C,CAAA;AACF,CAAA;AAGsB,eAAA,UAAA,CAAW,OAAkB,EAAA,EAAA,EAAqB,OAA6B,EAAA;AACnG,EAAM,MAAA,EAAE,OAAQ,EAAA,GAAI,MAAM,kBAAA;AAAA,IACxB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,KAAO,EAAA,EAAE,OAAS,EAAA,OAAA,EAAS,OAAQ,EAAA;AAAA,KACrC;AAAA,IACA,kBAAA,CAAmB,SAAS,YAAY,CAAA;AAAA,GAC1C,CAAA;AACA,EAAO,OAAA,OAAA,CAAA;AACT,CAAA;AAGsB,eAAA,aAAA,CAAc,SAAkB,aAAqC,EAAA;AACzF,EAAM,MAAA,EAAE,OAAQ,EAAA,GAAI,MAAM,kBAAA;AAAA,IACxB,MAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA,EAAE,IAAA,EAAM,EAAE,WAAA,EAAa,OAAQ,CAAA,UAAA,GAAa,MAAO,CAAA,OAAA,CAAQ,UAAU,CAAA,GAAI,KAAW,CAAA,EAAA,GAAG,eAAgB,EAAA;AAAA,IACvG,kBAAA,CAAmB,SAAS,eAAe,CAAA;AAAA,GAC7C,CAAA;AACA,EAAO,OAAA,OAAA,CAAA;AACT,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;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,gBAAgB,CAAA;AAAA,GAC9C,CAAA;AACA,EAAO,OAAA,OAAA,CAAA;AACT,CAAA;AAKsB,eAAA,gBAAA,CACpB,OACA,EAAA,EAAA,EACA,WACA,EAAA;AACA,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,MAAA;AAAA,IACA,cAAc,EAAE,CAAA,aAAA,CAAA;AAAA,IAChB;AAAA,MACE,IAAM,EAAA,WAAA;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,kBAAkB,CAAA;AAAA,GAChD,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"address.js","sources":["../../../src/api/address.ts"],"sourcesContent":["import { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport {\n AddressResponse,\n AddressListParams,\n CreateAddressRequest,\n UpdateAddressRequest,\n AddressListResponse,\n MergeAddressesRequest,\n SkipFutureChargeAddressRequest,\n SkipFutureChargeAddressResponse,\n GetAddressOptions,\n Session,\n UpdateAddressParams,\n} from '../types';\n\n/** Returns all addresses from the store, or addresses for the customer given in the parameter. */\nexport function listAddresses(session: Session, query?: AddressListParams) {\n return rechargeApiRequest<AddressListResponse>(\n 'get',\n `/addresses`,\n { query },\n getInternalSession(session, 'listAddresses')\n );\n}\n\n/** Retrieves address for customer based on specified address id. */\nexport async function getAddress(session: Session, id: string | number, options?: GetAddressOptions) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'get',\n `/addresses`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getAddress')\n );\n return address;\n}\n\n/** Create a new address for a customer. */\nexport async function createAddress(session: Session, createRequest: CreateAddressRequest) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'post',\n `/addresses`,\n { data: { customer_id: session.customerId ? Number(session.customerId) : undefined, ...createRequest } },\n getInternalSession(session, 'createAddress')\n );\n return address;\n}\n\n/** Updates an existing address to match the specified parameters. */\nexport async function updateAddress(\n session: Session,\n id: string | number,\n updateRequest: UpdateAddressRequest,\n query?: UpdateAddressParams\n) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'put',\n `/addresses`,\n { id, data: updateRequest, query },\n getInternalSession(session, 'updateAddress')\n );\n return address;\n}\n\n/** Apply discount code to an address. Addresses are currently limited to a single discount. */\nexport async function applyDiscountToAddress(\n session: Session,\n id: string | number,\n discountCode: string,\n query?: UpdateAddressParams\n) {\n return updateAddress(\n getInternalSession(session, 'applyDiscountToAddress'),\n id,\n {\n discounts: [{ code: discountCode }],\n },\n query\n );\n}\n\n/** Removes all discounts from an address. */\nexport async function removeDiscountsFromAddress(session: Session, id: string | number, query?: UpdateAddressParams) {\n if (id === undefined || id === '') {\n throw new Error('Id is required');\n }\n return updateAddress(getInternalSession(session, 'removeDiscountsFromAddress'), id, { discounts: [] }, query);\n}\n\n/** Deletes an address. Only Addresses with no active Subscriptions can be deleted. */\nexport function deleteAddress(session: Session, id: string | number) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n return rechargeApiRequest<void>('delete', `/addresses`, { id }, getInternalSession(session, 'deleteAddress'));\n}\n\n/**\n * Merges up to 10 source addresses into 1 target address.\n */\nexport async function mergeAddresses(session: Session, mergeRequest: MergeAddressesRequest) {\n const { address } = await rechargeApiRequest<AddressResponse>(\n 'post',\n `/addresses/merge`,\n {\n data: mergeRequest,\n },\n getInternalSession(session, 'mergeAddresses')\n );\n return address;\n}\n\n/**\n * Skip a Charge in the future for one or multiple Subscriptions associated with the Address.\n */\nexport async function skipFutureCharge(\n session: Session,\n id: string | number,\n skipRequest: SkipFutureChargeAddressRequest\n) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { charge } = await rechargeApiRequest<SkipFutureChargeAddressResponse>(\n 'post',\n `/addresses/${id}/charges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MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAO,OAAA,kBAAA,CAAyB,UAAU,CAAc,UAAA,CAAA,EAAA,EAAE,IAAM,EAAA,kBAAA,CAAmB,OAAS,EAAA,eAAe,CAAC,CAAA,CAAA;AAC9G,CAAA;AAKsB,eAAA,cAAA,CAAe,SAAkB,YAAqC,EAAA;AAC1F,EAAM,MAAA,EAAE,OAAQ,EAAA,GAAI,MAAM,kBAAA;AAAA,IACxB,MAAA;AAAA,IACA,CAAA,gBAAA,CAAA;AAAA,IACA;AAAA,MACE,IAAM,EAAA,YAAA;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,gBAAgB,CAAA;AAAA,GAC9C,CAAA;AACA,EAAO,OAAA,OAAA,CAAA;AACT,CAAA;AAKsB,eAAA,gBAAA,CACpB,OACA,EAAA,EAAA,EACA,WACA,EAAA;AACA,EAAI,IAAA,EAAA,KAAO,KAAa,CAAA,IAAA,EAAA,KAAO,EAAI,EAAA;AACjC,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,MAAA;AAAA,IACA,cAAc,EAAE,CAAA,aAAA,CAAA;AAAA,IAChB;AAAA,MACE,IAAM,EAAA,WAAA;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,kBAAkB,CAAA;AAAA,GAChD,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
@@ -15,7 +15,13 @@ async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToke
15
15
  return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);
16
16
  }
17
17
  async function loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken) {
18
+ if (!shopifyStorefrontToken) {
19
+ throw new Error("Shopify storefront token is required");
20
+ }
18
21
  const { storeIdentifier } = getOptions();
22
+ if (!storeIdentifier) {
23
+ throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");
24
+ }
19
25
  const {
20
26
  api_token: apiToken,
21
27
  customer_id: customerId,
@@ -31,6 +37,9 @@ async function loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustome
31
37
  }
32
38
  async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken) {
33
39
  const { storeIdentifier } = getOptions();
40
+ if (!storeIdentifier) {
41
+ throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");
42
+ }
34
43
  const {
35
44
  api_token: apiToken,
36
45
  customer_id: customerId,
@@ -44,7 +53,13 @@ async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken) {
44
53
  return apiToken ? { apiToken, customerId, message } : null;
45
54
  }
46
55
  async function sendPasswordlessCode(email, options = {}) {
56
+ if (!email) {
57
+ throw new Error("Email is required.");
58
+ }
47
59
  const { storeIdentifier } = getOptions();
60
+ if (!storeIdentifier) {
61
+ throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");
62
+ }
48
63
  const response = await rechargeAdminRequest("post", "/attempt_login", {
49
64
  data: {
50
65
  email,
@@ -58,6 +73,9 @@ async function sendPasswordlessCode(email, options = {}) {
58
73
  return response.session_token;
59
74
  }
60
75
  async function sendPasswordlessCodeAppProxy(email, options = {}) {
76
+ if (!email) {
77
+ throw new Error("Email is required.");
78
+ }
61
79
  const { storefrontAccessToken } = getOptions();
62
80
  const headers = {};
63
81
  if (storefrontAccessToken) {
@@ -76,7 +94,19 @@ async function sendPasswordlessCodeAppProxy(email, options = {}) {
76
94
  return response.session_token;
77
95
  }
78
96
  async function validatePasswordlessCode(email, session_token, code) {
97
+ if (!email) {
98
+ throw new Error("Email is required.");
99
+ }
100
+ if (!session_token) {
101
+ throw new Error("Session token is required.");
102
+ }
103
+ if (!code) {
104
+ throw new Error("Code is required.");
105
+ }
79
106
  const { storeIdentifier } = getOptions();
107
+ if (!storeIdentifier) {
108
+ throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");
109
+ }
80
110
  const response = await rechargeAdminRequest("post", "/validate_login", {
81
111
  data: {
82
112
  code,
@@ -91,6 +121,15 @@ async function validatePasswordlessCode(email, session_token, code) {
91
121
  return { apiToken: response.api_token, customerId: response.customer_id };
92
122
  }
93
123
  async function validatePasswordlessCodeAppProxy(email, session_token, code) {
124
+ if (!email) {
125
+ throw new Error("Email is required.");
126
+ }
127
+ if (!session_token) {
128
+ throw new Error("Session token is required.");
129
+ }
130
+ if (!code) {
131
+ throw new Error("Code is required.");
132
+ }
94
133
  const { storefrontAccessToken } = getOptions();
95
134
  const headers = {};
96
135
  if (storefrontAccessToken) {
@@ -140,7 +179,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
140
179
  ...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
141
180
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
142
181
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
143
- "X-Recharge-Sdk-Version": "1.28.0",
182
+ "X-Recharge-Sdk-Version": "1.28.1",
144
183
  ...headers ? headers : {}
145
184
  };
146
185
  return request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>('post', `/customers/${customerHash}/access`, {\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["baseRequest"],"mappings":";;;;AAcA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAI,UAAW,EAAA,CAAA;AAC7C,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAA,MAAM,WAAW,MAAM,sBAAA,CAAsC,OAAO,SAAW,EAAA,EAAE,SAAS,CAAA,CAAA;AAE1F,EAAO,OAAA,EAAE,UAAU,QAAS,CAAA,SAAA,EAAW,YAAY,QAAS,CAAA,WAAA,EAAa,OAAS,EAAA,QAAA,CAAS,OAAQ,EAAA,CAAA;AACrG,CAAA;AAGsB,eAAA,eAAA,CACpB,wBACA,0BACyB,EAAA;AACzB,EAAO,OAAA,0BAAA,CAA2B,wBAAwB,0BAA0B,CAAA,CAAA;AACtF,CAAA;AAEsB,eAAA,0BAAA,CACpB,wBACA,0BACyB,EAAA;AACzB,EAAM,MAAA,EAAE,eAAgB,EAAA,GAAI,UAAW,EAAA,CAAA;AACvC,EAAM,MAAA;AAAA,IACJ,SAAW,EAAA,QAAA;AAAA,IACX,WAAa,EAAA,UAAA;AAAA,IACb,OAAA;AAAA,GACE,GAAA,MAAM,oBAAoC,CAAA,MAAA,EAAQ,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AAA,KAAe,EAAC;AAAA,IACjE,wBAA0B,EAAA,QAAA;AAAA,IAC1B,GAAI,OAAU,GAAA,OAAA,GAAU,EAAC;AAAA,GAC3B,CAAA;AAEA,EAAA,OAAOA,OAAe,CAAA,MAAA,EAAQ,CAAG,EAAA,eAAe,CAAG,EAAA,GAAG,CAAI,CAAA,EAAA,EAAE,EAAI,EAAA,KAAA,EAAO,IAAM,EAAA,OAAA,EAAS,YAAY,CAAA,CAAA;AACpG;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n Method,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n RequestHeaders,\n RequestOptions,\n Session,\n} from '../types';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\n\nexport async function loginShopifyAppProxy(): Promise<Session> {\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<LoginResponse>('get', '/access', { headers });\n\n return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };\n}\n\n/** @deprecated Use `loginWithShopifyStorefront` instead */\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);\n}\n\nexport async function loginWithShopifyStorefront(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n if (!shopifyStorefrontToken) {\n throw new Error('Shopify storefront token is required');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_storefront_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await rechargeAdminRequest<LoginResponse>('post', '/shopify_customer_account_api_access', {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n shop: storeIdentifier,\n ...options,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function sendPasswordlessCodeAppProxy(email: string, options: PasswordlessOptions = {}): Promise<string> {\n if (!email) {\n throw new Error('Email is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessCodeResponse>('post', '/attempt_login', {\n data: {\n email,\n ...options,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return response.session_token;\n}\n\nexport async function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storeIdentifier } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const response = await rechargeAdminRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\n },\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nexport async function validatePasswordlessCodeAppProxy(\n email: string,\n session_token: string,\n code: string\n): Promise<Session> {\n if (!email) {\n throw new Error('Email is required.');\n }\n if (!session_token) {\n throw new Error('Session token is required.');\n }\n if (!code) {\n throw new Error('Code is required.');\n }\n const { storefrontAccessToken } = getOptions();\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await shopifyAppProxyRequest<PasswordlessValidateResponse>('post', '/validate_login', {\n data: {\n code,\n email,\n session_token,\n },\n headers,\n });\n\n if (response.errors) {\n throw new Error(response.errors);\n }\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nfunction getCustomerParams() {\n const { customerHash: devCustomerHash } = getOptions();\n const { pathname, search } = window.location;\n const urlParams = new URLSearchParams(search);\n const token = urlParams.get('token');\n const subpaths = pathname.split('/').filter(Boolean);\n const portalIndex = subpaths.findIndex(path => path === 'portal');\n const customerHash = portalIndex !== -1 ? subpaths[portalIndex + 1] : devCustomerHash;\n\n // make sure the URL contained the data we need\n if (!token || !customerHash) {\n throw new Error('Not in context of Recharge Customer Portal or URL did not contain correct params');\n }\n return { customerHash, token };\n}\n\nexport async function loginCustomerPortal(): Promise<Session> {\n const { customerHash, token } = getCustomerParams();\n const { storeIdentifier } = getOptions();\n const response = await rechargeAdminRequest<LoginResponse>('post', `/customers/${customerHash}/access`, {\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n\nasync function rechargeAdminRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n const { environment, environmentUri, storefrontAccessToken, appName, appVersion } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n ...(storefrontAccessToken ? { 'X-Recharge-Storefront-Access-Token': storefrontAccessToken } : {}),\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n ...(headers ? headers : {}),\n };\n\n return baseRequest<T>(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });\n}\n"],"names":["baseRequest"],"mappings":";;;;AAcA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAI,UAAW,EAAA,CAAA;AAC7C,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAA,MAAM,WAAW,MAAM,sBAAA,CAAsC,OAAO,SAAW,EAAA,EAAE,SAAS,CAAA,CAAA;AAE1F,EAAO,OAAA,EAAE,UAAU,QAAS,CAAA,SAAA,EAAW,YAAY,QAAS,CAAA,WAAA,EAAa,OAAS,EAAA,QAAA,CAAS,OAAQ,EAAA,CAAA;AACrG,CAAA;AAGsB,eAAA,eAAA,CACpB,wBACA,0BACyB,EAAA;AACzB,EAAO,OAAA,0BAAA,CAA2B,wBAAwB,0BAA0B,CAAA,CAAA;AACtF,CAAA;AAEsB,eAAA,0BAAA,CACpB,wBACA,0BACyB,EAAA;AACzB,EAAA,IAAI,CAAC,sBAAwB,EAAA;AAC3B,IAAM,MAAA,IAAI,MAAM,sCAAsC,CAAA,CAAA;AAAA,GACxD;AACA,EAAM,MAAA,EAAE,eAAgB,EAAA,GAAI,UAAW,EA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,EAAE,yBAA2B,EAAA,OAAA,KAAY,EAAC;AAAA,IACxD,GAAI,UAAa,GAAA,EAAE,4BAA8B,EAAA,UAAA,KAAe,EAAC;AAAA,IACjE,wBAA0B,EAAA,QAAA;AAAA,IAC1B,GAAI,OAAU,GAAA,OAAA,GAAU,EAAC;AAAA,GAC3B,CAAA;AAEA,EAAA,OAAOA,OAAe,CAAA,MAAA,EAAQ,CAAG,EAAA,eAAe,CAAG,EAAA,GAAG,CAAI,CAAA,EAAA,EAAE,EAAI,EAAA,KAAA,EAAO,IAAM,EAAA,OAAA,EAAS,YAAY,CAAA,CAAA;AACpG;;;;"}
@@ -138,6 +138,9 @@ function validateDynamicBundle(bundle) {
138
138
  return true;
139
139
  }
140
140
  async function getBundleSelection(session, id) {
141
+ if (id === void 0 || id === "") {
142
+ throw new Error("ID is required");
143
+ }
141
144
  const { bundle_selection } = await rechargeApiRequest(
142
145
  "get",
143
146
  `/bundle_selections`,
@@ -168,6 +171,9 @@ async function createBundleSelection(session, createRequest) {
168
171
  return bundle_selection;
169
172
  }
170
173
  async function updateBundleSelection(session, id, updateRequest) {
174
+ if (id === void 0 || id === "") {
175
+ throw new Error("ID is required");
176
+ }
171
177
  const { bundle_selection } = await rechargeApiRequest(
172
178
  "put",
173
179
  `/bundle_selections`,
@@ -180,6 +186,9 @@ async function updateBundleSelection(session, id, updateRequest) {
180
186
  return bundle_selection;
181
187
  }
182
188
  function deleteBundleSelection(session, id) {
189
+ if (id === void 0 || id === "") {
190
+ throw new Error("ID is required");
191
+ }
183
192
  return rechargeApiRequest(
184
193
  "delete",
185
194
  `/bundle_selections`,
@@ -190,6 +199,9 @@ function deleteBundleSelection(session, id) {
190
199
  );
191
200
  }
192
201
  async function updateBundle(session, purchase_item_id, updateRequest, query) {
202
+ if (purchase_item_id === void 0 || purchase_item_id === "") {
203
+ throw new Error("Purchase item ID is required");
204
+ }
193
205
  const { subscription } = await rechargeApiRequest(
194
206
  "put",
195
207
  "/bundles",
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n BundleData,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { BundleSelectionValidator, toLineItemProperty } from '../utils/bundle';\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 return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\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 function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\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 if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nexport async function validateBundleSelection(bundle: BundleAppProxy): Promise<{ valid: boolean; error?: string }> {\n try {\n const bundleData = await shopifyAppProxyRequest<BundleData>('get', `/bundle-data/${bundle.externalProductId}`);\n\n const selectionValidator = new BundleSelectionValidator(bundle.selections, bundleData);\n\n return { valid: selectionValidator.isBundleSelectionValid(bundle.externalVariantId) };\n } catch (error) {\n return { valid: false, error: String(error) };\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAmBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,GAAI,CAAA,CAAA;AACpC,CAAA;AAEA,eAAe,6BAAiD,GAAA;AAK9D,EAAI,IAAA;AACF,IAAM,MAAA,EA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,EAAO,OAAA,gBAAA,CAAA;AACT,CAAA;AAEsB,eAAA,qBAAA,CACpB,OACA,EAAA,EAAA,EACA,aAC0B,EAAA;AAC1B,EAAM,MAAA,EAAE,gBAAiB,EAAA,GAAI,MAAM,kBAAA;AAAA,IACjC,KAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,IAAM,EAAA,aAAA;AAAA,KACR;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACA,EAAO,OAAA,gBAAA,CAAA;AACT,CAAA;AAEgB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAO,OAAA,kBAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC7B,KAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid/non-secure';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n BundleData,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { BundleSelectionValidator, toLineItemProperty } from '../utils/bundle';\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 return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nexport async function getBundleId(bundle: BundleAppProxy): Promise<string> {\n const opts = getOptions();\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\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 function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string) {\n const isValid = validateDynamicBundle(bundle);\n if (isValid !== true) {\n throw new Error(`Dynamic Bundle is invalid. ${isValid}`);\n }\n // generate unique id for dynamic bundle\n const bundleId = `${nanoid(9)}:${bundle.externalProductId}`;\n return bundle.selections.map(item => {\n const itemData: DynamicBundleItemAppProxy = {\n id: item.externalVariantId,\n quantity: item.quantity,\n properties: {\n _rc_bundle: bundleId,\n _rc_bundle_variant: bundle.externalVariantId,\n _rc_bundle_parent: shopifyProductHandle,\n _rc_bundle_collection_id: item.collectionId,\n },\n };\n\n if (item.sellingPlan) {\n // this is used by SCI stores\n itemData.selling_plan = item.sellingPlan;\n } else if (item.shippingIntervalFrequency) {\n // this is used by RCS stores\n itemData.properties.shipping_interval_frequency = item.shippingIntervalFrequency;\n itemData.properties.shipping_interval_unit_type = item.shippingIntervalUnitType;\n itemData.id = `${item.discountedVariantId}`;\n }\n\n return itemData;\n });\n}\n\nexport async function validateBundle(bundle: BundleAppProxy): Promise<true | string> {\n try {\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 if (!bundle) {\n return 'Bundle is not defined';\n }\n // Don't make bundle settings call due to merchant issues\n // const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);\n // if (!bundleSettings) {\n // return 'Bundle settings do not exist for the given product';\n // }\n return true;\n } catch (e) {\n return `Error fetching bundle settings: ${e}`;\n }\n}\n\nexport async function validateBundleSelection(bundle: BundleAppProxy): Promise<{ valid: boolean; error?: string }> {\n try {\n const bundleData = await shopifyAppProxyRequest<BundleData>('get', `/bundle-data/${bundle.externalProductId}`);\n\n const selectionValidator = new BundleSelectionValidator(bundle.selections, bundleData);\n\n return { valid: selectionValidator.isBundleSelectionValid(bundle.externalVariantId) };\n } catch (error) {\n return { valid: false, error: String(error) };\n }\n}\n\nconst intervalUnitGroups = {\n day: ['day', 'days', 'Days'],\n days: ['day', 'days', 'Days'],\n Days: ['day', 'days', 'Days'],\n week: ['week', 'weeks', 'Weeks'],\n weeks: ['week', 'weeks', 'Weeks'],\n Weeks: ['week', 'weeks', 'Weeks'],\n month: ['month', 'months', 'Months'],\n months: ['month', 'months', 'Months'],\n Months: ['month', 'months', 'Months'],\n};\n\n/**\n * Validates a dynamic bundle\n *\n * @param bundle Dynamic Bundle being validated\n * @returns true or error message\n */\nexport function validateDynamicBundle(bundle: BundleAppProxy): true | string {\n if (!bundle) {\n return 'No bundle defined.';\n }\n if (bundle.selections.length === 0) {\n return 'No selections defined.';\n }\n // validation for RCS onetimes\n const { shippingIntervalFrequency, shippingIntervalUnitType } =\n bundle.selections.find(selection => selection.shippingIntervalFrequency || selection.shippingIntervalUnitType) ||\n {};\n if (shippingIntervalFrequency || shippingIntervalUnitType) {\n // if we have shipping intervals then we should have both defined\n if (!shippingIntervalFrequency || !shippingIntervalUnitType) {\n return 'Shipping intervals do not match on selections.';\n } else {\n // if we have shipping intervals then any that are defined should match\n const shippingIntervalUnitGroup = intervalUnitGroups[shippingIntervalUnitType];\n for (let x = 0; x < bundle.selections.length; x++) {\n const { shippingIntervalFrequency: frequency, shippingIntervalUnitType: unitType } = bundle.selections[x];\n if (\n (frequency && frequency !== shippingIntervalFrequency) ||\n (unitType && !shippingIntervalUnitGroup.includes(unitType))\n ) {\n return 'Shipping intervals do not match on selections.';\n }\n }\n }\n }\n return true;\n}\n\nexport async function getBundleSelection(session: Session, id: string | number): Promise<BundleSelection> {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'get',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'getBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>(\n 'get',\n `/bundle_selections`,\n { query },\n getInternalSession(session, 'listBundleSelections')\n );\n}\n\nexport async function createBundleSelection(\n session: Session,\n createRequest: CreateBundleSelectionRequest\n): Promise<BundleSelection> {\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'post',\n `/bundle_selections`,\n {\n data: createRequest,\n },\n getInternalSession(session, 'createBundleSelection')\n );\n return bundle_selection;\n}\n\nexport async function updateBundleSelection(\n session: Session,\n id: string | number,\n updateRequest: UpdateBundleSelectionRequest\n): Promise<BundleSelection> {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { bundle_selection } = await rechargeApiRequest<{ bundle_selection: BundleSelection }>(\n 'put',\n `/bundle_selections`,\n {\n id,\n data: updateRequest,\n },\n getInternalSession(session, 'updateBundleSelection')\n );\n return bundle_selection;\n}\n\nexport function deleteBundleSelection(session: Session, id: string | number): Promise<void> {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n return rechargeApiRequest<void>(\n 'delete',\n `/bundle_selections`,\n {\n id,\n },\n getInternalSession(session, 'deleteBundleSelection')\n );\n}\n\nexport async function updateBundle(\n session: Session,\n purchase_item_id: string | number,\n updateRequest: UpdateBundlePurchaseItem,\n query?: BundlePurchaseItemParams\n): Promise<BundlePurchaseItem> {\n if (purchase_item_id === undefined || purchase_item_id === '') {\n throw new Error('Purchase item ID is required');\n }\n const { subscription } = await rechargeApiRequest<{ subscription: BundlePurchaseItem }>(\n 'put',\n '/bundles',\n {\n id: purchase_item_id,\n data: updateRequest,\n query,\n },\n getInternalSession(session, 'updateBundle')\n );\n\n return subscription;\n}\n"],"names":[],"mappings":";;;;;AAmBA,MAAM,uBAA0B,GAAA,8BAAA,CAAA;AAEhC,SAAS,6BAAwC,GAAA;AAI/C,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,GAAA,KAAQ,GAAI,CAAA,CAAA;AACpC,CAAA;AAEA,eAAe,6BAAiD,GAAA;AAK9D,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,WAAc,GAAA,MAAM,uBAA8C,KAAO,EAAA,CAAA,EAAG,uBAAuB,CAAI,EAAA,CAAA,CAAA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AAAA,IACA;AAAA,MACE,EAAI,EAAA,gBAAA;AAAA,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
@@ -19,6 +19,9 @@ function cacheRequest(cacheKey, request) {
19
19
  return promiseCache.get(cacheKey);
20
20
  }
21
21
  async function getCDNProduct(externalProductId, query) {
22
+ if (externalProductId === void 0 || externalProductId === "") {
23
+ throw new Error("ID is required");
24
+ }
22
25
  const version = query?.version ?? "2020-12";
23
26
  const { product } = await cacheRequest(
24
27
  `product.${externalProductId}.${version}`,
@@ -1 +1 @@
1
- {"version":3,"file":"cdn.js","sources":["../../../src/api/cdn.ts"],"sourcesContent":["import {\n CDNWidgetSettings,\n CDNStoreSettings,\n CDNWidgetSettingsResource,\n CDNProductsAndSettings,\n CDNProductAndSettings,\n CDNProductsAndSettingsResource,\n CDNBundleSettings,\n CDNProductKeyObject,\n CDNProductRaw,\n CDNProductType,\n CDNProductQuery_2020_12,\n CDNProductQuery_2022_06,\n CDNProductResponseType,\n} from '../types';\nimport { productArrayMapper, productMapper, widgetSettingsMapper } from '../mappers/cdn';\nimport { cdnRequest } from '../utils/request';\n\nconst BASE_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 async function getCDNProduct<\n T extends CDNProductQuery_2020_12 | CDNProductQuery_2022_06 = CDNProductQuery_2020_12\n>(externalProductId: string | number, query?: T): Promise<CDNProductType<T>> {\n const version = query?.version ?? '2020-12';\n const { product } = await cacheRequest(`product.${externalProductId}.${version}`, () =>\n cdnRequest<CDNProductResponseType<T>>('get', `/product/${version}/${externalProductId}.json`)\n );\n\n if (version === '2020-12') {\n return productMapper(product as CDNProductRaw) as CDNProductType<T>;\n }\n return product as CDNProductType<T>;\n}\n\nexport async function getCDNStoreSettings(): Promise<CDNStoreSettings> {\n const storeSettings = await cacheRequest('storeSettings', () =>\n cdnRequest<CDNStoreSettings>('get', `/${BASE_CDN_VERSION}/store_settings.json`).catch(() => {\n return DEFAULT_STORE_SETTINGS;\n })\n );\n return storeSettings;\n}\n\nexport async function getCDNWidgetSettings(): Promise<CDNWidgetSettings> {\n const { widget_settings } = await cacheRequest('widgetSettings', () =>\n cdnRequest<CDNWidgetSettingsResource>('get', `/${BASE_CDN_VERSION}/widget_settings.json`)\n );\n\n const widgetSettings = widgetSettingsMapper(widget_settings);\n\n return widgetSettings;\n}\n\nexport async function getCDNProductsAndSettings(): Promise<CDNProductsAndSettings> {\n const { products, widget_settings, store_settings, meta } = await cacheRequest('productsAndSettings', () =>\n cdnRequest<CDNProductsAndSettingsResource>('get', `/product/${BASE_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: store_settings ?? {},\n };\n}\n\nexport async function getCDNProducts(): Promise<CDNProductKeyObject[]> {\n const { products } = await getCDNProductsAndSettings();\n return products;\n}\n\nexport async function getCDNProductAndSettings(externalProductId: string | number): Promise<CDNProductAndSettings> {\n const [product, store_settings, widget_settings] = await Promise.all([\n getCDNProduct(externalProductId),\n getCDNStoreSettings(),\n getCDNWidgetSettings(),\n ]);\n\n return {\n product,\n store_settings,\n widget_settings,\n storeSettings: store_settings,\n widgetSettings: widget_settings,\n };\n}\n\nexport async function getCDNBundleSettings(\n externalProductId: string | number\n): Promise<CDNBundleSettings | null | undefined> {\n const { bundle_product } = await getCDNProduct(externalProductId);\n\n return bundle_product;\n}\n\nexport async function resetCDNCache() {\n return Array.from(promiseCache.keys()).forEach(key => promiseCache.delete(key));\n}\n"],"names":[],"mappings":";;;AAkBA,MAAM,gBAAmB,GAAA,SAAA,CAAA;AAGzB,MAAM,sBAA2C,GAAA;AAAA,EAC/C,cAAgB,EAAA;AAAA,IACd,aAAe,EAAA,KAAA;AAAA,IACf,eAAiB,EAAA,GAAA;AAAA,IACjB,iBAAmB,EAAA,GAAA;AAAA,IACnB,mBAAqB,EAAA,GAAA;AAAA,IACrB,wBAA0B,EAAA,MAAA;AAAA,GAC5B;AACF,CAAA,CAAA;AAEA,MAAM,YAAA,uBAAmB,GAAI,EAAA,CAAA;AAG7B,SAAS,YAAA,CAAgB,UAAkB,OAAqB,EAAA;AAC9D,EAAA,IAAI,CAAC,YAAA,CAAa,GAAI,CAAA,QAAQ,CAAG,EAAA;AAC/B,IAAa,YAAA,CAAA,GAAA,CAAI,QAAU,EAAA,OAAA,EAAS,CAAA,CAAA;AAAA,GACtC;AACA,EAAO,OAAA,YAAA,CAAa,IAAI,QAAQ,CAAA,CAAA;AAClC,CAAA;AAEsB,eAAA,aAAA,CAEpB,mBAAoC,KAAuC,EAAA;AAC3E,EAAM,MAAA,OAAA,GAAU,OAAO,OAAW,IAAA,SAAA,CAAA;AAClC,EAAM,MAAA,EAAE,OAAQ,EAAA,GAAI,MAAM,YAAA;AAAA,IAAa,CAAA,QAAA,EAAW,iBAAiB,CAAA,CAAA,EAAI,OAAO,CAAA,CAAA;AAAA,IAAI,MAChF,UAAsC,CAAA,KAAA,EAAO,YAAY,OAAO,CAAA,CAAA,EAAI,iBAAiB,CAAO,KAAA,CAAA,CAAA;AAAA,GAC9F,CAAA;AAEA,EAAA,IAAI,YAAY,SAAW,EAAA;AACzB,IAAA,OAAO,cAAc,OAAwB,CAAA,CAAA;AAAA,GAC/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B,cAAiD,GAAA;AACrE,EAAA,MAAM,EAAE,QAAA,EAAa,GAAA,MAAM,yBAA0B,EAAA,CAAA;AACrD,EAAO,OAAA,QAAA,CAAA;AACT,CAAA;AAEA,eAAsB,yBAAyB,iBAAoE,EAAA;AACjH,EAAA,MAAM,CAAC,OAAS,EAAA,cAAA,EAAgB,eAAe,CAAI,GAAA,MAAM,QAAQ,GAAI,CAAA;AAAA,IACnE,cAAc,iBAAiB,CAAA;AAAA,IAC/B,mBAAoB,EAAA;AAAA,IACpB,oBAAqB,EAAA;AAAA,GACtB,CAAA,CAAA;AAED,EAAO,OAAA;AAAA,IACL,OAAA;AAAA,IACA,cAAA;AAAA,IACA,eAAA;AAAA,IACA,aAAe,EAAA,cAAA;AAAA,IACf,cAAgB,EAAA,eAAA;AAAA,GAClB,CAAA;AACF,CAAA;AAEA,eAAsB,qBACpB,iBAC+C,EAAA;AAC/C,EAAA,MAAM,EAAE,cAAA,EAAmB,GAAA,MAAM,cAAc,iBAAiB,CAAA,CAAA;AAEhE,EAAO,OAAA,cAAA,CAAA;AACT,CAAA;AAEA,eAAsB,aAAgB,GAAA;AACpC,EAAO,OAAA,KAAA,CAAM,IAAK,CAAA,YAAA,CAAa,IAAK,EAAC,CAAE,CAAA,OAAA,CAAQ,CAAO,GAAA,KAAA,YAAA,CAAa,MAAO,CAAA,GAAG,CAAC,CAAA,CAAA;AAChF;;;;"}
1
+ {"version":3,"file":"cdn.js","sources":["../../../src/api/cdn.ts"],"sourcesContent":["import {\n CDNWidgetSettings,\n CDNStoreSettings,\n CDNWidgetSettingsResource,\n CDNProductsAndSettings,\n CDNProductAndSettings,\n CDNProductsAndSettingsResource,\n CDNBundleSettings,\n CDNProductKeyObject,\n CDNProductRaw,\n CDNProductType,\n CDNProductQuery_2020_12,\n CDNProductQuery_2022_06,\n CDNProductResponseType,\n} from '../types';\nimport { productArrayMapper, productMapper, widgetSettingsMapper } from '../mappers/cdn';\nimport { cdnRequest } from '../utils/request';\n\nconst BASE_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 async function getCDNProduct<\n T extends CDNProductQuery_2020_12 | CDNProductQuery_2022_06 = CDNProductQuery_2020_12\n>(externalProductId: string | number, query?: T): Promise<CDNProductType<T>> {\n if (externalProductId === undefined || externalProductId === '') {\n throw new Error('ID is required');\n }\n const version = query?.version ?? '2020-12';\n const { product } = await cacheRequest(`product.${externalProductId}.${version}`, () =>\n cdnRequest<CDNProductResponseType<T>>('get', `/product/${version}/${externalProductId}.json`)\n );\n\n if (version === '2020-12') {\n return productMapper(product as CDNProductRaw) as CDNProductType<T>;\n }\n return product as CDNProductType<T>;\n}\n\nexport async function getCDNStoreSettings(): Promise<CDNStoreSettings> {\n const storeSettings = await cacheRequest('storeSettings', () =>\n cdnRequest<CDNStoreSettings>('get', `/${BASE_CDN_VERSION}/store_settings.json`).catch(() => {\n return DEFAULT_STORE_SETTINGS;\n })\n );\n return storeSettings;\n}\n\nexport async function getCDNWidgetSettings(): Promise<CDNWidgetSettings> {\n const { widget_settings } = await cacheRequest('widgetSettings', () =>\n cdnRequest<CDNWidgetSettingsResource>('get', `/${BASE_CDN_VERSION}/widget_settings.json`)\n );\n\n const widgetSettings = widgetSettingsMapper(widget_settings);\n\n return widgetSettings;\n}\n\nexport async function getCDNProductsAndSettings(): Promise<CDNProductsAndSettings> {\n const { products, widget_settings, store_settings, meta } = await cacheRequest('productsAndSettings', () =>\n cdnRequest<CDNProductsAndSettingsResource>('get', `/product/${BASE_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: store_settings ?? {},\n };\n}\n\nexport async function getCDNProducts(): Promise<CDNProductKeyObject[]> {\n const { products } = await getCDNProductsAndSettings();\n return products;\n}\n\nexport async function getCDNProductAndSettings(externalProductId: string | number): Promise<CDNProductAndSettings> {\n const [product, store_settings, widget_settings] = await Promise.all([\n getCDNProduct(externalProductId),\n getCDNStoreSettings(),\n getCDNWidgetSettings(),\n ]);\n\n return {\n product,\n store_settings,\n widget_settings,\n storeSettings: store_settings,\n widgetSettings: widget_settings,\n };\n}\n\nexport async function getCDNBundleSettings(\n externalProductId: string | number\n): Promise<CDNBundleSettings | null | undefined> {\n const { bundle_product } = await getCDNProduct(externalProductId);\n\n return bundle_product;\n}\n\nexport async function resetCDNCache() {\n return Array.from(promiseCache.keys()).forEach(key => promiseCache.delete(key));\n}\n"],"names":[],"mappings":";;;AAkBA,MAAM,gBAAmB,GAAA,SAAA,CAAA;AAGzB,MAAM,sBAA2C,GAAA;AAAA,EAC/C,cAAgB,EAAA;AAAA,IACd,aAAe,EAAA,KAAA;AAAA,IACf,eAAiB,EAAA,GAAA;AAAA,IACjB,iBAAmB,EAAA,GAAA;AAAA,IACnB,mBAAqB,EAAA,GAAA;AAAA,IACrB,wBAA0B,EAAA,MAAA;AAAA,GAC5B;AACF,CAAA,CAAA;AAEA,MAAM,YAAA,uBAAmB,GAAI,EAAA,CAAA;AAG7B,SAAS,YAAA,CAAgB,UAAkB,OAAqB,EAAA;AAC9D,EAAA,IAAI,CAAC,YAAA,CAAa,GAAI,CAAA,QAAQ,CAAG,EAAA;AAC/B,IAAa,YAAA,CAAA,GAAA,CAAI,QAAU,EAAA,OAAA,EAAS,CAAA,CAAA;AAAA,GACtC;AACA,EAAO,OAAA,YAAA,CAAa,IAAI,QAAQ,CAAA,CAAA;AAClC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;AAEhE,EAAO,OAAA,cAAA,CAAA;AACT,CAAA;AAEA,eAAsB,aAAgB,GAAA;AACpC,EAAO,OAAA,KAAA,CAAM,IAAK,CAAA,YAAA,CAAa,IAAK,EAAC,CAAE,CAAA,OAAA,CAAQ,CAAO,GAAA,KAAA,YAAA,CAAa,MAAO,CAAA,GAAG,CAAC,CAAA,CAAA;AAChF;;;;"}
@@ -1,6 +1,9 @@
1
1
  import { rechargeApiRequest, getInternalSession } from '../utils/request.js';
2
2
 
3
3
  async function getCharge(session, id, options) {
4
+ if (id === void 0 || id === "") {
5
+ throw new Error("ID is required");
6
+ }
4
7
  const { charge } = await rechargeApiRequest(
5
8
  "get",
6
9
  `/charges`,
@@ -18,6 +21,9 @@ function listCharges(session, query) {
18
21
  );
19
22
  }
20
23
  async function applyDiscountToCharge(session, id, discountCode) {
24
+ if (id === void 0 || id === "") {
25
+ throw new Error("ID is required");
26
+ }
21
27
  const { charge } = await rechargeApiRequest(
22
28
  "post",
23
29
  `/charges/${id}/apply_discount`,
@@ -29,6 +35,9 @@ async function applyDiscountToCharge(session, id, discountCode) {
29
35
  return charge;
30
36
  }
31
37
  async function removeDiscountsFromCharge(session, id) {
38
+ if (id === void 0 || id === "") {
39
+ throw new Error("ID is required");
40
+ }
32
41
  const { charge } = await rechargeApiRequest(
33
42
  "post",
34
43
  `/charges/${id}/remove_discount`,
@@ -38,6 +47,12 @@ async function removeDiscountsFromCharge(session, id) {
38
47
  return charge;
39
48
  }
40
49
  async function skipCharge(session, id, purchaseItemIds, query) {
50
+ if (id === void 0 || id === "") {
51
+ throw new Error("ID is required");
52
+ }
53
+ if (purchaseItemIds === void 0 || purchaseItemIds.length === 0) {
54
+ throw new Error("Purchase item IDs are required");
55
+ }
41
56
  const { charge } = await rechargeApiRequest(
42
57
  "post",
43
58
  `/charges/${id}/skip`,
@@ -52,6 +67,12 @@ async function skipCharge(session, id, purchaseItemIds, query) {
52
67
  return charge;
53
68
  }
54
69
  async function unskipCharge(session, id, purchaseItemIds, query) {
70
+ if (id === void 0 || id === "") {
71
+ throw new Error("ID is required");
72
+ }
73
+ if (purchaseItemIds === void 0 || purchaseItemIds.length === 0) {
74
+ throw new Error("Purchase item IDs are required");
75
+ }
55
76
  const { charge } = await rechargeApiRequest(
56
77
  "post",
57
78
  `/charges/${id}/unskip`,
@@ -66,6 +87,9 @@ async function unskipCharge(session, id, purchaseItemIds, query) {
66
87
  return charge;
67
88
  }
68
89
  async function processCharge(session, id) {
90
+ if (id === void 0 || id === "") {
91
+ throw new Error("ID is required");
92
+ }
69
93
  const { charge } = await rechargeApiRequest(
70
94
  "post",
71
95
  `/charges/${id}/process`,
@@ -1 +1 @@
1
- {"version":3,"file":"charge.js","sources":["../../../src/api/charge.ts"],"sourcesContent":["import {\n ChargeListParams,\n ChargeListResponse,\n ChargeResponse,\n GetChargeOptions,\n Session,\n SkipChargeParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\n/* Retrieve a Charge using the charge_id. */\nexport async function getCharge(session: Session, id: number | string, options?: GetChargeOptions) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'get',\n `/charges`,\n { id, query: { include: options?.include } },\n getInternalSession(session, 'getCharge')\n );\n return charge;\n}\n\n/** Lists charges */\nexport function listCharges(session: Session, query?: ChargeListParams) {\n return rechargeApiRequest<ChargeListResponse>(\n 'get',\n `/charges`,\n { query },\n getInternalSession(session, 'listCharges')\n );\n}\n\n/**\n * You cannot add a Discount to an existing queued Charge if the Charge or the associated Address already has one.\n * If a Charge has a Discount and it gets updated, or a regeneration occurs, the Discount will be lost. Regeneration is a process that refreshes the Charge JSON with new data in the case of the Subscription or Address being updated.\n */\nexport async function applyDiscountToCharge(session: Session, id: number | string, discountCode: string) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/apply_discount`,\n {\n data: { discount_code: discountCode },\n },\n getInternalSession(session, 'applyDiscountToCharge')\n );\n return charge;\n}\n\n/**\n * Remove all Discounts from a Charge without destroying the Discount.\n * In most cases the Discount should be removed from the Address. When the Discount is removed from the Address, the Discount is also removed from any future Charges.\n * If the Discount is on the parent Address, you cannot remove it using charge_id.\n * When removing your Discount, it is preferable to pass the address_id so that the Discount stays removed if the Charge is regenerated. Only pass charge_id in edge cases in which there are two or more Charges on a parent Address and you only want to remove the Discount from one Charge.\n * If you pass both parameters, it will remove the Discount from the Address.\n */\nexport async function removeDiscountsFromCharge(session: Session, id: number | string) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/remove_discount`,\n {},\n getInternalSession(session, 'removeDiscountsFromCharge')\n );\n return charge;\n}\n\n/* Skip a Charge. */\nexport async function skipCharge(\n session: Session,\n id: number | string,\n purchaseItemIds: (string | number)[],\n query?: SkipChargeParams\n) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/skip`,\n {\n query,\n data: {\n purchase_item_ids: purchaseItemIds.map(id => Number(id)),\n },\n },\n getInternalSession(session, 'skipCharge')\n );\n return charge;\n}\n\n/* Unskip a Charge. */\nexport async function unskipCharge(\n session: Session,\n id: number | string,\n purchaseItemIds: (string | number)[],\n query?: SkipChargeParams\n) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/unskip`,\n {\n query,\n data: {\n purchase_item_ids: purchaseItemIds.map(id => Number(id)),\n },\n },\n getInternalSession(session, 'unskipCharge')\n );\n return charge;\n}\n\n/* Process a Charge. */\nexport async function processCharge(session: Session, id: number | string) {\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/process`,\n {},\n getInternalSession(session, 'processCharge')\n );\n return charge;\n}\n"],"names":["id"],"mappings":";;AAWsB,eAAA,SAAA,CAAU,OAAkB,EAAA,EAAA,EAAqB,OAA4B,EAAA;AACjG,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,KAAA;AAAA,IACA,CAAA,QAAA,CA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A;AAAA,IACd;AAAA,MACE,KAAA;AAAA,MACA,IAAM,EAAA;AAAA,QACJ,mBAAmB,eAAgB,CAAA,GAAA,CAAI,CAAAA,GAAM,KAAA,MAAA,CAAOA,GAAE,CAAC,CAAA;AAAA,OACzD;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,YAAY,CAAA;AAAA,GAC1C,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;AAGA,eAAsB,YACpB,CAAA,OAAA,EACA,EACA,EAAA,eAAA,EACA,KACA,EAAA;AACA,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,MAAA;AAAA,IACA,YAAY,EAAE,CAAA,OAAA,CAAA;AAAA,IACd;AAAA,MACE,KAAA;AAAA,MACA,IAAM,EAAA;AAAA,QACJ,mBAAmB,eAAgB,CAAA,GAAA,CAAI,CAAAA,GAAM,KAAA,MAAA,CAAOA,GAAE,CAAC,CAAA;AAAA,OACzD;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;AAGsB,eAAA,aAAA,CAAc,SAAkB,EAAqB,EAAA;AACzE,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,MAAA;AAAA,IACA,YAAY,EAAE,CAAA,QAAA,CAAA;AAAA,IACd,EAAC;AAAA,IACD,kBAAA,CAAmB,SAAS,eAAe,CAAA;AAAA,GAC7C,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"charge.js","sources":["../../../src/api/charge.ts"],"sourcesContent":["import {\n ChargeListParams,\n ChargeListResponse,\n ChargeResponse,\n GetChargeOptions,\n Session,\n SkipChargeParams,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\n\n/* Retrieve a Charge using the charge_id. */\nexport async function getCharge(session: Session, id: number | string, options?: GetChargeOptions) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'get',\n `/charges`,\n { id, query: { include: options?.include } },\n getInternalSession(session, 'getCharge')\n );\n return charge;\n}\n\n/** Lists charges */\nexport function listCharges(session: Session, query?: ChargeListParams) {\n return rechargeApiRequest<ChargeListResponse>(\n 'get',\n `/charges`,\n { query },\n getInternalSession(session, 'listCharges')\n );\n}\n\n/**\n * You cannot add a Discount to an existing queued Charge if the Charge or the associated Address already has one.\n * If a Charge has a Discount and it gets updated, or a regeneration occurs, the Discount will be lost. Regeneration is a process that refreshes the Charge JSON with new data in the case of the Subscription or Address being updated.\n */\nexport async function applyDiscountToCharge(session: Session, id: number | string, discountCode: string) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/apply_discount`,\n {\n data: { discount_code: discountCode },\n },\n getInternalSession(session, 'applyDiscountToCharge')\n );\n return charge;\n}\n\n/**\n * Remove all Discounts from a Charge without destroying the Discount.\n * In most cases the Discount should be removed from the Address. When the Discount is removed from the Address, the Discount is also removed from any future Charges.\n * If the Discount is on the parent Address, you cannot remove it using charge_id.\n * When removing your Discount, it is preferable to pass the address_id so that the Discount stays removed if the Charge is regenerated. Only pass charge_id in edge cases in which there are two or more Charges on a parent Address and you only want to remove the Discount from one Charge.\n * If you pass both parameters, it will remove the Discount from the Address.\n */\nexport async function removeDiscountsFromCharge(session: Session, id: number | string) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/remove_discount`,\n {},\n getInternalSession(session, 'removeDiscountsFromCharge')\n );\n return charge;\n}\n\n/* Skip a Charge. */\nexport async function skipCharge(\n session: Session,\n id: number | string,\n purchaseItemIds: (string | number)[],\n query?: SkipChargeParams\n) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n if (purchaseItemIds === undefined || purchaseItemIds.length === 0) {\n throw new Error('Purchase item IDs are required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/skip`,\n {\n query,\n data: {\n purchase_item_ids: purchaseItemIds.map(id => Number(id)),\n },\n },\n getInternalSession(session, 'skipCharge')\n );\n return charge;\n}\n\n/* Unskip a Charge. */\nexport async function unskipCharge(\n session: Session,\n id: number | string,\n purchaseItemIds: (string | number)[],\n query?: SkipChargeParams\n) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n if (purchaseItemIds === undefined || purchaseItemIds.length === 0) {\n throw new Error('Purchase item IDs are required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/unskip`,\n {\n query,\n data: {\n purchase_item_ids: purchaseItemIds.map(id => Number(id)),\n },\n },\n getInternalSession(session, 'unskipCharge')\n );\n return charge;\n}\n\n/* Process a Charge. */\nexport async function processCharge(session: Session, id: number | string) {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { charge } = await rechargeApiRequest<ChargeResponse>(\n 'post',\n `/charges/${id}/process`,\n {},\n getInternalSession(session, 'processCharge')\n );\n return charge;\n}\n"],"names":["id"],"mappings":";;AAWsB,eAAA,SAAA,CAAU,OAAkB,EAAA,EAAA,EAAqB,OAA4B,EAAA;AACjG,EAAI,IAAA,EAAA,KAAO,KAAa,CAAA,IAAA,EAAA,KAAO,EAAI,EAAA;AACjC,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,KAAA;AAAA,IACA,CAAA,QAAA,CAAA;AAAA,IACA,EAAE,EAAI,EAAA,KAAA,EAAO,EAAE,OAAS,EAAA,OAAA,EAAS,SAAU,EAAA;AAAA,IAC3C,kBAAA,CAAmB,SAAS,WAAW,CAAA;AAAA,GACzC,CAAA;AACA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AA,GAAM,KAAA,MAAA,CAAOA,GAAE,CAAC,CAAA;AAAA,OACzD;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT,CAAA;AAGsB,eAAA,aAAA,CAAc,SAAkB,EAAqB,EAAA;AACzE,EAAI,IAAA,EAAA,KAAO,KAAa,CAAA,IAAA,EAAA,KAAO,EAAI,EAAA;AACjC,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,MAAM,kBAAA;AAAA,IACvB,MAAA;AAAA,IACA,YAAY,EAAE,CAAA,QAAA,CAAA;AAAA,IACd,EAAC;AAAA,IACD,kBAAA,CAAmB,SAAS,eAAe,CAAA;AAAA,GAC7C,CAAA;AACA,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
@@ -2,6 +2,9 @@ import { rechargeApiRequest, getInternalSession } from '../utils/request.js';
2
2
  import { productSearch } from './product.js';
3
3
 
4
4
  async function getCollection(session, id) {
5
+ if (id === void 0 || id === "") {
6
+ throw new Error("ID is required");
7
+ }
5
8
  const { collection } = await rechargeApiRequest(
6
9
  "get",
7
10
  `/collections`,
@@ -21,6 +24,9 @@ function listCollections(session, query) {
21
24
  );
22
25
  }
23
26
  async function listCollectionProducts(session, id, query) {
27
+ if (id === void 0 || id === "") {
28
+ throw new Error("ID is required");
29
+ }
24
30
  if (!["2020-12", "2022-06"].includes(query.format_version)) {
25
31
  throw new Error("Missing or unsupported format_version.");
26
32
  }
@@ -1 +1 @@
1
- {"version":3,"file":"collection.js","sources":["../../../src/api/collection.ts"],"sourcesContent":["import {\n Collection,\n CollectionListParams,\n CollectionsResponse,\n CollectionsSortBy,\n ProductSearchParams_2020_12,\n ProductSearchParams_2022_06,\n Product_2020_12,\n Product_2022_06,\n Session,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { productSearch } from './product';\n\nexport type ProductListResponse<T extends ProductSearchParams_2020_12 | ProductSearchParams_2022_06> =\n T extends ProductSearchParams_2020_12 ? { products: Product_2020_12[] } : { products: Product_2022_06[] };\n\nexport async function getCollection(session: Session, id: string | number): Promise<Collection> {\n const { collection } = await rechargeApiRequest<{ collection: Collection }>(\n 'get',\n `/collections`,\n {\n id,\n },\n getInternalSession(session, 'getCollection')\n );\n return collection;\n}\n\nexport function listCollections(session: Session, query?: CollectionListParams): Promise<CollectionsResponse> {\n return rechargeApiRequest<CollectionsResponse>(\n 'get',\n `/collections`,\n { query },\n getInternalSession(session, 'listCollections')\n );\n}\n\nexport async function listCollectionProducts<T extends ProductSearchParams_2020_12 | ProductSearchParams_2022_06>(\n session: Session,\n id: string | number,\n query: T\n): Promise<ProductListResponse<T>> {\n if (!['2020-12', '2022-06'].includes(query.format_version)) {\n throw new Error('Missing or unsupported format_version.');\n }\n\n const internalSession = getInternalSession(session, 'listCollectionProducts');\n const [{ sort_order, manual_sort_order }, { products }] = await Promise.all([\n getCollection(internalSession, id),\n productSearch(internalSession, {\n ...query,\n collection_ids: [id],\n limit: 250,\n }),\n ]);\n if (sort_order === 'manual') {\n return {\n products: manual_sort_order.reduce((prev, curr) => {\n const product = products.find(product => product.external_product_id === curr);\n if (product) {\n // @ts-expect-error types are unhappy with push\n prev.push(product);\n }\n return prev;\n }, [] as Product_2020_12[] | Product_2022_06[]),\n } as ProductListResponse<T>;\n } else {\n const compareFn = getProductCompareFn(sort_order);\n return { products: products.slice().sort(compareFn) } as ProductListResponse<T>;\n }\n}\n\nfunction sortByCreatedAt(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aCreatedAt = a.external_created_at;\n const bCreatedAt = b.external_created_at;\n return aCreatedAt < bCreatedAt ? -1 : bCreatedAt > aCreatedAt ? 1 : 0;\n}\n\nfunction sortById(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aProductId = a.external_product_id;\n const bProductId = b.external_product_id;\n return aProductId < bProductId ? -1 : bProductId > aProductId ? 1 : 0;\n}\n\nfunction sortByTitle(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aTitle = a.title.toLowerCase();\n const bTitle = b.title.toLowerCase();\n return aTitle < bTitle ? -1 : bTitle > aTitle ? 1 : 0;\n}\n\nfunction getProductCompareFn(sortOrder: CollectionsSortBy) {\n switch (sortOrder) {\n case 'created_at-asc':\n return sortByCreatedAt;\n case 'created_at-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortByCreatedAt(b, a);\n case 'id-asc':\n return sortById;\n case 'id-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortById(b, a);\n case 'title-asc':\n return sortByTitle;\n case 'title-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortByTitle(b, a);\n }\n}\n"],"names":["product"],"mappings":";;;AAiBsB,eAAA,aAAA,CAAc,SAAkB,EAA0C,EAAA;AAC9F,EAAM,MAAA,EAAE,UAAW,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC3B,KAAA;AAAA,IACA,CAAA,YAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,eAAe,CAAA;AAAA,GAC7C,CAAA;AACA,EAAO,OAAA,UAAA,CAAA;AACT,CAAA;AAEgB,SAAA,eAAA,CAAgB,SAAkB,KAA4D,EAAA;AAC5G,EAAO,OAAA,kBAAA;AAAA,IACL,KAAA;AAAA,IACA,CAAA,YAAA,CAAA;AAAA,IACA,EAAE,KAAM,EAAA;AAAA,IACR,kBAAA,CAAmB,SAAS,iBAAiB,CAAA;AAAA,GAC/C,CAAA;AACF,CAAA;AAEsB,eAAA,sBAAA,CACpB,OACA,EAAA,EAAA,EACA,KACiC,EAAA;AACjC,EAAI,IAAA,CAAC,CAAC,SAAW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AAyC,KAAA,WAAA,CAAY,GAAG,CAAC,CAAA,CAAA;AAAA,GAC3G;AACF;;;;"}
1
+ {"version":3,"file":"collection.js","sources":["../../../src/api/collection.ts"],"sourcesContent":["import {\n Collection,\n CollectionListParams,\n CollectionsResponse,\n CollectionsSortBy,\n ProductSearchParams_2020_12,\n ProductSearchParams_2022_06,\n Product_2020_12,\n Product_2022_06,\n Session,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { productSearch } from './product';\n\nexport type ProductListResponse<T extends ProductSearchParams_2020_12 | ProductSearchParams_2022_06> =\n T extends ProductSearchParams_2020_12 ? { products: Product_2020_12[] } : { products: Product_2022_06[] };\n\nexport async function getCollection(session: Session, id: string | number): Promise<Collection> {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n const { collection } = await rechargeApiRequest<{ collection: Collection }>(\n 'get',\n `/collections`,\n {\n id,\n },\n getInternalSession(session, 'getCollection')\n );\n return collection;\n}\n\nexport function listCollections(session: Session, query?: CollectionListParams): Promise<CollectionsResponse> {\n return rechargeApiRequest<CollectionsResponse>(\n 'get',\n `/collections`,\n { query },\n getInternalSession(session, 'listCollections')\n );\n}\n\nexport async function listCollectionProducts<T extends ProductSearchParams_2020_12 | ProductSearchParams_2022_06>(\n session: Session,\n id: string | number,\n query: T\n): Promise<ProductListResponse<T>> {\n if (id === undefined || id === '') {\n throw new Error('ID is required');\n }\n if (!['2020-12', '2022-06'].includes(query.format_version)) {\n throw new Error('Missing or unsupported format_version.');\n }\n\n const internalSession = getInternalSession(session, 'listCollectionProducts');\n const [{ sort_order, manual_sort_order }, { products }] = await Promise.all([\n getCollection(internalSession, id),\n productSearch(internalSession, {\n ...query,\n collection_ids: [id],\n limit: 250,\n }),\n ]);\n if (sort_order === 'manual') {\n return {\n products: manual_sort_order.reduce((prev, curr) => {\n const product = products.find(product => product.external_product_id === curr);\n if (product) {\n // @ts-expect-error types are unhappy with push\n prev.push(product);\n }\n return prev;\n }, [] as Product_2020_12[] | Product_2022_06[]),\n } as ProductListResponse<T>;\n } else {\n const compareFn = getProductCompareFn(sort_order);\n return { products: products.slice().sort(compareFn) } as ProductListResponse<T>;\n }\n}\n\nfunction sortByCreatedAt(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aCreatedAt = a.external_created_at;\n const bCreatedAt = b.external_created_at;\n return aCreatedAt < bCreatedAt ? -1 : bCreatedAt > aCreatedAt ? 1 : 0;\n}\n\nfunction sortById(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aProductId = a.external_product_id;\n const bProductId = b.external_product_id;\n return aProductId < bProductId ? -1 : bProductId > aProductId ? 1 : 0;\n}\n\nfunction sortByTitle(a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) {\n const aTitle = a.title.toLowerCase();\n const bTitle = b.title.toLowerCase();\n return aTitle < bTitle ? -1 : bTitle > aTitle ? 1 : 0;\n}\n\nfunction getProductCompareFn(sortOrder: CollectionsSortBy) {\n switch (sortOrder) {\n case 'created_at-asc':\n return sortByCreatedAt;\n case 'created_at-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortByCreatedAt(b, a);\n case 'id-asc':\n return sortById;\n case 'id-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortById(b, a);\n case 'title-asc':\n return sortByTitle;\n case 'title-desc':\n return (a: Product_2020_12 | Product_2022_06, b: Product_2020_12 | Product_2022_06) => sortByTitle(b, a);\n }\n}\n"],"names":["product"],"mappings":";;;AAiBsB,eAAA,aAAA,CAAc,SAAkB,EAA0C,EAAA;AAC9F,EAAI,IAAA,EAAA,KAAO,KAAa,CAAA,IAAA,EAAA,KAAO,EAAI,EAAA;AACjC,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,UAAW,EAAA,GAAI,MAAM,kBAAA;AAAA,IAC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WAAY,EAAA,CAAA;AACnC,EAAA,OAAO,MAAS,GAAA,MAAA,GAAS,CAAK,CAAA,GAAA,MAAA,GAAS,SAAS,CAAI,GAAA,CAAA,CAAA;AACtD,CAAA;AAEA,SAAS,oBAAoB,SAA8B,EAAA;AACzD,EAAA,QAAQ,SAAW;AAAA,IACjB,KAAK,gBAAA;AACH,MAAO,OAAA,eAAA,CAAA;AAAA,IACT,KAAK,iBAAA;AACH,MAAA,OAAO,CAAC,CAAA,EAAsC,CAAyC,KAAA,eAAA,CAAgB,GAAG,CAAC,CAAA,CAAA;AAAA,IAC7G,KAAK,QAAA;AACH,MAAO,OAAA,QAAA,CAAA;AAAA,IACT,KAAK,SAAA;AACH,MAAA,OAAO,CAAC,CAAA,EAAsC,CAAyC,KAAA,QAAA,CAAS,GAAG,CAAC,CAAA,CAAA;AAAA,IACtG,KAAK,WAAA;AACH,MAAO,OAAA,WAAA,CAAA;AAAA,IACT,KAAK,YAAA;AACH,MAAA,OAAO,CAAC,CAAA,EAAsC,CAAyC,KAAA,WAAA,CAAY,GAAG,CAAC,CAAA,CAAA;AAAA,GAC3G;AACF;;;;"}
@@ -51,6 +51,9 @@ async function getCustomerPortalAccess(session, query) {
51
51
  );
52
52
  }
53
53
  async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL) {
54
+ if (subscriptionId === void 0 || subscriptionId === "") {
55
+ throw new Error("Subscription ID is required");
56
+ }
54
57
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
55
58
  getInternalSession(session, "getActiveChurnLandingPageURL")
56
59
  );
@@ -60,6 +63,9 @@ async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL
60
63
  )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${redirectURL}`;
61
64
  }
62
65
  async function getGiftRedemptionLandingPageURL(session, giftId, redirectURL) {
66
+ if (giftId === void 0 || giftId === "") {
67
+ throw new Error("Gift ID is required");
68
+ }
63
69
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
64
70
  getInternalSession(session, "getGiftRedemptionLandingPageURL")
65
71
  );