diff --git a/.changeset/yummy-snails-work.md b/.changeset/yummy-snails-work.md new file mode 100644 index 00000000000..38482843035 --- /dev/null +++ b/.changeset/yummy-snails-work.md @@ -0,0 +1,9 @@ +--- +'@clerk/clerk-js': minor +'@clerk/types': minor +'@clerk/backend': patch +'@clerk/shared': patch +'@clerk/clerk-react': patch +--- + +[Billing Beta] Rename types, interfaces and classes that contain `commerce` to use `billing` instead. diff --git a/.typedoc/__tests__/__snapshots__/file-structure.test.ts.snap b/.typedoc/__tests__/__snapshots__/file-structure.test.ts.snap index 84f3fb5e041..624889f1e1a 100644 --- a/.typedoc/__tests__/__snapshots__/file-structure.test.ts.snap +++ b/.typedoc/__tests__/__snapshots__/file-structure.test.ts.snap @@ -6,6 +6,41 @@ exports[`Typedoc output > should have a deliberate file structure 1`] = ` "types/act-jwt-claim.mdx", "types/active-session-resource.mdx", "types/add-payment-source-params.mdx", + "types/billing-checkout-json.mdx", + "types/billing-checkout-resource.mdx", + "types/billing-checkout-totals-json.mdx", + "types/billing-checkout-totals.mdx", + "types/billing-initialized-payment-source-json.mdx", + "types/billing-initialized-payment-source-resource.mdx", + "types/billing-money-amount-json.mdx", + "types/billing-money-amount.mdx", + "types/billing-namespace.mdx", + "types/billing-payer-json.mdx", + "types/billing-payer-resource-type.mdx", + "types/billing-payer-resource.mdx", + "types/billing-payment-charge-type.mdx", + "types/billing-payment-json.mdx", + "types/billing-payment-resource.mdx", + "types/billing-payment-source-json.mdx", + "types/billing-payment-source-methods.mdx", + "types/billing-payment-source-resource.mdx", + "types/billing-payment-source-status.mdx", + "types/billing-payment-status.mdx", + "types/billing-plan-json.mdx", + "types/billing-plan-resource.mdx", + "types/billing-statement-group-json.mdx", + "types/billing-statement-group.mdx", + "types/billing-statement-json.mdx", + "types/billing-statement-resource.mdx", + "types/billing-statement-status.mdx", + "types/billing-statement-totals-json.mdx", + "types/billing-statement-totals.mdx", + "types/billing-subscription-item-json.mdx", + "types/billing-subscription-item-resource.mdx", + "types/billing-subscription-json.mdx", + "types/billing-subscription-plan-period.mdx", + "types/billing-subscription-resource.mdx", + "types/billing-subscription-status.mdx", "types/cancel-subscription-params.mdx", "types/check-authorization-fn.mdx", "types/check-authorization-from-session-claims.mdx", @@ -21,43 +56,6 @@ exports[`Typedoc output > should have a deliberate file structure 1`] = ` "types/clerk-resource.mdx", "types/clerk-status.mdx", "types/clerk.mdx", - "types/commerce-billing-namespace.mdx", - "types/commerce-checkout-json.mdx", - "types/commerce-checkout-resource.mdx", - "types/commerce-checkout-totals-json.mdx", - "types/commerce-checkout-totals.mdx", - "types/commerce-feature-json.mdx", - "types/commerce-feature-resource.mdx", - "types/commerce-initialized-payment-source-json.mdx", - "types/commerce-initialized-payment-source-resource.mdx", - "types/commerce-money-amount-json.mdx", - "types/commerce-money-amount.mdx", - "types/commerce-payer-json.mdx", - "types/commerce-payer-resource-type.mdx", - "types/commerce-payer-resource.mdx", - "types/commerce-payment-charge-type.mdx", - "types/commerce-payment-json.mdx", - "types/commerce-payment-resource.mdx", - "types/commerce-payment-source-json.mdx", - "types/commerce-payment-source-methods.mdx", - "types/commerce-payment-source-resource.mdx", - "types/commerce-payment-source-status.mdx", - "types/commerce-payment-status.mdx", - "types/commerce-plan-json.mdx", - "types/commerce-plan-resource.mdx", - "types/commerce-statement-group-json.mdx", - "types/commerce-statement-group.mdx", - "types/commerce-statement-json.mdx", - "types/commerce-statement-resource.mdx", - "types/commerce-statement-status.mdx", - "types/commerce-statement-totals-json.mdx", - "types/commerce-statement-totals.mdx", - "types/commerce-subscription-item-json.mdx", - "types/commerce-subscription-item-resource.mdx", - "types/commerce-subscription-json.mdx", - "types/commerce-subscription-plan-period.mdx", - "types/commerce-subscription-resource.mdx", - "types/commerce-subscription-status.mdx", "types/confirm-checkout-params.mdx", "types/create-checkout-params.mdx", "types/create-organization-params.mdx", @@ -67,6 +65,8 @@ exports[`Typedoc output > should have a deliberate file structure 1`] = ` "types/experimental_checkout-button-props.mdx", "types/experimental_plan-details-button-props.mdx", "types/experimental_subscription-details-button-props.mdx", + "types/feature-json.mdx", + "types/feature-resource.mdx", "types/field-error.mdx", "types/field-errors.mdx", "types/for-payer-type.mdx", diff --git a/packages/backend/src/api/resources/CommercePlan.ts b/packages/backend/src/api/resources/CommercePlan.ts index d23143922f4..a022519933a 100644 --- a/packages/backend/src/api/resources/CommercePlan.ts +++ b/packages/backend/src/api/resources/CommercePlan.ts @@ -1,4 +1,4 @@ -import type { CommerceMoneyAmount } from '@clerk/types'; +import type { BillingMoneyAmount } from '@clerk/types'; import { Feature } from './Feature'; import type { CommercePlanJSON } from './JSON'; @@ -49,15 +49,15 @@ export class CommercePlan { /** * The monthly fee of the plan. */ - readonly fee: CommerceMoneyAmount, + readonly fee: BillingMoneyAmount, /** * The annual fee of the plan. */ - readonly annualFee: CommerceMoneyAmount, + readonly annualFee: BillingMoneyAmount, /** * The annual fee of the plan on a monthly basis. */ - readonly annualMonthlyFee: CommerceMoneyAmount, + readonly annualMonthlyFee: BillingMoneyAmount, /** * The type of payer for the plan. */ diff --git a/packages/backend/src/api/resources/CommerceSubscription.ts b/packages/backend/src/api/resources/CommerceSubscription.ts index 8dcea408b37..38dff98b4d0 100644 --- a/packages/backend/src/api/resources/CommerceSubscription.ts +++ b/packages/backend/src/api/resources/CommerceSubscription.ts @@ -1,4 +1,4 @@ -import { type CommerceMoneyAmount } from '@clerk/types'; +import { type BillingMoneyAmount } from '@clerk/types'; import { CommerceSubscriptionItem } from './CommerceSubscriptionItem'; import type { CommerceSubscriptionJSON } from './JSON'; @@ -45,7 +45,7 @@ export class CommerceSubscription { /** * Information about the next scheduled payment. */ - readonly nextPayment: { date: number; amount: CommerceMoneyAmount } | null, + readonly nextPayment: { date: number; amount: BillingMoneyAmount } | null, /** * Whether the payer is eligible for a free trial. */ diff --git a/packages/backend/src/api/resources/CommerceSubscriptionItem.ts b/packages/backend/src/api/resources/CommerceSubscriptionItem.ts index 0340cdff561..9eaf0bf273a 100644 --- a/packages/backend/src/api/resources/CommerceSubscriptionItem.ts +++ b/packages/backend/src/api/resources/CommerceSubscriptionItem.ts @@ -1,4 +1,4 @@ -import type { CommerceMoneyAmount, CommerceMoneyAmountJSON } from '@clerk/types'; +import type { BillingMoneyAmount, BillingMoneyAmountJSON } from '@clerk/types'; import { CommercePlan } from './CommercePlan'; import type { CommerceSubscriptionItemJSON } from './JSON'; @@ -42,7 +42,7 @@ export class CommerceSubscriptionItem { /** * The current amount for the subscription item. */ - readonly amount: CommerceMoneyAmount | null | undefined, + readonly amount: BillingMoneyAmount | null | undefined, /** * The plan associated with this subscription item. */ @@ -86,13 +86,13 @@ export class CommerceSubscriptionItem { /** * The lifetime amount paid for this subscription item. */ - readonly lifetimePaid?: CommerceMoneyAmount | null, + readonly lifetimePaid?: BillingMoneyAmount | null, ) {} static fromJSON(data: CommerceSubscriptionItemJSON): CommerceSubscriptionItem { function formatAmountJSON( - amount: CommerceMoneyAmountJSON | null | undefined, - ): CommerceMoneyAmount | null | undefined { + amount: BillingMoneyAmountJSON | null | undefined, + ): BillingMoneyAmount | null | undefined { if (!amount) { return amount; } diff --git a/packages/clerk-js/src/core/clerk.ts b/packages/clerk-js/src/core/clerk.ts index 5e16c346007..1b3c5c9f613 100644 --- a/packages/clerk-js/src/core/clerk.ts +++ b/packages/clerk-js/src/core/clerk.ts @@ -30,13 +30,13 @@ import type { AuthenticateWithGoogleOneTapParams, AuthenticateWithMetamaskParams, AuthenticateWithOKXWalletParams, + BillingNamespace, Clerk as ClerkInterface, ClerkAPIError, ClerkAuthenticateWithWeb3Params, ClerkOptions, ClientJSONSnapshot, ClientResource, - CommerceBillingNamespace, CreateOrganizationParams, CreateOrganizationProps, CredentialReturn, @@ -148,7 +148,7 @@ import { createFapiClient } from './fapiClient'; import { createClientFromJwt } from './jwt-client'; import { APIKeys } from './modules/apiKeys'; import { createCheckoutInstance } from './modules/checkout/instance'; -import { CommerceBilling } from './modules/commerce'; +import { Billing } from './modules/commerce'; import { BaseResource, Client, @@ -206,7 +206,7 @@ export class Clerk implements ClerkInterface { version: __PKG_VERSION__, }; - private static _billing: CommerceBillingNamespace; + private static _billing: BillingNamespace; private static _apiKeys: APIKeysNamespace; private _checkout: ClerkInterface['__experimental_checkout'] | undefined; @@ -337,9 +337,9 @@ export class Clerk implements ClerkInterface { return this.#options.standardBrowser || false; } - get billing(): CommerceBillingNamespace { + get billing(): BillingNamespace { if (!Clerk._billing) { - Clerk._billing = new CommerceBilling(); + Clerk._billing = new Billing(); } return Clerk._billing; } @@ -625,7 +625,7 @@ export class Clerk implements ClerkInterface { this.assertComponentsReady(this.#componentControls); if (disabledAllBillingFeatures(this, this.environment)) { if (this.#instanceType === 'development') { - throw new ClerkRuntimeError(warnings.cannotRenderAnyCommerceComponent('Checkout'), { + throw new ClerkRuntimeError(warnings.cannotRenderAnyBillingComponent('Checkout'), { code: CANNOT_RENDER_BILLING_DISABLED_ERROR_CODE, }); } @@ -654,7 +654,7 @@ export class Clerk implements ClerkInterface { this.assertComponentsReady(this.#componentControls); if (disabledAllBillingFeatures(this, this.environment)) { if (this.#instanceType === 'development') { - throw new ClerkRuntimeError(warnings.cannotRenderAnyCommerceComponent('PlanDetails'), { + throw new ClerkRuntimeError(warnings.cannotRenderAnyBillingComponent('PlanDetails'), { code: CANNOT_RENDER_BILLING_DISABLED_ERROR_CODE, }); } @@ -1113,7 +1113,7 @@ export class Clerk implements ClerkInterface { this.assertComponentsReady(this.#componentControls); if (disabledAllBillingFeatures(this, this.environment)) { if (this.#instanceType === 'development') { - throw new ClerkRuntimeError(warnings.cannotRenderAnyCommerceComponent('PricingTable'), { + throw new ClerkRuntimeError(warnings.cannotRenderAnyBillingComponent('PricingTable'), { code: CANNOT_RENDER_BILLING_DISABLED_ERROR_CODE, }); } diff --git a/packages/clerk-js/src/core/modules/checkout/__tests__/manager.spec.ts b/packages/clerk-js/src/core/modules/checkout/__tests__/manager.spec.ts index e9ef1a04b5d..fe003965e5b 100644 --- a/packages/clerk-js/src/core/modules/checkout/__tests__/manager.spec.ts +++ b/packages/clerk-js/src/core/modules/checkout/__tests__/manager.spec.ts @@ -1,13 +1,13 @@ -import type { ClerkAPIResponseError, CommerceCheckoutResource } from '@clerk/types'; +import type { BillingCheckoutResource, ClerkAPIResponseError } from '@clerk/types'; import type { MockedFunction } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { type CheckoutCacheState, type CheckoutKey, createCheckoutManager, FETCH_STATUS } from '../manager'; -// Type-safe mock for CommerceCheckoutResource -const createMockCheckoutResource = (overrides: Partial = {}): CommerceCheckoutResource => ({ +// Type-safe mock for BillingCheckoutResource +const createMockCheckoutResource = (overrides: Partial = {}): BillingCheckoutResource => ({ id: 'checkout_123', - status: 'pending', + status: 'needs_confirmation', externalClientSecret: 'cs_test_123', externalGatewayId: 'gateway_123', totals: { @@ -20,18 +20,37 @@ const createMockCheckoutResource = (overrides: Partial }, isImmediatePlanChange: false, planPeriod: 'month', + freeTrialEndsAt: null, + payer: { + id: 'payer_123', + createdAt: new Date('2025-01-01'), + updatedAt: new Date('2025-01-01'), + firstName: 'Test Payer', + lastName: 'Test Payer', + email: 'test@clerk.com', + imageUrl: 'https://example.com/avatar.png', + pathRoot: '', + reload: vi.fn(), + }, plan: { id: 'plan_123', name: 'Pro Plan', description: 'Professional plan', features: [], - amount: 1000, - amountFormatted: '10.00', - annualAmount: 12000, - annualAmountFormatted: '120.00', - currency: 'USD', - currencySymbol: '$', + fee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, + annualFee: { amount: 12000, amountFormatted: '120.00', currency: 'USD', currencySymbol: '$' }, + annualMonthlyFee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, slug: 'pro-plan', + isDefault: false, + isRecurring: true, + hasBaseFee: false, + forPayerType: 'user', + publiclyVisible: true, + freeTrialDays: 0, + freeTrialEnabled: false, + avatarUrl: '', + pathRoot: '', + reload: vi.fn(), }, paymentSource: undefined, confirm: vi.fn(), @@ -166,7 +185,7 @@ describe('createCheckoutManager', () => { describe('executeOperation - start operations', () => { it('should execute start operation successfully', async () => { const mockCheckout = createMockCheckoutResource(); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(mockCheckout); @@ -192,7 +211,7 @@ describe('createCheckoutManager', () => { it('should set isStarting to true during operation', async () => { let capturedState: CheckoutCacheState | null = null; - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(async () => { // Capture state while operation is running @@ -212,7 +231,7 @@ describe('createCheckoutManager', () => { it('should handle operation errors correctly', async () => { const mockError = createMockError('Operation failed'); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockRejectedValue(mockError); @@ -237,7 +256,7 @@ describe('createCheckoutManager', () => { it('should clear previous errors when starting new operation', async () => { // First, create an error state const mockError = createMockError('Previous error'); - const failingOperation: MockedFunction<() => Promise> = vi + const failingOperation: MockedFunction<() => Promise> = vi .fn() .mockRejectedValue(mockError); @@ -252,7 +271,7 @@ describe('createCheckoutManager', () => { // Now start a successful operation const mockCheckout = createMockCheckoutResource(); - const successfulOperation: MockedFunction<() => Promise> = vi + const successfulOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(mockCheckout); @@ -271,7 +290,7 @@ describe('createCheckoutManager', () => { describe('executeOperation - confirm operations', () => { it('should execute confirm operation successfully', async () => { const mockCheckout = createMockCheckoutResource({ status: 'completed' }); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(mockCheckout); @@ -296,7 +315,7 @@ describe('createCheckoutManager', () => { it('should set isConfirming to true during operation', async () => { let capturedState: CheckoutCacheState | null = null; - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(async () => { capturedState = manager.getCacheState(); @@ -315,7 +334,7 @@ describe('createCheckoutManager', () => { it('should handle confirm operation errors', async () => { const mockError = createMockError('Confirm failed'); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockRejectedValue(mockError); @@ -339,7 +358,7 @@ describe('createCheckoutManager', () => { describe('operation deduplication', () => { it('should deduplicate concurrent start operations', async () => { const mockCheckout = createMockCheckoutResource(); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(mockCheckout), 50))); @@ -370,7 +389,7 @@ describe('createCheckoutManager', () => { it('should deduplicate concurrent confirm operations', async () => { const mockCheckout = createMockCheckoutResource(); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(mockCheckout), 50))); @@ -387,10 +406,10 @@ describe('createCheckoutManager', () => { const startCheckout = createMockCheckoutResource({ id: 'start_checkout' }); const confirmCheckout = createMockCheckoutResource({ id: 'confirm_checkout' }); - const startOperation: MockedFunction<() => Promise> = vi + const startOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(startCheckout), 50))); - const confirmOperation: MockedFunction<() => Promise> = vi + const confirmOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(confirmCheckout), 50))); @@ -413,7 +432,7 @@ describe('createCheckoutManager', () => { it('should propagate errors to all concurrent callers', async () => { const mockError = createMockError('Concurrent operation failed'); - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise((_, reject) => setTimeout(() => reject(mockError), 50))); @@ -439,8 +458,8 @@ describe('createCheckoutManager', () => { const checkout1 = createMockCheckoutResource({ id: 'checkout1' }); const checkout2 = createMockCheckoutResource({ id: 'checkout2' }); - const operation1: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout1); - const operation2: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout2); + const operation1: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout1); + const operation2: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout2); const result1 = await manager.executeOperation('start', operation1); const result2 = await manager.executeOperation('start', operation2); @@ -481,11 +500,11 @@ describe('createCheckoutManager', () => { it('should not clear checkout state when operations are pending', async () => { const mockCheckout = createMockCheckoutResource(); - let resolveOperation: ((value: CommerceCheckoutResource) => void) | undefined; + let resolveOperation: ((value: BillingCheckoutResource) => void) | undefined; - const mockOperation: MockedFunction<() => Promise> = vi.fn().mockImplementation( + const mockOperation: MockedFunction<() => Promise> = vi.fn().mockImplementation( () => - new Promise(resolve => { + new Promise(resolve => { resolveOperation = resolve; }), ); @@ -525,7 +544,7 @@ describe('createCheckoutManager', () => { // During operation - fetching let capturedState: CheckoutCacheState | null = null; - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(async () => { capturedState = manager.getCacheState(); @@ -540,7 +559,7 @@ describe('createCheckoutManager', () => { // After error - error const mockError = createMockError(); - const failingOperation: MockedFunction<() => Promise> = vi + const failingOperation: MockedFunction<() => Promise> = vi .fn() .mockRejectedValue(mockError); @@ -557,8 +576,8 @@ describe('createCheckoutManager', () => { expect(manager.getCacheState().status).toBe('needs_initialization'); // After starting checkout - needs confirmation - const pendingCheckout = createMockCheckoutResource({ status: 'pending' }); - const startOperation: MockedFunction<() => Promise> = vi + const pendingCheckout = createMockCheckoutResource({ status: 'needs_confirmation' }); + const startOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(pendingCheckout); @@ -567,7 +586,7 @@ describe('createCheckoutManager', () => { // After completing checkout - completed const completedCheckout = createMockCheckoutResource({ status: 'completed' }); - const confirmOperation: MockedFunction<() => Promise> = vi + const confirmOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(completedCheckout); @@ -579,7 +598,7 @@ describe('createCheckoutManager', () => { let startCapturedState: CheckoutCacheState | null = null; let confirmCapturedState: CheckoutCacheState | null = null; - const startOperation: MockedFunction<() => Promise> = vi + const startOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(async () => { await new Promise(resolve => setTimeout(resolve, 30)); @@ -587,7 +606,7 @@ describe('createCheckoutManager', () => { return createMockCheckoutResource({ id: 'start' }); }); - const confirmOperation: MockedFunction<() => Promise> = vi + const confirmOperation: MockedFunction<() => Promise> = vi .fn() .mockImplementation(async () => { await new Promise(resolve => setTimeout(resolve, 20)); @@ -620,8 +639,8 @@ describe('createCheckoutManager', () => { const checkout1 = createMockCheckoutResource({ id: 'checkout1' }); const checkout2 = createMockCheckoutResource({ id: 'checkout2' }); - const operation1: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout1); - const operation2: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout2); + const operation1: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout1); + const operation2: MockedFunction<() => Promise> = vi.fn().mockResolvedValue(checkout2); await manager1.executeOperation('start', operation1); await manager2.executeOperation('confirm', operation2); @@ -648,7 +667,7 @@ describe('createCheckoutManager', () => { manager2.subscribe(listener2); // Trigger operation on manager1 - const mockOperation: MockedFunction<() => Promise> = vi + const mockOperation: MockedFunction<() => Promise> = vi .fn() .mockResolvedValue(createMockCheckoutResource()); await manager1.executeOperation('start', mockOperation); @@ -665,10 +684,10 @@ describe('createCheckoutManager', () => { const checkout1 = createMockCheckoutResource({ id: 'checkout1' }); const checkout2 = createMockCheckoutResource({ id: 'checkout2' }); - const operation1: MockedFunction<() => Promise> = vi + const operation1: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(checkout1), 50))); - const operation2: MockedFunction<() => Promise> = vi + const operation2: MockedFunction<() => Promise> = vi .fn() .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(checkout2), 50))); diff --git a/packages/clerk-js/src/core/modules/checkout/manager.ts b/packages/clerk-js/src/core/modules/checkout/manager.ts index 9cc81b15f41..ef9ace116fe 100644 --- a/packages/clerk-js/src/core/modules/checkout/manager.ts +++ b/packages/clerk-js/src/core/modules/checkout/manager.ts @@ -1,8 +1,8 @@ import type { __experimental_CheckoutCacheState, __experimental_CheckoutInstance, + BillingCheckoutResource, ClerkAPIResponseError, - CommerceCheckoutResource, } from '@clerk/types'; type CheckoutKey = string & { readonly __tag: 'CheckoutKey' }; @@ -136,7 +136,7 @@ function createCheckoutManager(cacheKey: CheckoutKey) { // Shared operation handler to eliminate duplication async executeOperation( operationType: 'start' | 'confirm', - operationFn: () => Promise, + operationFn: () => Promise, ): Promise { const operationId = `${cacheKey}-${operationType}`; const isRunningField = operationType === 'start' ? 'isStarting' : 'isConfirming'; @@ -151,7 +151,7 @@ function createCheckoutManager(cacheKey: CheckoutKey) { // Create and store the operation promise const operationPromise = (async () => { - let data: CommerceCheckoutResource | null = null; + let data: BillingCheckoutResource | null = null; let error: ClerkAPIResponseError | null = null; try { // Mark operation as in progress and clear any previous errors diff --git a/packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts b/packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts index 99452702034..6976b653729 100644 --- a/packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts +++ b/packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts @@ -1,15 +1,15 @@ import type { + BillingCheckoutJSON, + BillingNamespace, + BillingPaymentJSON, + BillingPaymentResource, + BillingPlanJSON, + BillingPlanResource, + BillingStatementJSON, + BillingStatementResource, + BillingSubscriptionJSON, + BillingSubscriptionResource, ClerkPaginatedResponse, - CommerceBillingNamespace, - CommerceCheckoutJSON, - CommercePaymentJSON, - CommercePaymentResource, - CommercePlanJSON, - CommercePlanResource, - CommerceStatementJSON, - CommerceStatementResource, - CommerceSubscriptionJSON, - CommerceSubscriptionResource, CreateCheckoutParams, GetPaymentAttemptsParams, GetPlansParams, @@ -20,15 +20,15 @@ import type { import { convertPageToOffsetSearchParams } from '../../../utils/convertPageToOffsetSearchParams'; import { BaseResource, - CommerceCheckout, - CommercePayment, - CommercePlan, - CommerceStatement, - CommerceSubscription, + BillingCheckout, + BillingPayment, + BillingPlan, + BillingStatement, + BillingSubscription, } from '../../resources/internal'; -export class CommerceBilling implements CommerceBillingNamespace { - getPlans = async (params?: GetPlansParams): Promise> => { +export class Billing implements BillingNamespace { + getPlans = async (params?: GetPlansParams): Promise> => { const { for: forParam, ...safeParams } = params || {}; const searchParams = { ...safeParams, payer_type: forParam === 'organization' ? 'org' : 'user' }; return await BaseResource._fetch({ @@ -36,32 +36,32 @@ export class CommerceBilling implements CommerceBillingNamespace { method: 'GET', search: convertPageToOffsetSearchParams(searchParams), }).then(res => { - const { data: plans, total_count } = res as unknown as ClerkPaginatedResponse; + const { data: plans, total_count } = res as unknown as ClerkPaginatedResponse; return { total_count, - data: plans.map(plan => new CommercePlan(plan)), + data: plans.map(plan => new BillingPlan(plan)), }; }); }; // Inconsistent API - getPlan = async (params: { id: string }): Promise => { + getPlan = async (params: { id: string }): Promise => { const plan = (await BaseResource._fetch({ path: `/commerce/plans/${params.id}`, method: 'GET', - })) as unknown as CommercePlanJSON; - return new CommercePlan(plan); + })) as unknown as BillingPlanJSON; + return new BillingPlan(plan); }; - getSubscription = async (params: GetSubscriptionParams): Promise => { + getSubscription = async (params: GetSubscriptionParams): Promise => { return await BaseResource._fetch({ path: params.orgId ? `/organizations/${params.orgId}/commerce/subscription` : `/me/commerce/subscription`, method: 'GET', - }).then(res => new CommerceSubscription(res?.response as CommerceSubscriptionJSON)); + }).then(res => new BillingSubscription(res?.response as BillingSubscriptionJSON)); }; - getStatements = async (params: GetStatementsParams): Promise> => { + getStatements = async (params: GetStatementsParams): Promise> => { const { orgId, ...rest } = params; return await BaseResource._fetch({ @@ -70,16 +70,16 @@ export class CommerceBilling implements CommerceBillingNamespace { search: convertPageToOffsetSearchParams(rest), }).then(res => { const { data: statements, total_count } = - res?.response as unknown as ClerkPaginatedResponse; + res?.response as unknown as ClerkPaginatedResponse; return { total_count, - data: statements.map(statement => new CommerceStatement(statement)), + data: statements.map(statement => new BillingStatement(statement)), }; }); }; - getStatement = async (params: { id: string; orgId?: string }): Promise => { + getStatement = async (params: { id: string; orgId?: string }): Promise => { const statement = ( await BaseResource._fetch({ path: params.orgId @@ -87,13 +87,13 @@ export class CommerceBilling implements CommerceBillingNamespace { : `/me/commerce/statements/${params.id}`, method: 'GET', }) - )?.response as unknown as CommerceStatementJSON; - return new CommerceStatement(statement); + )?.response as unknown as BillingStatementJSON; + return new BillingStatement(statement); }; getPaymentAttempts = async ( params: GetPaymentAttemptsParams, - ): Promise> => { + ): Promise> => { const { orgId, ...rest } = params; return await BaseResource._fetch({ @@ -101,35 +101,35 @@ export class CommerceBilling implements CommerceBillingNamespace { method: 'GET', search: convertPageToOffsetSearchParams(rest), }).then(res => { - const { data: payments, total_count } = res as unknown as ClerkPaginatedResponse; + const { data: payments, total_count } = res as unknown as ClerkPaginatedResponse; return { total_count, - data: payments.map(payment => new CommercePayment(payment)), + data: payments.map(payment => new BillingPayment(payment)), }; }); }; - getPaymentAttempt = async (params: { id: string; orgId?: string }): Promise => { + getPaymentAttempt = async (params: { id: string; orgId?: string }): Promise => { const paymentAttempt = (await BaseResource._fetch({ path: params.orgId ? `/organizations/${params.orgId}/commerce/payment_attempts/${params.id}` : `/me/commerce/payment_attempts/${params.id}`, method: 'GET', - })) as unknown as CommercePaymentJSON; - return new CommercePayment(paymentAttempt); + })) as unknown as BillingPaymentJSON; + return new BillingPayment(paymentAttempt); }; startCheckout = async (params: CreateCheckoutParams) => { const { orgId, ...rest } = params; const json = ( - await BaseResource._fetch({ + await BaseResource._fetch({ path: orgId ? `/organizations/${orgId}/commerce/checkouts` : `/me/commerce/checkouts`, method: 'POST', body: rest as any, }) - )?.response as unknown as CommerceCheckoutJSON; + )?.response as unknown as BillingCheckoutJSON; - return new CommerceCheckout(json); + return new BillingCheckout(json); }; } diff --git a/packages/clerk-js/src/core/modules/commerce/payment-source-methods.ts b/packages/clerk-js/src/core/modules/commerce/payment-source-methods.ts index 5ce956d4f65..5dd2fc7bbc9 100644 --- a/packages/clerk-js/src/core/modules/commerce/payment-source-methods.ts +++ b/packages/clerk-js/src/core/modules/commerce/payment-source-methods.ts @@ -1,14 +1,14 @@ import type { AddPaymentSourceParams, + BillingInitializedPaymentSourceJSON, + BillingPaymentSourceJSON, ClerkPaginatedResponse, - CommerceInitializedPaymentSourceJSON, - CommercePaymentSourceJSON, GetPaymentSourcesParams, InitializePaymentSourceParams, } from '@clerk/types'; import { convertPageToOffsetSearchParams } from '../../../utils/convertPageToOffsetSearchParams'; -import { BaseResource, CommerceInitializedPaymentSource, CommercePaymentSource } from '../../resources/internal'; +import { BaseResource, BillingInitializedPaymentSource, BillingPaymentSource } from '../../resources/internal'; export const initializePaymentSource = async (params: InitializePaymentSourceParams) => { const { orgId, ...rest } = params; @@ -20,8 +20,8 @@ export const initializePaymentSource = async (params: InitializePaymentSourcePar method: 'POST', body: rest as any, }) - )?.response as unknown as CommerceInitializedPaymentSourceJSON; - return new CommerceInitializedPaymentSource(json); + )?.response as unknown as BillingInitializedPaymentSourceJSON; + return new BillingInitializedPaymentSource(json); }; export const addPaymentSource = async (params: AddPaymentSourceParams) => { @@ -33,8 +33,8 @@ export const addPaymentSource = async (params: AddPaymentSourceParams) => { method: 'POST', body: rest as any, }) - )?.response as unknown as CommercePaymentSourceJSON; - return new CommercePaymentSource(json); + )?.response as unknown as BillingPaymentSourceJSON; + return new BillingPaymentSource(json); }; export const getPaymentSources = async (params: GetPaymentSourcesParams) => { @@ -46,10 +46,10 @@ export const getPaymentSources = async (params: GetPaymentSourcesParams) => { search: convertPageToOffsetSearchParams(rest), }).then(res => { const { data: paymentSources, total_count } = - res?.response as unknown as ClerkPaginatedResponse; + res?.response as unknown as ClerkPaginatedResponse; return { total_count, - data: paymentSources.map(paymentSource => new CommercePaymentSource(paymentSource)), + data: paymentSources.map(paymentSource => new BillingPaymentSource(paymentSource)), }; }); }; diff --git a/packages/clerk-js/src/core/resources/CommerceCheckout.ts b/packages/clerk-js/src/core/resources/CommerceCheckout.ts index 57a8cc25c50..03d026a6021 100644 --- a/packages/clerk-js/src/core/resources/CommerceCheckout.ts +++ b/packages/clerk-js/src/core/resources/CommerceCheckout.ts @@ -1,39 +1,39 @@ import { retry } from '@clerk/shared/retry'; import type { - CommerceCheckoutJSON, - CommerceCheckoutResource, - CommerceCheckoutTotals, - CommercePayerResource, - CommerceSubscriptionPlanPeriod, + BillingCheckoutJSON, + BillingCheckoutResource, + BillingCheckoutTotals, + BillingPayerResource, + BillingSubscriptionPlanPeriod, ConfirmCheckoutParams, } from '@clerk/types'; import { unixEpochToDate } from '@/utils/date'; -import { commerceTotalsFromJSON } from '../../utils'; -import { CommercePayer } from './CommercePayer'; -import { BaseResource, CommercePaymentSource, CommercePlan, isClerkAPIResponseError } from './internal'; +import { billingTotalsFromJSON } from '../../utils'; +import { BillingPayer } from './CommercePayer'; +import { BaseResource, BillingPaymentSource, BillingPlan, isClerkAPIResponseError } from './internal'; -export class CommerceCheckout extends BaseResource implements CommerceCheckoutResource { +export class BillingCheckout extends BaseResource implements BillingCheckoutResource { id!: string; externalClientSecret!: string; externalGatewayId!: string; - paymentSource?: CommercePaymentSource; - plan!: CommercePlan; - planPeriod!: CommerceSubscriptionPlanPeriod; + paymentSource?: BillingPaymentSource; + plan!: BillingPlan; + planPeriod!: BillingSubscriptionPlanPeriod; planPeriodStart!: number | undefined; status!: 'needs_confirmation' | 'completed'; - totals!: CommerceCheckoutTotals; + totals!: BillingCheckoutTotals; isImmediatePlanChange!: boolean; freeTrialEndsAt!: Date | null; - payer!: CommercePayerResource; + payer!: BillingPayerResource; - constructor(data: CommerceCheckoutJSON) { + constructor(data: BillingCheckoutJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceCheckoutJSON | null): this { + protected fromJSON(data: BillingCheckoutJSON | null): this { if (!data) { return this; } @@ -41,15 +41,15 @@ export class CommerceCheckout extends BaseResource implements CommerceCheckoutRe this.id = data.id; this.externalClientSecret = data.external_client_secret; this.externalGatewayId = data.external_gateway_id; - this.paymentSource = data.payment_source ? new CommercePaymentSource(data.payment_source) : undefined; - this.plan = new CommercePlan(data.plan); + this.paymentSource = data.payment_source ? new BillingPaymentSource(data.payment_source) : undefined; + this.plan = new BillingPlan(data.plan); this.planPeriod = data.plan_period; this.planPeriodStart = data.plan_period_start; this.status = data.status; - this.totals = commerceTotalsFromJSON(data.totals); + this.totals = billingTotalsFromJSON(data.totals); this.isImmediatePlanChange = data.is_immediate_plan_change; this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null; - this.payer = new CommercePayer(data.payer); + this.payer = new BillingPayer(data.payer); return this; } diff --git a/packages/clerk-js/src/core/resources/CommerceFeature.ts b/packages/clerk-js/src/core/resources/CommerceFeature.ts index 2d1ea7a9455..6b46c351b85 100644 --- a/packages/clerk-js/src/core/resources/CommerceFeature.ts +++ b/packages/clerk-js/src/core/resources/CommerceFeature.ts @@ -1,20 +1,20 @@ -import type { CommerceFeatureJSON, CommerceFeatureJSONSnapshot, CommerceFeatureResource } from '@clerk/types'; +import type { FeatureJSON, FeatureResource } from '@clerk/types'; import { BaseResource } from './internal'; -export class CommerceFeature extends BaseResource implements CommerceFeatureResource { +export class Feature extends BaseResource implements FeatureResource { id!: string; name!: string; description!: string; slug!: string; avatarUrl!: string; - constructor(data: CommerceFeatureJSON) { + constructor(data: FeatureJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceFeatureJSON | null): this { + protected fromJSON(data: FeatureJSON | null): this { if (!data) { return this; } @@ -27,15 +27,4 @@ export class CommerceFeature extends BaseResource implements CommerceFeatureReso return this; } - - public __internal_toSnapshot(): CommerceFeatureJSONSnapshot { - return { - object: 'commerce_feature', - id: this.id, - name: this.name, - description: this.description, - slug: this.slug, - avatar_url: this.avatarUrl, - }; - } } diff --git a/packages/clerk-js/src/core/resources/CommercePayer.ts b/packages/clerk-js/src/core/resources/CommercePayer.ts index 5412e3f7837..67eafb0588a 100644 --- a/packages/clerk-js/src/core/resources/CommercePayer.ts +++ b/packages/clerk-js/src/core/resources/CommercePayer.ts @@ -1,10 +1,10 @@ -import type { CommercePayerJSON, CommercePayerResource } from '@clerk/types'; +import type { BillingPayerJSON, BillingPayerResource } from '@clerk/types'; import { unixEpochToDate } from '@/utils/date'; import { BaseResource } from './internal'; -export class CommercePayer extends BaseResource implements CommercePayerResource { +export class BillingPayer extends BaseResource implements BillingPayerResource { id!: string; createdAt!: Date; updatedAt!: Date; @@ -16,12 +16,12 @@ export class CommercePayer extends BaseResource implements CommercePayerResource organizationId?: string; organizationName?: string; - constructor(data: CommercePayerJSON) { + constructor(data: BillingPayerJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommercePayerJSON | null): this { + protected fromJSON(data: BillingPayerJSON | null): this { if (!data) { return this; } diff --git a/packages/clerk-js/src/core/resources/CommercePayment.ts b/packages/clerk-js/src/core/resources/CommercePayment.ts index 9abebfa84f8..c9365a5177b 100644 --- a/packages/clerk-js/src/core/resources/CommercePayment.ts +++ b/packages/clerk-js/src/core/resources/CommercePayment.ts @@ -1,45 +1,45 @@ import type { - CommerceMoneyAmount, - CommercePaymentChargeType, - CommercePaymentJSON, - CommercePaymentResource, - CommercePaymentSourceResource, - CommercePaymentStatus, - CommerceSubscriptionItemResource, + BillingMoneyAmount, + BillingPaymentChargeType, + BillingPaymentJSON, + BillingPaymentResource, + BillingPaymentSourceResource, + BillingPaymentStatus, + BillingSubscriptionItemResource, } from '@clerk/types'; -import { commerceMoneyAmountFromJSON } from '../../utils'; +import { billingMoneyAmountFromJSON } from '../../utils'; import { unixEpochToDate } from '../../utils/date'; -import { BaseResource, CommercePaymentSource, CommerceSubscriptionItem } from './internal'; +import { BaseResource, BillingPaymentSource, BillingSubscriptionItem } from './internal'; -export class CommercePayment extends BaseResource implements CommercePaymentResource { +export class BillingPayment extends BaseResource implements BillingPaymentResource { id!: string; - amount!: CommerceMoneyAmount; + amount!: BillingMoneyAmount; failedAt?: Date; paidAt?: Date; updatedAt!: Date; - paymentSource!: CommercePaymentSourceResource; - subscriptionItem!: CommerceSubscriptionItemResource; - chargeType!: CommercePaymentChargeType; - status!: CommercePaymentStatus; + paymentSource!: BillingPaymentSourceResource; + subscriptionItem!: BillingSubscriptionItemResource; + chargeType!: BillingPaymentChargeType; + status!: BillingPaymentStatus; - constructor(data: CommercePaymentJSON) { + constructor(data: BillingPaymentJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommercePaymentJSON | null): this { + protected fromJSON(data: BillingPaymentJSON | null): this { if (!data) { return this; } this.id = data.id; - this.amount = commerceMoneyAmountFromJSON(data.amount); + this.amount = billingMoneyAmountFromJSON(data.amount); this.paidAt = data.paid_at ? unixEpochToDate(data.paid_at) : undefined; this.failedAt = data.failed_at ? unixEpochToDate(data.failed_at) : undefined; this.updatedAt = unixEpochToDate(data.updated_at); - this.paymentSource = new CommercePaymentSource(data.payment_source); - this.subscriptionItem = new CommerceSubscriptionItem(data.subscription_item); + this.paymentSource = new BillingPaymentSource(data.payment_source); + this.subscriptionItem = new BillingSubscriptionItem(data.subscription_item); this.chargeType = data.charge_type; this.status = data.status; return this; diff --git a/packages/clerk-js/src/core/resources/CommercePaymentSource.ts b/packages/clerk-js/src/core/resources/CommercePaymentSource.ts index 8a2583ac66d..1339dc4db70 100644 --- a/packages/clerk-js/src/core/resources/CommercePaymentSource.ts +++ b/packages/clerk-js/src/core/resources/CommercePaymentSource.ts @@ -1,9 +1,9 @@ import type { - CommerceInitializedPaymentSourceJSON, - CommerceInitializedPaymentSourceResource, - CommercePaymentSourceJSON, - CommercePaymentSourceResource, - CommercePaymentSourceStatus, + BillingInitializedPaymentSourceJSON, + BillingInitializedPaymentSourceResource, + BillingPaymentSourceJSON, + BillingPaymentSourceResource, + BillingPaymentSourceStatus, DeletedObjectJSON, MakeDefaultPaymentSourceParams, RemovePaymentSourceParams, @@ -11,22 +11,22 @@ import type { import { BaseResource, DeletedObject } from './internal'; -export class CommercePaymentSource extends BaseResource implements CommercePaymentSourceResource { +export class BillingPaymentSource extends BaseResource implements BillingPaymentSourceResource { id!: string; last4!: string; paymentMethod!: string; cardType!: string; isDefault!: boolean; isRemovable!: boolean; - status!: CommercePaymentSourceStatus; + status!: BillingPaymentSourceStatus; walletType: string | undefined; - constructor(data: CommercePaymentSourceJSON) { + constructor(data: BillingPaymentSourceJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommercePaymentSourceJSON | null): this { + protected fromJSON(data: BillingPaymentSourceJSON | null): this { if (!data) { return this; } @@ -71,17 +71,17 @@ export class CommercePaymentSource extends BaseResource implements CommercePayme } } -export class CommerceInitializedPaymentSource extends BaseResource implements CommerceInitializedPaymentSourceResource { +export class BillingInitializedPaymentSource extends BaseResource implements BillingInitializedPaymentSourceResource { externalClientSecret!: string; externalGatewayId!: string; paymentMethodOrder!: string[]; - constructor(data: CommerceInitializedPaymentSourceJSON) { + constructor(data: BillingInitializedPaymentSourceJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceInitializedPaymentSourceJSON | null): this { + protected fromJSON(data: BillingInitializedPaymentSourceJSON | null): this { if (!data) { return this; } diff --git a/packages/clerk-js/src/core/resources/CommercePlan.ts b/packages/clerk-js/src/core/resources/CommercePlan.ts index ba55f177c12..c54f644b4ee 100644 --- a/packages/clerk-js/src/core/resources/CommercePlan.ts +++ b/packages/clerk-js/src/core/resources/CommercePlan.ts @@ -1,47 +1,42 @@ -import type { - CommerceMoneyAmount, - CommercePayerResourceType, - CommercePlanJSON, - CommercePlanResource, -} from '@clerk/types'; +import type { BillingMoneyAmount, BillingPayerResourceType, BillingPlanJSON, BillingPlanResource } from '@clerk/types'; -import { commerceMoneyAmountFromJSON } from '@/utils/commerce'; +import { billingMoneyAmountFromJSON } from '@/utils/commerce'; -import { BaseResource, CommerceFeature } from './internal'; +import { BaseResource, Feature } from './internal'; -export class CommercePlan extends BaseResource implements CommercePlanResource { +export class BillingPlan extends BaseResource implements BillingPlanResource { id!: string; name!: string; - fee!: CommerceMoneyAmount; - annualFee!: CommerceMoneyAmount; - annualMonthlyFee!: CommerceMoneyAmount; + fee!: BillingMoneyAmount; + annualFee!: BillingMoneyAmount; + annualMonthlyFee!: BillingMoneyAmount; description!: string; isDefault!: boolean; isRecurring!: boolean; hasBaseFee!: boolean; - forPayerType!: CommercePayerResourceType; + forPayerType!: BillingPayerResourceType; publiclyVisible!: boolean; slug!: string; avatarUrl!: string; - features!: CommerceFeature[]; + features!: Feature[]; freeTrialDays!: number | null; freeTrialEnabled!: boolean; - constructor(data: CommercePlanJSON) { + constructor(data: BillingPlanJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommercePlanJSON | null): this { + protected fromJSON(data: BillingPlanJSON | null): this { if (!data) { return this; } this.id = data.id; this.name = data.name; - this.fee = commerceMoneyAmountFromJSON(data.fee); - this.annualFee = commerceMoneyAmountFromJSON(data.annual_fee); - this.annualMonthlyFee = commerceMoneyAmountFromJSON(data.annual_monthly_fee); + this.fee = billingMoneyAmountFromJSON(data.fee); + this.annualFee = billingMoneyAmountFromJSON(data.annual_fee); + this.annualMonthlyFee = billingMoneyAmountFromJSON(data.annual_monthly_fee); this.description = data.description; this.isDefault = data.is_default; this.isRecurring = data.is_recurring; @@ -52,7 +47,7 @@ export class CommercePlan extends BaseResource implements CommercePlanResource { this.avatarUrl = data.avatar_url; this.freeTrialDays = this.withDefault(data.free_trial_days, null); this.freeTrialEnabled = this.withDefault(data.free_trial_enabled, false); - this.features = (data.features || []).map(feature => new CommerceFeature(feature)); + this.features = (data.features || []).map(feature => new Feature(feature)); return this; } diff --git a/packages/clerk-js/src/core/resources/CommerceStatement.ts b/packages/clerk-js/src/core/resources/CommerceStatement.ts index 0ae065dbd63..aa52c6aea1e 100644 --- a/packages/clerk-js/src/core/resources/CommerceStatement.ts +++ b/packages/clerk-js/src/core/resources/CommerceStatement.ts @@ -1,28 +1,28 @@ import type { - CommerceStatementGroupJSON, - CommerceStatementJSON, - CommerceStatementResource, - CommerceStatementStatus, - CommerceStatementTotals, + BillingStatementGroupJSON, + BillingStatementJSON, + BillingStatementResource, + BillingStatementStatus, + BillingStatementTotals, } from '@clerk/types'; -import { commerceTotalsFromJSON } from '../../utils'; +import { billingTotalsFromJSON } from '../../utils'; import { unixEpochToDate } from '../../utils/date'; -import { BaseResource, CommercePayment } from './internal'; +import { BaseResource, BillingPayment } from './internal'; -export class CommerceStatement extends BaseResource implements CommerceStatementResource { +export class BillingStatement extends BaseResource implements BillingStatementResource { id!: string; - status!: CommerceStatementStatus; + status!: BillingStatementStatus; timestamp!: Date; - totals!: CommerceStatementTotals; - groups!: CommerceStatementGroup[]; + totals!: BillingStatementTotals; + groups!: BillingStatementGroup[]; - constructor(data: CommerceStatementJSON) { + constructor(data: BillingStatementJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceStatementJSON | null): this { + protected fromJSON(data: BillingStatementJSON | null): this { if (!data) { return this; } @@ -30,29 +30,29 @@ export class CommerceStatement extends BaseResource implements CommerceStatement this.id = data.id; this.status = data.status; this.timestamp = unixEpochToDate(data.timestamp); - this.totals = commerceTotalsFromJSON(data.totals); - this.groups = data.groups.map(group => new CommerceStatementGroup(group)); + this.totals = billingTotalsFromJSON(data.totals); + this.groups = data.groups.map(group => new BillingStatementGroup(group)); return this; } } -export class CommerceStatementGroup { +export class BillingStatementGroup { id!: string; timestamp!: Date; - items!: CommercePayment[]; + items!: BillingPayment[]; - constructor(data: CommerceStatementGroupJSON) { + constructor(data: BillingStatementGroupJSON) { this.fromJSON(data); } - protected fromJSON(data: CommerceStatementGroupJSON | null): this { + protected fromJSON(data: BillingStatementGroupJSON | null): this { if (!data) { return this; } this.id = data.id; this.timestamp = unixEpochToDate(data.timestamp); - this.items = data.items.map(item => new CommercePayment(item)); + this.items = data.items.map(item => new BillingPayment(item)); return this; } } diff --git a/packages/clerk-js/src/core/resources/CommerceSubscription.ts b/packages/clerk-js/src/core/resources/CommerceSubscription.ts index 5677cff4f01..a5550d4c8d8 100644 --- a/packages/clerk-js/src/core/resources/CommerceSubscription.ts +++ b/packages/clerk-js/src/core/resources/CommerceSubscription.ts @@ -1,40 +1,40 @@ import type { + BillingMoneyAmount, + BillingSubscriptionItemJSON, + BillingSubscriptionItemResource, + BillingSubscriptionJSON, + BillingSubscriptionPlanPeriod, + BillingSubscriptionResource, + BillingSubscriptionStatus, CancelSubscriptionParams, - CommerceMoneyAmount, - CommerceSubscriptionItemJSON, - CommerceSubscriptionItemResource, - CommerceSubscriptionJSON, - CommerceSubscriptionPlanPeriod, - CommerceSubscriptionResource, - CommerceSubscriptionStatus, DeletedObjectJSON, } from '@clerk/types'; import { unixEpochToDate } from '@/utils/date'; -import { commerceMoneyAmountFromJSON } from '../../utils'; -import { BaseResource, CommercePlan, DeletedObject } from './internal'; +import { billingMoneyAmountFromJSON } from '../../utils'; +import { BaseResource, BillingPlan, DeletedObject } from './internal'; -export class CommerceSubscription extends BaseResource implements CommerceSubscriptionResource { +export class BillingSubscription extends BaseResource implements BillingSubscriptionResource { id!: string; - status!: Extract; + status!: Extract; activeAt!: Date; createdAt!: Date; pastDueAt!: Date | null; updatedAt!: Date | null; nextPayment: { - amount: CommerceMoneyAmount; + amount: BillingMoneyAmount; date: Date; } | null = null; - subscriptionItems!: CommerceSubscriptionItemResource[]; + subscriptionItems!: BillingSubscriptionItemResource[]; eligibleForFreeTrial?: boolean; - constructor(data: CommerceSubscriptionJSON) { + constructor(data: BillingSubscriptionJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceSubscriptionJSON | null): this { + protected fromJSON(data: BillingSubscriptionJSON | null): this { if (!data) { return this; } @@ -47,47 +47,47 @@ export class CommerceSubscription extends BaseResource implements CommerceSubscr this.pastDueAt = data.past_due_at ? unixEpochToDate(data.past_due_at) : null; this.nextPayment = data.next_payment ? { - amount: commerceMoneyAmountFromJSON(data.next_payment.amount), + amount: billingMoneyAmountFromJSON(data.next_payment.amount), date: unixEpochToDate(data.next_payment.date), } : null; - this.subscriptionItems = (data.subscription_items || []).map(item => new CommerceSubscriptionItem(item)); + this.subscriptionItems = (data.subscription_items || []).map(item => new BillingSubscriptionItem(item)); this.eligibleForFreeTrial = this.withDefault(data.eligible_for_free_trial, false); return this; } } -export class CommerceSubscriptionItem extends BaseResource implements CommerceSubscriptionItemResource { +export class BillingSubscriptionItem extends BaseResource implements BillingSubscriptionItemResource { id!: string; paymentSourceId!: string; - plan!: CommercePlan; - planPeriod!: CommerceSubscriptionPlanPeriod; - status!: CommerceSubscriptionStatus; + plan!: BillingPlan; + planPeriod!: BillingSubscriptionPlanPeriod; + status!: BillingSubscriptionStatus; createdAt!: Date; periodStart!: Date; periodEnd!: Date | null; canceledAt!: Date | null; pastDueAt!: Date | null; //TODO(@COMMERCE): Why can this be undefined ? - amount?: CommerceMoneyAmount; + amount?: BillingMoneyAmount; credit?: { - amount: CommerceMoneyAmount; + amount: BillingMoneyAmount; }; isFreeTrial!: boolean; - constructor(data: CommerceSubscriptionItemJSON) { + constructor(data: BillingSubscriptionItemJSON) { super(); this.fromJSON(data); } - protected fromJSON(data: CommerceSubscriptionItemJSON | null): this { + protected fromJSON(data: BillingSubscriptionItemJSON | null): this { if (!data) { return this; } this.id = data.id; this.paymentSourceId = data.payment_source_id; - this.plan = new CommercePlan(data.plan); + this.plan = new BillingPlan(data.plan); this.planPeriod = data.plan_period; this.status = data.status; @@ -98,9 +98,9 @@ export class CommerceSubscriptionItem extends BaseResource implements CommerceSu this.periodEnd = data.period_end ? unixEpochToDate(data.period_end) : null; this.canceledAt = data.canceled_at ? unixEpochToDate(data.canceled_at) : null; - this.amount = data.amount ? commerceMoneyAmountFromJSON(data.amount) : undefined; + this.amount = data.amount ? billingMoneyAmountFromJSON(data.amount) : undefined; this.credit = - data.credit && data.credit.amount ? { amount: commerceMoneyAmountFromJSON(data.credit.amount) } : undefined; + data.credit && data.credit.amount ? { amount: billingMoneyAmountFromJSON(data.credit.amount) } : undefined; this.isFreeTrial = this.withDefault(data.is_free_trial, false); return this; diff --git a/packages/clerk-js/src/core/warnings.ts b/packages/clerk-js/src/core/warnings.ts index 09f86d7a925..113ba5a1718 100644 --- a/packages/clerk-js/src/core/warnings.ts +++ b/packages/clerk-js/src/core/warnings.ts @@ -16,9 +16,9 @@ const createMessageForDisabledOrganizations = ( `The <${componentName}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`, ); }; -const createMessageForDisabledCommerce = (componentName: 'PricingTable' | 'Checkout' | 'PlanDetails') => { +const createMessageForDisabledBilling = (componentName: 'PricingTable' | 'Checkout' | 'PlanDetails') => { return formatWarning( - `The <${componentName}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable commerce. Since commerce is disabled, this is no-op.`, + `The <${componentName}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`, ); }; const warnings = { @@ -38,7 +38,7 @@ const warnings = { ' cannot render unless a user is signed in. Since no user is signed in, this is no-op.', cannotRenderComponentWhenOrgDoesNotExist: ` cannot render unless an organization is active. Since no organization is currently active, this is no-op.`, cannotRenderAnyOrganizationComponent: createMessageForDisabledOrganizations, - cannotRenderAnyCommerceComponent: createMessageForDisabledCommerce, + cannotRenderAnyBillingComponent: createMessageForDisabledBilling, cannotOpenUserProfile: 'The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.', cannotOpenCheckout: diff --git a/packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx b/packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx index b1ac58052a1..1178a58dc37 100644 --- a/packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx +++ b/packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx @@ -1,5 +1,5 @@ import { __experimental_useCheckout as useCheckout } from '@clerk/shared/react'; -import type { CommerceMoneyAmount, CommercePaymentSourceResource, ConfirmCheckoutParams } from '@clerk/types'; +import type { BillingMoneyAmount, BillingPaymentSourceResource, ConfirmCheckoutParams } from '@clerk/types'; import { useMemo, useState } from 'react'; import { Card } from '@/ui/elements/Card'; @@ -366,8 +366,8 @@ const ExistingPaymentSourceForm = withCardStateProvider( totalDueNow, paymentSources, }: { - totalDueNow: CommerceMoneyAmount; - paymentSources: CommercePaymentSourceResource[]; + totalDueNow: BillingMoneyAmount; + paymentSources: BillingPaymentSourceResource[]; }) => { const submitLabel = useSubmitLabel(); const { checkout } = useCheckout(); @@ -375,7 +375,7 @@ const ExistingPaymentSourceForm = withCardStateProvider( const { payWithExistingPaymentSource } = useCheckoutMutations(); const card = useCardState(); - const [selectedPaymentSource, setSelectedPaymentSource] = useState( + const [selectedPaymentSource, setSelectedPaymentSource] = useState( paymentSource || paymentSources.find(p => p.isDefault), ); diff --git a/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx b/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx index 182dec622a4..1987114f6ac 100644 --- a/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx +++ b/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx @@ -1,5 +1,5 @@ import { useClerk, useOrganization } from '@clerk/shared/react'; -import type { CommerceSubscriptionItemResource } from '@clerk/types'; +import type { BillingSubscriptionItemResource } from '@clerk/types'; import useSWR from 'swr'; import { Alert } from '@/ui/elements/Alert'; @@ -209,7 +209,7 @@ export const PaymentAttemptPage = () => { ); }; -function PaymentAttemptBody({ subscriptionItem }: { subscriptionItem: CommerceSubscriptionItemResource | undefined }) { +function PaymentAttemptBody({ subscriptionItem }: { subscriptionItem: BillingSubscriptionItemResource | undefined }) { if (!subscriptionItem) { return null; } diff --git a/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptsList.tsx b/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptsList.tsx index 19c7221bd1f..f9cbc3b1baf 100644 --- a/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptsList.tsx +++ b/packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptsList.tsx @@ -1,4 +1,4 @@ -import type { CommercePaymentResource } from '@clerk/types'; +import type { BillingPaymentResource } from '@clerk/types'; import { DataTable, DataTableRow } from '@/ui/elements/DataTable'; import { formatDate } from '@/ui/utils/formatDate'; @@ -40,7 +40,7 @@ export const PaymentAttemptsList = () => { ); }; -const PaymentAttemptsListRow = ({ paymentAttempt }: { paymentAttempt: CommercePaymentResource }) => { +const PaymentAttemptsListRow = ({ paymentAttempt }: { paymentAttempt: BillingPaymentResource }) => { const { id, amount, failedAt, paidAt, updatedAt, status } = paymentAttempt; const { navigate } = useRouter(); const handleClick = () => { diff --git a/packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx b/packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx index 16632e90e23..e97fbf2e37b 100644 --- a/packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx +++ b/packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx @@ -1,9 +1,9 @@ -import type { CommercePaymentSourceResource } from '@clerk/types'; +import type { BillingPaymentSourceResource } from '@clerk/types'; import { Badge, descriptors, Flex, Icon, localizationKeys, Text } from '../../customizables'; import { CreditCard, GenericPayment } from '../../icons'; -export const PaymentSourceRow = ({ paymentSource }: { paymentSource: CommercePaymentSourceResource }) => { +export const PaymentSourceRow = ({ paymentSource }: { paymentSource: BillingPaymentSourceResource }) => { return ( void; }) => { const { close } = useActionContext(); @@ -193,7 +193,7 @@ const PaymentSourceMenu = ({ paymentSource, revalidate, }: { - paymentSource: CommercePaymentSourceResource; + paymentSource: BillingPaymentSourceResource; revalidate: () => void; }) => { const { open } = useActionContext(); diff --git a/packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx b/packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx index d32194fd744..18005f87926 100644 --- a/packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx +++ b/packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx @@ -1,9 +1,9 @@ import { useClerk } from '@clerk/shared/react'; import type { __internal_PlanDetailsProps, + BillingPlanResource, + BillingSubscriptionPlanPeriod, ClerkAPIResponseError, - CommercePlanResource, - CommerceSubscriptionPlanPeriod, } from '@clerk/types'; import * as React from 'react'; import { useMemo, useState } from 'react'; @@ -80,13 +80,13 @@ const PlanDetailsInternal = ({ initialPlanPeriod = 'month', }: __internal_PlanDetailsProps) => { const clerk = useClerk(); - const [planPeriod, setPlanPeriod] = useState(initialPlanPeriod); + const [planPeriod, setPlanPeriod] = useState(initialPlanPeriod); const { data: plan, isLoading, error, - } = useSWR( + } = useSWR( planId || initialPlan ? { type: 'plan', id: planId || initialPlan?.id } : null, // @ts-expect-error we are handling it above () => clerk.billing.getPlan({ id: planId || initialPlan?.id }), @@ -217,9 +217,9 @@ const PlanDetailsInternal = ({ * -----------------------------------------------------------------------------------------------*/ interface HeaderProps { - plan: CommercePlanResource; - planPeriod: CommerceSubscriptionPlanPeriod; - setPlanPeriod: (val: CommerceSubscriptionPlanPeriod) => void; + plan: BillingPlanResource; + planPeriod: BillingSubscriptionPlanPeriod; + setPlanPeriod: (val: BillingSubscriptionPlanPeriod) => void; closeSlot?: React.ReactNode; } diff --git a/packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx b/packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx index 24c0f739284..08ff6ee7c6f 100644 --- a/packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx +++ b/packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx @@ -1,5 +1,5 @@ import { useClerk } from '@clerk/shared/react'; -import type { CommercePlanResource, CommerceSubscriptionPlanPeriod, PricingTableProps } from '@clerk/types'; +import type { BillingPlanResource, BillingSubscriptionPlanPeriod, PricingTableProps } from '@clerk/types'; import { useEffect, useMemo, useState } from 'react'; import { Flow } from '@/ui/customizables/Flow'; @@ -43,13 +43,13 @@ const PricingTableRoot = (props: PricingTableProps) => { return 'annual'; }, [isCompact, subscriptionItems]); - const [planPeriod, setPlanPeriod] = useState(defaultPlanPeriod); + const [planPeriod, setPlanPeriod] = useState(defaultPlanPeriod); useEffect(() => { setPlanPeriod(defaultPlanPeriod); }, [defaultPlanPeriod]); - const selectPlan = (plan: CommercePlanResource, event?: React.MouseEvent) => { + const selectPlan = (plan: BillingPlanResource, event?: React.MouseEvent) => { if (!clerk.isSignedIn) { if (signInMode === 'modal') { return clerk.openSignIn(); diff --git a/packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx b/packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx index 5e623e6c69a..40ef79be015 100644 --- a/packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx +++ b/packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx @@ -1,5 +1,5 @@ import { useClerk, useSession } from '@clerk/shared/react'; -import type { CommercePlanResource, CommerceSubscriptionPlanPeriod, PricingTableProps } from '@clerk/types'; +import type { BillingPlanResource, BillingSubscriptionPlanPeriod, PricingTableProps } from '@clerk/types'; import * as React from 'react'; import { Switch } from '@/ui/elements/Switch'; @@ -26,11 +26,11 @@ import { common, InternalThemeProvider } from '../../styledSystem'; import { SubscriptionBadge } from '../Subscriptions/badge'; interface PricingTableDefaultProps { - plans?: CommercePlanResource[] | null; - highlightedPlan?: CommercePlanResource['slug']; - planPeriod: CommerceSubscriptionPlanPeriod; - setPlanPeriod: (val: CommerceSubscriptionPlanPeriod) => void; - onSelect: (plan: CommercePlanResource) => void; + plans?: BillingPlanResource[] | null; + highlightedPlan?: BillingPlanResource['slug']; + planPeriod: BillingSubscriptionPlanPeriod; + setPlanPeriod: (val: BillingSubscriptionPlanPeriod) => void; + onSelect: (plan: BillingPlanResource) => void; isCompact?: boolean; props: PricingTableProps; } @@ -89,10 +89,10 @@ export function PricingTableDefault({ * -----------------------------------------------------------------------------------------------*/ interface CardProps { - plan: CommercePlanResource; - planPeriod: CommerceSubscriptionPlanPeriod; - setPlanPeriod: (p: CommerceSubscriptionPlanPeriod) => void; - onSelect: (plan: CommercePlanResource, event?: React.MouseEvent) => void; + plan: BillingPlanResource; + planPeriod: BillingSubscriptionPlanPeriod; + setPlanPeriod: (p: BillingSubscriptionPlanPeriod) => void; + onSelect: (plan: BillingPlanResource, event?: React.MouseEvent) => void; isCompact?: boolean; props: PricingTableProps; } @@ -290,10 +290,10 @@ function Card(props: CardProps) { * -----------------------------------------------------------------------------------------------*/ interface CardHeaderProps { - plan: CommercePlanResource; + plan: BillingPlanResource; isCompact?: boolean; - planPeriod: CommerceSubscriptionPlanPeriod; - setPlanPeriod: (val: CommerceSubscriptionPlanPeriod) => void; + planPeriod: BillingSubscriptionPlanPeriod; + setPlanPeriod: (val: BillingSubscriptionPlanPeriod) => void; badge?: React.ReactNode; } @@ -432,7 +432,7 @@ const CardHeader = React.forwardRef((props, ref * -----------------------------------------------------------------------------------------------*/ interface CardFeaturesListProps { - plan: CommercePlanResource; + plan: BillingPlanResource; /** * @default false */ diff --git a/packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx b/packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx index 7255c98744e..c0c7ff2cc7e 100644 --- a/packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx +++ b/packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx @@ -1,4 +1,4 @@ -import type { CommercePlanResource, CommerceSubscriptionPlanPeriod } from '@clerk/types'; +import type { BillingPlanResource, BillingSubscriptionPlanPeriod } from '@clerk/types'; import * as React from 'react'; import { Avatar } from '@/ui/elements/Avatar'; @@ -25,11 +25,11 @@ import { Check, InformationCircle } from '../../icons'; import { common, InternalThemeProvider, mqu, type ThemableCssProp } from '../../styledSystem'; interface PricingTableMatrixProps { - plans: CommercePlanResource[] | undefined; - highlightedPlan?: CommercePlanResource['slug']; - planPeriod: CommerceSubscriptionPlanPeriod; - setPlanPeriod: (val: CommerceSubscriptionPlanPeriod) => void; - onSelect: (plan: CommercePlanResource, event?: React.MouseEvent) => void; + plans: BillingPlanResource[] | undefined; + highlightedPlan?: BillingPlanResource['slug']; + planPeriod: BillingSubscriptionPlanPeriod; + setPlanPeriod: (val: BillingSubscriptionPlanPeriod) => void; + onSelect: (plan: BillingPlanResource, event?: React.MouseEvent) => void; } export function PricingTableMatrix({ @@ -140,7 +140,7 @@ export function PricingTableMatrix({ setPlanPeriod(value as CommerceSubscriptionPlanPeriod)} + onChange={value => setPlanPeriod(value as BillingSubscriptionPlanPeriod)} > { ); }; -const StatementsListRow = ({ statement }: { statement: CommerceStatementResource }) => { +const StatementsListRow = ({ statement }: { statement: BillingStatementResource }) => { const { timestamp, id, diff --git a/packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx b/packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx index 20feaae9f1a..8359687104a 100644 --- a/packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx +++ b/packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx @@ -2,8 +2,8 @@ import { useClerk, useOrganization } from '@clerk/shared/react'; import type { __internal_CheckoutProps, __internal_SubscriptionDetailsProps, - CommercePlanResource, - CommerceSubscriptionItemResource, + BillingPlanResource, + BillingSubscriptionItemResource, } from '@clerk/types'; import * as React from 'react'; import { useCallback, useContext, useState } from 'react'; @@ -44,12 +44,12 @@ import { } from '../../customizables'; import { SubscriptionBadge } from '../Subscriptions/badge'; -const isFreePlan = (plan: CommercePlanResource) => !plan.hasBaseFee; +const isFreePlan = (plan: BillingPlanResource) => !plan.hasBaseFee; // We cannot derive the state of confirmation modal from the existence subscription, as it will make the animation laggy when the confirmation closes. const SubscriptionForCancellationContext = React.createContext<{ - subscription: CommerceSubscriptionItemResource | null; - setSubscription: (subscription: CommerceSubscriptionItemResource | null) => void; + subscription: BillingSubscriptionItemResource | null; + setSubscription: (subscription: BillingSubscriptionItemResource | null) => void; confirmationOpen: boolean; setConfirmationOpen: (confirmationOpen: boolean) => void; }>({ @@ -77,17 +77,17 @@ export const SubscriptionDetails = (props: __internal_SubscriptionDetailsProps) type UseGuessableSubscriptionResult = Or extends 'throw' ? { - upcomingSubscription?: CommerceSubscriptionItemResource; - pastDueSubscription?: CommerceSubscriptionItemResource; - activeSubscription?: CommerceSubscriptionItemResource; - anySubscription: CommerceSubscriptionItemResource; + upcomingSubscription?: BillingSubscriptionItemResource; + pastDueSubscription?: BillingSubscriptionItemResource; + activeSubscription?: BillingSubscriptionItemResource; + anySubscription: BillingSubscriptionItemResource; isLoading: boolean; } : { - upcomingSubscription?: CommerceSubscriptionItemResource; - pastDueSubscription?: CommerceSubscriptionItemResource; - activeSubscription?: CommerceSubscriptionItemResource; - anySubscription?: CommerceSubscriptionItemResource; + upcomingSubscription?: BillingSubscriptionItemResource; + pastDueSubscription?: BillingSubscriptionItemResource; + activeSubscription?: BillingSubscriptionItemResource; + anySubscription?: BillingSubscriptionItemResource; isLoading: boolean; }; @@ -114,7 +114,7 @@ function useGuessableSubscription(op const SubscriptionDetailsInternal = (props: __internal_SubscriptionDetailsProps) => { const [subscriptionForCancellation, setSubscriptionForCancellation] = - useState(null); + useState(null); const [confirmationOpen, setConfirmationOpen] = useState(false); const { subscriptionItems, isLoading } = useSubscription(); @@ -363,7 +363,7 @@ function SubscriptionDetailsSummary() { ); } -const SubscriptionCardActions = ({ subscription }: { subscription: CommerceSubscriptionItemResource }) => { +const SubscriptionCardActions = ({ subscription }: { subscription: BillingSubscriptionItemResource }) => { const { portalRoot } = useSubscriptionDetailsContext(); const { __internal_openCheckout } = useClerk(); const subscriberType = useSubscriberTypeContext(); @@ -477,7 +477,7 @@ const SubscriptionCardActions = ({ subscription }: { subscription: CommerceSubsc }; // New component for individual subscription cards -const SubscriptionCard = ({ subscription }: { subscription: CommerceSubscriptionItemResource }) => { +const SubscriptionCard = ({ subscription }: { subscription: BillingSubscriptionItemResource }) => { const { t } = useLocalizations(); const fee = subscription.planPeriod === 'month' ? subscription.plan.fee : subscription.plan.annualFee; diff --git a/packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx b/packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx index c0178be0ee9..4ecd5bc38b2 100644 --- a/packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx +++ b/packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx @@ -1,4 +1,4 @@ -import type { CommercePlanResource, CommerceSubscriptionItemResource } from '@clerk/types'; +import type { BillingPlanResource, BillingSubscriptionItemResource } from '@clerk/types'; import { useMemo } from 'react'; import { useProtect } from '@/ui/common/Gate'; @@ -18,7 +18,7 @@ import { ArrowsUpDown, CogFilled, Plans, Plus } from '../../icons'; import { useRouter } from '../../router'; import { SubscriptionBadge } from './badge'; -const isFreePlan = (plan: CommercePlanResource) => !plan.hasBaseFee; +const isFreePlan = (plan: BillingPlanResource) => !plan.hasBaseFee; export function SubscriptionsList({ title, @@ -152,7 +152,7 @@ export function SubscriptionsList({ ); } -function SubscriptionRow({ subscription, length }: { subscription: CommerceSubscriptionItemResource; length: number }) { +function SubscriptionRow({ subscription, length }: { subscription: BillingSubscriptionItemResource; length: number }) { const fee = subscription.planPeriod === 'annual' ? subscription.plan.annualFee : subscription.plan.fee; const { captionForSubscription } = usePlansContext(); diff --git a/packages/clerk-js/src/ui/components/Subscriptions/__tests__/SubscriptionsList.test.tsx b/packages/clerk-js/src/ui/components/Subscriptions/__tests__/SubscriptionsList.test.tsx index a0284640073..988b5a3e5bc 100644 --- a/packages/clerk-js/src/ui/components/Subscriptions/__tests__/SubscriptionsList.test.tsx +++ b/packages/clerk-js/src/ui/components/Subscriptions/__tests__/SubscriptionsList.test.tsx @@ -1,4 +1,4 @@ -import type { CommercePayerResourceType } from '@clerk/types'; +import type { BillingPayerResourceType } from '@clerk/types'; import { render, waitFor } from '../../../../testUtils'; import { localizationKeys } from '../../../customizables'; @@ -74,7 +74,7 @@ describe('SubscriptionsList', () => { isDefault: true, isRecurring: true, hasBaseFee: false, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'free-plan', avatarUrl: '', @@ -140,7 +140,7 @@ describe('SubscriptionsList', () => { isDefault: false, isRecurring: true, hasBaseFee: true, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'pro-plan', avatarUrl: '', @@ -204,7 +204,7 @@ describe('SubscriptionsList', () => { isDefault: false, isRecurring: true, hasBaseFee: true, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'pro-plan', avatarUrl: '', @@ -269,7 +269,7 @@ describe('SubscriptionsList', () => { isDefault: false, isRecurring: true, hasBaseFee: true, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'pro-plan', avatarUrl: '', @@ -333,7 +333,7 @@ describe('SubscriptionsList', () => { isDefault: false, isRecurring: true, hasBaseFee: true, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'plus-plan', avatarUrl: '', @@ -369,7 +369,7 @@ describe('SubscriptionsList', () => { isDefault: false, isRecurring: true, hasBaseFee: true, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'pro-plan', avatarUrl: '', diff --git a/packages/clerk-js/src/ui/components/Subscriptions/badge.tsx b/packages/clerk-js/src/ui/components/Subscriptions/badge.tsx index eecba6b9abd..87249075782 100644 --- a/packages/clerk-js/src/ui/components/Subscriptions/badge.tsx +++ b/packages/clerk-js/src/ui/components/Subscriptions/badge.tsx @@ -1,4 +1,4 @@ -import type { CommerceSubscriptionItemResource } from '@clerk/types'; +import type { BillingSubscriptionItemResource } from '@clerk/types'; import { Badge, localizationKeys } from '@/ui/customizables'; import type { ElementDescriptor } from '@/ui/customizables/elementDescriptors'; @@ -17,7 +17,7 @@ const colors = { free_trial: 'secondary', }; -export const SubscriptionBadge = ({ +export const SubscriptionBadge = ({ subscription, elementDescriptor, }: { diff --git a/packages/clerk-js/src/ui/contexts/components/Plans.tsx b/packages/clerk-js/src/ui/contexts/components/Plans.tsx index f426e359447..5a402604a59 100644 --- a/packages/clerk-js/src/ui/contexts/components/Plans.tsx +++ b/packages/clerk-js/src/ui/contexts/components/Plans.tsx @@ -9,9 +9,9 @@ import { } from '@clerk/shared/react'; import type { Appearance, - CommercePlanResource, - CommerceSubscriptionItemResource, - CommerceSubscriptionPlanPeriod, + BillingPlanResource, + BillingSubscriptionItemResource, + BillingSubscriptionPlanPeriod, } from '@clerk/types'; import { useCallback, useMemo } from 'react'; @@ -90,8 +90,8 @@ export const usePlans = (params?: { mode: 'cache' }) => { }; type HandleSelectPlanProps = { - plan: CommercePlanResource; - planPeriod: CommerceSubscriptionPlanPeriod; + plan: BillingPlanResource; + planPeriod: BillingSubscriptionPlanPeriod; mode?: 'modal' | 'mounted'; event?: React.MouseEvent; appearance?: Appearance; @@ -141,7 +141,7 @@ export const usePlansContext = () => { // return the active or upcoming subscription for a plan if it exists const activeOrUpcomingSubscription = useCallback( - (plan: CommercePlanResource) => { + (plan: BillingPlanResource) => { return subscriptionItems.find(subscription => subscription.plan.id === plan.id); }, [subscriptionItems], @@ -149,7 +149,7 @@ export const usePlansContext = () => { // returns all subscriptions for a plan that are active or upcoming const activeAndUpcomingSubscriptions = useCallback( - (plan: CommercePlanResource) => { + (plan: BillingPlanResource) => { return subscriptionItems.filter(subscription => subscription.plan.id === plan.id); }, [subscriptionItems], @@ -157,7 +157,7 @@ export const usePlansContext = () => { // return the active or upcoming subscription for a plan based on the plan period, if there is no subscription for the plan period, return the first subscription const activeOrUpcomingSubscriptionWithPlanPeriod = useCallback( - (plan: CommercePlanResource, planPeriod: CommerceSubscriptionPlanPeriod = 'month') => { + (plan: BillingPlanResource, planPeriod: BillingSubscriptionPlanPeriod = 'month') => { const plansSubscriptions = activeAndUpcomingSubscriptions(plan); // Handle multiple subscriptions for the same plan if (plansSubscriptions.length > 1) { @@ -182,7 +182,7 @@ export const usePlansContext = () => { ); const canManageSubscription = useCallback( - ({ plan, subscription: sub }: { plan?: CommercePlanResource; subscription?: CommerceSubscriptionItemResource }) => { + ({ plan, subscription: sub }: { plan?: BillingPlanResource; subscription?: BillingSubscriptionItemResource }) => { const subscription = sub ?? (plan ? activeOrUpcomingSubscription(plan) : undefined); return !subscription || !subscription.canceledAt; @@ -199,10 +199,10 @@ export const usePlansContext = () => { isCompact = false, selectedPlanPeriod = 'annual', }: { - plan?: CommercePlanResource; - subscription?: CommerceSubscriptionItemResource; + plan?: BillingPlanResource; + subscription?: BillingSubscriptionItemResource; isCompact?: boolean; - selectedPlanPeriod?: CommerceSubscriptionPlanPeriod; + selectedPlanPeriod?: BillingSubscriptionPlanPeriod; }): { localizationKey: LocalizationKey; variant: 'bordered' | 'solid'; @@ -284,7 +284,7 @@ export const usePlansContext = () => { [activeOrUpcomingSubscriptionWithPlanPeriod, canManageBilling, subscriptionItems, topLevelSubscription], ); - const captionForSubscription = useCallback((subscription: CommerceSubscriptionItemResource) => { + const captionForSubscription = useCallback((subscription: BillingSubscriptionItemResource) => { if (subscription.pastDueAt) { return localizationKeys('badge__pastDueAt', { date: subscription.pastDueAt }); } diff --git a/packages/clerk-js/src/utils/commerce.ts b/packages/clerk-js/src/utils/commerce.ts index a705fa465c2..83a99444f64 100644 --- a/packages/clerk-js/src/utils/commerce.ts +++ b/packages/clerk-js/src/utils/commerce.ts @@ -1,13 +1,13 @@ import type { - CommerceCheckoutTotals, - CommerceCheckoutTotalsJSON, - CommerceMoneyAmount, - CommerceMoneyAmountJSON, - CommerceStatementTotals, - CommerceStatementTotalsJSON, + BillingCheckoutTotals, + BillingCheckoutTotalsJSON, + BillingMoneyAmount, + BillingMoneyAmountJSON, + BillingStatementTotals, + BillingStatementTotalsJSON, } from '@clerk/types'; -export const commerceMoneyAmountFromJSON = (data: CommerceMoneyAmountJSON): CommerceMoneyAmount => { +export const billingMoneyAmountFromJSON = (data: BillingMoneyAmountJSON): BillingMoneyAmount => { return { amount: data.amount, amountFormatted: data.amount_formatted, @@ -16,30 +16,28 @@ export const commerceMoneyAmountFromJSON = (data: CommerceMoneyAmountJSON): Comm }; }; -const hasPastDue = (data: unknown): data is { past_due: CommerceMoneyAmountJSON } => { +const hasPastDue = (data: unknown): data is { past_due: BillingMoneyAmountJSON } => { return typeof data === 'object' && data !== null && 'past_due' in data; }; -export const commerceTotalsFromJSON = ( +export const billingTotalsFromJSON = ( data: T, -): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => { - const totals: Partial = { - grandTotal: commerceMoneyAmountFromJSON(data.grand_total), - subtotal: commerceMoneyAmountFromJSON(data.subtotal), - taxTotal: commerceMoneyAmountFromJSON(data.tax_total), +): T extends { total_due_now: BillingMoneyAmountJSON } ? BillingCheckoutTotals : BillingStatementTotals => { + const totals: Partial = { + grandTotal: billingMoneyAmountFromJSON(data.grand_total), + subtotal: billingMoneyAmountFromJSON(data.subtotal), + taxTotal: billingMoneyAmountFromJSON(data.tax_total), }; if ('total_due_now' in data) { - totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now); + totals.totalDueNow = billingMoneyAmountFromJSON(data.total_due_now); } if ('credit' in data) { - totals.credit = commerceMoneyAmountFromJSON(data.credit); + totals.credit = billingMoneyAmountFromJSON(data.credit); } if (hasPastDue(data)) { - totals.pastDue = commerceMoneyAmountFromJSON(data.past_due); + totals.pastDue = billingMoneyAmountFromJSON(data.past_due); } - return totals as T extends { total_due_now: CommerceMoneyAmountJSON } - ? CommerceCheckoutTotals - : CommerceStatementTotals; + return totals as T extends { total_due_now: BillingMoneyAmountJSON } ? BillingCheckoutTotals : BillingStatementTotals; }; diff --git a/packages/react/src/components/__tests__/PlanDetailsButton.test.tsx b/packages/react/src/components/__tests__/PlanDetailsButton.test.tsx index f9e0b182a15..78c10a6f49c 100644 --- a/packages/react/src/components/__tests__/PlanDetailsButton.test.tsx +++ b/packages/react/src/components/__tests__/PlanDetailsButton.test.tsx @@ -1,6 +1,6 @@ import '@testing-library/jest-dom/vitest'; -import type { CommercePayerResourceType, CommercePlanResource, Theme } from '@clerk/types'; +import type { BillingPayerResourceType, BillingPlanResource, Theme } from '@clerk/types'; import { render, screen, waitFor } from '@testing-library/react'; import { userEvent } from '@testing-library/user-event'; import React from 'react'; @@ -28,7 +28,7 @@ vi.mock('../withClerk', () => { }; }); -const mockPlanResource: CommercePlanResource = { +const mockPlanResource: BillingPlanResource = { id: 'plan_123', name: 'Test Plan', fee: { @@ -53,7 +53,7 @@ const mockPlanResource: CommercePlanResource = { hasBaseFee: true, isRecurring: true, isDefault: false, - forPayerType: 'user' as CommercePayerResourceType, + forPayerType: 'user' as BillingPayerResourceType, publiclyVisible: true, slug: 'test-plan', avatarUrl: 'https://example.com/avatar.png', diff --git a/packages/react/src/isomorphicClerk.ts b/packages/react/src/isomorphicClerk.ts index 3fd9bf7061c..a53fd1d2984 100644 --- a/packages/react/src/isomorphicClerk.ts +++ b/packages/react/src/isomorphicClerk.ts @@ -16,12 +16,12 @@ import type { AuthenticateWithGoogleOneTapParams, AuthenticateWithMetamaskParams, AuthenticateWithOKXWalletParams, + BillingNamespace, Clerk, ClerkAuthenticateWithWeb3Params, ClerkOptions, ClerkStatus, ClientResource, - CommerceBillingNamespace, CreateOrganizationParams, CreateOrganizationProps, DomainOrProxyUrl, @@ -110,7 +110,7 @@ type IsomorphicLoadedClerk = Without< | '__internal_setActiveInProgress' > & { client: ClientResource | undefined; - billing: CommerceBillingNamespace | undefined; + billing: BillingNamespace | undefined; apiKeys: APIKeysNamespace | undefined; }; @@ -722,7 +722,7 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk { } } - get billing(): CommerceBillingNamespace | undefined { + get billing(): BillingNamespace | undefined { return this.clerkjs?.billing; } diff --git a/packages/shared/src/react/commerce.tsx b/packages/shared/src/react/commerce.tsx index e0660c9c6f3..72fd978f4b1 100644 --- a/packages/shared/src/react/commerce.tsx +++ b/packages/shared/src/react/commerce.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/consistent-type-imports */ -import type { CommerceCheckoutResource, EnvironmentResource, ForPayerType } from '@clerk/types'; +import type { BillingCheckoutResource, EnvironmentResource, ForPayerType } from '@clerk/types'; import type { Stripe, StripeElements } from '@stripe/stripe-js'; import React, { type PropsWithChildren, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; import useSWR from 'swr'; @@ -70,7 +70,7 @@ const usePaymentSourceUtils = (forResource: ForPayerType = 'user') => { const { data: initializedPaymentSource, trigger: initializePaymentSource } = useSWRMutation( { - key: 'commerce-payment-source-initialize', + key: 'billing-payment-source-initialize', resourceId: resource?.id, }, () => { @@ -140,7 +140,7 @@ type internalStripeAppearance = { }; type PaymentElementProviderProps = { - checkout?: CommerceCheckoutResource | ReturnType['checkout']; + checkout?: BillingCheckoutResource | ReturnType['checkout']; stripeAppearance?: internalStripeAppearance; /** * Default to `user` if not provided. diff --git a/packages/shared/src/react/contexts.tsx b/packages/shared/src/react/contexts.tsx index fef63ad0517..c54ea6f7a2a 100644 --- a/packages/shared/src/react/contexts.tsx +++ b/packages/shared/src/react/contexts.tsx @@ -1,9 +1,9 @@ 'use client'; import type { + BillingSubscriptionPlanPeriod, ClerkOptions, ClientResource, - CommerceSubscriptionPlanPeriod, ForPayerType, LoadedClerk, OrganizationResource, @@ -27,7 +27,7 @@ const OptionsContext = React.createContext({}); type UseCheckoutOptions = { for?: ForPayerType; - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; planId: string; }; diff --git a/packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts b/packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts index fc4ad905655..fcfaa8f00a1 100644 --- a/packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts +++ b/packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts @@ -1,9 +1,9 @@ import type { __experimental_CheckoutCacheState, __experimental_CheckoutInstance, + BillingCheckoutResource, + BillingSubscriptionPlanPeriod, ClerkAPIResponseError, - CommerceCheckoutResource, - CommerceSubscriptionPlanPeriod, ConfirmCheckoutParams, SetActiveNavigate, } from '@clerk/types'; @@ -24,7 +24,7 @@ describe('useCheckout type tests', () => { type ValidOptions = { for: 'organization'; planId: string; - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; }; expectTypeOf().toMatchTypeOf(); }); @@ -33,7 +33,7 @@ describe('useCheckout type tests', () => { type InvalidOptions = { for: 'invalid'; planId: string; - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; }; expectTypeOf().not.toEqualTypeOf(); }); @@ -51,7 +51,7 @@ describe('useCheckout type tests', () => { type InvalidOptions = { for: 'organization'; planId: string; - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; invalidProp: boolean; }; expectTypeOf().not.toEqualTypeOf(); @@ -78,7 +78,7 @@ describe('useCheckout type tests', () => { type CheckoutResult = | { - data: CommerceCheckoutResource; + data: BillingCheckoutResource; error: null; } | { @@ -101,7 +101,7 @@ describe('useCheckout type tests', () => { type CheckoutResult = | { - data: CommerceCheckoutResource; + data: BillingCheckoutResource; error: null; } | { diff --git a/packages/shared/src/react/hooks/createCommerceHook.tsx b/packages/shared/src/react/hooks/createCommerceHook.tsx index 9abaa5ce5dc..971ef67a438 100644 --- a/packages/shared/src/react/hooks/createCommerceHook.tsx +++ b/packages/shared/src/react/hooks/createCommerceHook.tsx @@ -110,3 +110,6 @@ export function createCommercePaginatedHook = { [K in keyof T]: null; }; -type CheckoutProperties = Omit, 'pathRoot' | 'status'>; +type CheckoutProperties = Omit, 'pathRoot' | 'status'>; type FetchStatusAndError = | { diff --git a/packages/shared/src/react/hooks/usePaymentAttempts.tsx b/packages/shared/src/react/hooks/usePaymentAttempts.tsx index 6c01fea08db..fe90e424dee 100644 --- a/packages/shared/src/react/hooks/usePaymentAttempts.tsx +++ b/packages/shared/src/react/hooks/usePaymentAttempts.tsx @@ -1,14 +1,14 @@ -import type { CommercePaymentResource, GetPaymentAttemptsParams } from '@clerk/types'; +import type { BillingPaymentResource, GetPaymentAttemptsParams } from '@clerk/types'; import { useClerkInstanceContext } from '../contexts'; -import { createCommercePaginatedHook } from './createCommerceHook'; +import { createBillingPaginatedHook as createCommercePaginatedHook } from './createCommerceHook'; /** * @internal */ -export const usePaymentAttempts = createCommercePaginatedHook({ +export const usePaymentAttempts = createCommercePaginatedHook({ hookName: 'usePaymentAttempts', - resourceType: 'commerce-payment-attempts', + resourceType: 'billing-payment-attempts', useFetcher: () => { const clerk = useClerkInstanceContext(); if (clerk.loaded) { diff --git a/packages/shared/src/react/hooks/usePaymentMethods.tsx b/packages/shared/src/react/hooks/usePaymentMethods.tsx index 62ceaad9c91..94310e1d114 100644 --- a/packages/shared/src/react/hooks/usePaymentMethods.tsx +++ b/packages/shared/src/react/hooks/usePaymentMethods.tsx @@ -1,4 +1,4 @@ -import type { CommercePaymentSourceResource, GetPaymentSourcesParams } from '@clerk/types'; +import type { BillingPaymentSourceResource, GetPaymentSourcesParams } from '@clerk/types'; import { useOrganizationContext, useUserContext } from '../contexts'; import { createCommercePaginatedHook } from './createCommerceHook'; @@ -6,7 +6,7 @@ import { createCommercePaginatedHook } from './createCommerceHook'; /** * @internal */ -export const usePaymentMethods = createCommercePaginatedHook({ +export const usePaymentMethods = createCommercePaginatedHook({ hookName: 'usePaymentMethods', resourceType: 'commerce-payment-methods', useFetcher: resource => { diff --git a/packages/shared/src/react/hooks/usePlans.tsx b/packages/shared/src/react/hooks/usePlans.tsx index 604f94ae48c..3ae4bfe7c56 100644 --- a/packages/shared/src/react/hooks/usePlans.tsx +++ b/packages/shared/src/react/hooks/usePlans.tsx @@ -1,14 +1,14 @@ -import type { CommercePlanResource, GetPlansParams } from '@clerk/types'; +import type { BillingPlanResource, GetPlansParams } from '@clerk/types'; import { useClerkInstanceContext } from '../contexts'; -import { createCommercePaginatedHook } from './createCommerceHook'; +import { createBillingPaginatedHook as createCommercePaginatedHook } from './createCommerceHook'; /** * @internal */ -export const usePlans = createCommercePaginatedHook({ +export const usePlans = createCommercePaginatedHook({ hookName: 'usePlans', - resourceType: 'commerce-plans', + resourceType: 'billing-plans', useFetcher: _for => { const clerk = useClerkInstanceContext(); if (!clerk.loaded) { diff --git a/packages/shared/src/react/hooks/useStatements.tsx b/packages/shared/src/react/hooks/useStatements.tsx index 44f0d8bb0a0..12cfd079938 100644 --- a/packages/shared/src/react/hooks/useStatements.tsx +++ b/packages/shared/src/react/hooks/useStatements.tsx @@ -1,14 +1,14 @@ -import type { CommerceStatementResource, GetStatementsParams } from '@clerk/types'; +import type { BillingStatementResource, GetStatementsParams } from '@clerk/types'; import { useClerkInstanceContext } from '../contexts'; -import { createCommercePaginatedHook } from './createCommerceHook'; +import { createBillingPaginatedHook as createCommercePaginatedHook } from './createCommerceHook'; /** * @internal */ -export const useStatements = createCommercePaginatedHook({ +export const useStatements = createCommercePaginatedHook({ hookName: 'useStatements', - resourceType: 'commerce-statements', + resourceType: 'billing-statements', useFetcher: () => { const clerk = useClerkInstanceContext(); if (clerk.loaded) { diff --git a/packages/types/src/clerk.ts b/packages/types/src/clerk.ts index f35bc68abf0..ad9f13f69a4 100644 --- a/packages/types/src/clerk.ts +++ b/packages/types/src/clerk.ts @@ -22,10 +22,10 @@ import type { } from './appearance'; import type { ClientResource } from './client'; import type { - CommerceBillingNamespace, - CommerceCheckoutResource, - CommercePlanResource, - CommerceSubscriptionPlanPeriod, + BillingCheckoutResource, + BillingNamespace, + BillingPlanResource, + BillingSubscriptionPlanPeriod, ConfirmCheckoutParams, ForPayerType, } from './commerce'; @@ -67,20 +67,20 @@ export type __experimental_CheckoutCacheState = Readonly<{ isStarting: boolean; isConfirming: boolean; error: ClerkAPIResponseError | null; - checkout: CommerceCheckoutResource | null; + checkout: BillingCheckoutResource | null; fetchStatus: 'idle' | 'fetching' | 'error'; status: __experimental_CheckoutStatus; }>; export type __experimental_CheckoutOptions = { for?: ForPayerType; - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; planId: string; }; type CheckoutResult = | { - data: CommerceCheckoutResource; + data: BillingCheckoutResource; error: null; } | { @@ -240,7 +240,7 @@ export interface Clerk { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - billing: CommerceBillingNamespace; + billing: BillingNamespace; telemetry: TelemetryCollector | undefined; @@ -1874,7 +1874,7 @@ export type RevokeAPIKeyParams = { export type __internal_CheckoutProps = { appearance?: CheckoutTheme; planId?: string; - planPeriod?: CommerceSubscriptionPlanPeriod; + planPeriod?: BillingSubscriptionPlanPeriod; for?: ForPayerType; onSubscriptionComplete?: () => void; portalId?: string; @@ -1892,7 +1892,7 @@ export type __internal_CheckoutProps = { */ export type __experimental_CheckoutButtonProps = { planId: string; - planPeriod?: CommerceSubscriptionPlanPeriod; + planPeriod?: BillingSubscriptionPlanPeriod; for?: ForPayerType; onSubscriptionComplete?: () => void; checkoutProps?: { @@ -1920,12 +1920,12 @@ export type __internal_PlanDetailsProps = ( /** * The plan object will be used as initial data until the plan is fetched from the server. */ - plan: CommercePlanResource; + plan: BillingPlanResource; planId?: never; } ) & { appearance?: PlanDetailTheme; - initialPlanPeriod?: CommerceSubscriptionPlanPeriod; + initialPlanPeriod?: BillingSubscriptionPlanPeriod; portalId?: string; portalRoot?: PortalRoot; }; @@ -1942,11 +1942,11 @@ export type __experimental_PlanDetailsButtonProps = ( /** * The plan object will be used as initial data until the plan is fetched from the server. */ - plan: CommercePlanResource; + plan: BillingPlanResource; planId?: never; } ) & { - initialPlanPeriod?: CommerceSubscriptionPlanPeriod; + initialPlanPeriod?: BillingSubscriptionPlanPeriod; planDetailsProps?: { appearance?: PlanDetailTheme; portalId?: string; diff --git a/packages/types/src/commerce.ts b/packages/types/src/commerce.ts index 2c16de1aea9..731ac4f8c8a 100644 --- a/packages/types/src/commerce.ts +++ b/packages/types/src/commerce.ts @@ -1,7 +1,6 @@ import type { DeletedObjectResource } from './deletedObject'; import type { ClerkPaginatedResponse, ClerkPaginationParams } from './pagination'; import type { ClerkResource } from './resource'; -import type { CommerceFeatureJSONSnapshot } from './snapshots'; type WithOptionalOrgType = T & { /** @@ -13,52 +12,52 @@ type WithOptionalOrgType = T & { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceBillingNamespace { +export interface BillingNamespace { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getPaymentAttempts: (params: GetPaymentAttemptsParams) => Promise>; + getPaymentAttempts: (params: GetPaymentAttemptsParams) => Promise>; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getPaymentAttempt: (params: { id: string; orgId?: string }) => Promise; + getPaymentAttempt: (params: { id: string; orgId?: string }) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getPlans: (params?: GetPlansParams) => Promise>; + getPlans: (params?: GetPlansParams) => Promise>; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getPlan: (params: { id: string }) => Promise; + getPlan: (params: { id: string }) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getSubscription: (params: GetSubscriptionParams) => Promise; + getSubscription: (params: GetSubscriptionParams) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getStatements: (params: GetStatementsParams) => Promise>; + getStatements: (params: GetStatementsParams) => Promise>; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - getStatement: (params: { id: string; orgId?: string }) => Promise; + getStatement: (params: { id: string; orgId?: string }) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - startCheckout: (params: CreateCheckoutParams) => Promise; + startCheckout: (params: CreateCheckoutParams) => Promise; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export type CommercePayerResourceType = 'org' | 'user'; +export type BillingPayerResourceType = 'org' | 'user'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -68,35 +67,35 @@ export type ForPayerType = 'organization' | 'user'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export type CommerceSubscriptionStatus = 'active' | 'ended' | 'upcoming' | 'past_due'; +export type BillingSubscriptionStatus = 'active' | 'ended' | 'upcoming' | 'past_due'; /** * The billing period for the plan. * * @inline */ -export type CommerceSubscriptionPlanPeriod = 'month' | 'annual'; +export type BillingSubscriptionPlanPeriod = 'month' | 'annual'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePaymentSourceMethods { +export interface BillingPaymentSourceMethods { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ initializePaymentSource: ( params: Exclude, - ) => Promise; + ) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - addPaymentSource: (params: Exclude) => Promise; + addPaymentSource: (params: Exclude) => Promise; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ getPaymentSources: ( params: Exclude, - ) => Promise>; + ) => Promise>; } /** @@ -112,7 +111,7 @@ export type GetPlansParams = ClerkPaginationParams<{ /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePlanResource extends ClerkResource { +export interface BillingPlanResource extends ClerkResource { id: string; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -121,15 +120,15 @@ export interface CommercePlanResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - fee: CommerceMoneyAmount; + fee: BillingMoneyAmount; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - annualFee: CommerceMoneyAmount; + annualFee: BillingMoneyAmount; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - annualMonthlyFee: CommerceMoneyAmount; + annualMonthlyFee: BillingMoneyAmount; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -154,7 +153,7 @@ export interface CommercePlanResource extends ClerkResource { * Each plan is exclusively created for either individual users or organizations, * and cannot be used interchangeably. */ - forPayerType: CommercePayerResourceType; + forPayerType: BillingPayerResourceType; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -170,7 +169,7 @@ export interface CommercePlanResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - features: CommerceFeatureResource[]; + features: FeatureResource[]; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -182,11 +181,11 @@ export interface CommercePlanResource extends ClerkResource { } /** - * The `CommerceFeatureResource` type represents a feature of a subscription plan. + * The `FeatureResource` type represents a feature of a plan. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceFeatureResource extends ClerkResource { +export interface FeatureResource extends ClerkResource { /** * The unique identifier for the feature. */ @@ -207,17 +206,13 @@ export interface CommerceFeatureResource extends ClerkResource { * The URL of the feature's avatar image. */ avatarUrl: string; - /** - * @hidden - */ - __internal_toSnapshot: () => CommerceFeatureJSONSnapshot; } /** * The status of a payment source. * @inline */ -export type CommercePaymentSourceStatus = 'active' | 'expired' | 'disconnected'; +export type BillingPaymentSourceStatus = 'active' | 'expired' | 'disconnected'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -264,11 +259,11 @@ export type RemovePaymentSourceParams = WithOptionalOrgType; export type MakeDefaultPaymentSourceParams = WithOptionalOrgType; /** - * The `CommercePaymentSourceResource` type represents a payment source for a checkout session. + * The `BillingPaymentSourceResource` type represents a payment source for a checkout session. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePaymentSourceResource extends ClerkResource { +export interface BillingPaymentSourceResource extends ClerkResource { /** * The unique identifier for the payment method. */ @@ -296,7 +291,7 @@ export interface CommercePaymentSourceResource extends ClerkResource { /** * The current status of the payment method. */ - status: CommercePaymentSourceStatus; + status: BillingPaymentSourceStatus; /** * The type of digital wallet, if applicable. For example, `'apple_pay'`, or `'google_pay'`. */ @@ -320,7 +315,7 @@ export interface CommercePaymentSourceResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceInitializedPaymentSourceResource extends ClerkResource { +export interface BillingInitializedPaymentSourceResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -338,22 +333,22 @@ export interface CommerceInitializedPaymentSourceResource extends ClerkResource /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export type CommercePaymentChargeType = 'checkout' | 'recurring'; +export type BillingPaymentChargeType = 'checkout' | 'recurring'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export type CommercePaymentStatus = 'pending' | 'paid' | 'failed'; +export type BillingPaymentStatus = 'pending' | 'paid' | 'failed'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePaymentResource extends ClerkResource { +export interface BillingPaymentResource extends ClerkResource { id: string; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - amount: CommerceMoneyAmount; + amount: BillingMoneyAmount; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -369,19 +364,19 @@ export interface CommercePaymentResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - paymentSource: CommercePaymentSourceResource; + paymentSource: BillingPaymentSourceResource; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - subscriptionItem: CommerceSubscriptionItemResource; + subscriptionItem: BillingSubscriptionItemResource; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - chargeType: CommercePaymentChargeType; + chargeType: BillingPaymentChargeType; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - status: CommercePaymentStatus; + status: BillingPaymentStatus; } /** @@ -398,21 +393,21 @@ export type GetStatementsParams = WithOptionalOrgType; * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export type CommerceStatementStatus = 'open' | 'closed'; +export type BillingStatementStatus = 'open' | 'closed'; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceStatementResource extends ClerkResource { +export interface BillingStatementResource extends ClerkResource { id: string; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - totals: CommerceStatementTotals; + totals: BillingStatementTotals; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - status: CommerceStatementStatus; + status: BillingStatementStatus; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -420,15 +415,15 @@ export interface CommerceStatementResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - groups: CommerceStatementGroup[]; + groups: BillingStatementGroup[]; } /** - * The `CommerceStatementGroup` type represents a group of payment items within a statement. + * The `BillingStatementGroup` type represents a group of payment items within a statement. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceStatementGroup { +export interface BillingStatementGroup { /** * The date and time when this group of payment items was created or last updated. */ @@ -436,7 +431,7 @@ export interface CommerceStatementGroup { /** * An array of payment resources that belong to this group. */ - items: CommercePaymentResource[]; + items: BillingPaymentResource[]; } /** @@ -454,8 +449,7 @@ export type CancelSubscriptionParams = WithOptionalOrgType; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - -export interface CommerceSubscriptionItemResource extends ClerkResource { +export interface BillingSubscriptionItemResource extends ClerkResource { id: string; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -465,15 +459,15 @@ export interface CommerceSubscriptionItemResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - plan: CommercePlanResource; + plan: BillingPlanResource; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - status: CommerceSubscriptionStatus; + status: BillingSubscriptionStatus; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -497,7 +491,7 @@ export interface CommerceSubscriptionItemResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - amount?: CommerceMoneyAmount; + amount?: BillingMoneyAmount; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ @@ -505,7 +499,7 @@ export interface CommerceSubscriptionItemResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - amount: CommerceMoneyAmount; + amount: BillingMoneyAmount; }; /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -522,7 +516,7 @@ export interface CommerceSubscriptionItemResource extends ClerkResource { * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceSubscriptionResource extends ClerkResource { +export interface BillingSubscriptionResource extends ClerkResource { /** * The unique identifier for the subscription. */ @@ -542,7 +536,7 @@ export interface CommerceSubscriptionResource extends ClerkResource { /** * The amount of the next payment. */ - amount: CommerceMoneyAmount; + amount: BillingMoneyAmount; /** * The date when the next payment is due. */ @@ -556,12 +550,12 @@ export interface CommerceSubscriptionResource extends ClerkResource { /** * The current status of the subscription. Due to the free plan subscription item, the top level subscription can either be `active` or `past_due`. */ - status: Extract; + status: Extract; /** * The list of items (plans/features) included in this subscription. */ - subscriptionItems: CommerceSubscriptionItemResource[]; + subscriptionItems: BillingSubscriptionItemResource[]; /** * The date when the subscription was last updated, or `null` if it hasn't been updated. @@ -575,11 +569,11 @@ export interface CommerceSubscriptionResource extends ClerkResource { } /** - * The `CommerceMoneyAmount` type represents a monetary value with currency information. + * The `BillingMoneyAmount` type represents a monetary value with currency information. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceMoneyAmount { +export interface BillingMoneyAmount { /** * The raw amount as a number, usually in the smallest unit of the currency (like cents for USD). For example, `1000` for $10.00. */ @@ -599,44 +593,44 @@ export interface CommerceMoneyAmount { } /** - * The `CommerceCheckoutTotals` type represents the total costs, taxes, and other pricing details for a checkout session. + * The `BillingCheckoutTotals` type represents the total costs, taxes, and other pricing details for a checkout session. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceCheckoutTotals { +export interface BillingCheckoutTotals { /** * The price of the items or plan before taxes, credits, or discounts are applied. */ - subtotal: CommerceMoneyAmount; + subtotal: BillingMoneyAmount; /** * The total amount for the checkout, including taxes and after credits/discounts are applied. This is the final amount due. */ - grandTotal: CommerceMoneyAmount; + grandTotal: BillingMoneyAmount; /** * The amount of tax included in the checkout. */ - taxTotal: CommerceMoneyAmount; + taxTotal: BillingMoneyAmount; /** * The amount that needs to be immediately paid to complete the checkout. */ - totalDueNow: CommerceMoneyAmount; + totalDueNow: BillingMoneyAmount; /** * Any credits (like account balance or promo credits) that are being applied to the checkout. */ - credit: CommerceMoneyAmount; + credit: BillingMoneyAmount; /** * Any outstanding amount from previous unpaid invoices that is being collected as part of the checkout. */ - pastDue: CommerceMoneyAmount; + pastDue: BillingMoneyAmount; } /** - * The `CommerceStatementTotals` type represents the total costs, taxes, and other pricing details for a statement. + * The `BillingStatementTotals` type represents the total costs, taxes, and other pricing details for a statement. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface CommerceStatementTotals extends Omit {} +export interface BillingStatementTotals extends Omit {} /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. @@ -649,7 +643,7 @@ export type CreateCheckoutParams = WithOptionalOrgType<{ /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; }>; /** @@ -686,11 +680,11 @@ export type ConfirmCheckoutParams = }; /** - * The `CommerceCheckoutResource` type represents information about a checkout session. + * The `BillingCheckoutResource` type represents information about a checkout session. * * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceCheckoutResource extends ClerkResource { +export interface BillingCheckoutResource extends ClerkResource { /** * The unique identifier for the checkout session. */ @@ -706,15 +700,15 @@ export interface CommerceCheckoutResource extends ClerkResource { /** * The payment source being used for the checkout, such as a credit card or bank account. */ - paymentSource?: CommercePaymentSourceResource; + paymentSource?: BillingPaymentSourceResource; /** * The subscription plan details for the checkout. */ - plan: CommercePlanResource; + plan: BillingPlanResource; /** * The billing period for the plan. */ - planPeriod: CommerceSubscriptionPlanPeriod; + planPeriod: BillingSubscriptionPlanPeriod; /** * Unix timestamp (milliseconds) of when the current period starts. */ @@ -726,11 +720,11 @@ export interface CommerceCheckoutResource extends ClerkResource { /** * The total costs, taxes, and other pricing details for the checkout. */ - totals: CommerceCheckoutTotals; + totals: BillingCheckoutTotals; /** * A function to confirm and finalize the checkout process, usually after payment information has been provided and validated. [Learn more.](#confirm) */ - confirm: (params: ConfirmCheckoutParams) => Promise; + confirm: (params: ConfirmCheckoutParams) => Promise; /** * Whether the plan change will take effect immediately after checkout. */ @@ -742,13 +736,13 @@ export interface CommerceCheckoutResource extends ClerkResource { /** * The payer associated with the checkout. */ - payer: CommercePayerResource; + payer: BillingPayerResource; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePayerResource extends ClerkResource { +export interface BillingPayerResource extends ClerkResource { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ diff --git a/packages/types/src/json.ts b/packages/types/src/json.ts index 9c41cb7861e..93b1c60ad0a 100644 --- a/packages/types/src/json.ts +++ b/packages/types/src/json.ts @@ -4,13 +4,13 @@ import type { APIKeysSettingsJSON } from './apiKeysSettings'; import type { - CommercePayerResourceType, - CommercePaymentChargeType, - CommercePaymentSourceStatus, - CommercePaymentStatus, - CommerceStatementStatus, - CommerceSubscriptionPlanPeriod, - CommerceSubscriptionStatus, + BillingPayerResourceType, + BillingPaymentChargeType, + BillingPaymentSourceStatus, + BillingPaymentStatus, + BillingStatementStatus, + BillingSubscriptionPlanPeriod, + BillingSubscriptionStatus, } from './commerce'; import type { CommerceSettingsJSON } from './commerceSettings'; import type { DisplayConfigJSON } from './displayConfig'; @@ -628,8 +628,8 @@ export interface WaitlistJSON extends ClerkResourceJSON { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceFeatureJSON extends ClerkResourceJSON { - object: 'commerce_feature'; +export interface FeatureJSON extends ClerkResourceJSON { + object: 'feature'; id: string; name: string; description: string; @@ -640,13 +640,13 @@ export interface CommerceFeatureJSON extends ClerkResourceJSON { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePlanJSON extends ClerkResourceJSON { +export interface BillingPlanJSON extends ClerkResourceJSON { object: 'commerce_plan'; id: string; name: string; - fee: CommerceMoneyAmountJSON; - annual_fee: CommerceMoneyAmountJSON; - annual_monthly_fee: CommerceMoneyAmountJSON; + fee: BillingMoneyAmountJSON; + annual_fee: BillingMoneyAmountJSON; + annual_monthly_fee: BillingMoneyAmountJSON; amount: number; amount_formatted: string; annual_amount: number; @@ -659,11 +659,11 @@ export interface CommercePlanJSON extends ClerkResourceJSON { is_default: boolean; is_recurring: boolean; has_base_fee: boolean; - for_payer_type: CommercePayerResourceType; + for_payer_type: BillingPayerResourceType; publicly_visible: boolean; slug: string; avatar_url: string; - features: CommerceFeatureJSON[]; + features: FeatureJSON[]; free_trial_days?: number | null; free_trial_enabled?: boolean; } @@ -671,7 +671,7 @@ export interface CommercePlanJSON extends ClerkResourceJSON { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePaymentSourceJSON extends ClerkResourceJSON { +export interface BillingPaymentSourceJSON extends ClerkResourceJSON { object: 'commerce_payment_source'; id: string; last4: string; @@ -679,14 +679,14 @@ export interface CommercePaymentSourceJSON extends ClerkResourceJSON { card_type: string; is_default: boolean; is_removable: boolean; - status: CommercePaymentSourceStatus; + status: BillingPaymentSourceStatus; wallet_type: string | null; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceInitializedPaymentSourceJSON extends ClerkResourceJSON { +export interface BillingInitializedPaymentSourceJSON extends ClerkResourceJSON { object: 'commerce_payment_source_initialize'; external_client_secret: string; external_gateway_id: string; @@ -696,55 +696,55 @@ export interface CommerceInitializedPaymentSourceJSON extends ClerkResourceJSON /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceStatementJSON extends ClerkResourceJSON { +export interface BillingStatementJSON extends ClerkResourceJSON { object: 'commerce_statement'; id: string; - status: CommerceStatementStatus; + status: BillingStatementStatus; timestamp: number; - groups: CommerceStatementGroupJSON[]; - totals: CommerceStatementTotalsJSON; + groups: BillingStatementGroupJSON[]; + totals: BillingStatementTotalsJSON; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceStatementGroupJSON extends ClerkResourceJSON { +export interface BillingStatementGroupJSON extends ClerkResourceJSON { object: 'commerce_statement_group'; timestamp: number; - items: CommercePaymentJSON[]; + items: BillingPaymentJSON[]; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePaymentJSON extends ClerkResourceJSON { +export interface BillingPaymentJSON extends ClerkResourceJSON { object: 'commerce_payment'; id: string; - amount: CommerceMoneyAmountJSON; + amount: BillingMoneyAmountJSON; paid_at?: number; failed_at?: number; updated_at: number; - payment_source: CommercePaymentSourceJSON; - subscription: CommerceSubscriptionItemJSON; - subscription_item: CommerceSubscriptionItemJSON; - charge_type: CommercePaymentChargeType; - status: CommercePaymentStatus; + payment_source: BillingPaymentSourceJSON; + subscription: BillingSubscriptionItemJSON; + subscription_item: BillingSubscriptionItemJSON; + charge_type: BillingPaymentChargeType; + status: BillingPaymentStatus; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceSubscriptionItemJSON extends ClerkResourceJSON { +export interface BillingSubscriptionItemJSON extends ClerkResourceJSON { object: 'commerce_subscription_item'; id: string; - amount?: CommerceMoneyAmountJSON; + amount?: BillingMoneyAmountJSON; credit?: { - amount: CommerceMoneyAmountJSON; + amount: BillingMoneyAmountJSON; }; payment_source_id: string; - plan: CommercePlanJSON; - plan_period: CommerceSubscriptionPlanPeriod; - status: CommerceSubscriptionStatus; + plan: BillingPlanJSON; + plan_period: BillingSubscriptionPlanPeriod; + status: BillingSubscriptionStatus; created_at: number; period_start: number; /** @@ -760,32 +760,32 @@ export interface CommerceSubscriptionItemJSON extends ClerkResourceJSON { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceSubscriptionJSON extends ClerkResourceJSON { +export interface BillingSubscriptionJSON extends ClerkResourceJSON { object: 'commerce_subscription'; id: string; /** * Describes the details for the next payment cycle. It is `undefined` for subscription items that are cancelled or on the free plan. */ next_payment?: { - amount: CommerceMoneyAmountJSON; + amount: BillingMoneyAmountJSON; date: number; }; /** * Due to the free plan subscription item, the top level subscription can either be `active` or `past_due`. */ - status: Extract; + status: Extract; created_at: number; active_at: number; updated_at: number | null; past_due_at: number | null; - subscription_items: CommerceSubscriptionItemJSON[] | null; + subscription_items: BillingSubscriptionItemJSON[] | null; eligible_for_free_trial?: boolean; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceMoneyAmountJSON { +export interface BillingMoneyAmountJSON { amount: number; amount_formatted: string; currency: string; @@ -795,44 +795,45 @@ export interface CommerceMoneyAmountJSON { /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceCheckoutTotalsJSON { - grand_total: CommerceMoneyAmountJSON; - subtotal: CommerceMoneyAmountJSON; - tax_total: CommerceMoneyAmountJSON; - total_due_now: CommerceMoneyAmountJSON; - credit: CommerceMoneyAmountJSON; +export interface BillingCheckoutTotalsJSON { + grand_total: BillingMoneyAmountJSON; + subtotal: BillingMoneyAmountJSON; + tax_total: BillingMoneyAmountJSON; + total_due_now: BillingMoneyAmountJSON; + credit: BillingMoneyAmountJSON; + past_due: BillingMoneyAmountJSON; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface CommerceStatementTotalsJSON extends Omit {} +export interface BillingStatementTotalsJSON extends Omit {} /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommerceCheckoutJSON extends ClerkResourceJSON { +export interface BillingCheckoutJSON extends ClerkResourceJSON { object: 'commerce_checkout'; id: string; external_client_secret: string; external_gateway_id: string; - payment_source?: CommercePaymentSourceJSON; - plan: CommercePlanJSON; - plan_period: CommerceSubscriptionPlanPeriod; + payment_source?: BillingPaymentSourceJSON; + plan: BillingPlanJSON; + plan_period: BillingSubscriptionPlanPeriod; plan_period_start?: number; status: 'needs_confirmation' | 'completed'; - totals: CommerceCheckoutTotalsJSON; + totals: BillingCheckoutTotalsJSON; is_immediate_plan_change: boolean; // TODO(@COMMERCE): Remove optional after GA. - free_trial_ends_at?: number | null; - payer: CommercePayerJSON; + free_trial_ends_at: number | null; + payer: BillingPayerJSON; } /** * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes. */ -export interface CommercePayerJSON extends ClerkResourceJSON { +export interface BillingPayerJSON extends ClerkResourceJSON { object: 'commerce_payer'; id: string; created_at: number; diff --git a/packages/types/src/organization.ts b/packages/types/src/organization.ts index 1c012d497f5..2ec09c37056 100644 --- a/packages/types/src/organization.ts +++ b/packages/types/src/organization.ts @@ -1,4 +1,4 @@ -import type { CommercePaymentSourceMethods } from './commerce'; +import type { BillingPaymentSourceMethods } from './commerce'; import type { OrganizationDomainResource, OrganizationEnrollmentMode } from './organizationDomain'; import type { OrganizationInvitationResource, OrganizationInvitationStatus } from './organizationInvitation'; import type { OrganizationCustomRoleKey, OrganizationMembershipResource } from './organizationMembership'; @@ -35,7 +35,7 @@ declare global { * * @interface */ -export interface OrganizationResource extends ClerkResource, CommercePaymentSourceMethods { +export interface OrganizationResource extends ClerkResource, BillingPaymentSourceMethods { id: string; name: string; slug: string | null; diff --git a/packages/types/src/snapshots.ts b/packages/types/src/snapshots.ts index 99b53912eea..13c423e8cb3 100644 --- a/packages/types/src/snapshots.ts +++ b/packages/types/src/snapshots.ts @@ -6,8 +6,6 @@ import type { DisplayConfigJSON } from './displayConfig'; import type { AuthConfigJSON, ClientJSON, - CommerceFeatureJSON, - CommercePlanJSON, EmailAddressJSON, EnterpriseAccountConnectionJSON, EnterpriseAccountJSON, @@ -189,8 +187,4 @@ export type PublicUserDataJSONSnapshot = PublicUserDataJSON; export type CommerceSettingsJSONSnapshot = CommerceSettingsJSON; -export type CommercePlanJSONSnapshot = CommercePlanJSON; - -export type CommerceFeatureJSONSnapshot = CommerceFeatureJSON; - export type APIKeysSettingsJSONSnapshot = APIKeysSettingsJSON; diff --git a/packages/types/src/user.ts b/packages/types/src/user.ts index 964621b678b..8e8c696b6ca 100644 --- a/packages/types/src/user.ts +++ b/packages/types/src/user.ts @@ -1,5 +1,5 @@ import type { BackupCodeResource } from './backupCode'; -import type { CommercePaymentSourceMethods } from './commerce'; +import type { BillingPaymentSourceMethods } from './commerce'; import type { DeletedObjectResource } from './deletedObject'; import type { EmailAddressResource } from './emailAddress'; import type { EnterpriseAccountResource } from './enterpriseAccount'; @@ -61,7 +61,7 @@ declare global { * * The ClerkJS SDK provides some helper [methods](#methods) on the `User` object to help retrieve and update user information and authentication status. */ -export interface UserResource extends ClerkResource, CommercePaymentSourceMethods { +export interface UserResource extends ClerkResource, BillingPaymentSourceMethods { id: string; externalId: string | null; primaryEmailAddressId: string | null;