@rechargeapps/storefront-client 2.6.0 → 2.6.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.
@@ -190,7 +190,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
190
190
  ...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
191
191
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
192
192
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
193
- "X-Recharge-Sdk-Version": "2.6.0",
193
+ "X-Recharge-Sdk-Version": "2.6.1",
194
194
  ...headers ? headers : {}
195
195
  };
196
196
  return request.request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
@@ -16,7 +16,7 @@ async function loadFromOnlineStore(id, country_code) {
16
16
  const { appName, appVersion } = options.getOptions();
17
17
  const headers = {
18
18
  "X-Recharge-Sdk-Fn": "loadFromOnlineStore",
19
- "X-Recharge-Sdk-Version": "2.6.0",
19
+ "X-Recharge-Sdk-Version": "2.6.1",
20
20
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
21
21
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {}
22
22
  };
@@ -53,6 +53,9 @@ async function getCustomerPortalAccess(session, query) {
53
53
  request.getInternalSession(session, "getCustomerPortalAccess")
54
54
  );
55
55
  }
56
+ function getLandingPagesBaseURL(portalBaseURL) {
57
+ return portalBaseURL.replace(/\/portal\/?$/, "/pages/");
58
+ }
56
59
  async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL) {
57
60
  if (subscriptionId === void 0 || subscriptionId === "") {
58
61
  throw new Error("Subscription ID is required");
@@ -60,9 +63,8 @@ async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL
60
63
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
61
64
  request.getInternalSession(session, "getActiveChurnLandingPageURL")
62
65
  );
63
- return `${base_url.replace(
64
- "portal",
65
- "pages"
66
+ return `${getLandingPagesBaseURL(
67
+ base_url
66
68
  )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(
67
69
  redirectURL
68
70
  )}`;
@@ -71,7 +73,7 @@ async function getFailedPaymentMethodRecoveryLandingPageURL(session) {
71
73
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
72
74
  request.getInternalSession(session, "getFailedPaymentMethodRecoveryLandingPageURL")
73
75
  );
74
- return `${base_url.replace("portal", "pages")}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;
76
+ return `${getLandingPagesBaseURL(base_url)}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;
75
77
  }
76
78
  async function getGiftRedemptionLandingPageURL(session, giftId, redirectURL) {
77
79
  if (giftId === void 0 || giftId === "") {
@@ -80,9 +82,8 @@ async function getGiftRedemptionLandingPageURL(session, giftId, redirectURL) {
80
82
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
81
83
  request.getInternalSession(session, "getGiftRedemptionLandingPageURL")
82
84
  );
83
- return `${base_url.replace(
84
- "portal",
85
- "pages"
85
+ return `${getLandingPagesBaseURL(
86
+ base_url
86
87
  )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;
87
88
  }
88
89
  const customerNotificationMap = {
@@ -1 +1 @@
1
- {"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessOptions,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n Session,\n UpdateCustomerRequest,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${encodePathSegment(id)}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n if (subscriptionId === undefined || subscriptionId === '') {\n throw new Error('Subscription ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(\n redirectURL\n )}`;\n}\n\nexport async function getFailedPaymentMethodRecoveryLandingPageURL(session: Session): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getFailedPaymentMethodRecoveryLandingPageURL')\n );\n return `${base_url.replace('portal', 'pages')}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n if (giftId === undefined || giftId === '') {\n throw new Error('Gift ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n SHOPIFY_MIGRATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_migrate_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n // Own-property check: a plain-object lookup resolves inherited keys such as\n // `__proto__`/`constructor` to truthy prototype values, bypassing this guard\n // (H1-3889216 / SEC-4002; same class as the CDN/bundle maps fixed in SEC-3996).\n if (!Object.prototype.hasOwnProperty.call(customerNotificationMap, notification)) {\n throw new Error('Notification not supported.');\n }\n const data = customerNotificationMap[notification];\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${encodePathSegment(customerId)}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${encodePathSegment(id)}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":["rechargeApiRequest","getInternalSession","encodePathSegment"],"mappings":";;;;;AAoBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAMA,0BAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,KAAO,EAAA,EAAE,OAAS,EAAA,OAAA,EAAS,OAAQ,EAAA;AAAA,KACrC;AAAA,IACAC,0BAAA,CAAmB,SAAS,aAAa,CAAA;AAAA,GAC3C,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACT,CAAA;AAEsB,eAAA,cAAA,CAAe,SAAkB,aAAyD,EAAA;AAC9G,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAMD,0BAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA,EAAE,EAAI,EAAA,IAAA,EAAM,aAAc,EAAA;AAAA,IAC1BC,0BAAA,CAAmB,SAAS,gBAAgB,CAAA;AAAA,GAC9C,CAAA;AACA,EAAO,O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,YAAA,EACA,OACe,EAAA;AACf,EAAA,MAAM,aAAa,OAAQ,CAAA,UAAA,CAAA;AAC3B,EAAA,IAAI,CAAC,UAAY,EAAA;AACf,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AAIA,EAAA,IAAI,CAAC,MAAO,CAAA,SAAA,CAAU,eAAe,IAAK,CAAA,uBAAA,EAAyB,YAAY,CAAG,EAAA;AAChF,IAAM,MAAA,IAAI,MAAM,6BAA6B,CAAA,CAAA;AAAA,GAC/C;AACA,EAAM,MAAA,IAAA,GAAO,wBAAwB,YAAY,CAAA,CAAA;AACjD,EAAO,OAAAD,0BAAA;AAAA,IACL,MAAA;AAAA,IACA,CAAA,WAAA,EAAcE,qBAAkB,CAAA,UAAU,CAAC,CAAA,cAAA,CAAA;AAAA,IAC3C;AAAA,MACE,IAAM,EAAA;AAAA,QACJ,GAAG,IAAA;AAAA,QACH,aAAe,EAAA,OAAA;AAAA,OACjB;AAAA,KACF;AAAA,IACAD,0BAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;;;;;;;;"}
1
+ {"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessOptions,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n Session,\n UpdateCustomerRequest,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${encodePathSegment(id)}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nfunction getLandingPagesBaseURL(portalBaseURL: string): string {\n return portalBaseURL.replace(/\\/portal\\/?$/, '/pages/');\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n if (subscriptionId === undefined || subscriptionId === '') {\n throw new Error('Subscription ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${getLandingPagesBaseURL(\n base_url\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(\n redirectURL\n )}`;\n}\n\nexport async function getFailedPaymentMethodRecoveryLandingPageURL(session: Session): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getFailedPaymentMethodRecoveryLandingPageURL')\n );\n return `${getLandingPagesBaseURL(base_url)}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n if (giftId === undefined || giftId === '') {\n throw new Error('Gift ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${getLandingPagesBaseURL(\n base_url\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n SHOPIFY_MIGRATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_migrate_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n // Own-property check: a plain-object lookup resolves inherited keys such as\n // `__proto__`/`constructor` to truthy prototype values, bypassing this guard\n // (H1-3889216 / SEC-4002; same class as the CDN/bundle maps fixed in SEC-3996).\n if (!Object.prototype.hasOwnProperty.call(customerNotificationMap, notification)) {\n throw new Error('Notification not supported.');\n }\n const data = customerNotificationMap[notification];\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${encodePathSegment(customerId)}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${encodePathSegment(id)}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":["rechargeApiRequest","getInternalSession","encodePathSegment"],"mappings":";;;;;AAoBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAMA,0BAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA;AAAA,MACE,EAAA;AAAA,MACA,KAAO,EAAA,EAAE,OAAS,EAAA,OAAA,EAAS,OAAQ,EAAA;AAAA,KACrC;AAAA,IACAC,0BAAA,CAAmB,SAAS,aAAa,CAAA;AAAA,GAC3C,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACT,CAAA;AAEsB,eAAA,cAAA,CAAe,SAAkB,aAAyD,EAAA;AAC9G,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EAAA,GAAI,MAAMD,0BAAA;AAAA,IACzB,KAAA;AAAA,IACA,CAAA,UAAA,CAAA;AAAA,IACA,EAAE,EAAI,EAAA,IAAA,EAAM,aAAc,EAAA;AAAA,IAC1BC,0BAAA,CAAmB,SAAS,gBAAgB,CAAA;AAAA,GAC9C,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACT,CAAA;AAEsB,eAAA,mBAAA,CACpB,SACA,KACqB,EAAA;AACrB,EAAA,MAAM,KAAK,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,CAAA,UAAA,CAAA;AAC3B,EAAA,IAAI,CAAC,UAAY,EAAA;AACf,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AAIA,EAAA,IAAI,CAAC,MAAO,CAAA,SAAA,CAAU,eAAe,IAAK,CAAA,uBAAA,EAAyB,YAAY,CAAG,EAAA;AAChF,IAAM,MAAA,IAAI,MAAM,6BAA6B,CAAA,CAAA;AAAA,GAC/C;AACA,EAAM,MAAA,IAAA,GAAO,wBAAwB,YAAY,CAAA,CAAA;AACjD,EAAO,OAAAD,0BAAA;AAAA,IACL,MAAA;AAAA,IACA,CAAA,WAAA,EAAcE,qBAAkB,CAAA,UAAU,CAAC,CAAA,cAAA,CAAA;AAAA,IAC3C;AAAA,MACE,IAAM,EAAA;AAAA,QACJ,GAAG,IAAA;AAAA,QACH,aAAe,EAAA,OAAA;AAAA,OACjB;AAAA,KACF;AAAA,IACAD,0BAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;;;;;;;;"}
@@ -46,7 +46,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
46
46
  "X-Recharge-Sdk-Fn": session.internalFnCall,
47
47
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
48
48
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
49
- "X-Recharge-Sdk-Version": "2.6.0",
49
+ "X-Recharge-Sdk-Version": "2.6.1",
50
50
  "X-Request-Id": session.internalRequestId,
51
51
  ...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
52
52
  ...headers ? headers : {}
@@ -188,7 +188,7 @@ async function rechargeAdminRequest(method, url, { id, query, data, headers } =
188
188
  ...storefrontAccessToken ? { "X-Recharge-Storefront-Access-Token": storefrontAccessToken } : {},
189
189
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
190
190
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
191
- "X-Recharge-Sdk-Version": "2.6.0",
191
+ "X-Recharge-Sdk-Version": "2.6.1",
192
192
  ...headers ? headers : {}
193
193
  };
194
194
  return request(method, `${rechargeBaseUrl}${url}`, { id, query, data, headers: reqHeaders });
@@ -14,7 +14,7 @@ async function loadFromOnlineStore(id, country_code) {
14
14
  const { appName, appVersion } = getOptions();
15
15
  const headers = {
16
16
  "X-Recharge-Sdk-Fn": "loadFromOnlineStore",
17
- "X-Recharge-Sdk-Version": "2.6.0",
17
+ "X-Recharge-Sdk-Version": "2.6.1",
18
18
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
19
19
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {}
20
20
  };
@@ -51,6 +51,9 @@ async function getCustomerPortalAccess(session, query) {
51
51
  getInternalSession(session, "getCustomerPortalAccess")
52
52
  );
53
53
  }
54
+ function getLandingPagesBaseURL(portalBaseURL) {
55
+ return portalBaseURL.replace(/\/portal\/?$/, "/pages/");
56
+ }
54
57
  async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL) {
55
58
  if (subscriptionId === void 0 || subscriptionId === "") {
56
59
  throw new Error("Subscription ID is required");
@@ -58,9 +61,8 @@ async function getActiveChurnLandingPageURL(session, subscriptionId, redirectURL
58
61
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
59
62
  getInternalSession(session, "getActiveChurnLandingPageURL")
60
63
  );
61
- return `${base_url.replace(
62
- "portal",
63
- "pages"
64
+ return `${getLandingPagesBaseURL(
65
+ base_url
64
66
  )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(
65
67
  redirectURL
66
68
  )}`;
@@ -69,7 +71,7 @@ async function getFailedPaymentMethodRecoveryLandingPageURL(session) {
69
71
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
70
72
  getInternalSession(session, "getFailedPaymentMethodRecoveryLandingPageURL")
71
73
  );
72
- return `${base_url.replace("portal", "pages")}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;
74
+ return `${getLandingPagesBaseURL(base_url)}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;
73
75
  }
74
76
  async function getGiftRedemptionLandingPageURL(session, giftId, redirectURL) {
75
77
  if (giftId === void 0 || giftId === "") {
@@ -78,9 +80,8 @@ async function getGiftRedemptionLandingPageURL(session, giftId, redirectURL) {
78
80
  const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(
79
81
  getInternalSession(session, "getGiftRedemptionLandingPageURL")
80
82
  );
81
- return `${base_url.replace(
82
- "portal",
83
- "pages"
83
+ return `${getLandingPagesBaseURL(
84
+ base_url
84
85
  )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;
85
86
  }
86
87
  const customerNotificationMap = {
@@ -1 +1 @@
1
- {"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessOptions,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n Session,\n UpdateCustomerRequest,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${encodePathSegment(id)}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n if (subscriptionId === undefined || subscriptionId === '') {\n throw new Error('Subscription ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(\n redirectURL\n )}`;\n}\n\nexport async function getFailedPaymentMethodRecoveryLandingPageURL(session: Session): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getFailedPaymentMethodRecoveryLandingPageURL')\n );\n return `${base_url.replace('portal', 'pages')}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n if (giftId === undefined || giftId === '') {\n throw new Error('Gift ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${base_url.replace(\n 'portal',\n 'pages'\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n SHOPIFY_MIGRATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_migrate_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n // Own-property check: a plain-object lookup resolves inherited keys such as\n // `__proto__`/`constructor` to truthy prototype values, bypassing this guard\n // (H1-3889216 / SEC-4002; same class as the CDN/bundle maps fixed in SEC-3996).\n if (!Object.prototype.hasOwnProperty.call(customerNotificationMap, notification)) {\n throw new Error('Notification not supported.');\n }\n const data = customerNotificationMap[notification];\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${encodePathSegment(customerId)}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${encodePathSegment(id)}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;;AAoBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,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AAA;AACjD,EAAO,OAAA,kBAAA;AAAA,IACL,MAAA;AAAA,IACA,CAAA,WAAA,EAAc,iBAAkB,CAAA,UAAU,CAAC,CAAA,cAAA,CAAA;AAAA,IAC3C;AAAA,MACE,IAAM,EAAA;AAAA,QACJ,GAAG,IAAA;AAAA,QACH,aAAe,EAAA,OAAA;AAAA,OACjB;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;"}
1
+ {"version":3,"file":"customer.js","sources":["../../../src/api/customer.ts"],"sourcesContent":["import {\n Customer,\n CustomerCreditSummary,\n CustomerDeliveryScheduleParams,\n CustomerDeliveryScheduleResponse,\n CustomerNotification,\n CustomerNotificationOptions,\n CustomerNotificationTemplate,\n CustomerNotificationType,\n CustomerPortalAccessOptions,\n CustomerPortalAccessResponse,\n Delivery,\n GetCreditSummaryOptions,\n GetCustomerOptions,\n Session,\n UpdateCustomerRequest,\n} from '../types';\nimport { getInternalSession, rechargeApiRequest } from '../utils/request';\nimport { encodePathSegment } from '../utils/url';\n\nexport async function getCustomer(session: Session, options?: GetCustomerOptions): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'get',\n `/customers`,\n {\n id,\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCustomer')\n );\n return customer;\n}\n\nexport async function updateCustomer(session: Session, updateRequest: UpdateCustomerRequest): Promise<Customer> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { customer } = await rechargeApiRequest<{ customer: Customer }>(\n 'put',\n `/customers`,\n { id, data: updateRequest },\n getInternalSession(session, 'updateCustomer')\n );\n return customer;\n}\n\nexport async function getDeliverySchedule(\n session: Session,\n query?: CustomerDeliveryScheduleParams\n): Promise<Delivery[]> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { deliveries } = await rechargeApiRequest<CustomerDeliveryScheduleResponse>(\n 'get',\n `/customers/${encodePathSegment(id)}/delivery_schedule`,\n { query },\n getInternalSession(session, 'getDeliverySchedule')\n );\n return deliveries;\n}\n\nexport async function getCustomerPortalAccess(\n session: Session,\n query?: CustomerPortalAccessOptions\n): Promise<CustomerPortalAccessResponse> {\n return rechargeApiRequest<CustomerPortalAccessResponse>(\n 'get',\n '/portal_access',\n { query },\n getInternalSession(session, 'getCustomerPortalAccess')\n );\n}\n\nfunction getLandingPagesBaseURL(portalBaseURL: string): string {\n return portalBaseURL.replace(/\\/portal\\/?$/, '/pages/');\n}\n\nexport async function getActiveChurnLandingPageURL(\n session: Session,\n subscriptionId: string | number,\n redirectURL: string\n): Promise<string> {\n if (subscriptionId === undefined || subscriptionId === '') {\n throw new Error('Subscription ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getActiveChurnLandingPageURL')\n );\n return `${getLandingPagesBaseURL(\n base_url\n )}${customer_hash}/subscriptions/${subscriptionId}/cancel?token=${temp_token}&subscription=${subscriptionId}&redirect_to=${encodeURIComponent(\n redirectURL\n )}`;\n}\n\nexport async function getFailedPaymentMethodRecoveryLandingPageURL(session: Session): Promise<string> {\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getFailedPaymentMethodRecoveryLandingPageURL')\n );\n return `${getLandingPagesBaseURL(base_url)}account/payment-methods?token=${temp_token}&hash=${customer_hash}`;\n}\n\nexport async function getGiftRedemptionLandingPageURL(\n session: Session,\n giftId: string | number,\n redirectURL: string\n): Promise<string> {\n if (giftId === undefined || giftId === '') {\n throw new Error('Gift ID is required');\n }\n const { base_url, customer_hash, temp_token } = await getCustomerPortalAccess(\n getInternalSession(session, 'getGiftRedemptionLandingPageURL')\n );\n return `${getLandingPagesBaseURL(\n base_url\n )}${customer_hash}/gifts/${giftId}?token=${temp_token}&redirect_to=${encodeURIComponent(redirectURL)}`;\n}\n\nconst customerNotificationMap: Record<\n CustomerNotification,\n { type: CustomerNotificationType; template_type: CustomerNotificationTemplate }\n> = {\n SHOPIFY_UPDATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_update_payment_information',\n },\n SHOPIFY_MIGRATE_PAYMENT_INFO: {\n type: 'email',\n template_type: 'shopify_migrate_payment_information',\n },\n};\n\nexport async function sendCustomerNotification<T extends CustomerNotification>(\n session: Session,\n notification: CustomerNotification,\n options?: CustomerNotificationOptions<T>\n): Promise<void> {\n const customerId = session.customerId;\n if (!customerId) {\n throw new Error('Not logged in.');\n }\n // Own-property check: a plain-object lookup resolves inherited keys such as\n // `__proto__`/`constructor` to truthy prototype values, bypassing this guard\n // (H1-3889216 / SEC-4002; same class as the CDN/bundle maps fixed in SEC-3996).\n if (!Object.prototype.hasOwnProperty.call(customerNotificationMap, notification)) {\n throw new Error('Notification not supported.');\n }\n const data = customerNotificationMap[notification];\n return rechargeApiRequest<void>(\n 'post',\n `/customers/${encodePathSegment(customerId)}/notifications`,\n {\n data: {\n ...data,\n template_vars: options,\n },\n },\n getInternalSession(session, 'sendCustomerNotification')\n );\n}\n\n/** @deprecated Use `getCreditSummary` on credit instead */\nexport async function getCreditSummary(\n session: Session,\n options?: GetCreditSummaryOptions\n): Promise<CustomerCreditSummary> {\n const id = session.customerId;\n if (!id) {\n throw new Error('Not logged in.');\n }\n const { credit_summary } = await rechargeApiRequest<{ credit_summary: CustomerCreditSummary }>(\n 'get',\n `/customers/${encodePathSegment(id)}/credit_summary`,\n {\n query: { include: options?.include },\n },\n getInternalSession(session, 'getCreditSummary')\n );\n return credit_summary;\n}\n"],"names":[],"mappings":";;;AAoBsB,eAAA,WAAA,CAAY,SAAkB,OAAiD,EAAA;AACnG,EAAA,MAAM,KAAK,OAAQ,CAAA,UAAA,CAAA;AACnB,EAAA,IAAI,CAAC,EAAI,EAAA;AACP,IAAM,MAAA,IAAI,MAAM,gBAAgB,CAAA,CAAA;AAAA,GAClC;AACA,EAAM,MAAA,EAAE,QAAS,EA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AA,CAAA;AAAA,IAC3C;AAAA,MACE,IAAM,EAAA;AAAA,QACJ,GAAG,IAAA;AAAA,QACH,aAAe,EAAA,OAAA;AAAA,OACjB;AAAA,KACF;AAAA,IACA,kBAAA,CAAmB,SAAS,0BAA0B,CAAA;AAAA,GACxD,CAAA;AACF;;;;"}
@@ -44,7 +44,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
44
44
  "X-Recharge-Sdk-Fn": session.internalFnCall,
45
45
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
46
46
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
47
- "X-Recharge-Sdk-Version": "2.6.0",
47
+ "X-Recharge-Sdk-Version": "2.6.1",
48
48
  "X-Request-Id": session.internalRequestId,
49
49
  ...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
50
50
  ...headers ? headers : {}
package/dist/index.d.ts CHANGED
@@ -1559,7 +1559,7 @@ interface SubscriptionBase {
1559
1559
  bundle_product?: BundleProduct<BundleVariantOptionSourceSubscription> | null;
1560
1560
  customer_entitlements?: CustomerEntitlement[] | null;
1561
1561
  addons?: Addon[] | null;
1562
- expires_at?: IsoDateString | null;
1562
+ expires_at?: (IsoDateString | null)[];
1563
1563
  };
1564
1564
  /** The id of the parent subscription. When present, this subscription will be created as a child and linked to the parent. */
1565
1565
  addon_parent_subscription_id?: number;
@@ -3970,6 +3970,8 @@ interface CustomerPortalSettings {
3970
3970
  /** @internal */
3971
3971
  enable_affinity_account_page_schema: BooleanNumbers;
3972
3972
  /** @internal */
3973
+ enable_affinity_orders_page_schema: BooleanNumbers;
3974
+ /** @internal */
3973
3975
  customer_portal_page_view_templates_published: string[];
3974
3976
  /** Whether enhanced slots are enabled or not. */
3975
3977
  enable_enhanced_slots: boolean;
@@ -1,2 +1,2 @@
1
- // recharge-client-2.6.0.min.js | MIT License | © Recharge Inc.
2
- (function(N,T){typeof exports=="object"&&typeof module<"u"?module.exports=T():typeof define=="function"&&define.amd?define(T):(N=typeof globalThis<"u"?globalThis:N||self,N.recharge=T())})(this,function(){"use strict";const N="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function T(t=21){let e="";for(let r=0;r<t;r++)e+=N[Math.random()*64|0];return e}let he={storeIdentifier:"",environment:"prod"};function tt(t){he=t}function b(){return he}const rt=(t,e="")=>{switch(t){case"prod":return"https://api.rechargeapps.com";case"stage":return"https://api.stage.rechargeapps.com";case"preprod":case"prestage":return`${e}/api`}},nt=(t,e="")=>{switch(t){case"prod":return"https://admin.rechargeapps.com";case"stage":return"https://admin.stage.rechargeapps.com";case"preprod":case"prestage":return e}},it=t=>{switch(t){case"prod":case"preprod":return"https://static.rechargecdn.com";case"stage":case"prestage":return"https://static.stage.rechargecdn.com"}},me="/tools/recurring";class F{constructor(e,r){this.name="RechargeRequestError",this.message=e,this.status=r}}function p(t){return encodeURIComponent(`${t}`.trim())}function st(t){const e=r=>encodeURIComponent(r===null?"":String(r));return Object.entries(t).filter(([,r])=>r!==void 0&&!(Array.isArray(r)&&r.length===0)).map(([r,n])=>`${r}=${Array.isArray(n)?n.map(e).join(","):e(n)}`).join("&")}const ot=new Set(["shop_url"]);function a(t,e){return{...t,internalFnCall:t.internalFnCall??e,internalRequestId:t.internalRequestId??T()}}async function V(t,e,r={}){const n=b();return S(t,`${it(n.environment)}/store/${n.storeIdentifier}${e}`,r)}async function c(t,e,{id:r,query:n,data:i,headers:s}={},o){const{environment:l,environmentUri:f,storeIdentifier:_,loginRetryFn:h,__unstable_twoFactorRetryFn:y,appName:v,appVersion:d}=b();if(!_)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const m=o.apiToken;if(!m)throw new Error("No API token defined on session.");const g=rt(l,f),I={"X-Recharge-Access-Token":m,"X-Recharge-Version":"2021-11","X-Recharge-Sdk-Fn":o.internalFnCall,...v?{"X-Recharge-Sdk-App-Name":v}:{},...d?{"X-Recharge-Sdk-App-Version":d}:{},"X-Recharge-Sdk-Version":"2.6.0","X-Request-Id":o.internalRequestId,...o.tmp_fn_identifier?{"X-Recharge-Sdk-Fn-Identifier":o.tmp_fn_identifier}:{},...s||{}},k=n,D={...k?Object.fromEntries(Object.entries(k).filter(([q])=>!ot.has(q))):void 0,shop_url:_};try{return await S(t,`${g}${e}`,{id:r,query:D,data:i,headers:I})}catch(q){if(h&&q instanceof F&&q.status===401)return h().then(O=>{if(O)return S(t,`${g}${e}`,{id:r,query:D,data:i,headers:{...I,"X-Recharge-Access-Token":O.apiToken}});throw q});if(y&&q instanceof F&&q.status===423)return y().then(O=>{if(O)return S(t,`${g}${e}`,{id:r,query:D,data:i,headers:{...I,"X-Recharge-Access-Token":O.apiToken}});throw q});throw q}}async function A(t,e,r={}){return S(t,`${me}${e}`,r)}async function S(t,e,{id:r,query:n,data:i,headers:s}={}){let o=e.trim();if(r&&(o=[o,p(r)].join("/")),n){let y;[o,y]=o.split("?");const v=[y,st(n)].join("&").replace(/^&/,"");o=`${o}${v?`?${v}`:""}`}let l;i&&t!=="get"&&(l=JSON.stringify(i));const f={Accept:"application/json","Content-Type":"application/json","X-Recharge-App":"storefront-client",...s||{}},_=await fetch(o,{method:t,headers:f,body:l});let h;try{h=await _.json()}catch{}if(!_.ok)throw _.status===502||_.status===504?new F("A gateway error occurred while making the request",_.status):h&&h.error?new F(h.error,_.status):h&&h.errors?new F(JSON.stringify(h.errors),_.status):new F("A connection error occurred while making the request");return h}function at(t,e){return c("get","/addresses",{query:e},a(t,"listAddresses"))}async function ct(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{address:n}=await c("get","/addresses",{id:e,query:{include:r?.include}},a(t,"getAddress"));return n}async function dt(t,e){const{address:r}=await c("post","/addresses",{data:{...e,customer_id:t.customerId?Number(t.customerId):void 0}},a(t,"createAddress"));return r}async function J(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{address:i}=await c("put","/addresses",{id:e,data:r,query:n},a(t,"updateAddress"));return i}async function ut(t,e,r,n){return J(a(t,"applyDiscountToAddress"),e,{discounts:[{code:r}]},n)}async function lt(t,e,r){if(e===void 0||e==="")throw new Error("Id is required");return J(a(t,"removeDiscountsFromAddress"),e,{discounts:[]},r)}function pt(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/addresses",{id:e},a(t,"deleteAddress"))}async function _t(t,e){const{address:r}=await c("post","/addresses/merge",{data:e},a(t,"mergeAddresses"));return r}async function ht(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/addresses/${p(e)}/charges/skip`,{data:r},a(t,"skipFutureCharge"));return n}var mt=Object.freeze({__proto__:null,applyDiscountToAddress:ut,createAddress:dt,deleteAddress:pt,getAddress:ct,listAddresses:at,mergeAddresses:_t,removeDiscountsFromAddress:lt,skipFutureCharge:ht,updateAddress:J});async function ft(){const{storefrontAccessToken:t}=b(),e={};t&&(e["X-Recharge-Storefront-Access-Token"]=t);const r=await A("get","/access",{headers:e});return{apiToken:r.api_token,customerId:r.customer_id,message:r.message}}async function gt(t,e){return fe(t,e)}async function fe(t,e){if(!t)throw new Error("Shopify storefront token is required");const{storeIdentifier:r}=b();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:n,customer_id:i,message:s}=await B("post","/shopify_storefront_access",{data:{customer_token:e,storefront_token:t,shop_url:r}});return n?{apiToken:n,customerId:i,message:s}:null}async function wt(t){const{storeIdentifier:e}=b();if(!e)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:r,customer_id:n,message:i}=await B("post","/shopify_customer_account_api_access",{data:{customer_token:t,shop_url:e}});return r?{apiToken:r,customerId:n,message:i}:null}async function yt(t,e={}){if(!t)throw new Error("Email is required.");const{storeIdentifier:r}=b();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{send_email:n,send_sms:i}=e,s=await B("post","/attempt_login",{data:{email:t,shop:r,...n!==void 0?{send_email:n}:{},...i!==void 0?{send_sms:i}:{}}});if(s.errors)throw new Error(s.errors);return s.session_token}async function bt(t,e={}){if(!t)throw new Error("Email is required.");const{storefrontAccessToken:r}=b(),n={};r&&(n["X-Recharge-Storefront-Access-Token"]=r);const{send_email:i,send_sms:s}=e,o=await A("post","/attempt_login",{data:{email:t,...i!==void 0?{send_email:i}:{},...s!==void 0?{send_sms:s}:{}},headers:n});if(o.errors)throw new Error(o.errors);return o.session_token}async function vt(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storeIdentifier:n}=b();if(!n)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const i=await B("post","/validate_login",{data:{code:r,email:t,session_token:e,shop:n}});if(i.errors)throw new Error(i.errors);return{apiToken:i.api_token,customerId:i.customer_id}}async function St(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storefrontAccessToken:n}=b(),i={};n&&(i["X-Recharge-Storefront-Access-Token"]=n);const s=await A("post","/validate_login",{data:{code:r,email:t,session_token:e},headers:i});if(s.errors)throw new Error(s.errors);return{apiToken:s.api_token,customerId:s.customer_id}}function $t(){const{customerHash:t}=b(),{pathname:e,search:r}=window.location,n=new URLSearchParams(r).get("token"),i=e.split("/").filter(Boolean),s=i.findIndex(l=>l==="portal"),o=s!==-1?i[s+1]:t;if(!n||!o)throw new Error("Not in context of Recharge Customer Portal or URL did not contain correct params");return{customerHash:o,token:n}}async function It(){const{customerHash:t,token:e}=$t(),{storeIdentifier:r}=b(),n=await B("post",`/customers/${p(t)}/access`,{data:{token:e,shop:r}});return{apiToken:n.api_token,customerId:n.customer_id}}async function B(t,e,{id:r,query:n,data:i,headers:s}={}){const{environment:o,environmentUri:l,storefrontAccessToken:f,appName:_,appVersion:h}=b(),y=nt(o,l),v={...f?{"X-Recharge-Storefront-Access-Token":f}:{},..._?{"X-Recharge-Sdk-App-Name":_}:{},...h?{"X-Recharge-Sdk-App-Version":h}:{},"X-Recharge-Sdk-Version":"2.6.0",...s||{}};return S(t,`${y}${e}`,{id:r,query:n,data:i,headers:v})}var qt=Object.freeze({__proto__:null,loginCustomerPortal:It,loginShopifyApi:gt,loginShopifyAppProxy:ft,loginWithShopifyCustomerAccount:wt,loginWithShopifyStorefront:fe,sendPasswordlessCode:yt,sendPasswordlessCodeAppProxy:bt,validatePasswordlessCode:vt,validatePasswordlessCodeAppProxy:St});const ge="XdrError";class u extends Error{constructor(e){super(e),this.name=ge}static[Symbol.hasInstance](e){return e instanceof Error&&e.name===ge}}function we(t){return(4-t%4)%4}function ye(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function be(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new u(`${e}: expected uint32 length`)}function Q(t,e,r,n){if(typeof t!="number"||!Number.isInteger(t)||t<e||t>r)throw new u(`${n}: expected integer in range ${e}..${r}`)}function Et(t,e,r,n){if(typeof t!="bigint"||t<e||t>r)throw new u(`${n}: expected bigint in range ${e}..${r}`)}function Ct(t,e){if(!(t instanceof Uint8Array))throw new u(`${e}: expected Uint8Array`);try{Uint8Array.prototype.at.call(t,0)}catch{throw new u(`${e}: Uint8Array is detached or out of bounds`)}}function kt(t,e){if(!Array.isArray(t))throw new u(`${e}: expected array`)}const ve=1500;class xt{#e=0;#i=0;#t;#n;#s;bytes;constructor(e,r=ve){if(r<0||!Number.isInteger(r))throw new u(`invalid maxDepth ${r}`);if(this.#t=r,!ArrayBuffer.isView(e)||e.BYTES_PER_ELEMENT!==1)throw new TypeError("Reader expects a Uint8Array");this.bytes=Object.getPrototypeOf(e)===Uint8Array.prototype?e:e.byteLength===0?new Uint8Array(0):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this.#n=this.bytes.buffer?.detached?new DataView(new ArrayBuffer(0)):new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.#s=this.#n.byteLength}#r(e,r){if(this.remaining<e)throw new u(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.#e;return this.#e+=e,n}get offset(){return this.#e}get remaining(){return this.#s-this.#e}enter(e){if(this.#i+=1,this.#i>this.#t)throw this.#i-=1,new u(`${e}: max recursion depth ${this.#t} exceeded`)}exit(){this.#i-=1}done(e){if(this.remaining!==0)throw new u(`${e}: trailing ${this.remaining} byte(s) after XDR value`)}readBytes(e,r){if(e<0||!Number.isInteger(e))throw new u(`${r}: invalid byte length ${e}`);if(this.remaining<e)throw new u(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.bytes.slice(this.#e,this.#e+e);if(n.length!==e)throw new u(`${r}: input shrank during decode`);return this.#e+=e,n}skipPadding(e,r){if(e<0||!Number.isInteger(e))throw new u(`${r}: invalid byte length ${e}`);const n=we(e);if(n===0)return;const i=this.#r(n,r);for(let s=0;s<n;s++)if(this.bytes[i+s]!==0)throw this.#e=i,new u(`${r}: non-zero XDR padding`)}readInt32(e){return this.#n.getInt32(this.#r(4,e),!1)}readUint32(e){return this.#n.getUint32(this.#r(4,e),!1)}readBigInt64(e){return this.#n.getBigInt64(this.#r(8,e),!1)}readBigUint64(e){return this.#n.getBigUint64(this.#r(8,e),!1)}readFloat32(e){return this.#n.getFloat32(this.#r(4,e),!1)}readFloat64(e){return this.#n.getFloat64(this.#r(8,e),!1)}}const Pt=8192;class Se{#e=new Uint8Array(Pt);#i=new DataView(this.#e.buffer);#t=0;#n=0;#s;constructor(e=ve){if(e<0||!Number.isInteger(e))throw new u(`invalid maxDepth ${e}`);this.#s=e}get offset(){return this.#t}enter(e){if(this.#n+=1,this.#n>this.#s)throw this.#n-=1,new u(`${e}: max recursion depth ${this.#s} exceeded`)}exit(){this.#n-=1}writeBytes(e){this.#o(e.length),this.#e.set(e,this.#t),this.#t+=e.length}writePadding(e){const r=we(e);r>0&&(this.#o(r),this.#e.fill(0,this.#t,this.#t+r),this.#t+=r)}writeInt32(e){const r=this.#r(4);this.#i.setInt32(r,e,!1),this.#t+=4}writeUint32(e){const r=this.#r(4);this.#i.setUint32(r,e,!1),this.#t+=4}writeBigInt64(e){const r=this.#r(8);this.#i.setBigInt64(r,e,!1),this.#t+=8}writeBigUint64(e){const r=this.#r(8);this.#i.setBigUint64(r,e,!1),this.#t+=8}writeFloat32(e){const r=this.#r(4);this.#i.setFloat32(r,e,!1),this.#t+=4}writeFloat64(e){const r=this.#r(8);this.#i.setFloat64(r,e,!1),this.#t+=8}#r(e){return this.#o(e),this.#t}toUint8Array(){return this.#e.slice(0,this.#t)}#o(e){const r=this.#t+e;if(r<=this.#e.length)return;let n=this.#e.length;for(;n<r;)n*=2;const i=new Uint8Array(n);i.set(this.#e),this.#e=i,this.#i=new DataView(i.buffer)}}const At=4294967295;class x{name;constructor(e=void 0){this.name=e}encode(e,r){const n=new Se(r?.maxDepth);return this._write(e,n,this.name??this.kind),n.toUint8Array()}decode(e,r){const n=new xt(e,r?.maxDepth),i=this._read(n,this.name??this.kind);return n.done(this.name??this.kind),i}validateXdr(e,r){try{return this.decode(e,r),!0}catch(n){if(n instanceof u)return!1;throw n}}validate(e){try{const r=new Se;return this._write(e,r,this.name??this.kind),!0}catch(r){if(r instanceof u)return!1;throw r}}}class Dt extends x{kind="array";element;maxLength;constructor(e,r){super(),be(r,"array maxLength"),this.element=e,this.maxLength=r}_read(e,r){e.enter(r);try{const n=e.readUint32(r);if(n>this.maxLength)throw new u(`${r}: array length ${n} exceeds maximum ${this.maxLength}`);if(n>e.remaining)throw new u(`${r}: array length ${n} exceeds remaining ${e.remaining} byte(s)`);return Tt(e,n,this.element,r)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(kt(e,n),e.length>this.maxLength)throw new u(`${n}: array length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),Ft(e,r,this.element,n)}finally{r.exit()}}}function Ot(t,e){return new Dt(t,e)}function Tt(t,e,r,n){const i=[];for(let s=0;s<e;s+=1){const o=t.offset,l=r._read(t,`${n}[${s}]`);if(t.offset===o)throw new u(`${n}[${s}]: element type '${r.name??r.kind}' consumed no input; an array element must encode to at least one byte`);i.push(l)}return i}function Ft(t,e,r,n){let i=0;for(const s of t){const o=e.offset;if(r._write(s,e,`${n}[${i}]`),e.offset===o)throw new u(`${n}[${i}]: element type '${r.name??r.kind}' encoded to zero bytes; an array element must encode to at least one byte`);i+=1}}const Rt=new Set(["__proto__","name","kind","encode","decode","validate","_read","_write","nameByValue"]);class Nt extends x{kind="enum";nameByValue;#e=new Set;constructor(e,r){super(e);const n=new Map;for(const[i,s]of Object.entries(r)){if(Q(s,-2147483648,2147483647,`${e}.${i}`),this.#e.has(s))throw new u(`${e}: duplicate enum value ${s}`);this.#e.add(s),n.set(s,i)}this.nameByValue=n}_read(e,r){const n=e.readInt32(r);if(!this.#e.has(n))throw new u(`${r}: unknown enum value ${n}`);return n}_write(e,r,n){if(typeof e!="number"||!this.#e.has(e))throw new u(`${n}: unknown enum value ${String(e)}`);r.writeInt32(e)}}function Bt(t,e){for(const n of Object.getOwnPropertyNames(e))if(Rt.has(n))throw new u(`${t}: enum member name ${n} collides with reserved property`);const r=new Nt(t,e);return Object.assign(r,e)}class Mt extends x{kind="int32";_read(e,r){return e.readInt32(r)}_write(e,r,n){Q(e,-2147483648,2147483647,n),r.writeInt32(e)}}function $e(){return new Mt}class jt extends x{constructor(e){super(),this.maxLength=e,be(e,"string maxLength")}maxLength;kind="string";_read(e,r){const n=e.readUint32(r);if(n>this.maxLength)throw new u(`${r}: string byte length ${n} exceeds maximum ${this.maxLength}`);const i=e.readBytes(n,r);return e.skipPadding(n,r),i}_write(e,r,n){if(Ct(e,n),e.length>this.maxLength)throw new u(`${n}: string byte length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),r.writeBytes(e),r.writePadding(e.length)}}function Ut(t){return new jt(t)}class Lt extends x{kind="struct";entries;constructor(e,r){if(super(e),Object.getOwnPropertyNames(r).includes("__proto__"))throw new u(`${e}: struct field name '__proto__' is not allowed`);this.entries=Object.entries(r)}_read(e,r){e.enter(r);try{const n={};for(const[i,s]of this.entries)n[i]=s._read(e,`${r}.${i}`);return n}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ye(e))throw new u(`${n}: expected plain object`);const i=e;for(const[s,o]of this.entries){if(!Object.prototype.hasOwnProperty.call(i,s))throw new u(`${n}.${s}: missing struct field`);o._write(i[s],r,`${n}.${s}`)}}finally{r.exit()}}}function Ie(t,e){return new Lt(t,e)}class Vt extends x{kind="uint32";_read(e,r){return e.readUint32(r)}_write(e,r,n){Q(e,0,4294967295,n),r.writeUint32(e)}}function qe(){return new Vt}class zt extends x{kind="uint64";_read(e,r){return e.readBigUint64(r)}_write(e,r,n){Et(e,0n,(1n<<64n)-1n,n),r.writeBigUint64(e)}}function z(){return new zt}const Z="default";class Xt extends x{kind="union";switchOn;cases;defaultArm;switchKey;#e=new Map;constructor(e,r,n,i,s){if(super(e),s==="__proto__")throw new u(`${e}: switchKey '__proto__' is not allowed`);if(this.switchOn=r,this.cases=n,this.defaultArm=i,this.switchKey=s,n.length===0&&i===void 0)throw new u(`${e}: union needs at least one case or a default arm`);const o=new Set;for(const l of n){if(!r.validate(l.discriminant))throw new u(`${e}.${l.name}: case discriminator ${String(l.discriminant)} is not a valid ${r.name??r.kind} value`);if(o.has(l.name))throw new u(`${e}: duplicate union case name ${l.name}`);if(o.add(l.name),this.#e.has(l.discriminant))throw new u(`${e}: duplicate union discriminator ${String(l.discriminant)}`);Ee(e,l.name,l.arm,s),this.#e.set(l.discriminant,l)}i!==void 0&&Ee(e,Z,i,s)}_read(e,r){e.enter(r);try{const n=this.switchOn._read(e,`${r}.${this.switchKey}`),i=this.#e.get(n),s=i?.arm??this.defaultArm;if(s===void 0)throw new u(`${r}: no case for union discriminator ${String(n)}`);return Ht(n,s,this.switchKey,e,`${r}.${i?.name??Z}`)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!ye(e)||!Object.prototype.hasOwnProperty.call(e,this.switchKey))throw new u(`${n}: expected union object with ${this.switchKey} discriminator`);const i=e,s=i[this.switchKey],o=this.#e.get(s),l=o?.arm??this.defaultArm;if(l===void 0)throw new u(`${n}: no case for union discriminator ${String(s)}`);this.switchOn._write(s,r,`${n}.${this.switchKey}`),Gt(i,l,r,`${n}.${o?.name??Z}`)}finally{r.exit()}}}function Wt(t,e){return{kind:"field",name:t,schema:e}}function ee(t,e,r){return{name:t,discriminant:e,arm:r}}function te(t,e){const r=e.switchKey??"type";return new Xt(t,e.switchOn,e.cases,e.defaultArm,r)}function Ht(t,e,r,n,i){const s={};return s[r]=t,X(e)?(s[e.name]=e.schema._read(n,`${i}.${e.name}`),s):(e._read(n,i),s)}function Gt(t,e,r,n){if(X(e)){if(!Object.prototype.hasOwnProperty.call(t,e.name))throw new u(`${n}.${e.name}: missing union arm payload`);e.schema._write(t[e.name],r,`${n}.${e.name}`);return}e._write(void 0,r,n)}function Ee(t,e,r,n){if(X(r)&&r.name===n)throw new u(`${t}.${e}: union arm payload field must not be named ${n}`);if(X(r)&&r.name==="__proto__")throw new u(`${t}.${e}: union arm payload field name '__proto__' is not allowed`)}function X(t){return"schema"in t}class Kt extends x{kind="void";_read(){}_write(e,r,n){if(e!==void 0)throw new u(`${n}: expected void`)}}function Ce(){return new Kt}var re=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},w=(t,e,r)=>(re(t,e,"read from private field"),r?r.call(t):e.get(t)),P=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},ne=(t,e,r,n)=>(re(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),$=(t,e,r)=>(re(t,e,"access private method"),r),E,C,M,ie,ke,se,xe,W,oe,R,j,U,H;const Yt=new TextEncoder,Pe={v:0};function Jt(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}const ae=Bt("EnvelopeType",{envelopeTypeBundle:0}),Qt=te("BundleItemExt",{switchOn:$e(),switchKey:"v",cases:[ee("v0",0,Ce())]}),Zt=Ie("BundleItem",{collectionId:z(),productId:z(),variantId:z(),sku:Ut(At),quantity:qe(),ext:Qt}),er=te("BundleExt",{switchOn:$e(),switchKey:"v",cases:[ee("v0",0,Ce())]}),tr=Ie("Bundle",{variantId:z(),items:Ot(Zt,500),version:qe(),ext:er}),rr=te("BundleEnvelope",{switchOn:ae,switchKey:"type",cases:[ee("envelopeTypeBundle",ae.envelopeTypeBundle,Wt("v1",tr))]});function nr(t){const e={type:ae.envelopeTypeBundle,v1:{variantId:BigInt(t.variantId.toString()),items:t.items.map(r=>({collectionId:BigInt(r.collectionId.toString()),productId:BigInt(r.productId.toString()),variantId:BigInt(r.variantId.toString()),sku:Yt.encode(r.sku||""),quantity:r.quantity,ext:Pe})),version:t.version||Math.floor(Date.now()/1e3),ext:Pe}};return Jt(rr.encode(e))}class ir{constructor(e,r){P(this,ie),P(this,se),P(this,W),P(this,R),P(this,U),P(this,E,void 0),P(this,C,void 0),P(this,M,void 0),ne(this,E,$(this,ie,ke).call(this,r)),ne(this,M,$(this,se,xe).call(this,r)),ne(this,C,e)}isInitialDataValid(){if(!w(this,M))throw"Bundle data does not exist for the given product.";if(!w(this,E))throw"Bundle settings do not exist for the given product.";if(!Array.isArray(w(this,C))||!w(this,C).length)throw"No bundle selection items provided.";return!0}isValidVariant(e){if(!w(this,E)?.variantsSettings[e])throw`The ${e} bundle variant is invalid.`;return!0}isSelectionInVariantRange(e){const r=w(this,C).reduce((i,s)=>i+s.quantity,0),n=w(this,E)?.variantsSettings[e].ranges||[];if(!$(this,W,oe).call(this,n,r))throw"The total number of products does not fall within the required variant range.";return!0}areItemsInMaxPerItemBound(){const e=w(this,E)?.bundleSettings.maxPerItem||0,r=w(this,C).filter(({quantity:n})=>n>e);if(e&&r.length)throw`The selected products (${$(this,R,j).call(this,r.map(({externalProductId:n})=>n)).join(", ")}) exceed the maximum limit of ${e} items per product.`;return!0}areSelectedCollectionsValid(e){const r=w(this,E)?.variantsSettings[e]?.optionSources,n=w(this,C).filter(({collectionId:i})=>!r||!$(this,U,H).call(this,r,i));if(n.length)throw`The collections (${$(this,R,j).call(this,n.map(({collectionId:i})=>i)).join(", ")}) are no longer valid for the bundle variant (${e}).`;return!0}areItemsQuantitiesValidForTheCollection(e){const r=w(this,C).reduce((s,o)=>(s[o.collectionId]=o.quantity+(s[o.collectionId]||0),s),Object.create(null)),n=w(this,E)?.variantsSettings[e],i=Object.values(n?.optionSources||{}).filter(s=>{const o=r[s.collectionId]||0;return!$(this,W,oe).call(this,[s],o)});if(!n||i.length)throw`The selection exceeds the limits for the collections (${$(this,R,j).call(this,i.map(({collectionId:s})=>s)).join(", ")}).`;return!0}areSelectedProductsValid(e){const r=w(this,E)?.variantsSettings[e]?.optionSources||{},n=Object.values(r).reduce((s,o)=>{const l=w(this,M)?.collections[o.collectionId];return l&&(s[o.collectionId]=l),s},Object.create(null));if(!Object.values(n).length)throw`No collections found for the bundle variant (${e}).`;const i=w(this,C).filter(({externalProductId:s,collectionId:o})=>$(this,U,H).call(this,n,o)?!$(this,U,H).call(this,n[o].products,s):!0);if(i.length)throw`The products (${$(this,R,j).call(this,i.map(({externalProductId:s})=>s)).join(", ")}) are no longer valid for the bundle product.`;return!0}isBundleSelectionValid(e){return this.isInitialDataValid(),this.isValidVariant(e),this.isSelectionInVariantRange(e),this.areItemsInMaxPerItemBound(),this.areSelectedCollectionsValid(e),this.areItemsQuantitiesValidForTheCollection(e),this.areSelectedProductsValid(e),!0}}E=new WeakMap,C=new WeakMap,M=new WeakMap,ie=new WeakSet,ke=function(t){try{const e=t.bundle_settings;return{bundleSettings:{maxPerItem:e.max_quantity_per_variant,isCustomizable:e.is_customizable},variantsSettings:e.variants.reduce((r,n)=>{if(!n.enabled)return r;let i=[{min:n.items_count,max:n.items_count}];return n.items_count||(i=n.ranges.map(({quantity_max:s,quantity_min:o})=>({min:o,max:s}))),r[n.external_variant_id]={externalVariantId:n.external_variant_id,optionSources:n.option_sources.reduce((s,o)=>(s[o.option_source_id]={min:o.quantity_min,max:o.quantity_max,collectionId:o.option_source_id},s),Object.create(null)),ranges:i},r},Object.create(null))}}catch{return null}},se=new WeakSet,xe=function(t){try{const e=Object.values(t.collections).reduce((r,n)=>(r[n.id]={...n,products:n.products.reduce((i,s)=>(i[s.id]=s,i),Object.create(null))},r),Object.create(null));return{...t,collections:e}}catch{return null}},W=new WeakSet,oe=function(t,e){return!!t.filter(({min:r,max:n})=>{const i=r??e,s=n??e;return i<=e&&e<=s}).length},R=new WeakSet,j=function(t){return Array.from(new Set(t))},U=new WeakSet,H=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};const sr="/bundling-storefront-manager";function Ae(t){return nr({variantId:t.externalVariantId,version:0,items:t.selections.map(e=>({collectionId:e.collectionId,productId:e.externalProductId,variantId:e.externalVariantId,quantity:e.quantity,sku:""}))})}async function or(t){const e=b(),r=await ce(t);if(r!==!0)throw new Error(r);const n=Ae(t);try{const i=await A("post",`${sr}/api/v1/bundles`,{data:{bundle:n},headers:{Origin:`https://${e.storeIdentifier}`}});if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}async function ar(t,e){const r=await ce(e);if(r!==!0)throw new Error(r);const n=Ae(e);try{const i=await c("post","/bundle_selections/bundle_id",{data:{bundle:n}},a(t,"getBundleSelectionId"));if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}function cr(t,e){const r=De(t);if(r!==!0)throw new Error(`Dynamic Bundle is invalid. ${r}`);const n=`${T(9)}:${t.externalProductId}`;return t.selections.map(i=>{const s={id:i.externalVariantId,quantity:i.quantity,properties:{_rc_bundle:n,_rc_bundle_variant:t.externalVariantId,_rc_bundle_parent:e,_rc_bundle_collection_id:i.collectionId}};return i.sellingPlan?s.selling_plan=i.sellingPlan:i.shippingIntervalFrequency&&(s.properties.shipping_interval_frequency=i.shippingIntervalFrequency,s.properties.shipping_interval_unit_type=i.shippingIntervalUnitType,s.id=`${i.discountedVariantId}`),s})}async function ce(t){try{return t?t.selections.length===0?"No selections defined":!0:"Bundle is not defined"}catch(e){return`Error fetching bundle settings: ${e}`}}async function dr(t){try{const e=await A("get",`/bundle-data/${p(t.externalProductId)}`);return{valid:new ir(t.selections,e).isBundleSelectionValid(t.externalVariantId)}}catch(e){return{valid:!1,error:String(e)}}}const ur={day:["day","days","Days"],days:["day","days","Days"],Days:["day","days","Days"],week:["week","weeks","Weeks"],weeks:["week","weeks","Weeks"],Weeks:["week","weeks","Weeks"],month:["month","months","Months"],months:["month","months","Months"],Months:["month","months","Months"]};function De(t){if(!t)return"No bundle defined.";if(t.selections.length===0)return"No selections defined.";const{shippingIntervalFrequency:e,shippingIntervalUnitType:r}=t.selections.find(n=>n.shippingIntervalFrequency||n.shippingIntervalUnitType)||{};if(e||r){if(!e||!r)return"Shipping intervals do not match on selections.";{const n=ur[r];for(let i=0;i<t.selections.length;i++){const{shippingIntervalFrequency:s,shippingIntervalUnitType:o}=t.selections[i];if(s&&s!==e||o&&!n.includes(o))return"Shipping intervals do not match on selections."}}}return!0}async function lr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:r}=await c("get","/bundle_selections",{id:e},a(t,"getBundleSelection"));return r}function pr(t,e){return c("get","/bundle_selections",{query:e},a(t,"listBundleSelections"))}async function _r(t,e){const{bundle_selection:r}=await c("post","/bundle_selections",{data:e},a(t,"createBundleSelection"));return r}async function hr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:n}=await c("put","/bundle_selections",{id:e,data:r},a(t,"updateBundleSelection"));return n}function mr(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/bundle_selections",{id:e},a(t,"deleteBundleSelection"))}async function fr(t,e,r,n){if(e===void 0||e==="")throw new Error("Purchase item ID is required");const{subscription:i}=await c("put","/bundles",{id:e,data:r,query:n},a(t,"updateBundle"));return i}var gr=Object.freeze({__proto__:null,createBundleSelection:_r,deleteBundleSelection:mr,getBundleId:or,getBundleSelection:lr,getBundleSelectionId:ar,getDynamicBundleItems:cr,listBundleSelections:pr,updateBundle:fr,updateBundleSelection:hr,validateBundle:ce,validateBundleSelection:dr,validateDynamicBundle:De});const wr=t=>{const e=t.layout_settings.addons,r=t.layout_settings.crossSells,n=t.customization_window,i=t.layout_settings?.defaultVariantId??t.default_bundle_variant_id,s=t.layout_settings.defaultFrequency,o=t.layout_settings.addToCartCallback;return{default_variant_id:i?String(i):null,is_customizable:t.is_customizable,price_rule:String(t.price_rule).toUpperCase(),customization_window:n?{active_days:n,disabled_message:t.customization_window_disabled_message||""}:null,addons:e.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,cross_sells:r.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,default_selling_plan_id:s||null,collapsible_collections:t.layout_settings.collapsibleSections,max_quantity_per_variant:t.max_quantity_per_variant,show_product_variants:t.layout_settings.showVariants,product_details_modal_enabled:t.layout_settings.learnMoreModal,addToCartBehavior:{type:o.type==="none"?"cart_page":o.type,value:o.value}}},yr=t=>t.tiered_discounts.length===0?null:{tiered_discounts:t.tiered_discounts},G=t=>({id:t.id,name:t.name,options:t.options.map(e=>({name:e.name,value:e.value})),recurring_deliveries:t.recurring_deliveries,price_adjustments:t.price_adjustments.map(({value:e,value_type:r})=>({value:e,value_type:r}))}),Oe=t=>({name:t.name,options:t.options.map(e=>({name:e.name,values:e.values})),selling_plans:t.selling_plans.map(G)}),Te=t=>({id:String(t.id),title:t.title,price:t.price,compare_at_price:t.compare_at_price,options:t.options,available_for_sale:t.available}),de=t=>t==null||typeof t=="string"?t:"src"in t?t.src:null,Fe=t=>({id:String(t.id),title:t.title,description:t.description,available_for_sale:t.available,featured_image:de(t.featured_image),images:t.images,requires_selling_plan:t.requires_selling_plan,selling_plan_groups:t.selling_plan_groups.map(Oe)}),Re=t=>{const e=vr(t.selling_plan_groups);return{...Fe(t),handle:t.handle,tags:t.tags,price_range:{min:t.price_min,max:t.price_max},compare_at_price_range:{min:t.compare_at_price_min,max:t.compare_at_price_max},options:t.options,variants:t.variants.map(r=>({...Te(r),selling_plan_allocations:r.selling_plan_allocations.map(n=>({price:n.price,compare_at_price:n.compare_at_price,selling_plan:G(e[`${n.selling_plan_group_id}-${n.selling_plan_id}`])})),option1:r.option1,option2:r.option2,option3:r.option3,sku:r.sku||"",requires_shipping:r.requires_shipping,taxable:r.taxable,featured_image:de(r.featured_image),public_title:r.public_title,requires_selling_plan:r.requires_selling_plan}))}},br=({items_count:t,ranges:e})=>e.length>0?e.map(({quantity_max:r,quantity_min:n})=>({min:n,max:r})):[{min:t,max:t}],vr=t=>t.reduce((e,r)=>(r.selling_plans.forEach(n=>{const i=`${r.id}-${n.id}`;e[i]=n}),e),{}),Sr=t=>Array.isArray(t)?t:[];function ue(t){const e=wr(t.bundle_settings),r=t.variants.reduce((n,i)=>(n[i.id]=i,n),{});return{id:String(t.id),title:t.title,description:t.description||null,handle:t.handle,options:t.options.map(n=>({name:n.name,position:n.position,values:n.values})),default_variant_id:e.default_variant_id,default_selling_plan_id:e.default_selling_plan_id?Number(e.default_selling_plan_id):null,available_for_sale:t.available,requires_selling_plan:t.requires_selling_plan,bundle_settings:{is_customizable:e.is_customizable,price_rule:e.price_rule,customization_window:e.customization_window,max_quantity_per_variant:e.max_quantity_per_variant,collapsible_collections:e.collapsible_collections,show_product_variants:e.show_product_variants,product_details_modal_enabled:e.product_details_modal_enabled,show_variants_as_individual_products:t.bundle_settings.settings.display_variants_as_separate_products_in_list,post_add_to_cart_behavior:e.addToCartBehavior},variants:t.bundle_settings.variants.filter(({enabled:n})=>n).map((n,i)=>{const s=r[String(n.external_variant_id)];return{id:String(n.external_variant_id),title:s.title,price:s.price,compare_at_price:s.compare_at_price,image:s.image||"",available_for_sale:s.available,options:s.options,requires_selling_plan:s.requires_selling_plan,selling_plan_allocations:s.selling_plan_allocations.map(o=>({price:o.price,compare_at_price:o.compare_at_price,selling_plan:G(o.selling_plan)})),ranges:br(n),collections:n.option_sources.map(o=>({id:o.option_source_id,source_platform:"shopify",min:o.quantity_min||0,max:o.quantity_max,position:o.position})),default_selections:n.selection_defaults.map(o=>({quantity:o.quantity,product:{id:String(o.product.id),handle:o.handle,title:o.product.title,description:o.product.description,images:o.product.images},variant:{id:o.external_variant_id,title:o.variant.title,featured_image:de(o.variant.featured_image),sku:o.sku||""}})),position:i}}),selling_plan_groups:t.selling_plan_groups.map(Oe),collections:Object.values(t.collections).reduce((n,i)=>(Array.isArray(i.products)&&(n[String(i.id)]={id:String(i.id),title:i.title,handle:i.handle,products:i.products.map(Re)}),n),{}),addons:t.addons.products.length?{collection_id:e.addons?.collection_id||"",collection_handle:e.addons?.collection_handle||"",products:t.addons.products.map(n=>({...Fe(n),price_range:{min:n.price,max:n.price},compare_at_price_range:{min:n.compare_at_price||0,max:n.compare_at_price},variants:n.variants.map(i=>({...Te(i),image:i.image,selling_plan_allocations:i.selling_plan_allocations.map(s=>({price:s.price,compare_at_price:s.compare_at_price,selling_plan:G(s.selling_plan)}))}))}))}:null,cross_sells:t.cross_sells.products.length?{collection_id:e.cross_sells?.collection_id||"",collection_handle:e.cross_sells?.collection_handle||"",products:t.cross_sells.products.map(Re)}:null,incentives:yr(t.incentives),filters:Sr(t.filters),templates:t.bundle_settings.layout_settings.templates||null,globalStyles:t.bundle_settings.layout_settings.globalStyles||null}}async function $r(t,e){return e?.source==="shopify_storefront"?qr():Ir(t,e?.country_code)}async function Ir(t,e){const{appName:r,appVersion:n}=b(),i={"X-Recharge-Sdk-Fn":"loadFromOnlineStore","X-Recharge-Sdk-Version":"2.6.0",...r?{"X-Recharge-Sdk-App-Name":r}:{},...n?{"X-Recharge-Sdk-App-Version":n}:{}};if(!e){const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return ue(o)}const s=new FormData;s.append("form_type","localization"),s.append("_method","put"),s.append("return_to",`${me}/bundle-data/${t}`),s.append("country_code",e);try{const o=await S("post","/localization",{headers:{"Content-Type":"multipart/form-data",...i},data:s});return ue(o)}catch{const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return ue(o)}}async function qr(t,e){if(!b().storeIdentifier)throw new Error("Store identifier is required for Shopify Storefront API requests");return{}}var Er=Object.freeze({__proto__:null,loadBundleData:$r});function Cr(t){try{return JSON.parse(t)}catch{return t}}function kr(t){return Object.entries(t).reduce((e,[r,n])=>({...e,[r]:Cr(n)}),{})}const Ne=t=>typeof t=="string"?t!=="0"&&t!=="false":!!t;function le(t,e){const r=new Set(e),n={};for(const i of Object.keys(t))r.has(i)||(n[i]=t[i]);return n}function Be(t){const e=kr(t),r=e.auto_inject===void 0?!0:e.auto_inject,n=e.display_on??[],i=e.first_option==="autodeliver";return{...le(e,["display_on","first_option"]),auto_inject:r,valid_pages:n,is_subscription_first:i,autoInject:r,validPages:n,isSubscriptionFirst:i}}function Me(t){const e=t.subscription_options?.storefront_purchase_options==="subscription_only";return{...t,is_subscription_only:e,isSubscriptionOnly:e}}function xr(t){return t.map(e=>{const r={};return Object.entries(e).forEach(([n,i])=>{Object.defineProperty(r,n,{value:Me(i),enumerable:!0,writable:!0,configurable:!0})}),r})}const pe="2020-12",Pr={store_currency:{currency_code:"USD",currency_symbol:"$",decimal_separator:".",thousands_separator:",",currency_symbol_location:"left"}},L=new Map;function K(t,e){return L.has(t)||L.set(t,e()),L.get(t)}async function _e(t,e){if(t===void 0||t==="")throw new Error("ID is required");const r=e?.version??"2020-12",{product:n}=await K(`product.${t}.${r}`,()=>V("get",`/product/${r}/${p(t)}.json`));return r==="2020-12"?Me(n):n}async function je(){return await K("storeSettings",()=>V("get",`/${pe}/store_settings.json`).catch(()=>Pr))}async function Ue(){const{widget_settings:t}=await K("widgetSettings",()=>V("get",`/${pe}/widget_settings.json`));return Be(t)}async function Le(){const{products:t,widget_settings:e,store_settings:r,meta:n}=await K("productsAndSettings",()=>V("get",`/product/${pe}/products.json`));return n?.status==="error"?Promise.reject(n.message):{products:xr(t),widget_settings:Be(e),store_settings:r??{}}}async function Ar(){const{products:t}=await Le();return t}async function Dr(t){const[e,r,n]=await Promise.all([_e(t),je(),Ue()]);return{product:e,store_settings:r,widget_settings:n,storeSettings:r,widgetSettings:n}}async function Or(t){const{bundle_product:e}=await _e(t);return e}async function Ve(){return Array.from(L.keys()).forEach(t=>L.delete(t))}var Tr=Object.freeze({__proto__:null,getCDNBundleSettings:Or,getCDNProduct:_e,getCDNProductAndSettings:Dr,getCDNProducts:Ar,getCDNProductsAndSettings:Le,getCDNStoreSettings:je,getCDNWidgetSettings:Ue,resetCDNCache:Ve});async function Fr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("get","/charges",{id:e,query:{include:r?.include}},a(t,"getCharge"));return n}function Rr(t,e){return c("get","/charges",{query:e},a(t,"listCharges"))}async function Nr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/apply_discount`,{data:{discount_code:r}},a(t,"applyDiscountToCharge"));return n}async function Br(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/remove_discount`,{},a(t,"removeDiscountsFromCharge"));return r}async function Mr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/skip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"skipCharge"));return i}async function jr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/unskip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"unskipCharge"));return i}async function Ur(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/process`,{},a(t,"processCharge"));return r}async function Lr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/change_next_charge_date`,{data:{next_charge_date:r}},a(t,"rescheduleCharge"));return n}var Vr=Object.freeze({__proto__:null,applyDiscountToCharge:Nr,getCharge:Fr,listCharges:Rr,processCharge:Ur,removeDiscountsFromCharge:Br,rescheduleCharge:Lr,skipCharge:Mr,unskipCharge:jr});async function ze(t,e){if(!["2020-12","2022-06"].includes(e.format_version))throw new Error("Missing or unsupported format_version.");return c("get","/product_search",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"productSearch"))}var zr=Object.freeze({__proto__:null,productSearch:ze});async function Xe(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{collection:r}=await c("get","/collections",{id:e},a(t,"getCollection"));return r}function Xr(t,e){return c("get","/collections",{query:e},a(t,"listCollections"))}async function Wr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");if(!["2020-12","2022-06"].includes(r.format_version))throw new Error("Missing or unsupported format_version.");const n=a(t,"listCollectionProducts"),[{sort_order:i,manual_sort_order:s},{products:o}]=await Promise.all([Xe(n,e),ze(n,{...r,collection_ids:[e],limit:250})]);if(i==="manual")return{products:s.reduce((l,f)=>{const _=o.find(h=>h.external_product_id===f);return _&&l.push(_),l},[])};{const l=Hr(i);return{products:o.slice().sort(l)}}}function We(t,e){const r=t.external_created_at,n=e.external_created_at;return r<n?-1:n>r?1:0}function He(t,e){const r=t.external_product_id,n=e.external_product_id;return r<n?-1:n>r?1:0}function Ge(t,e){const r=t.title.toLowerCase(),n=e.title.toLowerCase();return r<n?-1:n>r?1:0}function Hr(t){switch(t){case"created_at-asc":return We;case"created_at-desc":return(e,r)=>We(r,e);case"id-asc":return He;case"id-desc":return(e,r)=>He(r,e);case"title-asc":return Ge;case"title-desc":return(e,r)=>Ge(r,e)}}var Gr=Object.freeze({__proto__:null,getCollection:Xe,listCollectionProducts:Wr,listCollections:Xr});async function Kr(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("get","/customers",{id:r,query:{include:e?.include}},a(t,"getCustomer"));return n}async function Ke(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("put","/customers",{id:r,data:e},a(t,"updateCustomer"));return n}async function Yr(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{deliveries:n}=await c("get",`/customers/${p(r)}/delivery_schedule`,{query:e},a(t,"getDeliverySchedule"));return n}async function Y(t,e){return c("get","/portal_access",{query:e},a(t,"getCustomerPortalAccess"))}async function Jr(t,e,r){if(e===void 0||e==="")throw new Error("Subscription ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await Y(a(t,"getActiveChurnLandingPageURL"));return`${n.replace("portal","pages")}${i}/subscriptions/${e}/cancel?token=${s}&subscription=${e}&redirect_to=${encodeURIComponent(r)}`}async function Qr(t){const{base_url:e,customer_hash:r,temp_token:n}=await Y(a(t,"getFailedPaymentMethodRecoveryLandingPageURL"));return`${e.replace("portal","pages")}account/payment-methods?token=${n}&hash=${r}`}async function Zr(t,e,r){if(e===void 0||e==="")throw new Error("Gift ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await Y(a(t,"getGiftRedemptionLandingPageURL"));return`${n.replace("portal","pages")}${i}/gifts/${e}?token=${s}&redirect_to=${encodeURIComponent(r)}`}const Ye={SHOPIFY_UPDATE_PAYMENT_INFO:{type:"email",template_type:"shopify_update_payment_information"},SHOPIFY_MIGRATE_PAYMENT_INFO:{type:"email",template_type:"shopify_migrate_payment_information"}};async function en(t,e,r){const n=t.customerId;if(!n)throw new Error("Not logged in.");if(!Object.prototype.hasOwnProperty.call(Ye,e))throw new Error("Notification not supported.");const i=Ye[e];return c("post",`/customers/${p(n)}/notifications`,{data:{...i,template_vars:r}},a(t,"sendCustomerNotification"))}async function tn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include}},a(t,"getCreditSummary"));return n}var rn=Object.freeze({__proto__:null,getActiveChurnLandingPageURL:Jr,getCreditSummary:tn,getCustomer:Kr,getCustomerPortalAccess:Y,getDeliverySchedule:Yr,getFailedPaymentMethodRecoveryLandingPageURL:Qr,getGiftRedemptionLandingPageURL:Zr,sendCustomerNotification:en,updateCustomer:Ke});async function nn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include,presentment_currency_code:e?.presentment_currency_code}},a(t,"getCreditSummary"));return n}function sn(t,{recurring:e}){if(!t.customerId)throw new Error("Not logged in.");const r={};return e!==void 0&&(r.apply_credit_to_next_recurring_charge=e),Ke(a(t,"setApplyCreditsToNextCharge"),r)}async function on(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer_id:n,...i}=e??{};return await c("get","/credit_accounts",{query:{...i,customer_id:r}},a(t,"listCreditAccounts"))}var an=Object.freeze({__proto__:null,getCreditSummary:nn,listCreditAccounts:on,setApplyCreditsToNextCharge:sn});async function cn(t,e,r){return await c("post","/customer_surveys/cancellation_prevention",{data:{customer_id:e,subscription_id:r}},a(t,"getCustomerSurveyReasons"))}async function dn(t,e,r,n){return await c("post",`/customer_surveys/${p(r)}/customer_response`,{data:{customer_id:e,response_id:n}},a(t,"getCustomerSurveyOffers"))}async function un(t,e){return await c("post","/offers/claim",{data:e},a(t,"claimOfferCustomerSurvey")),{}}var ln=Object.freeze({__proto__:null,claimOfferCustomerSurvey:un,getCustomerSurveyOffers:dn,getCustomerSurveyReasons:cn});async function pn(t,e,r,n){if(e===void 0||e==="")throw new Error("Subscription ID is required");return c("post",`/flows/customer_portal_flow/subscription/${p(e)}`,{query:{action:r,flow_id:n?.flow_id},data:{}},a(t,"triggerCustomerPortalFlow"))}var _n=Object.freeze({__proto__:null,triggerCustomerPortalFlow:pn});function hn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/gift_purchases",{query:e},a(t,"listGiftPurchases"))}async function mn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{gift_purchase:r}=await c("get","/gift_purchases",{id:e},a(t,"getGiftPurchase"));return r}var fn=Object.freeze({__proto__:null,getGiftPurchase:mn,listGiftPurchases:hn});function gn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/incentives/tiered_discounts",{query:e},a(t,"listTieredDiscounts"))}async function wn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{tiered_discount:r}=await c("get",`/incentives/tiered_discounts/${p(e)}`,{},a(t,"getTieredDiscount"));return r}function yn(t,e){return c("post","/incentives/tiered_discounts/offers",{data:e},a(t,"getTieredDiscountOffers"))}var bn=Object.freeze({__proto__:null,getTieredDiscount:wn,getTieredDiscountOffers:yn,listTieredDiscounts:gn});async function vn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{membership:r}=await c("get","/memberships",{id:e},a(t,"getMembership"));return r}function Sn(t,e){return c("get","/memberships",{query:e},a(t,"listMemberships"))}async function $n(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/cancel`,{data:r},a(t,"cancelMembership"));return n}async function In(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/activate`,{data:r},a(t,"activateMembership"));return n}async function qn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/change`,{data:r},a(t,"changeMembership"));return n}var En=Object.freeze({__proto__:null,activateMembership:In,cancelMembership:$n,changeMembership:qn,getMembership:vn,listMemberships:Sn});async function Cn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership_program:n}=await c("get","/membership_programs",{id:e,query:{include:r?.include}},a(t,"getMembershipProgram"));return n}function kn(t,e){return c("get","/membership_programs",{query:e},a(t,"listMembershipPrograms"))}var xn=Object.freeze({__proto__:null,getMembershipProgram:Cn,listMembershipPrograms:kn});async function Pn(t,e){const{metafield:r}=await c("post","/metafields",{data:{metafield:e}},a(t,"createMetafield"));return r}async function An(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{metafield:n}=await c("put","/metafields",{id:e,data:{metafield:r}},a(t,"updateMetafield"));return n}function Dn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/metafields",{id:e},a(t,"deleteMetafield"))}var On=Object.freeze({__proto__:null,createMetafield:Pn,deleteMetafield:Dn,updateMetafield:An});async function Tn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:r}=await c("get","/onetimes",{id:e},a(t,"getOnetime"));return r}function Fn(t,e){return c("get","/onetimes",{query:e},a(t,"listOnetimes"))}async function Rn(t,e){const{onetime:r}=await c("post","/onetimes",{data:e},a(t,"createOnetime"));return r}async function Nn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:n}=await c("put","/onetimes",{id:e,data:r},a(t,"updateOnetime"));return n}function Bn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/onetimes",{id:e},a(t,"deleteOnetime"))}var Mn=Object.freeze({__proto__:null,createOnetime:Rn,deleteOnetime:Bn,getOnetime:Tn,listOnetimes:Fn,updateOnetime:Nn});async function jn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("get","/orders",{id:e},a(t,"getOrder"));return r}function Un(t,e){return c("get","/orders",{query:e},a(t,"listOrders"))}async function Ln(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("post",`/orders/${p(e)}/delay`,{},a(t,"delayOrder"));return r}var Vn=Object.freeze({__proto__:null,delayOrder:Ln,getOrder:jn,listOrders:Un});async function zn(t,e){return typeof window<"u"&&window.Spreedly?Promise.resolve():new Promise((r,n)=>{if(typeof document>"u"){n(new Error("Document is not available. This function must be called in a browser environment."));return}if(document.querySelector(`script[src="${t}"]`)){const s=()=>{window.Spreedly?r():setTimeout(s,50)};s();return}const i=document.createElement("script");i.src=t,i.integrity=e,i.crossOrigin="anonymous",i.addEventListener("load",()=>{const s=()=>{window.Spreedly?r():setTimeout(s,50)};s()}),i.addEventListener("error",()=>{n(new Error("Failed to load payment iFrame script"))}),document.head.appendChild(i)})}async function Xn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("get","/payment_methods",{id:e,query:{include:r?.include}},a(t,"getPaymentMethod"));return n}async function Je(t,e){const{payment_method:r}=await c("post","/payment_methods",{data:{...e,customer_id:t.customerId}},a(t,"createPaymentMethod"));return r}async function Wn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("put","/payment_methods",{id:e,data:r},a(t,"updatePaymentMethod"));return n}function Hn(t,e){return c("get","/payment_methods",{query:e},a(t,"listPaymentMethods"))}async function Gn(t,e){const r=await Kn(t,e),n=r.external.environment_key,i=r.payment_method_intent_id,s=r.external_customer_id.ecommerce,o=r.external.resource_url,l=r.external.integrity_hash,f=r.payment_method?.processor_payment_method_token;await zn(o,l);let _=!1,h=null,y=null,v=null;return{mount(d,m){if(typeof window>"u"||!window.Spreedly)throw new Error("Payment script failed to load");window.Spreedly.init(n,{numberEl:d.numberElementId,cvvEl:d.cvvElementId}),window.Spreedly.on("ready",()=>{_=!0,d.styles&&(window.Spreedly.setStyle("number",d.styles),window.Spreedly.setStyle("cvv",d.styles)),d.numberLabel&&window.Spreedly.setLabel("number",d.numberLabel),d.cvvLabel&&window.Spreedly.setLabel("cvv",d.cvvLabel),d.numberPlaceholder&&window.Spreedly.setPlaceholder("number",d.numberPlaceholder),d.cvvPlaceholder&&window.Spreedly.setPlaceholder("cvv",d.cvvPlaceholder),d.numberFormat==="plainFormat"?(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType),window.Spreedly.setNumberFormat("plainFormat")):d.numberFormat==="maskedFormat"?(window.Spreedly.setFieldType("cvv","text"),window.Spreedly.setFieldType("number","text"),window.Spreedly.setNumberFormat("maskedFormat")):d.numberFormat==="prettyFormat"?(d.numberFieldType==="text"||d.numberFieldType==="tel"?window.Spreedly.setFieldType("number",d.numberFieldType):window.Spreedly.setFieldType("number","tel"),d.cvvFieldType==="text"||d.cvvFieldType==="tel"?window.Spreedly.setFieldType("cvv",d.cvvFieldType):window.Spreedly.setFieldType("cvv","tel"),window.Spreedly.setNumberFormat("prettyFormat")):(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType)),m?.onReady?.()}),window.Spreedly.on("fieldEvent",(g,I,k,D)=>{m?.onFieldEvent?.(g,I,k,D)}),window.Spreedly.on("errors",g=>{m?.onErrors?.(g)}),window.Spreedly.on("paymentMethod",(g,I)=>{h=g,m?.onPaymentMethod?.(g,I),y&&(h=null,y(g),y=null)})},tokenize(d){if(!_||!window.Spreedly)throw new Error("Payment form is not initialized");let m=String(d.year);m.length===2&&(m=`20${m}`);const g=String(d.month).padStart(2,"0");"full_name"in d?window.Spreedly.tokenizeCreditCard({full_name:d.full_name,month:g,year:m}):window.Spreedly.tokenizeCreditCard({first_name:d.first_name,last_name:d.last_name,month:g,year:m})},async submit(d){if(!_)throw new Error("Payment form is not initialized");if(h){const m=h;return h=null,Qe(t,m,d,{external_payment_method_id:f,payment_method_intent_id:i,external_customer_id:s})}return new Promise((m,g)=>{v=d,y=async I=>{try{const k=await Qe(t,I,v,{external_payment_method_id:f,payment_method_intent_id:i,external_customer_id:s});m(k)}catch(k){g(k)}finally{v=null}},this.tokenize(d.card_details)})},reset(){window.Spreedly&&window.Spreedly.reload(),h=null,y=null,v=null},unmount(){window.Spreedly&&window.Spreedly.removeHandlers(),_=!1,h=null,y=null,v=null},addEventHandlers(d){d.onReady&&window.Spreedly.on("ready",d.onReady),d.onFieldEvent&&window.Spreedly.on("fieldEvent",d.onFieldEvent),d.onErrors&&window.Spreedly.on("errors",d.onErrors),d.onPaymentMethod&&window.Spreedly.on("paymentMethod",d.onPaymentMethod)},removeHandlers(){window.Spreedly&&window.Spreedly.removeHandlers()},setFieldType(d,m){window.Spreedly.setFieldType(d,m)},setLabel(d,m){window.Spreedly.setLabel(d,m)},setNumberFormat(d){window.Spreedly.setNumberFormat(d)},setPlaceholder(d,m){window.Spreedly.setPlaceholder(d,m)},setStyle(d,m){window.Spreedly.setStyle(d,m)}}}async function Kn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");return await c("post","/payment_method_intents",{data:{customer_id:r,payment_method_id:e}},a(t,"createFrictionlessPaymentIntentV1"))}async function Qe(t,e,{billing_address:r,default_payment_method:n,address_ids:i,apply_to_all_subscription_addresses:s},{external_payment_method_id:o,payment_method_intent_id:l,external_customer_id:f}){return await Je(a(t,"submitFrictionlessPaymentMethodV1"),{default:n??!1,payment_type:"CREDIT_CARD",processor_customer_token:f.toString(),processor_name:"frictionless",processor_payment_method_token:e,billing_address:r,payment_method_intent_id:l,address_ids:i,external_payment_method_id:o,apply_to_all_subscription_addresses:s})}var Yn=Object.freeze({__proto__:null,createPaymentMethod:Je,getPaymentMethod:Xn,initFrictionlessPaymentV1:Gn,listPaymentMethods:Hn,updatePaymentMethod:Wn});async function Jn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{plan:r}=await c("get","/plans",{id:e},a(t,"getPlan"));return r}function Qn(t,e){return c("get","/plans",{query:e},a(t,"listPlans"))}var Zn=Object.freeze({__proto__:null,getPlan:Jn,listPlans:Qn});async function ei(t,e){return await c("get","/shop/shipping_countries",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"getShippingCountries"))}async function ti(t){return await c("get","/shop/settings",{headers:{"X-Recharge-Version":"2021-01"}},a(t,"getStoreSettings"))}var ri=Object.freeze({__proto__:null,getShippingCountries:ei,getStoreSettings:ti});function ni(t,e){return{...le(e,["address_id","external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","status"]),customer_id:parseInt(t,10),shopify_variant_id:e.external_variant_id.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:{},...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:{},status:e.status?e.status.toUpperCase():void 0}}function ii(t,e){return{...le(e,["external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","use_external_variant_defaults"]),shopify_variant_id:e.external_variant_id?.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:void 0,...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:void 0,force_update:t}}function Ze(t){const{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:l,charge_interval_frequency:f,created_at:_,expire_after_specific_number_of_charges:h,shopify_product_id:y,shopify_variant_id:v,has_queued_charges:d,is_prepaid:m,is_skippable:g,is_swappable:I,max_retries_reached:k,next_charge_scheduled_at:D,order_day_of_month:q,order_day_of_week:O,order_interval_frequency:Ii,order_interval_unit:qi,presentment_currency:Ei,price:Ci,product_title:ki,properties:xi,quantity:Pi,sku:Ai,sku_override:Di,status:Oi,updated_at:Ti,variant_title:Fi}=t;return{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:l,charge_interval_frequency:parseInt(f,10),created_at:_,expire_after_specific_number_of_charges:h,external_product_id:{ecommerce:`${y}`},external_variant_id:{ecommerce:`${v}`},has_queued_charges:Ne(d),is_prepaid:m,is_skippable:g,is_swappable:I,max_retries_reached:Ne(k),next_charge_scheduled_at:D,order_day_of_month:q,order_day_of_week:O,order_interval_frequency:parseInt(Ii,10),order_interval_unit:qi,presentment_currency:Ei,price:`${Ci}`,product_title:ki??"",properties:xi,quantity:Pi,sku:Ai,sku_override:Di,status:Oi.toLowerCase(),updated_at:Ti,variant_title:Fi}}async function si(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("get","/subscriptions",{id:e,query:{include:r?.include}},a(t,"getSubscription"));return n}function oi(t,e){return c("get","/subscriptions",{query:e},a(t,"listSubscriptions"))}function ai(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");return c("get",`/subscriptions/${p(e)}/addons`,{query:r},a(t,"listSubscriptionAddons"))}async function ci(t,e,r){const{subscription:n}=await c("post","/subscriptions",{data:e,query:r},a(t,"createSubscription"));return n}async function di(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("put","/subscriptions",{id:e,data:r,query:n},a(t,"updateSubscription"));return i}async function ui(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/set_next_charge_date`,{data:{date:r},query:n},a(t,"updateSubscriptionChargeDate"));return i}async function li(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/change_address`,{data:{address_id:r}},a(t,"updateSubscriptionAddress"));return n}async function pi(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/cancel`,{data:r,query:n},a(t,"cancelSubscription"));return i}async function _i(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/activate`,{query:r},a(t,"activateSubscription"));return n}async function hi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/subscriptions/${p(e)}/charges/skip`,{data:{date:r,subscription_id:`${e}`}},a(t,"skipSubscriptionCharge"));return n}async function mi(t,e,r={}){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/pricing_preview`,{data:r},a(t,"getSubscriptionPricingPreview"));return n}async function fi(t,e,r){if(e===void 0||e.length===0)throw new Error("Subscription IDs are required");const{onetimes:n}=await c("post","/purchase_items/skip_gift",{data:{purchase_item_ids:e.map(Number),recipient_address:r}},a(t,"skipGiftSubscriptionCharge"));return n}async function gi(t,e,r){const n=e.length;if(n<1||n>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:i}=t;if(!i)throw new Error("No customerId in session.");const s=e[0].address_id;if(!e.every(_=>_.address_id===s))throw new Error("All subscriptions must have the same address_id.");const o=e.map(_=>ni(i,_));let l;r?.allow_onetimes!==void 0&&(l={allow_onetimes:r.allow_onetimes});const{subscriptions:f}=await c("post",`/addresses/${p(s)}/subscriptions-bulk`,{data:{subscriptions:o,commit_update:!!r?.commit},headers:{"X-Recharge-Version":"2021-01"},query:l},a(t,"createSubscriptions"));return f.map(Ze)}async function wi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");const o=!!n?.force_update,l=r.map(h=>ii(o,h));let f;n?.allow_onetimes!==void 0&&(f={allow_onetimes:n.allow_onetimes});const{subscriptions:_}=await c("put",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:l,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:f},a(t,"updateSubscriptions"));return _.map(Ze)}async function yi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");let o;n?.allow_onetimes!==void 0&&(o={allow_onetimes:n.allow_onetimes}),await c("delete",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:r,send_email:!!n?.send_email,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:o},a(t,"deleteSubscriptions"))}var bi=Object.freeze({__proto__:null,activateSubscription:_i,cancelSubscription:pi,createSubscription:ci,createSubscriptions:gi,deleteSubscriptions:yi,getSubscription:si,getSubscriptionPricingPreview:mi,listSubscriptionAddons:ai,listSubscriptions:oi,skipGiftSubscriptionCharge:fi,skipSubscriptionCharge:hi,updateSubscription:di,updateSubscriptionAddress:li,updateSubscriptionChargeDate:ui,updateSubscriptions:wi});const vi={get(t,e){return S("get",t,e)},post(t,e){return S("post",t,e)},put(t,e){return S("put",t,e)},delete(t,e){return S("delete",t,e)}};function Si(t){if(t)return t;if(window?.Shopify?.shop)return window.Shopify.shop;let e=window?.domain;if(!e){const r=location?.href.match(/(?:http[s]*:\/\/)*(.*?)\.(?=admin\.rechargeapps\.com)/i)?.[1].replace(/-sp$/,"");r&&(e=`${r}.myshopify.com`)}if(e)return e;throw new Error("No storeIdentifier was passed into init.")}function $i(t={}){const e=t,{storefrontAccessToken:r}=t;if(r&&!r.startsWith("strfnt"))throw new Error("Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.");tt({storeIdentifier:Si(t.storeIdentifier),loginRetryFn:t.loginRetryFn,__unstable_twoFactorRetryFn:t.__unstable_twoFactorRetryFn,storefrontAccessToken:r,appName:t.appName,appVersion:t.appVersion,environment:e.environment?e.environment:"prod",environmentUri:e.environmentUri,customerHash:e.customerHash}),Ve()}const et={init:$i,api:vi,address:mt,auth:qt,bundle:gr,bundleData:Er,charge:Vr,cdn:Tr,collection:Gr,credit:an,customer:rn,customerSurveys:ln,flow:_n,gift:fn,tieredDiscount:bn,membership:En,membershipProgram:xn,metafield:On,onetime:Mn,order:Vn,paymentMethod:Yn,plan:Zn,product:zr,store:ri,subscription:bi};try{et.init()}catch{}return et});
1
+ // recharge-client-2.6.1.min.js | MIT License | © Recharge Inc.
2
+ (function(N,T){typeof exports=="object"&&typeof module<"u"?module.exports=T():typeof define=="function"&&define.amd?define(T):(N=typeof globalThis<"u"?globalThis:N||self,N.recharge=T())})(this,function(){"use strict";const N="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function T(t=21){let e="";for(let r=0;r<t;r++)e+=N[Math.random()*64|0];return e}let me={storeIdentifier:"",environment:"prod"};function rt(t){me=t}function b(){return me}const nt=(t,e="")=>{switch(t){case"prod":return"https://api.rechargeapps.com";case"stage":return"https://api.stage.rechargeapps.com";case"preprod":case"prestage":return`${e}/api`}},it=(t,e="")=>{switch(t){case"prod":return"https://admin.rechargeapps.com";case"stage":return"https://admin.stage.rechargeapps.com";case"preprod":case"prestage":return e}},st=t=>{switch(t){case"prod":case"preprod":return"https://static.rechargecdn.com";case"stage":case"prestage":return"https://static.stage.rechargecdn.com"}},fe="/tools/recurring";class F{constructor(e,r){this.name="RechargeRequestError",this.message=e,this.status=r}}function p(t){return encodeURIComponent(`${t}`.trim())}function ot(t){const e=r=>encodeURIComponent(r===null?"":String(r));return Object.entries(t).filter(([,r])=>r!==void 0&&!(Array.isArray(r)&&r.length===0)).map(([r,n])=>`${r}=${Array.isArray(n)?n.map(e).join(","):e(n)}`).join("&")}const at=new Set(["shop_url"]);function a(t,e){return{...t,internalFnCall:t.internalFnCall??e,internalRequestId:t.internalRequestId??T()}}async function V(t,e,r={}){const n=b();return S(t,`${st(n.environment)}/store/${n.storeIdentifier}${e}`,r)}async function c(t,e,{id:r,query:n,data:i,headers:s}={},o){const{environment:l,environmentUri:f,storeIdentifier:_,loginRetryFn:h,__unstable_twoFactorRetryFn:y,appName:v,appVersion:d}=b();if(!_)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const m=o.apiToken;if(!m)throw new Error("No API token defined on session.");const g=nt(l,f),I={"X-Recharge-Access-Token":m,"X-Recharge-Version":"2021-11","X-Recharge-Sdk-Fn":o.internalFnCall,...v?{"X-Recharge-Sdk-App-Name":v}:{},...d?{"X-Recharge-Sdk-App-Version":d}:{},"X-Recharge-Sdk-Version":"2.6.1","X-Request-Id":o.internalRequestId,...o.tmp_fn_identifier?{"X-Recharge-Sdk-Fn-Identifier":o.tmp_fn_identifier}:{},...s||{}},k=n,D={...k?Object.fromEntries(Object.entries(k).filter(([q])=>!at.has(q))):void 0,shop_url:_};try{return await S(t,`${g}${e}`,{id:r,query:D,data:i,headers:I})}catch(q){if(h&&q instanceof F&&q.status===401)return h().then(O=>{if(O)return S(t,`${g}${e}`,{id:r,query:D,data:i,headers:{...I,"X-Recharge-Access-Token":O.apiToken}});throw q});if(y&&q instanceof F&&q.status===423)return y().then(O=>{if(O)return S(t,`${g}${e}`,{id:r,query:D,data:i,headers:{...I,"X-Recharge-Access-Token":O.apiToken}});throw q});throw q}}async function A(t,e,r={}){return S(t,`${fe}${e}`,r)}async function S(t,e,{id:r,query:n,data:i,headers:s}={}){let o=e.trim();if(r&&(o=[o,p(r)].join("/")),n){let y;[o,y]=o.split("?");const v=[y,ot(n)].join("&").replace(/^&/,"");o=`${o}${v?`?${v}`:""}`}let l;i&&t!=="get"&&(l=JSON.stringify(i));const f={Accept:"application/json","Content-Type":"application/json","X-Recharge-App":"storefront-client",...s||{}},_=await fetch(o,{method:t,headers:f,body:l});let h;try{h=await _.json()}catch{}if(!_.ok)throw _.status===502||_.status===504?new F("A gateway error occurred while making the request",_.status):h&&h.error?new F(h.error,_.status):h&&h.errors?new F(JSON.stringify(h.errors),_.status):new F("A connection error occurred while making the request");return h}function ct(t,e){return c("get","/addresses",{query:e},a(t,"listAddresses"))}async function dt(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{address:n}=await c("get","/addresses",{id:e,query:{include:r?.include}},a(t,"getAddress"));return n}async function ut(t,e){const{address:r}=await c("post","/addresses",{data:{...e,customer_id:t.customerId?Number(t.customerId):void 0}},a(t,"createAddress"));return r}async function J(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{address:i}=await c("put","/addresses",{id:e,data:r,query:n},a(t,"updateAddress"));return i}async function lt(t,e,r,n){return J(a(t,"applyDiscountToAddress"),e,{discounts:[{code:r}]},n)}async function pt(t,e,r){if(e===void 0||e==="")throw new Error("Id is required");return J(a(t,"removeDiscountsFromAddress"),e,{discounts:[]},r)}function _t(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/addresses",{id:e},a(t,"deleteAddress"))}async function ht(t,e){const{address:r}=await c("post","/addresses/merge",{data:e},a(t,"mergeAddresses"));return r}async function mt(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/addresses/${p(e)}/charges/skip`,{data:r},a(t,"skipFutureCharge"));return n}var ft=Object.freeze({__proto__:null,applyDiscountToAddress:lt,createAddress:ut,deleteAddress:_t,getAddress:dt,listAddresses:ct,mergeAddresses:ht,removeDiscountsFromAddress:pt,skipFutureCharge:mt,updateAddress:J});async function gt(){const{storefrontAccessToken:t}=b(),e={};t&&(e["X-Recharge-Storefront-Access-Token"]=t);const r=await A("get","/access",{headers:e});return{apiToken:r.api_token,customerId:r.customer_id,message:r.message}}async function wt(t,e){return ge(t,e)}async function ge(t,e){if(!t)throw new Error("Shopify storefront token is required");const{storeIdentifier:r}=b();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:n,customer_id:i,message:s}=await B("post","/shopify_storefront_access",{data:{customer_token:e,storefront_token:t,shop_url:r}});return n?{apiToken:n,customerId:i,message:s}:null}async function yt(t){const{storeIdentifier:e}=b();if(!e)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{api_token:r,customer_id:n,message:i}=await B("post","/shopify_customer_account_api_access",{data:{customer_token:t,shop_url:e}});return r?{apiToken:r,customerId:n,message:i}:null}async function bt(t,e={}){if(!t)throw new Error("Email is required.");const{storeIdentifier:r}=b();if(!r)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const{send_email:n,send_sms:i}=e,s=await B("post","/attempt_login",{data:{email:t,shop:r,...n!==void 0?{send_email:n}:{},...i!==void 0?{send_sms:i}:{}}});if(s.errors)throw new Error(s.errors);return s.session_token}async function vt(t,e={}){if(!t)throw new Error("Email is required.");const{storefrontAccessToken:r}=b(),n={};r&&(n["X-Recharge-Storefront-Access-Token"]=r);const{send_email:i,send_sms:s}=e,o=await A("post","/attempt_login",{data:{email:t,...i!==void 0?{send_email:i}:{},...s!==void 0?{send_sms:s}:{}},headers:n});if(o.errors)throw new Error(o.errors);return o.session_token}async function St(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storeIdentifier:n}=b();if(!n)throw new Error("InitRecharge has not been called and/or no store identifier has been defined.");const i=await B("post","/validate_login",{data:{code:r,email:t,session_token:e,shop:n}});if(i.errors)throw new Error(i.errors);return{apiToken:i.api_token,customerId:i.customer_id}}async function $t(t,e,r){if(!t)throw new Error("Email is required.");if(!e)throw new Error("Session token is required.");if(!r)throw new Error("Code is required.");const{storefrontAccessToken:n}=b(),i={};n&&(i["X-Recharge-Storefront-Access-Token"]=n);const s=await A("post","/validate_login",{data:{code:r,email:t,session_token:e},headers:i});if(s.errors)throw new Error(s.errors);return{apiToken:s.api_token,customerId:s.customer_id}}function It(){const{customerHash:t}=b(),{pathname:e,search:r}=window.location,n=new URLSearchParams(r).get("token"),i=e.split("/").filter(Boolean),s=i.findIndex(l=>l==="portal"),o=s!==-1?i[s+1]:t;if(!n||!o)throw new Error("Not in context of Recharge Customer Portal or URL did not contain correct params");return{customerHash:o,token:n}}async function qt(){const{customerHash:t,token:e}=It(),{storeIdentifier:r}=b(),n=await B("post",`/customers/${p(t)}/access`,{data:{token:e,shop:r}});return{apiToken:n.api_token,customerId:n.customer_id}}async function B(t,e,{id:r,query:n,data:i,headers:s}={}){const{environment:o,environmentUri:l,storefrontAccessToken:f,appName:_,appVersion:h}=b(),y=it(o,l),v={...f?{"X-Recharge-Storefront-Access-Token":f}:{},..._?{"X-Recharge-Sdk-App-Name":_}:{},...h?{"X-Recharge-Sdk-App-Version":h}:{},"X-Recharge-Sdk-Version":"2.6.1",...s||{}};return S(t,`${y}${e}`,{id:r,query:n,data:i,headers:v})}var Et=Object.freeze({__proto__:null,loginCustomerPortal:qt,loginShopifyApi:wt,loginShopifyAppProxy:gt,loginWithShopifyCustomerAccount:yt,loginWithShopifyStorefront:ge,sendPasswordlessCode:bt,sendPasswordlessCodeAppProxy:vt,validatePasswordlessCode:St,validatePasswordlessCodeAppProxy:$t});const we="XdrError";class u extends Error{constructor(e){super(e),this.name=we}static[Symbol.hasInstance](e){return e instanceof Error&&e.name===we}}function ye(t){return(4-t%4)%4}function be(t){if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ve(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new u(`${e}: expected uint32 length`)}function Q(t,e,r,n){if(typeof t!="number"||!Number.isInteger(t)||t<e||t>r)throw new u(`${n}: expected integer in range ${e}..${r}`)}function Ct(t,e,r,n){if(typeof t!="bigint"||t<e||t>r)throw new u(`${n}: expected bigint in range ${e}..${r}`)}function kt(t,e){if(!(t instanceof Uint8Array))throw new u(`${e}: expected Uint8Array`);try{Uint8Array.prototype.at.call(t,0)}catch{throw new u(`${e}: Uint8Array is detached or out of bounds`)}}function xt(t,e){if(!Array.isArray(t))throw new u(`${e}: expected array`)}const Se=1500;class Pt{#e=0;#i=0;#t;#n;#s;bytes;constructor(e,r=Se){if(r<0||!Number.isInteger(r))throw new u(`invalid maxDepth ${r}`);if(this.#t=r,!ArrayBuffer.isView(e)||e.BYTES_PER_ELEMENT!==1)throw new TypeError("Reader expects a Uint8Array");this.bytes=Object.getPrototypeOf(e)===Uint8Array.prototype?e:e.byteLength===0?new Uint8Array(0):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this.#n=this.bytes.buffer?.detached?new DataView(new ArrayBuffer(0)):new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.#s=this.#n.byteLength}#r(e,r){if(this.remaining<e)throw new u(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.#e;return this.#e+=e,n}get offset(){return this.#e}get remaining(){return this.#s-this.#e}enter(e){if(this.#i+=1,this.#i>this.#t)throw this.#i-=1,new u(`${e}: max recursion depth ${this.#t} exceeded`)}exit(){this.#i-=1}done(e){if(this.remaining!==0)throw new u(`${e}: trailing ${this.remaining} byte(s) after XDR value`)}readBytes(e,r){if(e<0||!Number.isInteger(e))throw new u(`${r}: invalid byte length ${e}`);if(this.remaining<e)throw new u(`${r}: incomplete XDR data at offset ${this.#e}, expected ${e} byte(s)`);const n=this.bytes.slice(this.#e,this.#e+e);if(n.length!==e)throw new u(`${r}: input shrank during decode`);return this.#e+=e,n}skipPadding(e,r){if(e<0||!Number.isInteger(e))throw new u(`${r}: invalid byte length ${e}`);const n=ye(e);if(n===0)return;const i=this.#r(n,r);for(let s=0;s<n;s++)if(this.bytes[i+s]!==0)throw this.#e=i,new u(`${r}: non-zero XDR padding`)}readInt32(e){return this.#n.getInt32(this.#r(4,e),!1)}readUint32(e){return this.#n.getUint32(this.#r(4,e),!1)}readBigInt64(e){return this.#n.getBigInt64(this.#r(8,e),!1)}readBigUint64(e){return this.#n.getBigUint64(this.#r(8,e),!1)}readFloat32(e){return this.#n.getFloat32(this.#r(4,e),!1)}readFloat64(e){return this.#n.getFloat64(this.#r(8,e),!1)}}const At=8192;class $e{#e=new Uint8Array(At);#i=new DataView(this.#e.buffer);#t=0;#n=0;#s;constructor(e=Se){if(e<0||!Number.isInteger(e))throw new u(`invalid maxDepth ${e}`);this.#s=e}get offset(){return this.#t}enter(e){if(this.#n+=1,this.#n>this.#s)throw this.#n-=1,new u(`${e}: max recursion depth ${this.#s} exceeded`)}exit(){this.#n-=1}writeBytes(e){this.#o(e.length),this.#e.set(e,this.#t),this.#t+=e.length}writePadding(e){const r=ye(e);r>0&&(this.#o(r),this.#e.fill(0,this.#t,this.#t+r),this.#t+=r)}writeInt32(e){const r=this.#r(4);this.#i.setInt32(r,e,!1),this.#t+=4}writeUint32(e){const r=this.#r(4);this.#i.setUint32(r,e,!1),this.#t+=4}writeBigInt64(e){const r=this.#r(8);this.#i.setBigInt64(r,e,!1),this.#t+=8}writeBigUint64(e){const r=this.#r(8);this.#i.setBigUint64(r,e,!1),this.#t+=8}writeFloat32(e){const r=this.#r(4);this.#i.setFloat32(r,e,!1),this.#t+=4}writeFloat64(e){const r=this.#r(8);this.#i.setFloat64(r,e,!1),this.#t+=8}#r(e){return this.#o(e),this.#t}toUint8Array(){return this.#e.slice(0,this.#t)}#o(e){const r=this.#t+e;if(r<=this.#e.length)return;let n=this.#e.length;for(;n<r;)n*=2;const i=new Uint8Array(n);i.set(this.#e),this.#e=i,this.#i=new DataView(i.buffer)}}const Dt=4294967295;class x{name;constructor(e=void 0){this.name=e}encode(e,r){const n=new $e(r?.maxDepth);return this._write(e,n,this.name??this.kind),n.toUint8Array()}decode(e,r){const n=new Pt(e,r?.maxDepth),i=this._read(n,this.name??this.kind);return n.done(this.name??this.kind),i}validateXdr(e,r){try{return this.decode(e,r),!0}catch(n){if(n instanceof u)return!1;throw n}}validate(e){try{const r=new $e;return this._write(e,r,this.name??this.kind),!0}catch(r){if(r instanceof u)return!1;throw r}}}class Ot extends x{kind="array";element;maxLength;constructor(e,r){super(),ve(r,"array maxLength"),this.element=e,this.maxLength=r}_read(e,r){e.enter(r);try{const n=e.readUint32(r);if(n>this.maxLength)throw new u(`${r}: array length ${n} exceeds maximum ${this.maxLength}`);if(n>e.remaining)throw new u(`${r}: array length ${n} exceeds remaining ${e.remaining} byte(s)`);return Ft(e,n,this.element,r)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(xt(e,n),e.length>this.maxLength)throw new u(`${n}: array length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),Rt(e,r,this.element,n)}finally{r.exit()}}}function Tt(t,e){return new Ot(t,e)}function Ft(t,e,r,n){const i=[];for(let s=0;s<e;s+=1){const o=t.offset,l=r._read(t,`${n}[${s}]`);if(t.offset===o)throw new u(`${n}[${s}]: element type '${r.name??r.kind}' consumed no input; an array element must encode to at least one byte`);i.push(l)}return i}function Rt(t,e,r,n){let i=0;for(const s of t){const o=e.offset;if(r._write(s,e,`${n}[${i}]`),e.offset===o)throw new u(`${n}[${i}]: element type '${r.name??r.kind}' encoded to zero bytes; an array element must encode to at least one byte`);i+=1}}const Nt=new Set(["__proto__","name","kind","encode","decode","validate","_read","_write","nameByValue"]);class Bt extends x{kind="enum";nameByValue;#e=new Set;constructor(e,r){super(e);const n=new Map;for(const[i,s]of Object.entries(r)){if(Q(s,-2147483648,2147483647,`${e}.${i}`),this.#e.has(s))throw new u(`${e}: duplicate enum value ${s}`);this.#e.add(s),n.set(s,i)}this.nameByValue=n}_read(e,r){const n=e.readInt32(r);if(!this.#e.has(n))throw new u(`${r}: unknown enum value ${n}`);return n}_write(e,r,n){if(typeof e!="number"||!this.#e.has(e))throw new u(`${n}: unknown enum value ${String(e)}`);r.writeInt32(e)}}function Mt(t,e){for(const n of Object.getOwnPropertyNames(e))if(Nt.has(n))throw new u(`${t}: enum member name ${n} collides with reserved property`);const r=new Bt(t,e);return Object.assign(r,e)}class jt extends x{kind="int32";_read(e,r){return e.readInt32(r)}_write(e,r,n){Q(e,-2147483648,2147483647,n),r.writeInt32(e)}}function Ie(){return new jt}class Ut extends x{constructor(e){super(),this.maxLength=e,ve(e,"string maxLength")}maxLength;kind="string";_read(e,r){const n=e.readUint32(r);if(n>this.maxLength)throw new u(`${r}: string byte length ${n} exceeds maximum ${this.maxLength}`);const i=e.readBytes(n,r);return e.skipPadding(n,r),i}_write(e,r,n){if(kt(e,n),e.length>this.maxLength)throw new u(`${n}: string byte length ${e.length} exceeds maximum ${this.maxLength}`);r.writeUint32(e.length),r.writeBytes(e),r.writePadding(e.length)}}function Lt(t){return new Ut(t)}class Vt extends x{kind="struct";entries;constructor(e,r){if(super(e),Object.getOwnPropertyNames(r).includes("__proto__"))throw new u(`${e}: struct field name '__proto__' is not allowed`);this.entries=Object.entries(r)}_read(e,r){e.enter(r);try{const n={};for(const[i,s]of this.entries)n[i]=s._read(e,`${r}.${i}`);return n}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!be(e))throw new u(`${n}: expected plain object`);const i=e;for(const[s,o]of this.entries){if(!Object.prototype.hasOwnProperty.call(i,s))throw new u(`${n}.${s}: missing struct field`);o._write(i[s],r,`${n}.${s}`)}}finally{r.exit()}}}function qe(t,e){return new Vt(t,e)}class zt extends x{kind="uint32";_read(e,r){return e.readUint32(r)}_write(e,r,n){Q(e,0,4294967295,n),r.writeUint32(e)}}function Ee(){return new zt}class Xt extends x{kind="uint64";_read(e,r){return e.readBigUint64(r)}_write(e,r,n){Ct(e,0n,(1n<<64n)-1n,n),r.writeBigUint64(e)}}function z(){return new Xt}const Z="default";class Wt extends x{kind="union";switchOn;cases;defaultArm;switchKey;#e=new Map;constructor(e,r,n,i,s){if(super(e),s==="__proto__")throw new u(`${e}: switchKey '__proto__' is not allowed`);if(this.switchOn=r,this.cases=n,this.defaultArm=i,this.switchKey=s,n.length===0&&i===void 0)throw new u(`${e}: union needs at least one case or a default arm`);const o=new Set;for(const l of n){if(!r.validate(l.discriminant))throw new u(`${e}.${l.name}: case discriminator ${String(l.discriminant)} is not a valid ${r.name??r.kind} value`);if(o.has(l.name))throw new u(`${e}: duplicate union case name ${l.name}`);if(o.add(l.name),this.#e.has(l.discriminant))throw new u(`${e}: duplicate union discriminator ${String(l.discriminant)}`);Ce(e,l.name,l.arm,s),this.#e.set(l.discriminant,l)}i!==void 0&&Ce(e,Z,i,s)}_read(e,r){e.enter(r);try{const n=this.switchOn._read(e,`${r}.${this.switchKey}`),i=this.#e.get(n),s=i?.arm??this.defaultArm;if(s===void 0)throw new u(`${r}: no case for union discriminator ${String(n)}`);return Gt(n,s,this.switchKey,e,`${r}.${i?.name??Z}`)}finally{e.exit()}}_write(e,r,n){r.enter(n);try{if(!be(e)||!Object.prototype.hasOwnProperty.call(e,this.switchKey))throw new u(`${n}: expected union object with ${this.switchKey} discriminator`);const i=e,s=i[this.switchKey],o=this.#e.get(s),l=o?.arm??this.defaultArm;if(l===void 0)throw new u(`${n}: no case for union discriminator ${String(s)}`);this.switchOn._write(s,r,`${n}.${this.switchKey}`),Kt(i,l,r,`${n}.${o?.name??Z}`)}finally{r.exit()}}}function Ht(t,e){return{kind:"field",name:t,schema:e}}function ee(t,e,r){return{name:t,discriminant:e,arm:r}}function te(t,e){const r=e.switchKey??"type";return new Wt(t,e.switchOn,e.cases,e.defaultArm,r)}function Gt(t,e,r,n,i){const s={};return s[r]=t,X(e)?(s[e.name]=e.schema._read(n,`${i}.${e.name}`),s):(e._read(n,i),s)}function Kt(t,e,r,n){if(X(e)){if(!Object.prototype.hasOwnProperty.call(t,e.name))throw new u(`${n}.${e.name}: missing union arm payload`);e.schema._write(t[e.name],r,`${n}.${e.name}`);return}e._write(void 0,r,n)}function Ce(t,e,r,n){if(X(r)&&r.name===n)throw new u(`${t}.${e}: union arm payload field must not be named ${n}`);if(X(r)&&r.name==="__proto__")throw new u(`${t}.${e}: union arm payload field name '__proto__' is not allowed`)}function X(t){return"schema"in t}class Yt extends x{kind="void";_read(){}_write(e,r,n){if(e!==void 0)throw new u(`${n}: expected void`)}}function ke(){return new Yt}var re=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},w=(t,e,r)=>(re(t,e,"read from private field"),r?r.call(t):e.get(t)),P=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},ne=(t,e,r,n)=>(re(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),$=(t,e,r)=>(re(t,e,"access private method"),r),E,C,M,ie,xe,se,Pe,W,oe,R,j,U,H;const Jt=new TextEncoder,Ae={v:0};function Qt(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}const ae=Mt("EnvelopeType",{envelopeTypeBundle:0}),Zt=te("BundleItemExt",{switchOn:Ie(),switchKey:"v",cases:[ee("v0",0,ke())]}),er=qe("BundleItem",{collectionId:z(),productId:z(),variantId:z(),sku:Lt(Dt),quantity:Ee(),ext:Zt}),tr=te("BundleExt",{switchOn:Ie(),switchKey:"v",cases:[ee("v0",0,ke())]}),rr=qe("Bundle",{variantId:z(),items:Tt(er,500),version:Ee(),ext:tr}),nr=te("BundleEnvelope",{switchOn:ae,switchKey:"type",cases:[ee("envelopeTypeBundle",ae.envelopeTypeBundle,Ht("v1",rr))]});function ir(t){const e={type:ae.envelopeTypeBundle,v1:{variantId:BigInt(t.variantId.toString()),items:t.items.map(r=>({collectionId:BigInt(r.collectionId.toString()),productId:BigInt(r.productId.toString()),variantId:BigInt(r.variantId.toString()),sku:Jt.encode(r.sku||""),quantity:r.quantity,ext:Ae})),version:t.version||Math.floor(Date.now()/1e3),ext:Ae}};return Qt(nr.encode(e))}class sr{constructor(e,r){P(this,ie),P(this,se),P(this,W),P(this,R),P(this,U),P(this,E,void 0),P(this,C,void 0),P(this,M,void 0),ne(this,E,$(this,ie,xe).call(this,r)),ne(this,M,$(this,se,Pe).call(this,r)),ne(this,C,e)}isInitialDataValid(){if(!w(this,M))throw"Bundle data does not exist for the given product.";if(!w(this,E))throw"Bundle settings do not exist for the given product.";if(!Array.isArray(w(this,C))||!w(this,C).length)throw"No bundle selection items provided.";return!0}isValidVariant(e){if(!w(this,E)?.variantsSettings[e])throw`The ${e} bundle variant is invalid.`;return!0}isSelectionInVariantRange(e){const r=w(this,C).reduce((i,s)=>i+s.quantity,0),n=w(this,E)?.variantsSettings[e].ranges||[];if(!$(this,W,oe).call(this,n,r))throw"The total number of products does not fall within the required variant range.";return!0}areItemsInMaxPerItemBound(){const e=w(this,E)?.bundleSettings.maxPerItem||0,r=w(this,C).filter(({quantity:n})=>n>e);if(e&&r.length)throw`The selected products (${$(this,R,j).call(this,r.map(({externalProductId:n})=>n)).join(", ")}) exceed the maximum limit of ${e} items per product.`;return!0}areSelectedCollectionsValid(e){const r=w(this,E)?.variantsSettings[e]?.optionSources,n=w(this,C).filter(({collectionId:i})=>!r||!$(this,U,H).call(this,r,i));if(n.length)throw`The collections (${$(this,R,j).call(this,n.map(({collectionId:i})=>i)).join(", ")}) are no longer valid for the bundle variant (${e}).`;return!0}areItemsQuantitiesValidForTheCollection(e){const r=w(this,C).reduce((s,o)=>(s[o.collectionId]=o.quantity+(s[o.collectionId]||0),s),Object.create(null)),n=w(this,E)?.variantsSettings[e],i=Object.values(n?.optionSources||{}).filter(s=>{const o=r[s.collectionId]||0;return!$(this,W,oe).call(this,[s],o)});if(!n||i.length)throw`The selection exceeds the limits for the collections (${$(this,R,j).call(this,i.map(({collectionId:s})=>s)).join(", ")}).`;return!0}areSelectedProductsValid(e){const r=w(this,E)?.variantsSettings[e]?.optionSources||{},n=Object.values(r).reduce((s,o)=>{const l=w(this,M)?.collections[o.collectionId];return l&&(s[o.collectionId]=l),s},Object.create(null));if(!Object.values(n).length)throw`No collections found for the bundle variant (${e}).`;const i=w(this,C).filter(({externalProductId:s,collectionId:o})=>$(this,U,H).call(this,n,o)?!$(this,U,H).call(this,n[o].products,s):!0);if(i.length)throw`The products (${$(this,R,j).call(this,i.map(({externalProductId:s})=>s)).join(", ")}) are no longer valid for the bundle product.`;return!0}isBundleSelectionValid(e){return this.isInitialDataValid(),this.isValidVariant(e),this.isSelectionInVariantRange(e),this.areItemsInMaxPerItemBound(),this.areSelectedCollectionsValid(e),this.areItemsQuantitiesValidForTheCollection(e),this.areSelectedProductsValid(e),!0}}E=new WeakMap,C=new WeakMap,M=new WeakMap,ie=new WeakSet,xe=function(t){try{const e=t.bundle_settings;return{bundleSettings:{maxPerItem:e.max_quantity_per_variant,isCustomizable:e.is_customizable},variantsSettings:e.variants.reduce((r,n)=>{if(!n.enabled)return r;let i=[{min:n.items_count,max:n.items_count}];return n.items_count||(i=n.ranges.map(({quantity_max:s,quantity_min:o})=>({min:o,max:s}))),r[n.external_variant_id]={externalVariantId:n.external_variant_id,optionSources:n.option_sources.reduce((s,o)=>(s[o.option_source_id]={min:o.quantity_min,max:o.quantity_max,collectionId:o.option_source_id},s),Object.create(null)),ranges:i},r},Object.create(null))}}catch{return null}},se=new WeakSet,Pe=function(t){try{const e=Object.values(t.collections).reduce((r,n)=>(r[n.id]={...n,products:n.products.reduce((i,s)=>(i[s.id]=s,i),Object.create(null))},r),Object.create(null));return{...t,collections:e}}catch{return null}},W=new WeakSet,oe=function(t,e){return!!t.filter(({min:r,max:n})=>{const i=r??e,s=n??e;return i<=e&&e<=s}).length},R=new WeakSet,j=function(t){return Array.from(new Set(t))},U=new WeakSet,H=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};const or="/bundling-storefront-manager";function De(t){return ir({variantId:t.externalVariantId,version:0,items:t.selections.map(e=>({collectionId:e.collectionId,productId:e.externalProductId,variantId:e.externalVariantId,quantity:e.quantity,sku:""}))})}async function ar(t){const e=b(),r=await ce(t);if(r!==!0)throw new Error(r);const n=De(t);try{const i=await A("post",`${or}/api/v1/bundles`,{data:{bundle:n},headers:{Origin:`https://${e.storeIdentifier}`}});if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}async function cr(t,e){const r=await ce(e);if(r!==!0)throw new Error(r);const n=De(e);try{const i=await c("post","/bundle_selections/bundle_id",{data:{bundle:n}},a(t,"getBundleSelectionId"));if(!i.id||i.code!==200)throw new Error(`1: failed generating rb_id: ${JSON.stringify(i)}`);return i.id}catch(i){throw new Error(`2: failed generating rb_id ${i}`)}}function dr(t,e){const r=Oe(t);if(r!==!0)throw new Error(`Dynamic Bundle is invalid. ${r}`);const n=`${T(9)}:${t.externalProductId}`;return t.selections.map(i=>{const s={id:i.externalVariantId,quantity:i.quantity,properties:{_rc_bundle:n,_rc_bundle_variant:t.externalVariantId,_rc_bundle_parent:e,_rc_bundle_collection_id:i.collectionId}};return i.sellingPlan?s.selling_plan=i.sellingPlan:i.shippingIntervalFrequency&&(s.properties.shipping_interval_frequency=i.shippingIntervalFrequency,s.properties.shipping_interval_unit_type=i.shippingIntervalUnitType,s.id=`${i.discountedVariantId}`),s})}async function ce(t){try{return t?t.selections.length===0?"No selections defined":!0:"Bundle is not defined"}catch(e){return`Error fetching bundle settings: ${e}`}}async function ur(t){try{const e=await A("get",`/bundle-data/${p(t.externalProductId)}`);return{valid:new sr(t.selections,e).isBundleSelectionValid(t.externalVariantId)}}catch(e){return{valid:!1,error:String(e)}}}const lr={day:["day","days","Days"],days:["day","days","Days"],Days:["day","days","Days"],week:["week","weeks","Weeks"],weeks:["week","weeks","Weeks"],Weeks:["week","weeks","Weeks"],month:["month","months","Months"],months:["month","months","Months"],Months:["month","months","Months"]};function Oe(t){if(!t)return"No bundle defined.";if(t.selections.length===0)return"No selections defined.";const{shippingIntervalFrequency:e,shippingIntervalUnitType:r}=t.selections.find(n=>n.shippingIntervalFrequency||n.shippingIntervalUnitType)||{};if(e||r){if(!e||!r)return"Shipping intervals do not match on selections.";{const n=lr[r];for(let i=0;i<t.selections.length;i++){const{shippingIntervalFrequency:s,shippingIntervalUnitType:o}=t.selections[i];if(s&&s!==e||o&&!n.includes(o))return"Shipping intervals do not match on selections."}}}return!0}async function pr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:r}=await c("get","/bundle_selections",{id:e},a(t,"getBundleSelection"));return r}function _r(t,e){return c("get","/bundle_selections",{query:e},a(t,"listBundleSelections"))}async function hr(t,e){const{bundle_selection:r}=await c("post","/bundle_selections",{data:e},a(t,"createBundleSelection"));return r}async function mr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{bundle_selection:n}=await c("put","/bundle_selections",{id:e,data:r},a(t,"updateBundleSelection"));return n}function fr(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/bundle_selections",{id:e},a(t,"deleteBundleSelection"))}async function gr(t,e,r,n){if(e===void 0||e==="")throw new Error("Purchase item ID is required");const{subscription:i}=await c("put","/bundles",{id:e,data:r,query:n},a(t,"updateBundle"));return i}var wr=Object.freeze({__proto__:null,createBundleSelection:hr,deleteBundleSelection:fr,getBundleId:ar,getBundleSelection:pr,getBundleSelectionId:cr,getDynamicBundleItems:dr,listBundleSelections:_r,updateBundle:gr,updateBundleSelection:mr,validateBundle:ce,validateBundleSelection:ur,validateDynamicBundle:Oe});const yr=t=>{const e=t.layout_settings.addons,r=t.layout_settings.crossSells,n=t.customization_window,i=t.layout_settings?.defaultVariantId??t.default_bundle_variant_id,s=t.layout_settings.defaultFrequency,o=t.layout_settings.addToCartCallback;return{default_variant_id:i?String(i):null,is_customizable:t.is_customizable,price_rule:String(t.price_rule).toUpperCase(),customization_window:n?{active_days:n,disabled_message:t.customization_window_disabled_message||""}:null,addons:e.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,cross_sells:r.collectionId?{collection_id:e.collectionId,collection_handle:e.collectionHandle}:null,default_selling_plan_id:s||null,collapsible_collections:t.layout_settings.collapsibleSections,max_quantity_per_variant:t.max_quantity_per_variant,show_product_variants:t.layout_settings.showVariants,product_details_modal_enabled:t.layout_settings.learnMoreModal,addToCartBehavior:{type:o.type==="none"?"cart_page":o.type,value:o.value}}},br=t=>t.tiered_discounts.length===0?null:{tiered_discounts:t.tiered_discounts},G=t=>({id:t.id,name:t.name,options:t.options.map(e=>({name:e.name,value:e.value})),recurring_deliveries:t.recurring_deliveries,price_adjustments:t.price_adjustments.map(({value:e,value_type:r})=>({value:e,value_type:r}))}),Te=t=>({name:t.name,options:t.options.map(e=>({name:e.name,values:e.values})),selling_plans:t.selling_plans.map(G)}),Fe=t=>({id:String(t.id),title:t.title,price:t.price,compare_at_price:t.compare_at_price,options:t.options,available_for_sale:t.available}),de=t=>t==null||typeof t=="string"?t:"src"in t?t.src:null,Re=t=>({id:String(t.id),title:t.title,description:t.description,available_for_sale:t.available,featured_image:de(t.featured_image),images:t.images,requires_selling_plan:t.requires_selling_plan,selling_plan_groups:t.selling_plan_groups.map(Te)}),Ne=t=>{const e=Sr(t.selling_plan_groups);return{...Re(t),handle:t.handle,tags:t.tags,price_range:{min:t.price_min,max:t.price_max},compare_at_price_range:{min:t.compare_at_price_min,max:t.compare_at_price_max},options:t.options,variants:t.variants.map(r=>({...Fe(r),selling_plan_allocations:r.selling_plan_allocations.map(n=>({price:n.price,compare_at_price:n.compare_at_price,selling_plan:G(e[`${n.selling_plan_group_id}-${n.selling_plan_id}`])})),option1:r.option1,option2:r.option2,option3:r.option3,sku:r.sku||"",requires_shipping:r.requires_shipping,taxable:r.taxable,featured_image:de(r.featured_image),public_title:r.public_title,requires_selling_plan:r.requires_selling_plan}))}},vr=({items_count:t,ranges:e})=>e.length>0?e.map(({quantity_max:r,quantity_min:n})=>({min:n,max:r})):[{min:t,max:t}],Sr=t=>t.reduce((e,r)=>(r.selling_plans.forEach(n=>{const i=`${r.id}-${n.id}`;e[i]=n}),e),{}),$r=t=>Array.isArray(t)?t:[];function ue(t){const e=yr(t.bundle_settings),r=t.variants.reduce((n,i)=>(n[i.id]=i,n),{});return{id:String(t.id),title:t.title,description:t.description||null,handle:t.handle,options:t.options.map(n=>({name:n.name,position:n.position,values:n.values})),default_variant_id:e.default_variant_id,default_selling_plan_id:e.default_selling_plan_id?Number(e.default_selling_plan_id):null,available_for_sale:t.available,requires_selling_plan:t.requires_selling_plan,bundle_settings:{is_customizable:e.is_customizable,price_rule:e.price_rule,customization_window:e.customization_window,max_quantity_per_variant:e.max_quantity_per_variant,collapsible_collections:e.collapsible_collections,show_product_variants:e.show_product_variants,product_details_modal_enabled:e.product_details_modal_enabled,show_variants_as_individual_products:t.bundle_settings.settings.display_variants_as_separate_products_in_list,post_add_to_cart_behavior:e.addToCartBehavior},variants:t.bundle_settings.variants.filter(({enabled:n})=>n).map((n,i)=>{const s=r[String(n.external_variant_id)];return{id:String(n.external_variant_id),title:s.title,price:s.price,compare_at_price:s.compare_at_price,image:s.image||"",available_for_sale:s.available,options:s.options,requires_selling_plan:s.requires_selling_plan,selling_plan_allocations:s.selling_plan_allocations.map(o=>({price:o.price,compare_at_price:o.compare_at_price,selling_plan:G(o.selling_plan)})),ranges:vr(n),collections:n.option_sources.map(o=>({id:o.option_source_id,source_platform:"shopify",min:o.quantity_min||0,max:o.quantity_max,position:o.position})),default_selections:n.selection_defaults.map(o=>({quantity:o.quantity,product:{id:String(o.product.id),handle:o.handle,title:o.product.title,description:o.product.description,images:o.product.images},variant:{id:o.external_variant_id,title:o.variant.title,featured_image:de(o.variant.featured_image),sku:o.sku||""}})),position:i}}),selling_plan_groups:t.selling_plan_groups.map(Te),collections:Object.values(t.collections).reduce((n,i)=>(Array.isArray(i.products)&&(n[String(i.id)]={id:String(i.id),title:i.title,handle:i.handle,products:i.products.map(Ne)}),n),{}),addons:t.addons.products.length?{collection_id:e.addons?.collection_id||"",collection_handle:e.addons?.collection_handle||"",products:t.addons.products.map(n=>({...Re(n),price_range:{min:n.price,max:n.price},compare_at_price_range:{min:n.compare_at_price||0,max:n.compare_at_price},variants:n.variants.map(i=>({...Fe(i),image:i.image,selling_plan_allocations:i.selling_plan_allocations.map(s=>({price:s.price,compare_at_price:s.compare_at_price,selling_plan:G(s.selling_plan)}))}))}))}:null,cross_sells:t.cross_sells.products.length?{collection_id:e.cross_sells?.collection_id||"",collection_handle:e.cross_sells?.collection_handle||"",products:t.cross_sells.products.map(Ne)}:null,incentives:br(t.incentives),filters:$r(t.filters),templates:t.bundle_settings.layout_settings.templates||null,globalStyles:t.bundle_settings.layout_settings.globalStyles||null}}async function Ir(t,e){return e?.source==="shopify_storefront"?Er():qr(t,e?.country_code)}async function qr(t,e){const{appName:r,appVersion:n}=b(),i={"X-Recharge-Sdk-Fn":"loadFromOnlineStore","X-Recharge-Sdk-Version":"2.6.1",...r?{"X-Recharge-Sdk-App-Name":r}:{},...n?{"X-Recharge-Sdk-App-Version":n}:{}};if(!e){const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return ue(o)}const s=new FormData;s.append("form_type","localization"),s.append("_method","put"),s.append("return_to",`${fe}/bundle-data/${t}`),s.append("country_code",e);try{const o=await S("post","/localization",{headers:{"Content-Type":"multipart/form-data",...i},data:s});return ue(o)}catch{const o=await A("get",`/bundle-data/${p(t)}`,{headers:i});return ue(o)}}async function Er(t,e){if(!b().storeIdentifier)throw new Error("Store identifier is required for Shopify Storefront API requests");return{}}var Cr=Object.freeze({__proto__:null,loadBundleData:Ir});function kr(t){try{return JSON.parse(t)}catch{return t}}function xr(t){return Object.entries(t).reduce((e,[r,n])=>({...e,[r]:kr(n)}),{})}const Be=t=>typeof t=="string"?t!=="0"&&t!=="false":!!t;function le(t,e){const r=new Set(e),n={};for(const i of Object.keys(t))r.has(i)||(n[i]=t[i]);return n}function Me(t){const e=xr(t),r=e.auto_inject===void 0?!0:e.auto_inject,n=e.display_on??[],i=e.first_option==="autodeliver";return{...le(e,["display_on","first_option"]),auto_inject:r,valid_pages:n,is_subscription_first:i,autoInject:r,validPages:n,isSubscriptionFirst:i}}function je(t){const e=t.subscription_options?.storefront_purchase_options==="subscription_only";return{...t,is_subscription_only:e,isSubscriptionOnly:e}}function Pr(t){return t.map(e=>{const r={};return Object.entries(e).forEach(([n,i])=>{Object.defineProperty(r,n,{value:je(i),enumerable:!0,writable:!0,configurable:!0})}),r})}const pe="2020-12",Ar={store_currency:{currency_code:"USD",currency_symbol:"$",decimal_separator:".",thousands_separator:",",currency_symbol_location:"left"}},L=new Map;function K(t,e){return L.has(t)||L.set(t,e()),L.get(t)}async function _e(t,e){if(t===void 0||t==="")throw new Error("ID is required");const r=e?.version??"2020-12",{product:n}=await K(`product.${t}.${r}`,()=>V("get",`/product/${r}/${p(t)}.json`));return r==="2020-12"?je(n):n}async function Ue(){return await K("storeSettings",()=>V("get",`/${pe}/store_settings.json`).catch(()=>Ar))}async function Le(){const{widget_settings:t}=await K("widgetSettings",()=>V("get",`/${pe}/widget_settings.json`));return Me(t)}async function Ve(){const{products:t,widget_settings:e,store_settings:r,meta:n}=await K("productsAndSettings",()=>V("get",`/product/${pe}/products.json`));return n?.status==="error"?Promise.reject(n.message):{products:Pr(t),widget_settings:Me(e),store_settings:r??{}}}async function Dr(){const{products:t}=await Ve();return t}async function Or(t){const[e,r,n]=await Promise.all([_e(t),Ue(),Le()]);return{product:e,store_settings:r,widget_settings:n,storeSettings:r,widgetSettings:n}}async function Tr(t){const{bundle_product:e}=await _e(t);return e}async function ze(){return Array.from(L.keys()).forEach(t=>L.delete(t))}var Fr=Object.freeze({__proto__:null,getCDNBundleSettings:Tr,getCDNProduct:_e,getCDNProductAndSettings:Or,getCDNProducts:Dr,getCDNProductsAndSettings:Ve,getCDNStoreSettings:Ue,getCDNWidgetSettings:Le,resetCDNCache:ze});async function Rr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("get","/charges",{id:e,query:{include:r?.include}},a(t,"getCharge"));return n}function Nr(t,e){return c("get","/charges",{query:e},a(t,"listCharges"))}async function Br(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/apply_discount`,{data:{discount_code:r}},a(t,"applyDiscountToCharge"));return n}async function Mr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/remove_discount`,{},a(t,"removeDiscountsFromCharge"));return r}async function jr(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/skip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"skipCharge"));return i}async function Ur(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");if(r===void 0||r.length===0)throw new Error("Purchase item IDs are required");const{charge:i}=await c("post",`/charges/${p(e)}/unskip`,{query:n,data:{purchase_item_ids:r.map(s=>Number(s))}},a(t,"unskipCharge"));return i}async function Lr(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{charge:r}=await c("post",`/charges/${p(e)}/process`,{},a(t,"processCharge"));return r}async function Vr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/charges/${p(e)}/change_next_charge_date`,{data:{next_charge_date:r}},a(t,"rescheduleCharge"));return n}var zr=Object.freeze({__proto__:null,applyDiscountToCharge:Br,getCharge:Rr,listCharges:Nr,processCharge:Lr,removeDiscountsFromCharge:Mr,rescheduleCharge:Vr,skipCharge:jr,unskipCharge:Ur});async function Xe(t,e){if(!["2020-12","2022-06"].includes(e.format_version))throw new Error("Missing or unsupported format_version.");return c("get","/product_search",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"productSearch"))}var Xr=Object.freeze({__proto__:null,productSearch:Xe});async function We(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{collection:r}=await c("get","/collections",{id:e},a(t,"getCollection"));return r}function Wr(t,e){return c("get","/collections",{query:e},a(t,"listCollections"))}async function Hr(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");if(!["2020-12","2022-06"].includes(r.format_version))throw new Error("Missing or unsupported format_version.");const n=a(t,"listCollectionProducts"),[{sort_order:i,manual_sort_order:s},{products:o}]=await Promise.all([We(n,e),Xe(n,{...r,collection_ids:[e],limit:250})]);if(i==="manual")return{products:s.reduce((l,f)=>{const _=o.find(h=>h.external_product_id===f);return _&&l.push(_),l},[])};{const l=Gr(i);return{products:o.slice().sort(l)}}}function He(t,e){const r=t.external_created_at,n=e.external_created_at;return r<n?-1:n>r?1:0}function Ge(t,e){const r=t.external_product_id,n=e.external_product_id;return r<n?-1:n>r?1:0}function Ke(t,e){const r=t.title.toLowerCase(),n=e.title.toLowerCase();return r<n?-1:n>r?1:0}function Gr(t){switch(t){case"created_at-asc":return He;case"created_at-desc":return(e,r)=>He(r,e);case"id-asc":return Ge;case"id-desc":return(e,r)=>Ge(r,e);case"title-asc":return Ke;case"title-desc":return(e,r)=>Ke(r,e)}}var Kr=Object.freeze({__proto__:null,getCollection:We,listCollectionProducts:Hr,listCollections:Wr});async function Yr(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("get","/customers",{id:r,query:{include:e?.include}},a(t,"getCustomer"));return n}async function Ye(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer:n}=await c("put","/customers",{id:r,data:e},a(t,"updateCustomer"));return n}async function Jr(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{deliveries:n}=await c("get",`/customers/${p(r)}/delivery_schedule`,{query:e},a(t,"getDeliverySchedule"));return n}async function Y(t,e){return c("get","/portal_access",{query:e},a(t,"getCustomerPortalAccess"))}function he(t){return t.replace(/\/portal\/?$/,"/pages/")}async function Qr(t,e,r){if(e===void 0||e==="")throw new Error("Subscription ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await Y(a(t,"getActiveChurnLandingPageURL"));return`${he(n)}${i}/subscriptions/${e}/cancel?token=${s}&subscription=${e}&redirect_to=${encodeURIComponent(r)}`}async function Zr(t){const{base_url:e,customer_hash:r,temp_token:n}=await Y(a(t,"getFailedPaymentMethodRecoveryLandingPageURL"));return`${he(e)}account/payment-methods?token=${n}&hash=${r}`}async function en(t,e,r){if(e===void 0||e==="")throw new Error("Gift ID is required");const{base_url:n,customer_hash:i,temp_token:s}=await Y(a(t,"getGiftRedemptionLandingPageURL"));return`${he(n)}${i}/gifts/${e}?token=${s}&redirect_to=${encodeURIComponent(r)}`}const Je={SHOPIFY_UPDATE_PAYMENT_INFO:{type:"email",template_type:"shopify_update_payment_information"},SHOPIFY_MIGRATE_PAYMENT_INFO:{type:"email",template_type:"shopify_migrate_payment_information"}};async function tn(t,e,r){const n=t.customerId;if(!n)throw new Error("Not logged in.");if(!Object.prototype.hasOwnProperty.call(Je,e))throw new Error("Notification not supported.");const i=Je[e];return c("post",`/customers/${p(n)}/notifications`,{data:{...i,template_vars:r}},a(t,"sendCustomerNotification"))}async function rn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include}},a(t,"getCreditSummary"));return n}var nn=Object.freeze({__proto__:null,getActiveChurnLandingPageURL:Qr,getCreditSummary:rn,getCustomer:Yr,getCustomerPortalAccess:Y,getDeliverySchedule:Jr,getFailedPaymentMethodRecoveryLandingPageURL:Zr,getGiftRedemptionLandingPageURL:en,sendCustomerNotification:tn,updateCustomer:Ye});async function sn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{credit_summary:n}=await c("get",`/customers/${p(r)}/credit_summary`,{query:{include:e?.include,presentment_currency_code:e?.presentment_currency_code}},a(t,"getCreditSummary"));return n}function on(t,{recurring:e}){if(!t.customerId)throw new Error("Not logged in.");const r={};return e!==void 0&&(r.apply_credit_to_next_recurring_charge=e),Ye(a(t,"setApplyCreditsToNextCharge"),r)}async function an(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");const{customer_id:n,...i}=e??{};return await c("get","/credit_accounts",{query:{...i,customer_id:r}},a(t,"listCreditAccounts"))}var cn=Object.freeze({__proto__:null,getCreditSummary:sn,listCreditAccounts:an,setApplyCreditsToNextCharge:on});async function dn(t,e,r){return await c("post","/customer_surveys/cancellation_prevention",{data:{customer_id:e,subscription_id:r}},a(t,"getCustomerSurveyReasons"))}async function un(t,e,r,n){return await c("post",`/customer_surveys/${p(r)}/customer_response`,{data:{customer_id:e,response_id:n}},a(t,"getCustomerSurveyOffers"))}async function ln(t,e){return await c("post","/offers/claim",{data:e},a(t,"claimOfferCustomerSurvey")),{}}var pn=Object.freeze({__proto__:null,claimOfferCustomerSurvey:ln,getCustomerSurveyOffers:un,getCustomerSurveyReasons:dn});async function _n(t,e,r,n){if(e===void 0||e==="")throw new Error("Subscription ID is required");return c("post",`/flows/customer_portal_flow/subscription/${p(e)}`,{query:{action:r,flow_id:n?.flow_id},data:{}},a(t,"triggerCustomerPortalFlow"))}var hn=Object.freeze({__proto__:null,triggerCustomerPortalFlow:_n});function mn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/gift_purchases",{query:e},a(t,"listGiftPurchases"))}async function fn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{gift_purchase:r}=await c("get","/gift_purchases",{id:e},a(t,"getGiftPurchase"));return r}var gn=Object.freeze({__proto__:null,getGiftPurchase:fn,listGiftPurchases:mn});function wn(t,e){if(!t.customerId)throw new Error("Not logged in.");return c("get","/incentives/tiered_discounts",{query:e},a(t,"listTieredDiscounts"))}async function yn(t,e){if(!t.customerId)throw new Error("Not logged in.");if(e===void 0||e==="")throw new Error("ID is required");const{tiered_discount:r}=await c("get",`/incentives/tiered_discounts/${p(e)}`,{},a(t,"getTieredDiscount"));return r}function bn(t,e){return c("post","/incentives/tiered_discounts/offers",{data:e},a(t,"getTieredDiscountOffers"))}var vn=Object.freeze({__proto__:null,getTieredDiscount:yn,getTieredDiscountOffers:bn,listTieredDiscounts:wn});async function Sn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{membership:r}=await c("get","/memberships",{id:e},a(t,"getMembership"));return r}function $n(t,e){return c("get","/memberships",{query:e},a(t,"listMemberships"))}async function In(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/cancel`,{data:r},a(t,"cancelMembership"));return n}async function qn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/activate`,{data:r},a(t,"activateMembership"));return n}async function En(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership:n}=await c("post",`/memberships/${p(e)}/change`,{data:r},a(t,"changeMembership"));return n}var Cn=Object.freeze({__proto__:null,activateMembership:qn,cancelMembership:In,changeMembership:En,getMembership:Sn,listMemberships:$n});async function kn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{membership_program:n}=await c("get","/membership_programs",{id:e,query:{include:r?.include}},a(t,"getMembershipProgram"));return n}function xn(t,e){return c("get","/membership_programs",{query:e},a(t,"listMembershipPrograms"))}var Pn=Object.freeze({__proto__:null,getMembershipProgram:kn,listMembershipPrograms:xn});async function An(t,e){const{metafield:r}=await c("post","/metafields",{data:{metafield:e}},a(t,"createMetafield"));return r}async function Dn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{metafield:n}=await c("put","/metafields",{id:e,data:{metafield:r}},a(t,"updateMetafield"));return n}function On(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/metafields",{id:e},a(t,"deleteMetafield"))}var Tn=Object.freeze({__proto__:null,createMetafield:An,deleteMetafield:On,updateMetafield:Dn});async function Fn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:r}=await c("get","/onetimes",{id:e},a(t,"getOnetime"));return r}function Rn(t,e){return c("get","/onetimes",{query:e},a(t,"listOnetimes"))}async function Nn(t,e){const{onetime:r}=await c("post","/onetimes",{data:e},a(t,"createOnetime"));return r}async function Bn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{onetime:n}=await c("put","/onetimes",{id:e,data:r},a(t,"updateOnetime"));return n}function Mn(t,e){if(e===void 0||e==="")throw new Error("ID is required");return c("delete","/onetimes",{id:e},a(t,"deleteOnetime"))}var jn=Object.freeze({__proto__:null,createOnetime:Nn,deleteOnetime:Mn,getOnetime:Fn,listOnetimes:Rn,updateOnetime:Bn});async function Un(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("get","/orders",{id:e},a(t,"getOrder"));return r}function Ln(t,e){return c("get","/orders",{query:e},a(t,"listOrders"))}async function Vn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{order:r}=await c("post",`/orders/${p(e)}/delay`,{},a(t,"delayOrder"));return r}var zn=Object.freeze({__proto__:null,delayOrder:Vn,getOrder:Un,listOrders:Ln});async function Xn(t,e){return typeof window<"u"&&window.Spreedly?Promise.resolve():new Promise((r,n)=>{if(typeof document>"u"){n(new Error("Document is not available. This function must be called in a browser environment."));return}if(document.querySelector(`script[src="${t}"]`)){const s=()=>{window.Spreedly?r():setTimeout(s,50)};s();return}const i=document.createElement("script");i.src=t,i.integrity=e,i.crossOrigin="anonymous",i.addEventListener("load",()=>{const s=()=>{window.Spreedly?r():setTimeout(s,50)};s()}),i.addEventListener("error",()=>{n(new Error("Failed to load payment iFrame script"))}),document.head.appendChild(i)})}async function Wn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("get","/payment_methods",{id:e,query:{include:r?.include}},a(t,"getPaymentMethod"));return n}async function Qe(t,e){const{payment_method:r}=await c("post","/payment_methods",{data:{...e,customer_id:t.customerId}},a(t,"createPaymentMethod"));return r}async function Hn(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{payment_method:n}=await c("put","/payment_methods",{id:e,data:r},a(t,"updatePaymentMethod"));return n}function Gn(t,e){return c("get","/payment_methods",{query:e},a(t,"listPaymentMethods"))}async function Kn(t,e){const r=await Yn(t,e),n=r.external.environment_key,i=r.payment_method_intent_id,s=r.external_customer_id.ecommerce,o=r.external.resource_url,l=r.external.integrity_hash,f=r.payment_method?.processor_payment_method_token;await Xn(o,l);let _=!1,h=null,y=null,v=null;return{mount(d,m){if(typeof window>"u"||!window.Spreedly)throw new Error("Payment script failed to load");window.Spreedly.init(n,{numberEl:d.numberElementId,cvvEl:d.cvvElementId}),window.Spreedly.on("ready",()=>{_=!0,d.styles&&(window.Spreedly.setStyle("number",d.styles),window.Spreedly.setStyle("cvv",d.styles)),d.numberLabel&&window.Spreedly.setLabel("number",d.numberLabel),d.cvvLabel&&window.Spreedly.setLabel("cvv",d.cvvLabel),d.numberPlaceholder&&window.Spreedly.setPlaceholder("number",d.numberPlaceholder),d.cvvPlaceholder&&window.Spreedly.setPlaceholder("cvv",d.cvvPlaceholder),d.numberFormat==="plainFormat"?(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType),window.Spreedly.setNumberFormat("plainFormat")):d.numberFormat==="maskedFormat"?(window.Spreedly.setFieldType("cvv","text"),window.Spreedly.setFieldType("number","text"),window.Spreedly.setNumberFormat("maskedFormat")):d.numberFormat==="prettyFormat"?(d.numberFieldType==="text"||d.numberFieldType==="tel"?window.Spreedly.setFieldType("number",d.numberFieldType):window.Spreedly.setFieldType("number","tel"),d.cvvFieldType==="text"||d.cvvFieldType==="tel"?window.Spreedly.setFieldType("cvv",d.cvvFieldType):window.Spreedly.setFieldType("cvv","tel"),window.Spreedly.setNumberFormat("prettyFormat")):(d.numberFieldType&&window.Spreedly.setFieldType("number",d.numberFieldType),d.cvvFieldType&&window.Spreedly.setFieldType("cvv",d.cvvFieldType)),m?.onReady?.()}),window.Spreedly.on("fieldEvent",(g,I,k,D)=>{m?.onFieldEvent?.(g,I,k,D)}),window.Spreedly.on("errors",g=>{m?.onErrors?.(g)}),window.Spreedly.on("paymentMethod",(g,I)=>{h=g,m?.onPaymentMethod?.(g,I),y&&(h=null,y(g),y=null)})},tokenize(d){if(!_||!window.Spreedly)throw new Error("Payment form is not initialized");let m=String(d.year);m.length===2&&(m=`20${m}`);const g=String(d.month).padStart(2,"0");"full_name"in d?window.Spreedly.tokenizeCreditCard({full_name:d.full_name,month:g,year:m}):window.Spreedly.tokenizeCreditCard({first_name:d.first_name,last_name:d.last_name,month:g,year:m})},async submit(d){if(!_)throw new Error("Payment form is not initialized");if(h){const m=h;return h=null,Ze(t,m,d,{external_payment_method_id:f,payment_method_intent_id:i,external_customer_id:s})}return new Promise((m,g)=>{v=d,y=async I=>{try{const k=await Ze(t,I,v,{external_payment_method_id:f,payment_method_intent_id:i,external_customer_id:s});m(k)}catch(k){g(k)}finally{v=null}},this.tokenize(d.card_details)})},reset(){window.Spreedly&&window.Spreedly.reload(),h=null,y=null,v=null},unmount(){window.Spreedly&&window.Spreedly.removeHandlers(),_=!1,h=null,y=null,v=null},addEventHandlers(d){d.onReady&&window.Spreedly.on("ready",d.onReady),d.onFieldEvent&&window.Spreedly.on("fieldEvent",d.onFieldEvent),d.onErrors&&window.Spreedly.on("errors",d.onErrors),d.onPaymentMethod&&window.Spreedly.on("paymentMethod",d.onPaymentMethod)},removeHandlers(){window.Spreedly&&window.Spreedly.removeHandlers()},setFieldType(d,m){window.Spreedly.setFieldType(d,m)},setLabel(d,m){window.Spreedly.setLabel(d,m)},setNumberFormat(d){window.Spreedly.setNumberFormat(d)},setPlaceholder(d,m){window.Spreedly.setPlaceholder(d,m)},setStyle(d,m){window.Spreedly.setStyle(d,m)}}}async function Yn(t,e){const r=t.customerId;if(!r)throw new Error("Not logged in.");return await c("post","/payment_method_intents",{data:{customer_id:r,payment_method_id:e}},a(t,"createFrictionlessPaymentIntentV1"))}async function Ze(t,e,{billing_address:r,default_payment_method:n,address_ids:i,apply_to_all_subscription_addresses:s},{external_payment_method_id:o,payment_method_intent_id:l,external_customer_id:f}){return await Qe(a(t,"submitFrictionlessPaymentMethodV1"),{default:n??!1,payment_type:"CREDIT_CARD",processor_customer_token:f.toString(),processor_name:"frictionless",processor_payment_method_token:e,billing_address:r,payment_method_intent_id:l,address_ids:i,external_payment_method_id:o,apply_to_all_subscription_addresses:s})}var Jn=Object.freeze({__proto__:null,createPaymentMethod:Qe,getPaymentMethod:Wn,initFrictionlessPaymentV1:Kn,listPaymentMethods:Gn,updatePaymentMethod:Hn});async function Qn(t,e){if(e===void 0||e==="")throw new Error("ID is required");const{plan:r}=await c("get","/plans",{id:e},a(t,"getPlan"));return r}function Zn(t,e){return c("get","/plans",{query:e},a(t,"listPlans"))}var ei=Object.freeze({__proto__:null,getPlan:Qn,listPlans:Zn});async function ti(t,e){return await c("get","/shop/shipping_countries",{query:e,headers:{"X-Recharge-Version":"2021-01"}},a(t,"getShippingCountries"))}async function ri(t){return await c("get","/shop/settings",{headers:{"X-Recharge-Version":"2021-01"}},a(t,"getStoreSettings"))}var ni=Object.freeze({__proto__:null,getShippingCountries:ti,getStoreSettings:ri});function ii(t,e){return{...le(e,["address_id","external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","status"]),customer_id:parseInt(t,10),shopify_variant_id:e.external_variant_id.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:{},...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:{},status:e.status?e.status.toUpperCase():void 0}}function si(t,e){return{...le(e,["external_variant_id","external_product_id","charge_interval_frequency","order_interval_frequency","price","use_external_variant_defaults"]),shopify_variant_id:e.external_variant_id?.ecommerce?parseInt(e.external_variant_id.ecommerce,10):void 0,...e.charge_interval_frequency?{charge_interval_frequency:`${e.charge_interval_frequency}`}:void 0,...e.order_interval_frequency?{order_interval_frequency:`${e.order_interval_frequency}`}:void 0,force_update:t}}function et(t){const{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:l,charge_interval_frequency:f,created_at:_,expire_after_specific_number_of_charges:h,shopify_product_id:y,shopify_variant_id:v,has_queued_charges:d,is_prepaid:m,is_skippable:g,is_swappable:I,max_retries_reached:k,next_charge_scheduled_at:D,order_day_of_month:q,order_day_of_week:O,order_interval_frequency:qi,order_interval_unit:Ei,presentment_currency:Ci,price:ki,product_title:xi,properties:Pi,quantity:Ai,sku:Di,sku_override:Oi,status:Ti,updated_at:Fi,variant_title:Ri}=t;return{id:e,address_id:r,customer_id:n,analytics_data:i,cancellation_reason:s,cancellation_reason_comments:o,cancelled_at:l,charge_interval_frequency:parseInt(f,10),created_at:_,expire_after_specific_number_of_charges:h,external_product_id:{ecommerce:`${y}`},external_variant_id:{ecommerce:`${v}`},has_queued_charges:Be(d),is_prepaid:m,is_skippable:g,is_swappable:I,max_retries_reached:Be(k),next_charge_scheduled_at:D,order_day_of_month:q,order_day_of_week:O,order_interval_frequency:parseInt(qi,10),order_interval_unit:Ei,presentment_currency:Ci,price:`${ki}`,product_title:xi??"",properties:Pi,quantity:Ai,sku:Di,sku_override:Oi,status:Ti.toLowerCase(),updated_at:Fi,variant_title:Ri}}async function oi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("get","/subscriptions",{id:e,query:{include:r?.include}},a(t,"getSubscription"));return n}function ai(t,e){return c("get","/subscriptions",{query:e},a(t,"listSubscriptions"))}function ci(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");return c("get",`/subscriptions/${p(e)}/addons`,{query:r},a(t,"listSubscriptionAddons"))}async function di(t,e,r){const{subscription:n}=await c("post","/subscriptions",{data:e,query:r},a(t,"createSubscription"));return n}async function ui(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("put","/subscriptions",{id:e,data:r,query:n},a(t,"updateSubscription"));return i}async function li(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/set_next_charge_date`,{data:{date:r},query:n},a(t,"updateSubscriptionChargeDate"));return i}async function pi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/change_address`,{data:{address_id:r}},a(t,"updateSubscriptionAddress"));return n}async function _i(t,e,r,n){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:i}=await c("post",`/subscriptions/${p(e)}/cancel`,{data:r,query:n},a(t,"cancelSubscription"));return i}async function hi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/activate`,{query:r},a(t,"activateSubscription"));return n}async function mi(t,e,r){if(e===void 0||e==="")throw new Error("ID is required");const{charge:n}=await c("post",`/subscriptions/${p(e)}/charges/skip`,{data:{date:r,subscription_id:`${e}`}},a(t,"skipSubscriptionCharge"));return n}async function fi(t,e,r={}){if(e===void 0||e==="")throw new Error("ID is required");const{subscription:n}=await c("post",`/subscriptions/${p(e)}/pricing_preview`,{data:r},a(t,"getSubscriptionPricingPreview"));return n}async function gi(t,e,r){if(e===void 0||e.length===0)throw new Error("Subscription IDs are required");const{onetimes:n}=await c("post","/purchase_items/skip_gift",{data:{purchase_item_ids:e.map(Number),recipient_address:r}},a(t,"skipGiftSubscriptionCharge"));return n}async function wi(t,e,r){const n=e.length;if(n<1||n>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:i}=t;if(!i)throw new Error("No customerId in session.");const s=e[0].address_id;if(!e.every(_=>_.address_id===s))throw new Error("All subscriptions must have the same address_id.");const o=e.map(_=>ii(i,_));let l;r?.allow_onetimes!==void 0&&(l={allow_onetimes:r.allow_onetimes});const{subscriptions:f}=await c("post",`/addresses/${p(s)}/subscriptions-bulk`,{data:{subscriptions:o,commit_update:!!r?.commit},headers:{"X-Recharge-Version":"2021-01"},query:l},a(t,"createSubscriptions"));return f.map(et)}async function yi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");const o=!!n?.force_update,l=r.map(h=>si(o,h));let f;n?.allow_onetimes!==void 0&&(f={allow_onetimes:n.allow_onetimes});const{subscriptions:_}=await c("put",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:l,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:f},a(t,"updateSubscriptions"));return _.map(et)}async function bi(t,e,r,n){if(e===void 0||e==="")throw new Error("Address ID is required");const i=r.length;if(i<1||i>21)throw new Error("Number of subscriptions must be between 1 and 20.");const{customerId:s}=t;if(!s)throw new Error("No customerId in session.");let o;n?.allow_onetimes!==void 0&&(o={allow_onetimes:n.allow_onetimes}),await c("delete",`/addresses/${p(e)}/subscriptions-bulk`,{data:{subscriptions:r,send_email:!!n?.send_email,commit_update:!!n?.commit},headers:{"X-Recharge-Version":"2021-01"},query:o},a(t,"deleteSubscriptions"))}var vi=Object.freeze({__proto__:null,activateSubscription:hi,cancelSubscription:_i,createSubscription:di,createSubscriptions:wi,deleteSubscriptions:bi,getSubscription:oi,getSubscriptionPricingPreview:fi,listSubscriptionAddons:ci,listSubscriptions:ai,skipGiftSubscriptionCharge:gi,skipSubscriptionCharge:mi,updateSubscription:ui,updateSubscriptionAddress:pi,updateSubscriptionChargeDate:li,updateSubscriptions:yi});const Si={get(t,e){return S("get",t,e)},post(t,e){return S("post",t,e)},put(t,e){return S("put",t,e)},delete(t,e){return S("delete",t,e)}};function $i(t){if(t)return t;if(window?.Shopify?.shop)return window.Shopify.shop;let e=window?.domain;if(!e){const r=location?.href.match(/(?:http[s]*:\/\/)*(.*?)\.(?=admin\.rechargeapps\.com)/i)?.[1].replace(/-sp$/,"");r&&(e=`${r}.myshopify.com`)}if(e)return e;throw new Error("No storeIdentifier was passed into init.")}function Ii(t={}){const e=t,{storefrontAccessToken:r}=t;if(r&&!r.startsWith("strfnt"))throw new Error("Incorrect storefront access token used. See https://storefront.rechargepayments.com/client/docs/getting_started/package_setup/#initialization-- for more information.");rt({storeIdentifier:$i(t.storeIdentifier),loginRetryFn:t.loginRetryFn,__unstable_twoFactorRetryFn:t.__unstable_twoFactorRetryFn,storefrontAccessToken:r,appName:t.appName,appVersion:t.appVersion,environment:e.environment?e.environment:"prod",environmentUri:e.environmentUri,customerHash:e.customerHash}),ze()}const tt={init:Ii,api:Si,address:ft,auth:Et,bundle:wr,bundleData:Cr,charge:zr,cdn:Fr,collection:Kr,credit:cn,customer:nn,customerSurveys:pn,flow:hn,gift:gn,tieredDiscount:vn,membership:Cn,membershipProgram:Pn,metafield:Tn,onetime:jn,order:zn,paymentMethod:Jn,plan:ei,product:Xr,store:ni,subscription:vi};try{tt.init()}catch{}return tt});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rechargeapps/storefront-client",
3
3
  "description": "Storefront client for Recharge",
4
- "version": "2.6.0",
4
+ "version": "2.6.1",
5
5
  "author": "Recharge Inc.",
6
6
  "license": "MIT",
7
7
  "main": "dist/cjs/index.js",