@rechargeapps/storefront-client 1.16.2 → 1.17.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.
@@ -14,6 +14,9 @@ async function loginShopifyAppProxy() {
14
14
  return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };
15
15
  }
16
16
  async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToken) {
17
+ return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);
18
+ }
19
+ async function loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken) {
17
20
  const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = options.getOptions();
18
21
  const rechargeBaseUrl = api.RECHARGE_ADMIN_URL(environment, environmentUri);
19
22
  const headers = {};
@@ -34,6 +37,26 @@ async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToke
34
37
  });
35
38
  return apiToken ? { apiToken, customerId, message } : null;
36
39
  }
40
+ async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken) {
41
+ const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = options.getOptions();
42
+ const rechargeBaseUrl = api.RECHARGE_ADMIN_URL(environment, environmentUri);
43
+ const headers = {};
44
+ if (storefrontAccessToken) {
45
+ headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
46
+ }
47
+ const {
48
+ api_token: apiToken,
49
+ customer_id: customerId,
50
+ message
51
+ } = await request.request("post", `${rechargeBaseUrl}/shopify_customer_account_api_access`, {
52
+ data: {
53
+ customer_token: shopifyCustomerAccessToken,
54
+ shop_url: storeIdentifier
55
+ },
56
+ headers
57
+ });
58
+ return apiToken ? { apiToken, customerId, message } : null;
59
+ }
37
60
  async function sendPasswordlessCode(email, options$1 = {}) {
38
61
  const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = options.getOptions();
39
62
  const rechargeBaseUrl = api.RECHARGE_ADMIN_URL(environment, environmentUri);
@@ -145,6 +168,8 @@ async function loginCustomerPortal() {
145
168
  exports.loginCustomerPortal = loginCustomerPortal;
146
169
  exports.loginShopifyApi = loginShopifyApi;
147
170
  exports.loginShopifyAppProxy = loginShopifyAppProxy;
171
+ exports.loginWithShopifyCustomerAccount = loginWithShopifyCustomerAccount;
172
+ exports.loginWithShopifyStorefront = loginWithShopifyStorefront;
148
173
  exports.sendPasswordlessCode = sendPasswordlessCode;
149
174
  exports.sendPasswordlessCodeAppProxy = sendPasswordlessCodeAppProxy;
150
175
  exports.validatePasswordlessCode = validatePasswordlessCode;
@@ -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 PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n} from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\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 { 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] : undefined;\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["getOptions","shopifyAppProxyRequest","RECHARGE_ADMIN_URL","baseRequest","options"],"mappings":";;;;;;AAYA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAIA,kBAAW,EAAA,CAAA;AAC7C,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,G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,EAAA,eAAA,KAAoBD,kBAAW,EAAA,CAAA;AAC3F,EAAM,MAAA,eAAA,GAAkBE,sBAAmB,CAAA,WAAA,EAAa,cAAc,CAAA,CAAA;AACtE,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAM,MAAA,QAAA,GAAW,MAAMC,eAA2B,CAAA,MAAA,EAAQ,GAAG,eAAe,CAAA,WAAA,EAAc,YAAY,CAAW,OAAA,CAAA,EAAA;AAAA,IAC/G,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,KAAA;AAAA,MACA,IAAM,EAAA,eAAA;AAAA,KACR;AAAA,GACD,CAAA,CAAA;AAED,EAAA,OAAO,EAAE,QAAU,EAAA,QAAA,CAAS,SAAW,EAAA,UAAA,EAAY,SAAS,WAAY,EAAA,CAAA;AAC1E;;;;;;;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n} from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_customer_account_api_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\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 { 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] : undefined;\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["getOptions","shopifyAppProxyRequest","RECHARGE_ADMIN_URL","baseRequest","options"],"mappings":";;;;;;AAYA,eAAsB,oBAAyC,GAAA;AAC7D,EAAM,MAAA,EAAE,qBAAsB,EAAA,GAAIA,kBAAW,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,MAAMC,8BAAA,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,0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');
6
- var cdn = require('./cdn.js');
7
6
  var bundle = require('../utils/bundle.js');
8
7
 
9
8
  const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
@@ -94,10 +93,6 @@ async function validateBundle(bundle) {
94
93
  if (!bundle) {
95
94
  return "Bundle is not defined";
96
95
  }
97
- const bundleSettings = await cdn.getCDNBundleSettings(bundle.externalProductId);
98
- if (!bundleSettings) {
99
- return "Bundle settings do not exist for the given product";
100
- }
101
96
  return true;
102
97
  } catch (e) {
103
98
  return `Error fetching bundle settings: ${e}`;
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\nimport { 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 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 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 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\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 session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\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 session\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 session\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 session\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 session\n );\n\n return subscription;\n}\n"],"names":["shopifyAppProxyRequest","bundle","getOptions","toLineItemProperty","nanoid","getCDNBundleSettings","rechargeApiRequest"],"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;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gB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAO,OAAAA,0BAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,OAAA;AAAA,GACF,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAMA,0BAAA;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,OAAA;AAAA,GACF,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\nimport { 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 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 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\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 session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\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 session\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 session\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 session\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 session\n );\n\n return subscription;\n}\n"],"names":["shopifyAppProxyRequest","bundle","getOptions","toLineItemProperty","nanoid","rechargeApiRequest"],"mappings":";;;;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F,CAAA;AACA,EAAO,OAAA,gBAAA,CAAA;AACT,CAAA;AAEgB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAO,OAAAA,0BAAA;AAAA,IACL,QAAA;AAAA,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACA,OAAA;AAAA,GACF,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAMA,0BAAA;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,OAAA;AAAA,GACF,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;;;;;;;;;;"}
package/dist/cjs/index.js CHANGED
@@ -33,6 +33,8 @@ exports.updateAddress = address.updateAddress;
33
33
  exports.loginCustomerPortal = auth.loginCustomerPortal;
34
34
  exports.loginShopifyApi = auth.loginShopifyApi;
35
35
  exports.loginShopifyAppProxy = auth.loginShopifyAppProxy;
36
+ exports.loginWithShopifyCustomerAccount = auth.loginWithShopifyCustomerAccount;
37
+ exports.loginWithShopifyStorefront = auth.loginWithShopifyStorefront;
36
38
  exports.sendPasswordlessCode = auth.sendPasswordlessCode;
37
39
  exports.sendPasswordlessCodeAppProxy = auth.sendPasswordlessCodeAppProxy;
38
40
  exports.validatePasswordlessCode = auth.validatePasswordlessCode;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -12,6 +12,9 @@ async function loginShopifyAppProxy() {
12
12
  return { apiToken: response.api_token, customerId: response.customer_id, message: response.message };
13
13
  }
14
14
  async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToken) {
15
+ return loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken);
16
+ }
17
+ async function loginWithShopifyStorefront(shopifyStorefrontToken, shopifyCustomerAccessToken) {
15
18
  const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();
16
19
  const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
17
20
  const headers = {};
@@ -32,6 +35,26 @@ async function loginShopifyApi(shopifyStorefrontToken, shopifyCustomerAccessToke
32
35
  });
33
36
  return apiToken ? { apiToken, customerId, message } : null;
34
37
  }
38
+ async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken) {
39
+ const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();
40
+ const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
41
+ const headers = {};
42
+ if (storefrontAccessToken) {
43
+ headers["X-Recharge-Storefront-Access-Token"] = storefrontAccessToken;
44
+ }
45
+ const {
46
+ api_token: apiToken,
47
+ customer_id: customerId,
48
+ message
49
+ } = await request("post", `${rechargeBaseUrl}/shopify_customer_account_api_access`, {
50
+ data: {
51
+ customer_token: shopifyCustomerAccessToken,
52
+ shop_url: storeIdentifier
53
+ },
54
+ headers
55
+ });
56
+ return apiToken ? { apiToken, customerId, message } : null;
57
+ }
35
58
  async function sendPasswordlessCode(email, options = {}) {
36
59
  const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();
37
60
  const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);
@@ -140,5 +163,5 @@ async function loginCustomerPortal() {
140
163
  return { apiToken: response.api_token, customerId: response.customer_id };
141
164
  }
142
165
 
143
- export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
166
+ export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
144
167
  //# sourceMappingURL=auth.js.map
@@ -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 PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n} from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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\nexport async function loginShopifyApi(\n shopifyStorefrontToken: string,\n shopifyCustomerAccessToken?: string\n): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\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 { 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] : undefined;\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["baseRequest"],"mappings":";;;;AAYA,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,qBAA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,KAAoB,UAAW,EAAA,CAAA;AAC3F,EAAM,MAAA,eAAA,GAAkB,kBAAmB,CAAA,WAAA,EAAa,cAAc,CAAA,CAAA;AACtE,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAM,MAAA,QAAA,GAAW,MAAMA,OAA2B,CAAA,MAAA,EAAQ,GAAG,eAAe,CAAA,WAAA,EAAc,YAAY,CAAW,OAAA,CAAA,EAAA;AAAA,IAC/G,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,KAAA;AAAA,MACA,IAAM,EAAA,eAAA;AAAA,KACR;AAAA,GACD,CAAA,CAAA;AAED,EAAA,OAAO,EAAE,QAAU,EAAA,QAAA,CAAS,SAAW,EAAA,UAAA,EAAY,SAAS,WAAY,EAAA,CAAA;AAC1E;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../src/api/auth.ts"],"sourcesContent":["import { request as baseRequest, shopifyAppProxyRequest } from '../utils/request';\nimport {\n LoginResponse,\n PasswordlessCodeResponse,\n PasswordlessOptions,\n PasswordlessValidateResponse,\n} from '../types/auth';\nimport { getOptions } from '../utils/options';\nimport { RECHARGE_ADMIN_URL } from '../constants/api';\nimport { Session } from '../types/session';\nimport { RequestHeaders } from '../types';\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_storefront_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n storefront_token: shopifyStorefrontToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const {\n api_token: apiToken,\n customer_id: customerId,\n message,\n } = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/shopify_customer_account_api_access`, {\n data: {\n customer_token: shopifyCustomerAccessToken,\n shop_url: storeIdentifier,\n },\n headers,\n });\n\n return apiToken ? { apiToken, customerId, message } : null;\n}\n\nexport async function sendPasswordlessCode(email: string, options: PasswordlessOptions = {}): Promise<string> {\n const { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessCodeResponse>('post', `${rechargeBaseUrl}/attempt_login`, {\n data: {\n email,\n shop: storeIdentifier,\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 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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<PasswordlessValidateResponse>('post', `${rechargeBaseUrl}/validate_login`, {\n data: {\n code,\n email,\n session_token,\n shop: storeIdentifier,\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\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 { 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] : undefined;\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 { environment, environmentUri, storefrontAccessToken, storeIdentifier } = getOptions();\n const rechargeBaseUrl = RECHARGE_ADMIN_URL(environment, environmentUri);\n const headers: RequestHeaders = {};\n if (storefrontAccessToken) {\n headers['X-Recharge-Storefront-Access-Token'] = storefrontAccessToken;\n }\n const response = await baseRequest<LoginResponse>('post', `${rechargeBaseUrl}/customers/${customerHash}/access`, {\n headers,\n data: {\n token,\n shop: storeIdentifier,\n },\n });\n\n return { apiToken: response.api_token, customerId: response.customer_id };\n}\n"],"names":["baseRequest"],"mappings":";;;;AAYA,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,MAAM,EAAE,WAAa,EAAA,cAAA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A,CAAA,CAAA,GAAK,QAAS,CAAA,WAAA,GAAc,CAAC,CAAI,GAAA,KAAA,CAAA,CAAA;AAGtE,EAAI,IAAA,CAAC,KAAS,IAAA,CAAC,YAAc,EAAA;AAC3B,IAAM,MAAA,IAAI,MAAM,kFAAkF,CAAA,CAAA;AAAA,GACpG;AACA,EAAO,OAAA,EAAE,cAAc,KAAM,EAAA,CAAA;AAC/B,CAAA;AAEA,eAAsB,mBAAwC,GAAA;AAC5D,EAAA,MAAM,EAAE,YAAA,EAAc,KAAM,EAAA,GAAI,iBAAkB,EAAA,CAAA;AAClD,EAAA,MAAM,EAAE,WAAa,EAAA,cAAA,EAAgB,qBAAuB,EAAA,eAAA,KAAoB,UAAW,EAAA,CAAA;AAC3F,EAAM,MAAA,eAAA,GAAkB,kBAAmB,CAAA,WAAA,EAAa,cAAc,CAAA,CAAA;AACtE,EAAA,MAAM,UAA0B,EAAC,CAAA;AACjC,EAAA,IAAI,qBAAuB,EAAA;AACzB,IAAA,OAAA,CAAQ,oCAAoC,CAAI,GAAA,qBAAA,CAAA;AAAA,GAClD;AACA,EAAM,MAAA,QAAA,GAAW,MAAMA,OAA2B,CAAA,MAAA,EAAQ,GAAG,eAAe,CAAA,WAAA,EAAc,YAAY,CAAW,OAAA,CAAA,EAAA;AAAA,IAC/G,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,KAAA;AAAA,MACA,IAAM,EAAA,eAAA;AAAA,KACR;AAAA,GACD,CAAA,CAAA;AAED,EAAA,OAAO,EAAE,QAAU,EAAA,QAAA,CAAS,SAAW,EAAA,UAAA,EAAY,SAAS,WAAY,EAAA,CAAA;AAC1E;;;;"}
@@ -1,7 +1,6 @@
1
1
  import { nanoid } from 'nanoid';
2
2
  import { shopifyAppProxyRequest, rechargeApiRequest } from '../utils/request.js';
3
3
  import { getOptions } from '../utils/options.js';
4
- import { getCDNBundleSettings } from './cdn.js';
5
4
  import { toLineItemProperty } from '../utils/bundle.js';
6
5
 
7
6
  const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
@@ -92,10 +91,6 @@ async function validateBundle(bundle) {
92
91
  if (!bundle) {
93
92
  return "Bundle is not defined";
94
93
  }
95
- const bundleSettings = await getCDNBundleSettings(bundle.externalProductId);
96
- if (!bundleSettings) {
97
- return "Bundle settings do not exist for the given product";
98
- }
99
94
  return true;
100
95
  } catch (e) {
101
96
  return `Error fetching bundle settings: ${e}`;
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\nimport { 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 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 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 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\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 session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\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 session\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 session\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 session\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 session\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,CAAM,EAAA,CAAA,EAAA;AAAA,MAC/G,OAAA,EAAS,EAAE,gBAA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A,IACA,OAAA;AAAA,GACF,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,OAAA;AAAA,GACF,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
1
+ {"version":3,"file":"bundle.js","sources":["../../../src/api/bundle.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport {\n BundleAppProxy,\n DynamicBundleItemAppProxy,\n BundleSelection,\n BundleSelectionListParams,\n BundleSelectionsResponse,\n CreateBundleSelectionRequest,\n Session,\n UpdateBundleSelectionRequest,\n UpdateBundlePurchaseItem,\n BundlePurchaseItem,\n BundlePurchaseItemParams,\n} from '../types';\nimport { rechargeApiRequest, shopifyAppProxyRequest } from '../utils/request';\nimport { getOptions } from '../utils/options';\nimport { getCDNBundleSettings } from './cdn';\nimport { 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 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 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\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 session\n );\n return bundle_selection;\n}\n\nexport function listBundleSelections(\n session: Session,\n query?: BundleSelectionListParams\n): Promise<BundleSelectionsResponse> {\n return rechargeApiRequest<BundleSelectionsResponse>('get', `/bundle_selections`, { query }, session);\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 session\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 session\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 session\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 session\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,MAA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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,OAAA;AAAA,GACF,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;"}
package/dist/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { applyDiscountToAddress, createAddress, deleteAddress, getAddress, listAddresses, mergeAddresses, removeDiscountsFromAddress, skipFutureCharge, updateAddress } from './api/address.js';
2
- export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy } from './api/auth.js';
2
+ export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy } from './api/auth.js';
3
3
  export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSelection, getDynamicBundleItems, listBundleSelections, updateBundle, updateBundleSelection, validateBundle, validateDynamicBundle } from './api/bundle.js';
4
4
  export { getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, resetCDNCache } from './api/cdn.js';
5
5
  export { applyDiscountToCharge, getCharge, listCharges, processCharge, removeDiscountsFromCharge, skipCharge, unskipCharge } from './api/charge.js';
package/dist/index.d.ts CHANGED
@@ -1450,7 +1450,10 @@ interface PasswordlessValidateResponse {
1450
1450
  }
1451
1451
 
1452
1452
  declare function loginShopifyAppProxy(): Promise<Session>;
1453
+ /** @deprecated Use `loginWithShopifyStorefront` instead */
1453
1454
  declare function loginShopifyApi(shopifyStorefrontToken: string, shopifyCustomerAccessToken?: string): Promise<Session | null>;
1455
+ declare function loginWithShopifyStorefront(shopifyStorefrontToken: string, shopifyCustomerAccessToken?: string): Promise<Session | null>;
1456
+ declare function loginWithShopifyCustomerAccount(shopifyCustomerAccessToken?: string): Promise<Session | null>;
1454
1457
  declare function sendPasswordlessCode(email: string, options?: PasswordlessOptions): Promise<string>;
1455
1458
  declare function sendPasswordlessCodeAppProxy(email: string, options?: PasswordlessOptions): Promise<string>;
1456
1459
  declare function validatePasswordlessCode(email: string, session_token: string, code: string): Promise<Session>;
@@ -2646,4 +2649,4 @@ declare const api: {
2646
2649
  };
2647
2650
  declare function initRecharge(opt?: InitOptions): void;
2648
2651
 
2649
- export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BundleAppProxy, type BundlePriceRule, type BundleProduct, type BundleProductLayoutSettings, type BundlePurchaseItem, type BundlePurchaseItemParams, type BundleSelection, type BundleSelectionAppProxy, type BundleSelectionItem, type BundleSelectionItemRequiredCreateProps, type BundleSelectionListParams, type BundleSelectionsResponse, type BundleSelectionsSortBy, type BundleTemplateSettings, type BundleTemplateType, type BundleTranslations, type BundleVariant, type BundleVariantOptionSource, type BundleVariantRange, type BundleVariantSelectionDefault, type CDNBaseWidgetSettings, type CDNBundleSettings, type CDNBundleVariant, type CDNBundleVariantOptionSource, type CDNPlan, type CDNProduct, type CDNProductAndSettings, type CDNProductKeyObject, type CDNProductQuery_2020_12, type CDNProductQuery_2022_06, type CDNProductRaw, type CDNProductResource, type CDNProductResponseType, type CDNProductType, type CDNProductVariant_2022_06, type CDNProduct_2022_06, type CDNProductsAndSettings, type CDNProductsAndSettingsResource, type CDNStoreSettings, type CDNSubscriptionOption, type CDNVariant, type CDNVersion, type CDNWidgetSettings, type CDNWidgetSettingsRaw, type CDNWidgetSettingsResource, type CRUDRequestOptions, type CancelMembershipRequest, type CancelSubscriptionRequest, type ChangeMembershipRequest, type ChannelSettings, type Charge, type ChargeIncludes, type ChargeListParams, type ChargeListResponse, type ChargeResponse, type ChargeSortBy, type ChargeStatus, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreditAccount, type CreditAccountType, type CreditSummaryIncludes, type CrossSellsSettings, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessResponse, type Delivery, type DeliveryLineItem, type DeliveryOrder, type DeliveryPaymentMethod, type Discount, type DiscountType, type DynamicBundleItemAppProxy, type DynamicBundlePropertiesAppProxy, type ExternalAttributeSchema, type ExternalId, type ExternalTransactionId, type FirstOption, type GetAddressOptions, type GetChargeOptions, type GetCreditSummaryOptions, type GetCustomerOptions, type GetMembershipProgramOptions, type GetPaymentMethodOptions, type GetRequestOptions, type GetSubscriptionOptions, type GiftPurchase, type GiftPurchasesParams, type GiftPurchasesResponse, type HTMLString, type InitOptions, type IntervalUnit, type IsoDateString, type LineItem, type ListParams, type LoginResponse, type Membership, type MembershipBenefit, type MembershipIncludes, type MembershipListParams, type MembershipListResponse, type MembershipProgram, type MembershipProgramIncludes, type MembershipProgramListParams, type MembershipProgramListResponse, type MembershipProgramResponse, type MembershipProgramSortBy, type MembershipProgramStatus, type MembershipResponse, type MembershipStatus, type MembershipsSortBy, type MergeAddressesRequest, type Metafield, type MetafieldOptionalCreateProps, type MetafieldOwnerResource, type MetafieldRequiredCreateProps, type Method, type Modifier, type MultiStepSettings, type OnePageSettings, type Onetime, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimesResponse, type OnetimesSortBy, type Order, type OrderIncludes, type OrderListParams, type OrderSortBy, type OrderStatus, type OrderType, type OrdersResponse, type PasswordlessCodeResponse, type PasswordlessOptions, type PasswordlessValidateResponse, type PaymentDetails, type PaymentMethod, type PaymentMethodIncludes, type PaymentMethodListParams, type PaymentMethodOptionalCreateProps, type PaymentMethodRequiredCreateProps, type PaymentMethodSortBy, type PaymentMethodStatus, type PaymentMethodsResponse, type PaymentType, type Plan, type PlanListParams, type PlanSortBy, type PlanType, type PlansResponse, type ProcessorName, type ProductImage, type ProductInclude, type ProductOption, type ProductSearchParams_2020_12, type ProductSearchParams_2022_06, type ProductSearchResponse_2020_12, type ProductSearchResponse_2022_06, type ProductSearchType, type ProductSource, type ProductValueOption, type ProductVariant_2020_12, type ProductVariant_2022_06, type Product_2020_12, type Product_2022_06, type Property, type PublishStatus, type Request, type RequestHeaders, type RequestOptions, type SellingPlan, type SellingPlanGroup, type Session, type ShippingCountriesOptions, type ShippingCountriesResponse, type ShippingCountry, type ShippingLine, type ShippingProvince, type ShopifyUpdatePaymentInfoOptions, type SkipChargeParams, type SkipFutureChargeAddressRequest, type SkipFutureChargeAddressResponse, type SortBy, type SortField, type SortKeys, type StepSettings, type StepSettingsCommon, type StepSettingsTypes, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionIncludes, type SubscriptionListParams, type SubscriptionOption, type SubscriptionOptionalCreateProps, type SubscriptionPreferences, type SubscriptionRequiredCreateProps, type SubscriptionSortBy, type SubscriptionStatus, type Subscription_2021_01, type SubscriptionsResponse, type TaxLine, type Translations, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionParams, type UpdateSubscriptionRequest, type UpdateSubscriptionsParams, type UpdateSubscriptionsRequest, type VariantSelector, type VariantSelectorStepSetting, type WidgetIconColor, type WidgetTemplateType, type WidgetVisibility, activateMembership, activateSubscription, api, applyDiscountToAddress, applyDiscountToCharge, cancelMembership, cancelSubscription, changeMembership, createAddress, createBundleSelection, createMetafield, createOnetime, createPaymentMethod, createSubscription, createSubscriptions, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
2652
+ export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BundleAppProxy, type BundlePriceRule, type BundleProduct, type BundleProductLayoutSettings, type BundlePurchaseItem, type BundlePurchaseItemParams, type BundleSelection, type BundleSelectionAppProxy, type BundleSelectionItem, type BundleSelectionItemRequiredCreateProps, type BundleSelectionListParams, type BundleSelectionsResponse, type BundleSelectionsSortBy, type BundleTemplateSettings, type BundleTemplateType, type BundleTranslations, type BundleVariant, type BundleVariantOptionSource, type BundleVariantRange, type BundleVariantSelectionDefault, type CDNBaseWidgetSettings, type CDNBundleSettings, type CDNBundleVariant, type CDNBundleVariantOptionSource, type CDNPlan, type CDNProduct, type CDNProductAndSettings, type CDNProductKeyObject, type CDNProductQuery_2020_12, type CDNProductQuery_2022_06, type CDNProductRaw, type CDNProductResource, type CDNProductResponseType, type CDNProductType, type CDNProductVariant_2022_06, type CDNProduct_2022_06, type CDNProductsAndSettings, type CDNProductsAndSettingsResource, type CDNStoreSettings, type CDNSubscriptionOption, type CDNVariant, type CDNVersion, type CDNWidgetSettings, type CDNWidgetSettingsRaw, type CDNWidgetSettingsResource, type CRUDRequestOptions, type CancelMembershipRequest, type CancelSubscriptionRequest, type ChangeMembershipRequest, type ChannelSettings, type Charge, type ChargeIncludes, type ChargeListParams, type ChargeListResponse, type ChargeResponse, type ChargeSortBy, type ChargeStatus, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreditAccount, type CreditAccountType, type CreditSummaryIncludes, type CrossSellsSettings, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessResponse, type Delivery, type DeliveryLineItem, type DeliveryOrder, type DeliveryPaymentMethod, type Discount, type DiscountType, type DynamicBundleItemAppProxy, type DynamicBundlePropertiesAppProxy, type ExternalAttributeSchema, type ExternalId, type ExternalTransactionId, type FirstOption, type GetAddressOptions, type GetChargeOptions, type GetCreditSummaryOptions, type GetCustomerOptions, type GetMembershipProgramOptions, type GetPaymentMethodOptions, type GetRequestOptions, type GetSubscriptionOptions, type GiftPurchase, type GiftPurchasesParams, type GiftPurchasesResponse, type HTMLString, type InitOptions, type IntervalUnit, type IsoDateString, type LineItem, type ListParams, type LoginResponse, type Membership, type MembershipBenefit, type MembershipIncludes, type MembershipListParams, type MembershipListResponse, type MembershipProgram, type MembershipProgramIncludes, type MembershipProgramListParams, type MembershipProgramListResponse, type MembershipProgramResponse, type MembershipProgramSortBy, type MembershipProgramStatus, type MembershipResponse, type MembershipStatus, type MembershipsSortBy, type MergeAddressesRequest, type Metafield, type MetafieldOptionalCreateProps, type MetafieldOwnerResource, type MetafieldRequiredCreateProps, type Method, type Modifier, type MultiStepSettings, type OnePageSettings, type Onetime, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimesResponse, type OnetimesSortBy, type Order, type OrderIncludes, type OrderListParams, type OrderSortBy, type OrderStatus, type OrderType, type OrdersResponse, type PasswordlessCodeResponse, type PasswordlessOptions, type PasswordlessValidateResponse, type PaymentDetails, type PaymentMethod, type PaymentMethodIncludes, type PaymentMethodListParams, type PaymentMethodOptionalCreateProps, type PaymentMethodRequiredCreateProps, type PaymentMethodSortBy, type PaymentMethodStatus, type PaymentMethodsResponse, type PaymentType, type Plan, type PlanListParams, type PlanSortBy, type PlanType, type PlansResponse, type ProcessorName, type ProductImage, type ProductInclude, type ProductOption, type ProductSearchParams_2020_12, type ProductSearchParams_2022_06, type ProductSearchResponse_2020_12, type ProductSearchResponse_2022_06, type ProductSearchType, type ProductSource, type ProductValueOption, type ProductVariant_2020_12, type ProductVariant_2022_06, type Product_2020_12, type Product_2022_06, type Property, type PublishStatus, type Request, type RequestHeaders, type RequestOptions, type SellingPlan, type SellingPlanGroup, type Session, type ShippingCountriesOptions, type ShippingCountriesResponse, type ShippingCountry, type ShippingLine, type ShippingProvince, type ShopifyUpdatePaymentInfoOptions, type SkipChargeParams, type SkipFutureChargeAddressRequest, type SkipFutureChargeAddressResponse, type SortBy, type SortField, type SortKeys, type StepSettings, type StepSettingsCommon, type StepSettingsTypes, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionIncludes, type SubscriptionListParams, type SubscriptionOption, type SubscriptionOptionalCreateProps, type SubscriptionPreferences, type SubscriptionRequiredCreateProps, type SubscriptionSortBy, type SubscriptionStatus, type Subscription_2021_01, type SubscriptionsResponse, type TaxLine, type Translations, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionParams, type UpdateSubscriptionRequest, type UpdateSubscriptionsParams, type UpdateSubscriptionsRequest, type VariantSelector, type VariantSelectorStepSetting, type WidgetIconColor, type WidgetTemplateType, type WidgetVisibility, activateMembership, activateSubscription, api, applyDiscountToAddress, applyDiscountToCharge, cancelMembership, cancelSubscription, changeMembership, createAddress, createBundleSelection, createMetafield, createOnetime, createPaymentMethod, createSubscription, createSubscriptions, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };