@rechargeapps/storefront-client 1.37.1 → 1.38.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.
@@ -181,7 +181,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
181
181
  ...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
182
182
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
183
183
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
184
- "X-Recharge-Sdk-Version": "1.37.1",
184
+ "X-Recharge-Sdk-Version": "1.38.1",
185
185
  ...headers ? headers : {}
186
186
  };
187
187
  return request.request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
@@ -18,14 +18,22 @@ async function getTimestampSecondsFromServer() {
18
18
  return getTimestampSecondsFromClient();
19
19
  }
20
20
  }
21
- async function getBundleId(bundle$1) {
22
- const opts = options.getOptions();
23
- const isValid = await validateBundle(bundle$1);
24
- if (isValid !== true) {
25
- throw new Error(isValid);
21
+ async function getTimestampSecondsFromServerApi(internalSession) {
22
+ try {
23
+ const { timestamp } = await request.rechargeApiRequest(
24
+ "get",
25
+ `/bundle_selections/timestamp`,
26
+ {},
27
+ internalSession
28
+ );
29
+ return timestamp;
30
+ } catch (ex) {
31
+ console.error(`Fetch failed: ${ex}. Using client-side date.`);
32
+ return getTimestampSecondsFromClient();
26
33
  }
27
- const timestampSeconds = await getTimestampSecondsFromServer();
28
- const bundleData = bundle.toLineItemProperty({
34
+ }
35
+ function createBundleData(bundle$1, timestampSeconds) {
36
+ return bundle.toLineItemProperty({
29
37
  variantId: bundle$1.externalVariantId,
30
38
  version: timestampSeconds,
31
39
  items: bundle$1.selections.map((item) => {
@@ -38,6 +46,15 @@ async function getBundleId(bundle$1) {
38
46
  };
39
47
  })
40
48
  });
49
+ }
50
+ async function getBundleId(bundle) {
51
+ const opts = options.getOptions();
52
+ const isValid = await validateBundle(bundle);
53
+ if (isValid !== true) {
54
+ throw new Error(isValid);
55
+ }
56
+ const timestampSeconds = await getTimestampSecondsFromServer();
57
+ const bundleData = createBundleData(bundle, timestampSeconds);
41
58
  try {
42
59
  const payload = await request.shopifyAppProxyRequest(
43
60
  "post",
@@ -59,6 +76,33 @@ async function getBundleId(bundle$1) {
59
76
  throw new Error(`2: failed generating rb_id ${e}`);
60
77
  }
61
78
  }
79
+ async function getBundleSelectionId(session, bundle) {
80
+ const isValid = await validateBundle(bundle);
81
+ if (isValid !== true) {
82
+ throw new Error(isValid);
83
+ }
84
+ const internalSession = request.getInternalSession(session, "getBundleSelectionId");
85
+ const timestampSeconds = await getTimestampSecondsFromServerApi(internalSession);
86
+ const bundleData = createBundleData(bundle, timestampSeconds);
87
+ try {
88
+ const payload = await request.rechargeApiRequest(
89
+ "post",
90
+ `/bundle_selections/bundle_id`,
91
+ {
92
+ data: {
93
+ bundle: bundleData
94
+ }
95
+ },
96
+ internalSession
97
+ );
98
+ if (!payload.id || payload.code !== 200) {
99
+ throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);
100
+ }
101
+ return payload.id;
102
+ } catch (e) {
103
+ throw new Error(`2: failed generating rb_id ${e}`);
104
+ }
105
+ }
62
106
  function getDynamicBundleItems(bundle, shopifyProductHandle) {
63
107
  const isValid = validateDynamicBundle(bundle);
64
108
  if (isValid !== true) {
@@ -91,6 +135,9 @@ async function validateBundle(bundle) {
91
135
  if (!bundle) {
92
136
  return "Bundle is not defined";
93
137
  }
138
+ if (bundle.selections.length === 0) {
139
+ return "No selections defined";
140
+ }
94
141
  return true;
95
142
  } catch (e) {
96
143
  return `Error fetching bundle settings: ${e}`;
@@ -221,6 +268,7 @@ exports.createBundleSelection = createBundleSelection;
221
268
  exports.deleteBundleSelection = deleteBundleSelection;
222
269
  exports.getBundleId = getBundleId;
223
270
  exports.getBundleSelection = getBundleSelection;
271
+ exports.getBundleSelectionId = getBundleSelectionId;
224
272
  exports.getDynamicBundleItems = getDynamicBundleItems;
225
273
  exports.listBundleSelections = listBundleSelections;
226
274
  exports.updateBundle = updateBundle;
@@ -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 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":["shopifyAppProxyRequest","bundle","getOptions","toLineItemProperty","nanoid","BundleSelectionValidator","rechargeApiRequest","getInternalSession"],"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,MAAMA,+BAA8C,KAAO,EAAA,CAAA,EAAG,uBAAuB,CAAI,EAAA,CAAA,CAAA,CAAA;AAC/G,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,CAAA,CAAA;AAC5D,IAAA,OAAO,6BAA8B,EAAA,CAAA;AAAA,GACvC;AACF,CAAA;AAEA,eAAsB,YAAYC,QAAyC,EAAA;AACzE,EAAA,MAAM,OAAOC,kBAAW,EAAA,CAAA;AACxB,EAAM,MAAA,OAAA,GAAU,MAAM,cAAA,CAAeD,QAAM,CAAA,CAAA;AAC3C,EAAA,IAAI,YAAY,IAAM,EAAA;AACpB,IAAM,MAAA,IAAI,MAAM,OAAO,CAAA,CAAA;AAAA,GACzB;AACA,EAAM,MAAA,gBAAA,GAAmB,MAAM,6BAA8B,EAAA,CAAA;AAC7D,EAAA,MAAM,aAAaE,yBAAmB,CAAA;AAAA,IACpC,WAAWF,QAAO,CAAA,iBAAA;AAAA,IAClB,OAAS,EAAA,gBAAA;AAAA,IACT,KAAO,EAAAA,QAAA,CAAO,UAAW,CAAA,GAAA,CAAI,CAAQ,IAAA,KAAA;AACnC,MAAO,OAAA;AAAA,QACL,cAAc,IAAK,CAAA,YAAA;AAAA,QACnB,WAAW,IAAK,CAAA,iBAAA;AAAA,QAChB,WAAW,IA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,IACA,CAAA,kBAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,KACF;AAAA,IACAC,0BAAA,CAAmB,SAAS,uBAAuB,CAAA;AAAA,GACrD,CAAA;AACF,CAAA;AAEA,eAAsB,YACpB,CAAA,OAAA,EACA,gBACA,EAAA,aAAA,EACA,KAC6B,EAAA;AAC7B,EAAI,IAAA,gBAAA,KAAqB,KAAa,CAAA,IAAA,gBAAA,KAAqB,EAAI,EAAA;AAC7D,IAAM,MAAA,IAAI,MAAM,8BAA8B,CAAA,CAAA;AAAA,GAChD;AACA,EAAM,MAAA,EAAE,YAAa,EAAA,GAAI,MAAMD,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,IACAC,0BAAA,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 InternalSession,\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\nasync function getTimestampSecondsFromServerApi(internalSession: InternalSession): Promise<number> {\n /**\n * Same as getTimestampSecondsFromServer, but using the recharge API server instead of the storefront manager.\n * This is done to bypass origin validation and expose this endpoint to headless storefronts.\n */\n try {\n const { timestamp } = await rechargeApiRequest<{ timestamp: number }>(\n 'get',\n `/bundle_selections/timestamp`,\n {},\n internalSession\n );\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nfunction createBundleData(bundle: BundleAppProxy, timestampSeconds: number) {\n return 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\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 = createBundleData(bundle, timestampSeconds);\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 async function getBundleSelectionId(session: Session, bundle: BundleAppProxy): Promise<string> {\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const internalSession = getInternalSession(session, 'getBundleSelectionId');\n const timestampSeconds = await getTimestampSecondsFromServerApi(internalSession);\n const bundleData = createBundleData(bundle, timestampSeconds);\n\n try {\n const payload = await rechargeApiRequest<{ id: string; code: number; message: string }>(\n 'post',\n `/bundle_selections/bundle_id`,\n {\n data: {\n bundle: bundleData,\n },\n },\n internalSession\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 if (bundle.selections.length === 0) {\n return 'No selections 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":["shopifyAppProxyRequest","rechargeApiRequest","bundle","toLineItemProperty","getOptions","getInternalSession","nanoid","BundleSelectionValidator"],"mappings":";;;;;;;AAoBA,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,MAAMA,+BAA8C,KAAO,EAAA,CAAA,EAAG,uBAAuB,CAAI,EAAA,CAAA,CAAA,CAAA;AAC/G,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,CAAA,CAAA;AAC5D,IAAA,OAAO,6BAA8B,EAAA,CAAA;AAAA,GACvC;AACF,CAAA;AAEA,eAAe,iCAAiC,eAAmD,EAAA;AAKjG,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,SAAU,EAAA,GAAI,MAAMC,0BAAA;AAAA,MAC1B,KAAA;AAAA,MACA,CAAA,4BAAA,CAAA;AAAA,MACA,EAAC;AAAA,MACD,eAAA;AAAA,KACF,CAAA;AACA,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,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,MACJ,IAAM,EAAA,aAAA;AAAA,MACN,KAAA;AAAA,KACF;AAAA,IACAI,0BAAA,CAAmB,SAAS,cAAc,CAAA;AAAA,GAC5C,CAAA;AAEA,EAAO,OAAA,YAAA,CAAA;AACT;;;;;;;;;;;;;;;"}
package/dist/cjs/index.js CHANGED
@@ -45,6 +45,7 @@ exports.createBundleSelection = bundle.createBundleSelection;
45
45
  exports.deleteBundleSelection = bundle.deleteBundleSelection;
46
46
  exports.getBundleId = bundle.getBundleId;
47
47
  exports.getBundleSelection = bundle.getBundleSelection;
48
+ exports.getBundleSelectionId = bundle.getBundleSelectionId;
48
49
  exports.getDynamicBundleItems = bundle.getDynamicBundleItems;
49
50
  exports.listBundleSelections = bundle.listBundleSelections;
50
51
  exports.updateBundle = bundle.updateBundle;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -41,7 +41,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
41
41
  "X-Recharge-Sdk-Fn": session.internalFnCall,
42
42
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
43
43
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
44
- "X-Recharge-Sdk-Version": "1.37.1",
44
+ "X-Recharge-Sdk-Version": "1.38.1",
45
45
  "X-Request-Id": session.internalRequestId,
46
46
  ...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
47
47
  ...headers ? headers : {}
@@ -179,7 +179,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
179
179
  ...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
180
180
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
181
181
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
182
- "X-Recharge-Sdk-Version": "1.37.1",
182
+ "X-Recharge-Sdk-Version": "1.38.1",
183
183
  ...headers ? headers : {}
184
184
  };
185
185
  return request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
@@ -1,7 +1,7 @@
1
1
  import { nanoid } from 'nanoid/non-secure';
2
- import { shopifyAppProxyRequest, rechargeApiRequest, getInternalSession } from '../utils/request.js';
2
+ import { shopifyAppProxyRequest, getInternalSession, rechargeApiRequest } from '../utils/request.js';
3
3
  import { getOptions } from '../utils/options.js';
4
- import { toLineItemProperty, BundleSelectionValidator } from '../utils/bundle.js';
4
+ import { BundleSelectionValidator, toLineItemProperty } from '../utils/bundle.js';
5
5
 
6
6
  const STORE_FRONT_MANAGER_URL = "/bundling-storefront-manager";
7
7
  function getTimestampSecondsFromClient() {
@@ -16,14 +16,22 @@ async function getTimestampSecondsFromServer() {
16
16
  return getTimestampSecondsFromClient();
17
17
  }
18
18
  }
19
- async function getBundleId(bundle) {
20
- const opts = getOptions();
21
- const isValid = await validateBundle(bundle);
22
- if (isValid !== true) {
23
- throw new Error(isValid);
19
+ async function getTimestampSecondsFromServerApi(internalSession) {
20
+ try {
21
+ const { timestamp } = await rechargeApiRequest(
22
+ "get",
23
+ `/bundle_selections/timestamp`,
24
+ {},
25
+ internalSession
26
+ );
27
+ return timestamp;
28
+ } catch (ex) {
29
+ console.error(`Fetch failed: ${ex}. Using client-side date.`);
30
+ return getTimestampSecondsFromClient();
24
31
  }
25
- const timestampSeconds = await getTimestampSecondsFromServer();
26
- const bundleData = toLineItemProperty({
32
+ }
33
+ function createBundleData(bundle, timestampSeconds) {
34
+ return toLineItemProperty({
27
35
  variantId: bundle.externalVariantId,
28
36
  version: timestampSeconds,
29
37
  items: bundle.selections.map((item) => {
@@ -36,6 +44,15 @@ async function getBundleId(bundle) {
36
44
  };
37
45
  })
38
46
  });
47
+ }
48
+ async function getBundleId(bundle) {
49
+ const opts = getOptions();
50
+ const isValid = await validateBundle(bundle);
51
+ if (isValid !== true) {
52
+ throw new Error(isValid);
53
+ }
54
+ const timestampSeconds = await getTimestampSecondsFromServer();
55
+ const bundleData = createBundleData(bundle, timestampSeconds);
39
56
  try {
40
57
  const payload = await shopifyAppProxyRequest(
41
58
  "post",
@@ -57,6 +74,33 @@ async function getBundleId(bundle) {
57
74
  throw new Error(`2: failed generating rb_id ${e}`);
58
75
  }
59
76
  }
77
+ async function getBundleSelectionId(session, bundle) {
78
+ const isValid = await validateBundle(bundle);
79
+ if (isValid !== true) {
80
+ throw new Error(isValid);
81
+ }
82
+ const internalSession = getInternalSession(session, "getBundleSelectionId");
83
+ const timestampSeconds = await getTimestampSecondsFromServerApi(internalSession);
84
+ const bundleData = createBundleData(bundle, timestampSeconds);
85
+ try {
86
+ const payload = await rechargeApiRequest(
87
+ "post",
88
+ `/bundle_selections/bundle_id`,
89
+ {
90
+ data: {
91
+ bundle: bundleData
92
+ }
93
+ },
94
+ internalSession
95
+ );
96
+ if (!payload.id || payload.code !== 200) {
97
+ throw new Error(`1: failed generating rb_id: ${JSON.stringify(payload)}`);
98
+ }
99
+ return payload.id;
100
+ } catch (e) {
101
+ throw new Error(`2: failed generating rb_id ${e}`);
102
+ }
103
+ }
60
104
  function getDynamicBundleItems(bundle, shopifyProductHandle) {
61
105
  const isValid = validateDynamicBundle(bundle);
62
106
  if (isValid !== true) {
@@ -89,6 +133,9 @@ async function validateBundle(bundle) {
89
133
  if (!bundle) {
90
134
  return "Bundle is not defined";
91
135
  }
136
+ if (bundle.selections.length === 0) {
137
+ return "No selections defined";
138
+ }
92
139
  return true;
93
140
  } catch (e) {
94
141
  return `Error fetching bundle settings: ${e}`;
@@ -215,5 +262,5 @@ async function updateBundle(session, purchase_item_id, updateRequest, query) {
215
262
  return subscription;
216
263
  }
217
264
 
218
- export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSelection, getDynamicBundleItems, listBundleSelections, updateBundle, updateBundleSelection, validateBundle, validateBundleSelection, validateDynamicBundle };
265
+ export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSelection, getBundleSelectionId, getDynamicBundleItems, listBundleSelections, updateBundle, updateBundleSelection, validateBundle, validateBundleSelection, validateDynamicBundle };
219
266
  //# sourceMappingURL=bundle.js.map
@@ -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 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,CAAA;AAC/G,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,CAAA,CAAA;AAC5D,IAAA,OAAO,6BAA8B,EAAA,CAAA;AAAA,GACvC;AACF,CAAA;AAEA,eAAsB,YAAY,MAAyC,EAAA;AACzE,EAAA,MAAM,OAAO,UAAW,EAAA,CAAA;AACxB,EAAM,MAAA,OAAA,GAAU,MAAM,cAAA,CAAe,MAAM,CAAA,CAAA;AAC3C,EAAA,IAAI,YAAY,IAAM,EAAA;AACpB,IAAM,MAAA,IAAI,MAAM,OAAO,CAAA,CAAA;AAAA,GACzB;AACA,EAAM,MAAA,gBAAA,GAAmB,MAAM,6BAA8B,EAAA,CAAA;AAC7D,EAAA,MAAM,aA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gBAAA,CAAA;AACT,CAAA;AAEgB,SAAA,qBAAA,CAAsB,SAAkB,EAAoC,EAAA;AAC1F,EAAI,IAAA,EAAA,KAAO,KAAa,CAAA,IAAA,EAAA,KAAO,EAAI,EAAA;AACjC,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,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,EAAI,IAAA,gBAAA,KAAqB,KAAa,CAAA,IAAA,gBAAA,KAAqB,EAAI,EAAA;AAC7D,IAAM,MAAA,IAAI,MAAM,8BAA8B,CAAA,CAAA;AAAA,GAChD;AACA,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 InternalSession,\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\nasync function getTimestampSecondsFromServerApi(internalSession: InternalSession): Promise<number> {\n /**\n * Same as getTimestampSecondsFromServer, but using the recharge API server instead of the storefront manager.\n * This is done to bypass origin validation and expose this endpoint to headless storefronts.\n */\n try {\n const { timestamp } = await rechargeApiRequest<{ timestamp: number }>(\n 'get',\n `/bundle_selections/timestamp`,\n {},\n internalSession\n );\n return timestamp;\n } catch (ex) {\n console.error(`Fetch failed: ${ex}. Using client-side date.`);\n return getTimestampSecondsFromClient();\n }\n}\n\nfunction createBundleData(bundle: BundleAppProxy, timestampSeconds: number) {\n return 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\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 = createBundleData(bundle, timestampSeconds);\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 async function getBundleSelectionId(session: Session, bundle: BundleAppProxy): Promise<string> {\n const isValid = await validateBundle(bundle);\n if (isValid !== true) {\n throw new Error(isValid);\n }\n const internalSession = getInternalSession(session, 'getBundleSelectionId');\n const timestampSeconds = await getTimestampSecondsFromServerApi(internalSession);\n const bundleData = createBundleData(bundle, timestampSeconds);\n\n try {\n const payload = await rechargeApiRequest<{ id: string; code: number; message: string }>(\n 'post',\n `/bundle_selections/bundle_id`,\n {\n data: {\n bundle: bundleData,\n },\n },\n internalSession\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 if (bundle.selections.length === 0) {\n return 'No selections 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":";;;;;AAoBA,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,CAAA;AAC/G,IAAO,OAAA,SAAA,CAAA;AAAA,WACA,EAAI,EAAA;AACX,IAAQ,OAAA,CAAA,KAAA,CAAM,CAAiB,cAAA,EAAA,EAAE,CAA2B,yBAAA,CAAA,CAAA,CAAA;AAC5D,IAAA,OAAO,6BAA8B,EAAA,CAAA;AAAA,GACvC;AACF,CAAA;AAEA,eAAe,iCAAiC,eAAmD,EAAA;AAKjG,EAAI,IAAA;AACF,IAAM,MAAA,EAAE,SAAU,EAAA,GAAI,MAAM,kBAAA;AAAA,MAC1B,KAAA;AAAA,MACA,CAAA,4BAAA,CAAA;AAAA,MACA,EAAC;AAAA,MACD,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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;;;;"}
package/dist/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { applyDiscountToAddress, createAddress, deleteAddress, getAddress, listAddresses, mergeAddresses, removeDiscountsFromAddress, skipFutureCharge, updateAddress } from './api/address.js';
2
2
  export { loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, sendPasswordlessCode, sendPasswordlessCodeAppProxy, validatePasswordlessCode, validatePasswordlessCodeAppProxy } from './api/auth.js';
3
- export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSelection, getDynamicBundleItems, listBundleSelections, updateBundle, updateBundleSelection, validateBundle, validateBundleSelection, validateDynamicBundle } from './api/bundle.js';
3
+ export { createBundleSelection, deleteBundleSelection, getBundleId, getBundleSelection, getBundleSelectionId, getDynamicBundleItems, listBundleSelections, updateBundle, updateBundleSelection, validateBundle, validateBundleSelection, 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';
6
6
  export { getCollection, listCollectionProducts, listCollections } from './api/collection.js';
@@ -39,7 +39,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
39
39
  "X-Recharge-Sdk-Fn": session.internalFnCall,
40
40
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
41
41
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
42
- "X-Recharge-Sdk-Version": "1.37.1",
42
+ "X-Recharge-Sdk-Version": "1.38.1",
43
43
  "X-Request-Id": session.internalRequestId,
44
44
  ...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
45
45
  ...headers ? headers : {}
package/dist/index.d.ts CHANGED
@@ -2520,8 +2520,8 @@ interface Onetime {
2520
2520
  };
2521
2521
  }
2522
2522
  type OnetimeIncludes = 'address' | 'customer' | 'metafields' | 'bundle_product' | 'bundle_selections' | 'charge_activities';
2523
- type OnetimeRequiredCreateProps = 'address_id' | 'external_variant_id' | 'product_title' | 'quantity';
2524
- type OnetimeOptionalCreateProps = 'external_product_id' | 'next_charge_scheduled_at' | 'properties' | 'sku';
2523
+ type OnetimeRequiredCreateProps = 'address_id' | 'external_variant_id' | 'quantity';
2524
+ type OnetimeOptionalCreateProps = 'external_product_id' | 'next_charge_scheduled_at' | 'product_title' | 'properties' | 'sku';
2525
2525
  interface CreateOnetimeRequest extends SubType<Onetime, OnetimeRequiredCreateProps, OnetimeOptionalCreateProps> {
2526
2526
  /** Instructs to add the Onetime to the next charge scheduled under this Address. */
2527
2527
  add_to_next_charge?: boolean;
@@ -2831,6 +2831,7 @@ declare function validatePasswordlessCodeAppProxy(email: string, session_token:
2831
2831
  declare function loginCustomerPortal(): Promise<Session>;
2832
2832
 
2833
2833
  declare function getBundleId(bundle: BundleAppProxy): Promise<string>;
2834
+ declare function getBundleSelectionId(session: Session, bundle: BundleAppProxy): Promise<string>;
2834
2835
  declare function getDynamicBundleItems(bundle: BundleAppProxy, shopifyProductHandle: string): DynamicBundleItemAppProxy[];
2835
2836
  declare function validateBundle(bundle: BundleAppProxy): Promise<true | string>;
2836
2837
  declare function validateBundleSelection(bundle: BundleAppProxy): Promise<{
@@ -3037,4 +3038,4 @@ declare const api: {
3037
3038
  };
3038
3039
  declare function initRecharge(opt?: InitOptions): void;
3039
3040
 
3040
- export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type ApplyCreditOptions, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BulkSubscriptionParams, type BundleAppProxy, type BundleData, 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 Collection, type CollectionListParams, type CollectionTypes, type CollectionsResponse, type CollectionsSortBy, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreateSubscriptionsParams, type CreateSubscriptionsRequest, type CreditAccount, type CreditAccountIncludes, type CreditAccountListParams, type CreditAccountType, type CreditAccountsResponse, type CreditAccountsSortBy, type CreditSummaryIncludes, type CrossSellsSettings, type CurrencyPriceSet, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessOptions, type CustomerPortalAccessResponse, type CustomerPortalSettings, type DeleteSubscriptionsParams, type DeleteSubscriptionsRequest, 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 InternalSession, 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 OfferAttributes, type OnePageSettings, type Onetime, type OnetimeIncludes, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimeSubscription, 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 PriceSet, type ProcessorName, type ProductImage, type ProductInclude, type ProductListResponse, 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 RecurringSubscription, type ReferralInfo, type ReferralUrl, 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 StoreSettings, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionBase, type SubscriptionCancelled, 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 UpdateAddressParams, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionChargeDateParams, 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, delayOrder, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, deleteSubscriptions, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCollection, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getFailedPaymentMethodRecoveryLandingPageURL, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getStoreSettings, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listCollectionProducts, listCollections, listCreditAccounts, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, setApplyCreditsToNextCharge, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateBundleSelection, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };
3041
+ export { type ActivateMembershipRequest, type AddToCartCallbackSettings, type AddonSettings, type Address, type AddressIncludes, type AddressListParams, type AddressListResponse, type AddressResponse, type AddressSortBy, type AnalyticsData, type ApplyCreditOptions, type AssociatedAddress, type BasicSubscriptionParams, type BooleanLike, type BooleanNumbers, type BooleanString, type BooleanStringNumbers, type BulkSubscriptionParams, type BundleAppProxy, type BundleData, 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 Collection, type CollectionListParams, type CollectionTypes, type CollectionsResponse, type CollectionsSortBy, type ColorString, type CreateAddressRequest, type CreateBundleSelectionRequest, type CreateMetafieldRequest, type CreateOnetimeRequest, type CreatePaymentMethodRequest, type CreateRecipientAddress, type CreateSubscriptionRequest, type CreateSubscriptionsParams, type CreateSubscriptionsRequest, type CreditAccount, type CreditAccountIncludes, type CreditAccountListParams, type CreditAccountType, type CreditAccountsResponse, type CreditAccountsSortBy, type CreditSummaryIncludes, type CrossSellsSettings, type CurrencyPriceSet, type Customer, type CustomerCreditSummary, type CustomerDeliveryScheduleParams, type CustomerDeliveryScheduleResponse, type CustomerIncludes, type CustomerNotification, type CustomerNotificationOptions, type CustomerNotificationTemplate, type CustomerNotificationType, type CustomerPortalAccessOptions, type CustomerPortalAccessResponse, type CustomerPortalSettings, type DeleteSubscriptionsParams, type DeleteSubscriptionsRequest, 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 InternalSession, 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 OfferAttributes, type OnePageSettings, type Onetime, type OnetimeIncludes, type OnetimeListParams, type OnetimeOptionalCreateProps, type OnetimeRequiredCreateProps, type OnetimeSubscription, 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 PriceSet, type ProcessorName, type ProductImage, type ProductInclude, type ProductListResponse, 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 RecurringSubscription, type ReferralInfo, type ReferralUrl, 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 StoreSettings, type StorefrontEnvironment, type StorefrontOptions, type StorefrontPurchaseOption, type SubType, type Subscription, type SubscriptionBase, type SubscriptionCancelled, 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 UpdateAddressParams, type UpdateAddressRequest, type UpdateBundlePurchaseItem, type UpdateBundleSelectionRequest, type UpdateCustomerRequest, type UpdateMetafieldRequest, type UpdateOnetimeRequest, type UpdatePaymentMethodRequest, type UpdateSubscriptionChargeDateParams, 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, delayOrder, deleteAddress, deleteBundleSelection, deleteMetafield, deleteOnetime, deleteSubscriptions, getActiveChurnLandingPageURL, getAddress, getBundleId, getBundleSelection, getBundleSelectionId, getCDNBundleSettings, getCDNProduct, getCDNProductAndSettings, getCDNProducts, getCDNProductsAndSettings, getCDNStoreSettings, getCDNWidgetSettings, getCharge, getCollection, getCreditSummary, getCustomer, getCustomerPortalAccess, getDeliverySchedule, getDynamicBundleItems, getFailedPaymentMethodRecoveryLandingPageURL, getGiftPurchase, getGiftRedemptionLandingPageURL, getMembership, getMembershipProgram, getOnetime, getOrder, getPaymentMethod, getPlan, getShippingCountries, getStoreSettings, getSubscription, initRecharge, type intervalUnit, listAddresses, listBundleSelections, listCharges, listCollectionProducts, listCollections, listCreditAccounts, listGiftPurchases, listMembershipPrograms, listMemberships, listOnetimes, listOrders, listPaymentMethods, listPlans, listSubscriptions, loginCustomerPortal, loginShopifyApi, loginShopifyAppProxy, loginWithShopifyCustomerAccount, loginWithShopifyStorefront, type membershipIncludes, mergeAddresses, processCharge, productSearch, removeDiscountsFromAddress, removeDiscountsFromCharge, resetCDNCache, sendCustomerNotification, sendPasswordlessCode, sendPasswordlessCodeAppProxy, setApplyCreditsToNextCharge, skipCharge, skipFutureCharge, skipGiftSubscriptionCharge, skipSubscriptionCharge, unskipCharge, updateAddress, updateBundle, updateBundleSelection, updateCustomer, updateMetafield, updateOnetime, updatePaymentMethod, updateSubscription, updateSubscriptionAddress, updateSubscriptionChargeDate, updateSubscriptions, validateBundle, validateBundleSelection, validateDynamicBundle, validatePasswordlessCode, validatePasswordlessCodeAppProxy };