@metamask-previews/subscription-controller 6.2.2-preview-58a4a8b71 → 6.2.2-preview-4c8a5dfcb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/SubscriptionController.cjs +18 -26
  3. package/dist/SubscriptionController.cjs.map +1 -1
  4. package/dist/SubscriptionController.d.cts +5 -9
  5. package/dist/SubscriptionController.d.cts.map +1 -1
  6. package/dist/SubscriptionController.d.mts +5 -9
  7. package/dist/SubscriptionController.d.mts.map +1 -1
  8. package/dist/SubscriptionController.mjs +18 -26
  9. package/dist/SubscriptionController.mjs.map +1 -1
  10. package/dist/SubscriptionService-method-action-types.cjs +7 -0
  11. package/dist/SubscriptionService-method-action-types.cjs.map +1 -0
  12. package/dist/SubscriptionService-method-action-types.d.cts +151 -0
  13. package/dist/SubscriptionService-method-action-types.d.cts.map +1 -0
  14. package/dist/SubscriptionService-method-action-types.d.mts +151 -0
  15. package/dist/SubscriptionService-method-action-types.d.mts.map +1 -0
  16. package/dist/SubscriptionService-method-action-types.mjs +6 -0
  17. package/dist/SubscriptionService-method-action-types.mjs.map +1 -0
  18. package/dist/SubscriptionService-structs.cjs +135 -0
  19. package/dist/SubscriptionService-structs.cjs.map +1 -0
  20. package/dist/SubscriptionService-structs.d.cts +773 -0
  21. package/dist/SubscriptionService-structs.d.cts.map +1 -0
  22. package/dist/SubscriptionService-structs.d.mts +773 -0
  23. package/dist/SubscriptionService-structs.d.mts.map +1 -0
  24. package/dist/SubscriptionService-structs.mjs +132 -0
  25. package/dist/SubscriptionService-structs.mjs.map +1 -0
  26. package/dist/SubscriptionService.cjs +257 -87
  27. package/dist/SubscriptionService.cjs.map +1 -1
  28. package/dist/SubscriptionService.d.cts +90 -10
  29. package/dist/SubscriptionService.d.cts.map +1 -1
  30. package/dist/SubscriptionService.d.mts +90 -10
  31. package/dist/SubscriptionService.d.mts.map +1 -1
  32. package/dist/SubscriptionService.mjs +257 -87
  33. package/dist/SubscriptionService.mjs.map +1 -1
  34. package/dist/index.cjs +3 -1
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +4 -3
  37. package/dist/index.d.cts.map +1 -1
  38. package/dist/index.d.mts +4 -3
  39. package/dist/index.d.mts.map +1 -1
  40. package/dist/index.mjs +1 -1
  41. package/dist/index.mjs.map +1 -1
  42. package/package.json +5 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubscriptionService-structs.d.mts","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"AA8DA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkB7B,CAAC;AAEH,eAAO,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAMzC,CAAC;AAEH,eAAO,MAAM,+BAA+B;;;;EAE1C,CAAC;AAEH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;EAGhD,CAAC;AAEH,eAAO,MAAM,qCAAqC;;;;EAEhD,CAAC;AAEH,eAAO,MAAM,2BAA2B;;;;EAEtC,CAAC;AAEH,eAAO,MAAM,oCAAoC;;;;;;EAG/C,CAAC;AAsCH,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAGhC,CAAC;AASH,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EASxC,CAAC;AAEH,eAAO,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE9C,CAAC"}
@@ -0,0 +1,132 @@
1
+ import { array, boolean, enums, nullable, number, optional, string, type, union } from "@metamask/superstruct";
2
+ import { StrictHexStruct, CaipAccountIdStruct } from "@metamask/utils";
3
+ import { CANCEL_TYPES, CRYPTO_PAYMENT_METHOD_ERRORS, PAYMENT_TYPES, PRODUCT_TYPES, RECURRING_INTERVALS, SUBSCRIPTION_STATUSES } from "./types.mjs";
4
+ const ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));
5
+ const PaymentTypeStruct = enums(Object.values(PAYMENT_TYPES));
6
+ const RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));
7
+ const SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));
8
+ const CancelTypeStruct = enums(Object.values(CANCEL_TYPES));
9
+ const CryptoPaymentMethodErrorStruct = enums(Object.values(CRYPTO_PAYMENT_METHOD_ERRORS));
10
+ const ProductStruct = type({
11
+ name: ProductTypeStruct,
12
+ currency: enums(['usd']),
13
+ unitAmount: number(),
14
+ unitDecimals: number(),
15
+ });
16
+ const SubscriptionCardPaymentMethodStruct = type({
17
+ type: enums([PAYMENT_TYPES.byCard]),
18
+ card: type({
19
+ brand: string(),
20
+ displayBrand: string(),
21
+ last4: string(),
22
+ }),
23
+ });
24
+ const SubscriptionCryptoPaymentMethodStruct = type({
25
+ type: enums([PAYMENT_TYPES.byCrypto]),
26
+ crypto: type({
27
+ payerAddress: StrictHexStruct,
28
+ chainId: StrictHexStruct,
29
+ tokenSymbol: string(),
30
+ error: optional(CryptoPaymentMethodErrorStruct),
31
+ }),
32
+ });
33
+ const SubscriptionPaymentMethodStruct = union([
34
+ SubscriptionCardPaymentMethodStruct,
35
+ SubscriptionCryptoPaymentMethodStruct,
36
+ ]);
37
+ export const SubscriptionStruct = type({
38
+ id: string(),
39
+ products: array(ProductStruct),
40
+ currentPeriodStart: string(),
41
+ currentPeriodEnd: string(),
42
+ cancelAtPeriodEnd: optional(boolean()),
43
+ status: SubscriptionStatusStruct,
44
+ interval: RecurringIntervalStruct,
45
+ paymentMethod: SubscriptionPaymentMethodStruct,
46
+ trialPeriodDays: optional(number()),
47
+ trialStart: optional(string()),
48
+ trialEnd: optional(string()),
49
+ endDate: optional(string()),
50
+ canceledAt: optional(string()),
51
+ cancelType: CancelTypeStruct,
52
+ inactiveAt: optional(string()),
53
+ isEligibleForSupport: boolean(),
54
+ billingCycles: optional(number()),
55
+ });
56
+ export const GetSubscriptionsResponseStruct = type({
57
+ customerId: optional(string()),
58
+ subscriptions: array(SubscriptionStruct),
59
+ trialedProducts: array(ProductTypeStruct),
60
+ lastSubscription: optional(SubscriptionStruct),
61
+ rewardAccountId: optional(CaipAccountIdStruct),
62
+ });
63
+ export const StartSubscriptionResponseStruct = type({
64
+ checkoutSessionUrl: string(),
65
+ });
66
+ export const StartCryptoSubscriptionResponseStruct = type({
67
+ subscriptionId: string(),
68
+ status: SubscriptionStatusStruct,
69
+ });
70
+ export const UpdatePaymentMethodCardResponseStruct = type({
71
+ redirectUrl: string(),
72
+ });
73
+ export const BillingPortalResponseStruct = type({
74
+ url: string(),
75
+ });
76
+ export const SubscriptionApiGeneralResponseStruct = type({
77
+ success: boolean(),
78
+ message: optional(string()),
79
+ });
80
+ const ProductPriceStruct = type({
81
+ interval: RecurringIntervalStruct,
82
+ unitAmount: number(),
83
+ unitDecimals: number(),
84
+ currency: enums(['usd']),
85
+ trialPeriodDays: number(),
86
+ minBillingCycles: number(),
87
+ minBillingCyclesForBalance: number(),
88
+ });
89
+ const ProductPricingStruct = type({
90
+ name: ProductTypeStruct,
91
+ prices: array(ProductPriceStruct),
92
+ });
93
+ const TokenPaymentInfoStruct = type({
94
+ symbol: string(),
95
+ address: StrictHexStruct,
96
+ decimals: number(),
97
+ conversionRate: type({
98
+ usd: string(),
99
+ }),
100
+ });
101
+ const ChainPaymentInfoStruct = type({
102
+ chainId: StrictHexStruct,
103
+ paymentAddress: StrictHexStruct,
104
+ tokens: array(TokenPaymentInfoStruct),
105
+ isSponsorshipSupported: optional(boolean()),
106
+ });
107
+ const PricingPaymentMethodStruct = type({
108
+ type: PaymentTypeStruct,
109
+ chains: optional(array(ChainPaymentInfoStruct)),
110
+ });
111
+ export const PricingResponseStruct = type({
112
+ products: array(ProductPricingStruct),
113
+ paymentMethods: array(PricingPaymentMethodStruct),
114
+ });
115
+ const CohortStruct = type({
116
+ cohort: string(),
117
+ eligibilityRate: number(),
118
+ priority: number(),
119
+ eligible: boolean(),
120
+ });
121
+ export const SubscriptionEligibilityStruct = type({
122
+ product: ProductTypeStruct,
123
+ canSubscribe: optional(boolean()),
124
+ canViewEntryModal: optional(boolean()),
125
+ modalType: optional(enums(['A', 'B'])),
126
+ cohorts: optional(array(CohortStruct)),
127
+ assignedCohort: optional(nullable(string())),
128
+ assignedAt: optional(string()),
129
+ hasAssignedCohortExpired: optional(boolean()),
130
+ });
131
+ export const SubscriptionEligibilityArrayStruct = array(SubscriptionEligibilityStruct);
132
+ //# sourceMappingURL=SubscriptionService-structs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SubscriptionService-structs.mjs","sourceRoot":"","sources":["../src/SubscriptionService-structs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,QAAQ,EACR,MAA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CAAC;IAC5C,UAAU,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC9B,wBAAwB,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CAC9C,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,kCAAkC,GAAG,KAAK,CACrD,6BAA6B,CAC9B,CAAC","sourcesContent":["import {\n array,\n boolean,\n enums,\n nullable,\n number,\n optional,\n string,\n type,\n union,\n} from '@metamask/superstruct';\nimport { StrictHexStruct, CaipAccountIdStruct } from '@metamask/utils';\n\nimport {\n CANCEL_TYPES,\n CRYPTO_PAYMENT_METHOD_ERRORS,\n PAYMENT_TYPES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n SUBSCRIPTION_STATUSES,\n} from './types.js';\n\nconst ProductTypeStruct = enums(Object.values(PRODUCT_TYPES));\nconst PaymentTypeStruct = enums(Object.values(PAYMENT_TYPES));\nconst RecurringIntervalStruct = enums(Object.values(RECURRING_INTERVALS));\nconst SubscriptionStatusStruct = enums(Object.values(SUBSCRIPTION_STATUSES));\nconst CancelTypeStruct = enums(Object.values(CANCEL_TYPES));\nconst CryptoPaymentMethodErrorStruct = enums(\n Object.values(CRYPTO_PAYMENT_METHOD_ERRORS),\n);\n\nconst ProductStruct = type({\n name: ProductTypeStruct,\n currency: enums(['usd']),\n unitAmount: number(),\n unitDecimals: number(),\n});\n\nconst SubscriptionCardPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCard]),\n card: type({\n brand: string(),\n displayBrand: string(),\n last4: string(),\n }),\n});\n\nconst SubscriptionCryptoPaymentMethodStruct = type({\n type: enums([PAYMENT_TYPES.byCrypto]),\n crypto: type({\n payerAddress: StrictHexStruct,\n chainId: StrictHexStruct,\n tokenSymbol: string(),\n error: optional(CryptoPaymentMethodErrorStruct),\n }),\n});\n\nconst SubscriptionPaymentMethodStruct = union([\n SubscriptionCardPaymentMethodStruct,\n SubscriptionCryptoPaymentMethodStruct,\n]);\n\nexport const SubscriptionStruct = type({\n id: string(),\n products: array(ProductStruct),\n currentPeriodStart: string(),\n currentPeriodEnd: string(),\n cancelAtPeriodEnd: optional(boolean()),\n status: SubscriptionStatusStruct,\n interval: RecurringIntervalStruct,\n paymentMethod: SubscriptionPaymentMethodStruct,\n trialPeriodDays: optional(number()),\n trialStart: optional(string()),\n trialEnd: optional(string()),\n endDate: optional(string()),\n canceledAt: optional(string()),\n cancelType: CancelTypeStruct,\n inactiveAt: optional(string()),\n isEligibleForSupport: boolean(),\n billingCycles: optional(number()),\n});\n\nexport const GetSubscriptionsResponseStruct = type({\n customerId: optional(string()),\n subscriptions: array(SubscriptionStruct),\n trialedProducts: array(ProductTypeStruct),\n lastSubscription: optional(SubscriptionStruct),\n rewardAccountId: optional(CaipAccountIdStruct),\n});\n\nexport const StartSubscriptionResponseStruct = type({\n checkoutSessionUrl: string(),\n});\n\nexport const StartCryptoSubscriptionResponseStruct = type({\n subscriptionId: string(),\n status: SubscriptionStatusStruct,\n});\n\nexport const UpdatePaymentMethodCardResponseStruct = type({\n redirectUrl: string(),\n});\n\nexport const BillingPortalResponseStruct = type({\n url: string(),\n});\n\nexport const SubscriptionApiGeneralResponseStruct = type({\n success: boolean(),\n message: optional(string()),\n});\n\nconst ProductPriceStruct = type({\n interval: RecurringIntervalStruct,\n unitAmount: number(),\n unitDecimals: number(),\n currency: enums(['usd']),\n trialPeriodDays: number(),\n minBillingCycles: number(),\n minBillingCyclesForBalance: number(),\n});\n\nconst ProductPricingStruct = type({\n name: ProductTypeStruct,\n prices: array(ProductPriceStruct),\n});\n\nconst TokenPaymentInfoStruct = type({\n symbol: string(),\n address: StrictHexStruct,\n decimals: number(),\n conversionRate: type({\n usd: string(),\n }),\n});\n\nconst ChainPaymentInfoStruct = type({\n chainId: StrictHexStruct,\n paymentAddress: StrictHexStruct,\n tokens: array(TokenPaymentInfoStruct),\n isSponsorshipSupported: optional(boolean()),\n});\n\nconst PricingPaymentMethodStruct = type({\n type: PaymentTypeStruct,\n chains: optional(array(ChainPaymentInfoStruct)),\n});\n\nexport const PricingResponseStruct = type({\n products: array(ProductPricingStruct),\n paymentMethods: array(PricingPaymentMethodStruct),\n});\n\nconst CohortStruct = type({\n cohort: string(),\n eligibilityRate: number(),\n priority: number(),\n eligible: boolean(),\n});\n\nexport const SubscriptionEligibilityStruct = type({\n product: ProductTypeStruct,\n canSubscribe: optional(boolean()),\n canViewEntryModal: optional(boolean()),\n modalType: optional(enums(['A', 'B'])),\n cohorts: optional(array(CohortStruct)),\n assignedCohort: optional(nullable(string())),\n assignedAt: optional(string()),\n hasAssignedCohortExpired: optional(boolean()),\n});\n\nexport const SubscriptionEligibilityArrayStruct = array(\n SubscriptionEligibilityStruct,\n);\n"]}
@@ -10,36 +10,104 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_makeRequest, _SubscriptionService_getAuthorizationHeader, _SubscriptionService_getSubscriptionApiUrl;
13
+ var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.SubscriptionService = exports.SUBSCRIPTION_URL = void 0;
15
+ exports.SubscriptionService = exports.SUBSCRIPTION_URL = exports.serviceName = void 0;
16
+ const base_data_service_1 = require("@metamask/base-data-service");
17
+ const controller_utils_1 = require("@metamask/controller-utils");
18
+ const superstruct_1 = require("@metamask/superstruct");
16
19
  const constants_js_1 = require("./constants.cjs");
17
20
  const errors_js_1 = require("./errors.cjs");
18
21
  const logger_js_1 = require("./logger.cjs");
22
+ const SubscriptionService_structs_js_1 = require("./SubscriptionService-structs.cjs");
23
+ exports.serviceName = 'SubscriptionService';
19
24
  const SUBSCRIPTION_URL = (env, path) => `${(0, constants_js_1.getEnvUrls)(env).subscriptionApiUrl}/v1/${path}`;
20
25
  exports.SUBSCRIPTION_URL = SUBSCRIPTION_URL;
26
+ const MESSENGER_EXPOSED_METHODS = [
27
+ 'getSubscriptions',
28
+ 'cancelSubscription',
29
+ 'unCancelSubscription',
30
+ 'startSubscriptionWithCard',
31
+ 'startSubscriptionWithCrypto',
32
+ 'updatePaymentMethodCard',
33
+ 'updatePaymentMethodCrypto',
34
+ 'getSubscriptionsEligibilities',
35
+ 'submitUserEvent',
36
+ 'assignUserToCohort',
37
+ 'submitSponsorshipIntents',
38
+ 'linkRewards',
39
+ 'getPricing',
40
+ 'getBillingPortalUrl',
41
+ ];
21
42
  const log = (0, logger_js_1.createModuleLogger)(logger_js_1.projectLogger, 'SubscriptionService');
22
- class SubscriptionService {
23
- constructor(config) {
43
+ function isRetryableError(error) {
44
+ if (error instanceof controller_utils_1.HttpError) {
45
+ if (error.httpStatus === 429) {
46
+ return true;
47
+ }
48
+ return error.httpStatus < 400 || error.httpStatus >= 500;
49
+ }
50
+ return true;
51
+ }
52
+ const DEFAULT_POLICY_OPTIONS = {
53
+ retryFilterPolicy: (0, controller_utils_1.handleWhen)(isRetryableError),
54
+ };
55
+ /**
56
+ * Data service for the Subscription API.
57
+ *
58
+ * All requests are authenticated via JWT Bearer tokens obtained from the
59
+ * `AuthenticationController:getBearerToken` messenger action. Cached queries
60
+ * are scoped by `profileId` from
61
+ * `AuthenticationController:getSessionProfile`.
62
+ */
63
+ class SubscriptionService extends base_data_service_1.BaseDataService {
64
+ constructor({ messenger, fetchFunction = globalThis.fetch, env = constants_js_1.Env.PRD, captureException, queryClientConfig = {}, policyOptions = {}, }) {
65
+ super({
66
+ name: exports.serviceName,
67
+ messenger,
68
+ queryClientConfig,
69
+ policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },
70
+ });
24
71
  _SubscriptionService_instances.add(this);
25
72
  _SubscriptionService_env.set(this, void 0);
26
73
  _SubscriptionService_fetch.set(this, void 0);
27
74
  _SubscriptionService_captureException.set(this, void 0);
28
- __classPrivateFieldSet(this, _SubscriptionService_env, config.env, "f");
29
- this.authUtils = config.auth;
30
- __classPrivateFieldSet(this, _SubscriptionService_fetch, config.fetchFunction, "f");
31
- __classPrivateFieldSet(this, _SubscriptionService_captureException, config.captureException, "f");
75
+ __classPrivateFieldSet(this, _SubscriptionService_env, env, "f");
76
+ __classPrivateFieldSet(this, _SubscriptionService_fetch, fetchFunction, "f");
77
+ __classPrivateFieldSet(this, _SubscriptionService_captureException, captureException, "f");
78
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
32
79
  }
80
+ /**
81
+ * Fetches the user's subscriptions.
82
+ *
83
+ * @returns The subscriptions response.
84
+ */
33
85
  async getSubscriptions() {
34
- const path = 'subscriptions';
35
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
36
- path,
86
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
87
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
88
+ profileKey,
89
+ bearerToken,
90
+ methodName: 'getSubscriptions',
91
+ requestParams: null,
92
+ path: 'subscriptions',
37
93
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetSubscriptions,
38
94
  });
95
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.GetSubscriptionsResponseStruct);
39
96
  }
97
+ /**
98
+ * Cancels a subscription.
99
+ *
100
+ * @param params - The cancel subscription request.
101
+ * @returns The updated subscription.
102
+ */
40
103
  async cancelSubscription(params) {
104
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
41
105
  const path = `subscriptions/${params.subscriptionId}/cancel`;
42
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
106
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
107
+ profileKey,
108
+ bearerToken,
109
+ methodName: 'cancelSubscription',
110
+ requestParams: params,
43
111
  path,
44
112
  method: 'POST',
45
113
  body: {
@@ -47,40 +115,87 @@ class SubscriptionService {
47
115
  },
48
116
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToCancelSubscription,
49
117
  });
118
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionStruct);
50
119
  }
120
+ /**
121
+ * Reverses a pending subscription cancellation.
122
+ *
123
+ * @param params - The uncancel subscription request.
124
+ * @param params.subscriptionId - The subscription ID to uncancel.
125
+ * @returns The updated subscription.
126
+ */
51
127
  async unCancelSubscription(params) {
128
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
52
129
  const path = `subscriptions/${params.subscriptionId}/uncancel`;
53
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
130
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
131
+ profileKey,
132
+ bearerToken,
133
+ methodName: 'unCancelSubscription',
134
+ requestParams: params,
54
135
  path,
55
136
  method: 'POST',
56
137
  body: {},
57
138
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToUncancelSubscription,
58
139
  });
140
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionStruct);
59
141
  }
142
+ /**
143
+ * Starts a subscription with a card payment method.
144
+ *
145
+ * @param request - The start subscription request.
146
+ * @returns The checkout session response.
147
+ */
60
148
  async startSubscriptionWithCard(request) {
61
149
  if (request.products.length === 0) {
62
150
  throw new errors_js_1.SubscriptionServiceError(constants_js_1.SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
63
151
  }
64
- const path = 'subscriptions/card';
65
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
66
- path,
152
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
153
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
154
+ profileKey,
155
+ bearerToken,
156
+ methodName: 'startSubscriptionWithCard',
157
+ requestParams: request,
158
+ path: 'subscriptions/card',
67
159
  method: 'POST',
68
160
  body: request,
69
161
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,
70
162
  });
163
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.StartSubscriptionResponseStruct);
71
164
  }
165
+ /**
166
+ * Starts a subscription with a crypto payment method.
167
+ *
168
+ * @param request - The start crypto subscription request.
169
+ * @returns The created subscription response.
170
+ */
72
171
  async startSubscriptionWithCrypto(request) {
73
- const path = 'subscriptions/crypto';
74
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
75
- path,
172
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
173
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
174
+ profileKey,
175
+ bearerToken,
176
+ methodName: 'startSubscriptionWithCrypto',
177
+ requestParams: request,
178
+ path: 'subscriptions/crypto',
76
179
  method: 'POST',
77
180
  body: request,
78
181
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,
79
182
  });
183
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.StartCryptoSubscriptionResponseStruct);
80
184
  }
185
+ /**
186
+ * Updates a subscription's card payment method.
187
+ *
188
+ * @param request - The update payment method request.
189
+ * @returns The redirect URL response.
190
+ */
81
191
  async updatePaymentMethodCard(request) {
192
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
82
193
  const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
83
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
194
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
195
+ profileKey,
196
+ bearerToken,
197
+ methodName: 'updatePaymentMethodCard',
198
+ requestParams: request,
84
199
  path,
85
200
  method: 'PATCH',
86
201
  body: {
@@ -89,10 +204,21 @@ class SubscriptionService {
89
204
  },
90
205
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,
91
206
  });
207
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.UpdatePaymentMethodCardResponseStruct);
92
208
  }
209
+ /**
210
+ * Updates a subscription's crypto payment method.
211
+ *
212
+ * @param request - The update payment method request.
213
+ */
93
214
  async updatePaymentMethodCrypto(request) {
215
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
94
216
  const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
95
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
217
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
218
+ profileKey,
219
+ bearerToken,
220
+ methodName: 'updatePaymentMethodCrypto',
221
+ requestParams: request,
96
222
  path,
97
223
  method: 'PATCH',
98
224
  body: {
@@ -109,23 +235,28 @@ class SubscriptionService {
109
235
  * @returns The eligibility for a shield subscription
110
236
  */
111
237
  async getSubscriptionsEligibilities(request) {
112
- const path = 'subscriptions/eligibility';
113
- let query;
238
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
239
+ let queryParams;
114
240
  if (request?.balanceCategory !== undefined) {
115
- query = { balanceCategory: request.balanceCategory };
241
+ queryParams = { balanceCategory: request.balanceCategory };
116
242
  }
117
- const results = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
118
- path,
119
- queryParams: query,
243
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
244
+ profileKey,
245
+ bearerToken,
246
+ methodName: 'getSubscriptionsEligibilities',
247
+ requestParams: request ?? null,
248
+ path: 'subscriptions/eligibility',
249
+ queryParams,
120
250
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,
121
251
  });
252
+ const results = (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionEligibilityArrayStruct);
122
253
  return results.map((result) => ({
123
254
  ...result,
124
- canSubscribe: result.canSubscribe || false,
125
- canViewEntryModal: result.canViewEntryModal || false,
126
- cohorts: result.cohorts || [],
255
+ canSubscribe: result.canSubscribe ?? false,
256
+ canViewEntryModal: result.canViewEntryModal ?? false,
257
+ cohorts: result.cohorts ?? [],
127
258
  assignedCohort: result.assignedCohort ?? null,
128
- hasAssignedCohortExpired: result.hasAssignedCohortExpired || false,
259
+ hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,
129
260
  }));
130
261
  }
131
262
  /**
@@ -135,9 +266,13 @@ class SubscriptionService {
135
266
  * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }
136
267
  */
137
268
  async submitUserEvent(request) {
138
- const path = 'user-events';
139
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
140
- path,
269
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
270
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
271
+ profileKey,
272
+ bearerToken,
273
+ methodName: 'submitUserEvent',
274
+ requestParams: request,
275
+ path: 'user-events',
141
276
  method: 'POST',
142
277
  body: request,
143
278
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,
@@ -150,9 +285,13 @@ class SubscriptionService {
150
285
  * @example { cohort: 'post_tx' }
151
286
  */
152
287
  async assignUserToCohort(request) {
153
- const path = 'cohorts/assign';
154
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
155
- path,
288
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
289
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
290
+ profileKey,
291
+ bearerToken,
292
+ methodName: 'assignUserToCohort',
293
+ requestParams: request,
294
+ path: 'cohorts/assign',
156
295
  method: 'POST',
157
296
  body: request,
158
297
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,
@@ -168,9 +307,13 @@ class SubscriptionService {
168
307
  * @example { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }
169
308
  */
170
309
  async submitSponsorshipIntents(request) {
171
- const path = 'transaction-sponsorship/intents';
172
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
173
- path,
310
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
311
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
312
+ profileKey,
313
+ bearerToken,
314
+ methodName: 'submitSponsorshipIntents',
315
+ requestParams: request,
316
+ path: 'transaction-sponsorship/intents',
174
317
  method: 'POST',
175
318
  body: request,
176
319
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,
@@ -184,81 +327,107 @@ class SubscriptionService {
184
327
  * @returns The response from the API.
185
328
  */
186
329
  async linkRewards(request) {
187
- const path = 'rewards/link';
188
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
189
- path,
330
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
331
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
332
+ profileKey,
333
+ bearerToken,
334
+ methodName: 'linkRewards',
335
+ requestParams: request,
336
+ path: 'rewards/link',
190
337
  method: 'POST',
191
338
  body: request,
192
339
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToLinkRewards,
193
340
  });
341
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.SubscriptionApiGeneralResponseStruct);
194
342
  }
343
+ /**
344
+ * Fetches subscription pricing information.
345
+ *
346
+ * @returns The pricing response.
347
+ */
195
348
  async getPricing() {
196
- const path = 'pricing';
197
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
198
- path,
349
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
350
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
351
+ profileKey,
352
+ bearerToken,
353
+ methodName: 'getPricing',
354
+ requestParams: null,
355
+ path: 'pricing',
199
356
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetPricing,
200
357
  });
358
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.PricingResponseStruct);
201
359
  }
360
+ /**
361
+ * Fetches the billing portal URL.
362
+ *
363
+ * @returns The billing portal response.
364
+ */
202
365
  async getBillingPortalUrl() {
203
- const path = 'billing-portal';
204
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
205
- path,
366
+ const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
367
+ const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
368
+ profileKey,
369
+ bearerToken,
370
+ methodName: 'getBillingPortalUrl',
371
+ requestParams: null,
372
+ path: 'billing-portal',
206
373
  errorMessage: constants_js_1.SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,
207
374
  });
375
+ return (0, superstruct_1.create)(jsonResponse, SubscriptionService_structs_js_1.BillingPortalResponseStruct);
208
376
  }
209
377
  }
210
378
  exports.SubscriptionService = SubscriptionService;
211
- _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_makeRequest =
212
- /**
213
- * Makes a request to the Subscription Service backend.
214
- *
215
- * @param params - The request object containing the path, method, body, query parameters, and error message.
216
- * @param params.path - The path of the request.
217
- * @param params.method - The method of the request.
218
- * @param params.body - The body of the request.
219
- * @param params.queryParams - The query parameters of the request.
220
- * @param params.errorMessage - The error message to throw if the request fails.
221
- * @returns The result of the request.
222
- */
223
- async function _SubscriptionService_makeRequest({ path, method = 'GET', body, queryParams, errorMessage, }) {
379
+ _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_fetchJson = async function _SubscriptionService_fetchJson({ profileKey, bearerToken, methodName, requestParams, path, method = 'GET', body, queryParams, errorMessage, }) {
224
380
  const url = __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getSubscriptionApiUrl).call(this, path);
225
- const headers = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthorizationHeader).call(this);
381
+ if (queryParams) {
382
+ Object.entries(queryParams).forEach(([key, value]) => {
383
+ url.searchParams.append(key, value);
384
+ });
385
+ }
226
386
  try {
227
- if (queryParams) {
228
- Object.entries(queryParams).forEach(([key, value]) => {
229
- url.searchParams.append(key, value);
230
- });
231
- }
232
- const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
233
- method,
234
- headers: {
235
- 'Content-Type': 'application/json',
236
- ...headers,
387
+ return await this.fetchQuery({
388
+ queryKey: [
389
+ `${this.name}:${methodName}`,
390
+ profileKey,
391
+ requestParams,
392
+ ],
393
+ staleTime: 0,
394
+ cacheTime: 0,
395
+ queryFn: async () => {
396
+ const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
397
+ method,
398
+ headers: {
399
+ 'Content-Type': 'application/json',
400
+ ...__classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_headersForToken).call(this, bearerToken),
401
+ },
402
+ body: body ? JSON.stringify(body) : undefined,
403
+ });
404
+ if (!response.ok) {
405
+ const apiError = await (0, errors_js_1.getSubscriptionErrorFromResponse)(response);
406
+ throw new controller_utils_1.HttpError(response.status, apiError.message);
407
+ }
408
+ return response.json();
237
409
  },
238
- body: body ? JSON.stringify(body) : undefined,
239
410
  });
240
- if (!response.ok) {
241
- const error = await (0, errors_js_1.getSubscriptionErrorFromResponse)(response);
242
- throw error;
243
- }
244
- const data = await response.json();
245
- return data;
246
411
  }
247
412
  catch (error) {
248
413
  log(errorMessage, error);
249
414
  const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;
250
415
  const errorToCapture = error instanceof Error ? error : new Error(errorMessage);
251
416
  __classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, (0, errors_js_1.createSentryError)(errorMessageWithUrl, errorToCapture));
417
+ if (error instanceof errors_js_1.SubscriptionServiceError) {
418
+ throw error;
419
+ }
252
420
  throw new errors_js_1.SubscriptionServiceError(`Failed to make request. ${errorMessageWithUrl}`, {
253
421
  cause: errorToCapture,
254
422
  });
255
423
  }
256
- }, _SubscriptionService_getAuthorizationHeader =
257
- // eslint-disable-next-line @typescript-eslint/naming-convention
258
- async function _SubscriptionService_getAuthorizationHeader() {
424
+ }, _SubscriptionService_getAuthenticatedContext = async function _SubscriptionService_getAuthenticatedContext() {
259
425
  try {
260
- const accessToken = await this.authUtils.getAccessToken();
261
- return { Authorization: `Bearer ${accessToken}` };
426
+ const [bearerToken, sessionProfile] = await Promise.all([
427
+ this.messenger.call('AuthenticationController:getBearerToken'),
428
+ this.messenger.call('AuthenticationController:getSessionProfile'),
429
+ ]);
430
+ return { profileKey: sessionProfile.profileId, bearerToken };
262
431
  }
263
432
  catch (error) {
264
433
  const errorMessage = error instanceof Error
@@ -269,10 +438,11 @@ async function _SubscriptionService_getAuthorizationHeader() {
269
438
  cause: error instanceof Error ? error : new Error(errorMessage),
270
439
  });
271
440
  }
441
+ }, _SubscriptionService_headersForToken = function _SubscriptionService_headersForToken(bearerToken) {
442
+ return { Authorization: `Bearer ${bearerToken}` };
272
443
  }, _SubscriptionService_getSubscriptionApiUrl = function _SubscriptionService_getSubscriptionApiUrl(path) {
273
444
  try {
274
- const url = new URL((0, exports.SUBSCRIPTION_URL)(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
275
- return url;
445
+ return new URL((0, exports.SUBSCRIPTION_URL)(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
276
446
  }
277
447
  catch (error) {
278
448
  const errorMessage = error instanceof Error