Skip to content

chore(clerk-js,shared): Expose experimental useSubscription #6317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jul 23, 2025

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Jul 15, 2025

Description

This PR replaces the paginated hooks useSubscriptionItems for the non-paginated useSubscription.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Introduced a top-level subscription resource with detailed metadata alongside individual subscription items.
    • Added a new method and hook for fetching single subscription data supporting user and organization contexts.
  • Improvements

    • Clarified and unified the distinction between subscriptions and subscription items in UI components, hooks, and API.
    • Updated subscription-related components and hooks to leverage the new data structure for enhanced accuracy.
    • Enhanced commerce hooks to support paginated data fetching.
  • Deprecations

    • Deprecated the existing method for fetching multiple subscriptions in favor of the new single subscription fetch method.
    • Marked older subscription properties as deprecated to encourage migration to the new model.
  • Bug Fixes

    • Updated tests and UI components to maintain compatibility with the revised subscription data model.

Copy link

changeset-bot bot commented Jul 15, 2025

🦋 Changeset detected

Latest commit: b8af083

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/types Minor
@clerk/shared Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/vue Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Jul 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 23, 2025 10:00am

# Conflicts:
#	packages/shared/src/react/hooks/useOrganization.tsx
#	packages/types/src/organization.ts
# Conflicts:
#	packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
#	packages/clerk-js/src/ui/contexts/components/Plans.tsx
#	packages/shared/src/react/hooks/index.ts
@panteliselef panteliselef marked this pull request as ready for review July 21, 2025 17:56
Copy link

pkg-pr-new bot commented Jul 21, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6317

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6317

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6317

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6317

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6317

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6317

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6317

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6317

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6317

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6317

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6317

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6317

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6317

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6317

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6317

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6317

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6317

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6317

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6317

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6317

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6317

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6317

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6317

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6317

commit: b8af083

Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

📝 Walkthrough

Walkthrough

This change set introduces a clear distinction between "subscriptions" and "subscription items" across the commerce modules, types, hooks, and UI components. A new CommerceSubscriptionResource type and class are added to represent a top-level subscription entity, while the previous CommerceSubscriptionResource is renamed to CommerceSubscriptionItemResource to represent individual subscription items. The billing API gains a new getSubscription method for fetching a single subscription, while the old getSubscriptions method is deprecated and now returns paginated subscription items. All related types, interfaces, and method signatures are updated to reflect this separation. React hooks and UI components are refactored to use the new data model, with hooks like useSubscription replacing useSubscriptionItems, and context, props, and test mocks updated accordingly. The changes also propagate to payment, organization, and plan-related modules, ensuring consistent use of the new subscription and subscription item types throughout the codebase.

Estimated code review effort

4 (~90 minutes)


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e1c9e6 and b8af083.

⛔ Files ignored due to path filters (1)
  • .typedoc/__tests__/__snapshots__/file-structure.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (9 hunks)
  • packages/shared/src/react/hooks/useSubscription.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/tests/SubscriptionDetails.test.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🔭 Outside diff range comments (2)
packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (1)

68-86: Consider deprecating or renaming getSubscriptions for clarity

The getSubscriptions method now returns subscription items instead of subscriptions, which is a breaking change. This could be confusing for API consumers. Consider:

  1. Deprecating this method and creating a new getSubscriptionItems method
  2. Adding JSDoc comments to clearly document the return type change
  3. Updating the endpoint path to reflect that it returns items (if backend supports it)
packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (1)

1-575: Add comprehensive tests for the subscription architecture changes

This PR introduces significant architectural changes but doesn't include test updates. Please add tests to cover:

  1. The new useSubscription hook behavior
  2. The subscription/subscription-item data model transformations
  3. The updated cancellation flow
  4. Edge cases for free plans, past due subscriptions, etc.

Would you like me to help generate test cases for these changes?

🧹 Nitpick comments (2)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)

72-73: Address the TODO about undefined amount

The TODO comment questions why amount can be undefined. This should be clarified:

  1. Document when/why amount might be undefined (e.g., for free plans?)
  2. Consider making it required if it should always have a value
  3. Add validation or default value handling if needed

Would you like me to help investigate when the amount field might be undefined by analyzing the codebase?

packages/types/src/commerce.ts (1)

956-957: Resolve TODO comment before merging

There's a TODO comment questioning whether paymentSourceId should be nullable. This should be resolved before the PR is merged.

Would you like me to help analyze the usage patterns of paymentSourceId across the codebase to determine if it should be nullable?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61b592e and c0c8c89.

📒 Files selected for processing (21)
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (5 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (3 hunks)
  • packages/clerk-js/src/core/resources/Organization.ts (3 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (9 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (2 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (8 hunks)
  • packages/shared/src/react/hooks/createCommerceHook.tsx (1 hunks)
  • packages/shared/src/react/hooks/index.ts (1 hunks)
  • packages/shared/src/react/hooks/useOrganization.tsx (5 hunks)
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePaymentMethods.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePlans.tsx (1 hunks)
  • packages/shared/src/react/hooks/useStatements.tsx (1 hunks)
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx (1 hunks)
  • packages/types/src/commerce.ts (7 hunks)
  • packages/types/src/json.ts (3 hunks)
  • packages/types/src/organization.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*

⚙️ CodeRabbit Configuration File

**/*: If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Whenever reviewing a pull request, if there are any changes that could impact security, always tag clerk/security in the PR.

Security-impacting changes include, but are not limited to:

  • Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
  • Any modification to access control, authorization checks, or role-based permissions
  • Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
  • Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
  • Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
  • Modifications to security headers, cookie flags, CORS policies, or CSRF protections
  • Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
  • Changes to rate limiting, abuse prevention, or input validation

If you're unsure whether a change is security-relevant, err on the side of caution and tag clerk/security.

Any time that you tag clerk/security, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
packages/**/index.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/shared/src/react/hooks/index.ts
**/index.ts

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/shared/src/react/hooks/index.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
🧬 Code Graph Analysis (9)
packages/shared/src/react/hooks/createCommerceHook.tsx (2)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/shared/src/react/types.ts (1)
  • PagesOrInfiniteOptions (124-144)
packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useSubscription (56-68)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (1)
  • useSubscription (20-50)
packages/clerk-js/src/core/resources/Organization.ts (4)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/json.ts (1)
  • CommerceSubscriptionItemJSON (767-783)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)
  • CommerceSubscriptionItem (58-122)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (3)
packages/shared/src/react/hooks/index.ts (1)
  • useSubscription (15-15)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useSubscription (56-68)
packages/react/src/isomorphicClerk.ts (1)
  • organization (673-679)
packages/types/src/organization.ts (2)
packages/types/src/commerce.ts (2)
  • GetSubscriptionsParams (914-914)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/shared/src/react/hooks/useOrganization.tsx (3)
packages/shared/src/react/types.ts (1)
  • PaginatedResourcesWithDefault (83-85)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/json.ts (2)
packages/backend/src/api/resources/JSON.ts (1)
  • ClerkResourceJSON (70-79)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionStatus (111-111)
packages/types/src/commerce.ts (2)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
🪛 Biome (1.9.4)
packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx

[error] 559-559: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
🔇 Additional comments (34)
packages/shared/src/react/hooks/createCommerceHook.tsx (1)

41-41: LGTM: Function rename improves semantic clarity.

The rename from createCommerceHook to createCommercePaginatedHook better reflects the function's purpose of creating paginated commerce hooks. The comprehensive JSDoc documentation clearly explains the hook factory's capabilities.

packages/shared/src/react/hooks/usePaymentAttempts.tsx (1)

4-4: LGTM: Correctly updated to use renamed hook factory.

The import and usage have been properly updated to use createCommercePaginatedHook, maintaining consistency with the refactor.

Also applies to: 9-9

packages/shared/src/react/hooks/index.ts (1)

15-15: LGTM: Successfully exposes experimental useSubscription hook.

This export change aligns perfectly with the PR objective to expose the experimental useSubscription hook. The experimental prefix appropriately indicates this is a new API that may change.

packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)

1-1: LGTM: Type update aligns with subscription/subscription item distinction.

The update from CommerceSubscriptionResource to CommerceSubscriptionItemResource is consistent with the broader refactor. The component logic remains compatible since both types include the status property used by the component.

Also applies to: 22-22

packages/shared/src/react/hooks/usePlans.tsx (1)

4-4: LGTM: Consistently updated to use paginated hook factory.

The changes properly update usePlans to use createCommercePaginatedHook, maintaining consistency with other commerce hooks like usePaymentAttempts. The hook's external API remains unchanged while gaining pagination capabilities.

Also applies to: 9-9

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (4)

5-5: Import path updated to absolute alias.

The Flow import was changed from a relative path to use an absolute path alias. This aligns with better module organization practices.


7-7: Hook import updated from useSubscriptions to useSubscription.

The import reflects the broader refactor to distinguish between subscription items and top-level subscriptions. This change is consistent with the new data model.


15-15: Destructuring updated to use subscriptionItems.

The destructuring changed from data: subscriptions to subscriptionItems, which is consistent with the new useSubscription hook structure that exposes subscriptionItems directly.


21-21: All subscription references consistently updated.

All references to subscriptions have been properly updated to subscriptionItems, including:

  • Variable usage in the find operations
  • The useMemo dependency array

The logic remains unchanged - it still finds upcoming and active subscriptions to determine the default plan period.

Also applies to: 27-27, 36-36

packages/shared/src/react/hooks/useStatements.tsx (1)

4-4: Hook factory updated to support pagination.

The change from createCommerceHook to createCommercePaginatedHook enables pagination support for statements, which is consistent with similar updates to other commerce hooks like usePaymentMethods, usePaymentAttempts, and usePlans.

Also applies to: 9-9

packages/shared/src/react/hooks/usePaymentMethods.tsx (1)

4-4: Hook factory updated to support pagination.

The change from createCommerceHook to createCommercePaginatedHook enables pagination support for payment methods, maintaining consistency with other commerce hooks that have been updated to support pagination.

Also applies to: 9-9

packages/types/src/organization.ts (2)

1-5: Import updated to include subscription item types.

The import statement now includes CommerceSubscriptionItemResource and GetSubscriptionsParams, which are needed for the updated getSubscriptions method signature.


66-68: Method signature updated to return subscription items.

The getSubscriptions method now returns CommerceSubscriptionItemResource instead of CommerceSubscriptionResource, reflecting the refactor that distinguishes between subscription items and top-level subscriptions. This is consistent with the implementation changes in the commerce modules.

packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (5)

1-1: React.useMemo import added for performance optimization.

The useMemo import is added to support the memoized sorting of subscription items, which is a good performance optimization.


10-10: Hook updated to use new subscription model.

The import changed from useSubscriptions to useSubscription, consistent with the broader refactor to distinguish between subscription items and top-level subscriptions.


44-44: Destructuring updated for new hook structure.

The destructuring changed from data: subscriptions to subscriptionItems, which aligns with the new useSubscription hook that exposes subscriptionItems directly.


50-65: Memoized sorting added for performance optimization.

The sorting logic has been wrapped in useMemo with proper dependencies (subscriptionItems), which prevents unnecessary re-sorting on every render. The sorting logic prioritizes active subscriptions, which is appropriate for the UI.


77-77: All subscription references consistently updated.

All conditional checks and references have been properly updated from subscriptions to subscriptionItems, maintaining the existing functionality while using the new data structure.

Also applies to: 199-199, 206-206

packages/clerk-js/src/core/resources/Organization.ts (1)

5-6: LGTM! Consistent refactoring from subscription to subscription item types.

The changes systematically update the Organization resource to work with subscription items instead of subscriptions, aligning with the broader refactor described in the PR objectives. All imports, type annotations, and instantiations are consistently updated.

Also applies to: 35-35, 238-238, 245-245, 249-249

packages/shared/src/react/hooks/useOrganization.tsx (1)

4-4: LGTM! Hook types updated consistently with the subscription item refactor.

All type annotations have been systematically updated from CommerceSubscriptionResource to CommerceSubscriptionItemResource, maintaining consistency with the underlying Organization resource changes.

Also applies to: 118-118, 128-128, 151-151, 468-468

packages/clerk-js/src/core/resources/CommercePayment.ts (1)

6-6: LGTM! Good backward compatibility approach with deprecation pattern.

The changes introduce both deprecated subscription and new subscriptionItem properties, allowing for a smooth migration. Both properties are correctly typed as CommerceSubscriptionItemResource and instantiated using the appropriate JSON fields.

Also applies to: 8-8, 13-13, 21-21, 22-26, 46-47

packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (1)

36-79: LGTM! Test mocks updated to match new subscription data structure.

The test mocks have been properly updated to use getSubscription instead of getSubscriptions, returning single subscription objects with subscriptionItems arrays. This aligns with the new data model described in the PR.

Also applies to: 129-172, 222-265

packages/shared/src/react/hooks/useSubscriptionItems.tsx (2)

1-50: LGTM! Well-implemented hook with proper SWR usage and context handling.

The new useSubscription hook is well-structured with:

  • Proper context switching between user and organization
  • Conditional fetching based on user presence
  • Appropriate SWR configuration with deduplication
  • Clean API with revalidate function
  • Telemetry recording for usage tracking

7-15: Good TypeScript interface design for hook parameters.

The UseSubscriptionParams interface provides clear options for subscription context and data persistence, with proper JSDoc documentation for the keepPreviousData option.

packages/clerk-js/src/ui/contexts/components/Plans.tsx (2)

13-13: Type updates are consistent with the new data model

The type changes from CommerceSubscriptionResource to CommerceSubscriptionItemResource are applied consistently throughout the file, maintaining type safety with the new subscription architecture.

Also applies to: 175-175, 192-192, 262-262


108-146: Clean adaptation to the new subscription data model

The usePlansContext hook has been properly updated to work with subscriptionItems from the new useSubscription hook. The business logic remains intact while adapting to the new data structure.

Also applies to: 245-245, 259-259

packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (2)

61-66: New subscription fetching method looks good

The getSubscription method is well-implemented and follows the established pattern for organization/user scoped resources. The singular endpoint path indicates it fetches the top-level subscription resource.


52-59: Clarify the "Inconsistent API" comment

The comment on line 52 doesn't explain what's inconsistent about the API. Please either:

  1. Expand the comment to explain the specific inconsistency
  2. Create a TODO with an issue reference
  3. Remove the comment if it's no longer relevant
packages/types/src/json.ts (1)

809-809: Ensure consistent naming and nullability in CommerceSubscriptionJSON

A quick grep shows that every other JSON interface in packages/types/src/json.ts uses updated_at, but here we have:

  active_at: number;
  update_at: number | null;
  past_due_at: number | null;
  subscription_items: CommerceSubscriptionItemJSON[] | null;

update_at vs. updated_at
– Every other model uses updated_at. Please confirm whether the API really returns update_at. If this is a typo, rename to updated_at in both the JSON type and the corresponding resource class.

subscription_items: … | null
– Nullability here forces callers to guard against null. If the API always returns an array (possibly empty), tighten this to a non-nullable array. Otherwise ensure downstream code can safely handle a null value.

packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (3)

44-54: Good separation of concerns for cancellation flow

The refactored SubscriptionForCancellationContext properly separates the cancellation state management from the main subscription data, improving code clarity and maintainability.


216-219: Verify the footer visibility logic

The footer visibility now depends on subscription?.nextPayment being present. This is cleaner than the previous approach, but please ensure:

  1. Free plans never have a nextPayment property
  2. This correctly handles all edge cases (past due, cancelled, etc.)

41-42: Free plan detection verified

  • Across the UI and core resources, hasBaseFee is the only flag used to distinguish free plans.

  • No other properties (isDefault, isRecurring, etc.) control free-plan status.

  • Optional improvement: add a getter on CommercePlanResource, e.g.:

    // in src/core/resources/CommercePlan.ts
    get isFree(): boolean {
      return !this.hasBaseFee;
    }

    Then replace the standalone helper with plan.isFree for consistency.

packages/types/src/commerce.ts (2)

1081-1188: Well-structured subscription resource interface

The new CommerceSubscriptionResource interface is well-designed with:

  • Clear separation of concerns between subscription and subscription items
  • Appropriate use of nullable types
  • Good documentation explaining the business logic
  • Type-safe status restriction

1-1514: Consider adding tests for the new types

These type changes introduce a significant refactoring of the subscription model. Please ensure that:

  1. Unit tests are added or updated to cover the new getSubscription method
  2. Integration tests verify the deprecation path works correctly
  3. Type tests confirm the new interfaces work as expected

Would you like me to help generate test cases for these new types and interfaces?

Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

📝 Walkthrough

Walkthrough

This change set introduces a structural refactor and type distinction between "subscriptions" and "subscription items" in the commerce billing domain. It adds a new CommerceSubscriptionResource interface and class to represent aggregate subscriptions, while the previous CommerceSubscriptionResource is renamed to CommerceSubscriptionItemResource to represent individual subscription items. API methods and hooks are updated to reflect this distinction, with new methods like getSubscription for fetching a single subscription and deprecating or updating previous paginated item fetchers. Type signatures, resource wrappers, and component props across the codebase are adjusted to use the new types, and related hooks are refactored for improved data fetching and context awareness. Test mocks and UI components are updated to align with the new data structures and API responses.

Estimated code review effort

4 (~90 minutes)


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🔭 Outside diff range comments (2)
packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (2)

103-104: Avoid using type assertions with as any

Using as any defeats TypeScript's type safety. The types should be properly inferred based on the conditional logic.

-    activeSubscription: activeSubscription as any, // Type is correct due to the throw above
-    anySubscription: (upcomingSubscription || activeSubscription || pastDueSubscription) as any,
+    activeSubscription: activeSubscription!,
+    anySubscription: (upcomingSubscription || activeSubscription || pastDueSubscription)!,

The non-null assertion (!) is more appropriate here since the throw ensures these values exist when or === 'throw'.


1-50: Missing tests for the new useSubscription hook

This PR introduces a new useSubscription hook but doesn't include any tests. Given the experimental nature of this feature and the significant refactoring, comprehensive tests are essential.

Please add tests to cover:

  • Hook behavior with different parameter combinations
  • Error handling scenarios
  • SWR caching behavior
  • Telemetry event recording
  • Integration with organization/user contexts
🧹 Nitpick comments (6)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (1)

34-34: Missing error handling for API call

The clerk.billing.getSubscription call doesn't have explicit error handling. While SWR will catch errors, it's good practice to add error boundaries or handle specific error cases.

Consider adding error handling for better user experience:

-    ({ args }) => clerk.billing.getSubscription(args),
+    async ({ args }) => {
+      try {
+        return await clerk.billing.getSubscription(args);
+      } catch (error) {
+        // Log error for debugging
+        console.error('Failed to fetch subscription:', error);
+        throw error;
+      }
+    },
packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (2)

52-52: Address the "Inconsistent API" comment

The comment suggests there's an API inconsistency that should be resolved. This technical debt should be tracked.

Would you like me to open an issue to track this API inconsistency and propose a consistent API design?


61-66: Add parameter validation for getSubscription

The method doesn't validate the params object. Consider adding validation to ensure robust error handling.

  getSubscription = async (params: GetSubscriptionParams): Promise<CommerceSubscriptionResource> => {
+    if (!params || typeof params !== 'object') {
+      throw new Error('Invalid parameters provided to getSubscription');
+    }
     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));
   };
packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (2)

43-43: Fix typo in comment

Minor typo in the comment.

-// We cannot derive the state of confirmation modal from the existence subscription, as it will make the animation laggy when the confirmation closes.
+// We cannot derive the state of confirmation modal from the existing subscription, as it will make the animation laggy when the confirmation closes.

217-219: Clarify the comment about nextPayment

The comment could be more specific about why free plans don't have nextPayment.

-  // Missing nextPayment means that an upcoming subscription is for the free plan
+  // Free plans don't have nextPayment since there's no payment required
packages/types/src/commerce.ts (1)

956-957: Address the TODO comment about nullable paymentSourceId.

The TODO comment indicates uncertainty about whether paymentSourceId should be nullable. This is an important design decision that affects API contracts and error handling.

Consider the business logic: Can a subscription item exist without a payment source (e.g., for free plans)? If so, make it nullable and ensure proper handling throughout the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61b592e and c0c8c89.

📒 Files selected for processing (21)
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (5 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (3 hunks)
  • packages/clerk-js/src/core/resources/Organization.ts (3 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (9 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (2 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (8 hunks)
  • packages/shared/src/react/hooks/createCommerceHook.tsx (1 hunks)
  • packages/shared/src/react/hooks/index.ts (1 hunks)
  • packages/shared/src/react/hooks/useOrganization.tsx (5 hunks)
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePaymentMethods.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePlans.tsx (1 hunks)
  • packages/shared/src/react/hooks/useStatements.tsx (1 hunks)
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx (1 hunks)
  • packages/types/src/commerce.ts (7 hunks)
  • packages/types/src/json.ts (3 hunks)
  • packages/types/src/organization.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
**/*

⚙️ CodeRabbit Configuration File

**/*: If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Whenever reviewing a pull request, if there are any changes that could impact security, always tag clerk/security in the PR.

Security-impacting changes include, but are not limited to:

  • Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
  • Any modification to access control, authorization checks, or role-based permissions
  • Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
  • Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
  • Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
  • Modifications to security headers, cookie flags, CORS policies, or CSRF protections
  • Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
  • Changes to rate limiting, abuse prevention, or input validation

If you're unsure whether a change is security-relevant, err on the side of caution and tag clerk/security.

Any time that you tag clerk/security, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
packages/**/index.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/shared/src/react/hooks/index.ts
**/index.ts

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/shared/src/react/hooks/index.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
🧬 Code Graph Analysis (11)
packages/shared/src/react/hooks/createCommerceHook.tsx (2)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/shared/src/react/types.ts (1)
  • PagesOrInfiniteOptions (124-144)
packages/types/src/organization.ts (2)
packages/types/src/commerce.ts (2)
  • GetSubscriptionsParams (914-914)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useSubscription (56-68)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (1)
  • useSubscription (20-50)
packages/clerk-js/src/core/resources/Organization.ts (5)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/clerk-js/src/utils/convertPageToOffsetSearchParams.ts (1)
  • convertPageToOffsetSearchParams (4-16)
packages/types/src/json.ts (1)
  • CommerceSubscriptionItemJSON (767-783)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)
  • CommerceSubscriptionItem (58-122)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (4)
packages/shared/src/react/hooks/index.ts (1)
  • useSubscription (15-15)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (1)
  • useSubscription (20-50)
packages/clerk-js/src/ui/contexts/components/SubscriberType.ts (1)
  • useSubscriberTypeContext (7-7)
packages/types/src/commerce.ts (2)
  • CommercePlanResource (241-411)
  • CommerceSubscriptionItemResource (946-1079)
packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (4)
packages/types/src/commerce.ts (4)
  • GetSubscriptionParams (924-926)
  • CommerceSubscriptionResource (1089-1188)
  • GetSubscriptionsParams (914-914)
  • CommerceSubscriptionItemResource (946-1079)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
  • CommerceSubscription (18-56)
  • CommerceSubscriptionItem (58-122)
packages/types/src/json.ts (2)
  • CommerceSubscriptionJSON (793-812)
  • CommerceSubscriptionItemJSON (767-783)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/shared/src/react/hooks/usePaymentAttempts.tsx (3)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePaymentAttempts (35-43)
packages/shared/src/react/hooks/createCommerceHook.tsx (1)
  • createCommercePaginatedHook (41-105)
packages/types/src/commerce.ts (2)
  • CommercePaymentResource (712-796)
  • GetPaymentAttemptsParams (806-806)
packages/types/src/json.ts (2)
packages/backend/src/api/resources/JSON.ts (1)
  • ClerkResourceJSON (70-79)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionStatus (111-111)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
packages/types/src/commerce.ts (3)
  • CommerceSubscriptionStatus (111-111)
  • CommerceMoney (1198-1235)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/json.ts (2)
  • CommerceSubscriptionJSON (793-812)
  • CommerceSubscriptionItemJSON (767-783)
packages/types/src/commerce.ts (2)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
🪛 Biome (1.9.4)
packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx

[error] 559-559: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
🔇 Additional comments (45)
packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)

1-1: LGTM: Type update aligns with subscription resource model refactor.

The change from CommerceSubscriptionResource to CommerceSubscriptionItemResource correctly reflects the component's usage of individual subscription items rather than aggregate subscriptions. The component logic remains unchanged and continues to access the status property which is available on the updated resource type.

Also applies to: 22-22

packages/shared/src/react/hooks/index.ts (1)

15-15: No changes needed: useSubscription export verified

I confirmed that packages/shared/src/react/hooks/useSubscriptionItems.tsx exports useSubscription (and no longer exports useSubscriptionItems), so the aliased re-export

export { useSubscription as __experimental_useSubscription } from './useSubscriptionItems';

is correct. Proceed as is.

packages/shared/src/react/hooks/createCommerceHook.tsx (1)

41-41: LGTM: Function rename improves clarity.

Renaming createCommerceHook to createCommercePaginatedHook better reflects the function's purpose of creating paginated commerce hooks. The implementation remains unchanged, maintaining backward compatibility while improving code readability and documentation accuracy.

packages/shared/src/react/hooks/usePlans.tsx (1)

4-4: LGTM: Consistent with hook factory rename.

The update to use createCommercePaginatedHook is consistent with the factory function rename and maintains the same functionality while making the pagination support more explicit in the hook creation.

Also applies to: 9-9

packages/shared/src/react/hooks/useStatements.tsx (1)

4-4: LGTM: Consistent with hook factory rename.

The update to use createCommercePaginatedHook follows the same pattern as other commerce hooks and maintains consistency with the factory function rename. The functionality remains unchanged while making pagination support more explicit.

Also applies to: 9-9

packages/shared/src/react/hooks/usePaymentAttempts.tsx (2)

4-4: LGTM: Import updated for pagination support.

The import change from createCommerceHook to createCommercePaginatedHook is correct and aligns with the broader refactor to add pagination support to commerce hooks.


9-16: LGTM: Hook creation updated for pagination.

The migration to createCommercePaginatedHook is correct. This hook now supports pagination and requires a for parameter (organization or user scope), which is properly provided by the wrapper hook in packages/clerk-js/src/ui/contexts/components/Plans.tsx (lines 34-42).

packages/shared/src/react/hooks/usePaymentMethods.tsx (2)

4-4: LGTM: Import updated for pagination support.

Consistent with other commerce hooks being migrated to use createCommercePaginatedHook.


9-21: LGTM: Hook creation updated for pagination.

The migration to createCommercePaginatedHook is correctly implemented and follows the same pattern as other commerce hooks in this refactor.

packages/types/src/organization.ts (2)

1-5: LGTM: Import updated for new subscription item type.

The addition of CommerceSubscriptionItemResource import is consistent with the refactor to distinguish between subscription items and aggregate subscriptions.


66-68: LGTM: Method signature updated to return subscription items.

The change from CommerceSubscriptionResource to CommerceSubscriptionItemResource aligns with the broader refactor. The method continues to return a paginated response, maintaining the expected interface contract while updating to the new resource type.

packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (5)

1-1: LGTM: Added useMemo import for performance optimization.

Good addition to support memoization of the sorted subscriptions array.


10-10: LGTM: Updated hook import for new subscription model.

The change from useSubscriptions to useSubscription aligns with the refactor to handle subscription items instead of aggregate subscriptions.


44-44: LGTM: Updated destructuring for subscription items.

Correctly destructures subscriptionItems from the new useSubscription hook.


50-65: LGTM: Added memoization for sorted subscriptions.

Good performance optimization by memoizing the sorted array. The sorting logic correctly prioritizes active subscriptions and depends on subscriptionItems for proper memoization.


77-77: LGTM: Updated references to use subscriptionItems.

All conditional checks and references have been correctly updated to use subscriptionItems instead of the previous subscriptions array.

Also applies to: 199-199, 206-206

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (4)

5-5: LGTM: Updated import to use absolute path alias.

Good consistency improvement using the absolute path alias instead of relative import.


7-7: LGTM: Updated hook import for new subscription model.

Consistent with other components, changing from useSubscriptions to useSubscription to align with the subscription items refactor.


15-15: LGTM: Updated destructuring for subscription items.

Correctly destructures subscriptionItems from the new hook.


21-36: LGTM: Updated useMemo logic for subscription items.

The logic correctly adapts to use subscriptionItems while maintaining the same business logic for determining the default plan period. The dependency array is properly updated to include subscriptionItems.

packages/shared/src/react/hooks/useOrganization.tsx (3)

4-4: LGTM: Import type updated consistently.

The import change from CommerceSubscriptionResource to CommerceSubscriptionItemResource aligns with the broader refactor to distinguish between aggregate subscriptions and individual subscription items.


118-118: LGTM: Type annotations updated consistently.

The subscriptions property type is correctly updated to CommerceSubscriptionItemResource across all union members of the UseOrganizationReturn interface, maintaining type consistency with the new subscription item model.

Also applies to: 128-128, 151-151


468-468: LGTM: Generic type parameter correctly updated.

The usePagesOrInfinite hook's generic type parameter is properly updated to CommerceSubscriptionItemResource, ensuring type safety for the paginated subscription items response.

packages/clerk-js/src/core/resources/Organization.ts (5)

5-6: LGTM: Import types updated for subscription item refactor.

The imports are correctly updated from CommerceSubscriptionJSON and CommerceSubscriptionResource to their subscription item equivalents, supporting the new data model distinction.


35-35: LGTM: Internal import updated to match class rename.

The import correctly changes from CommerceSubscription to CommerceSubscriptionItem, aligning with the refactored class structure.


238-238: LGTM: Method return type correctly updated.

The getSubscriptions method return type is properly updated to Promise<ClerkPaginatedResponse<CommerceSubscriptionItemResource>>, maintaining type safety with the new subscription item model.


245-245: LGTM: Response type cast updated for subscription items.

The type cast correctly changes to CommerceSubscriptionItemJSON, ensuring the API response is properly typed for the new subscription item JSON format.


249-249: LGTM: Instance creation updated to use subscription item class.

The mapping correctly creates CommerceSubscriptionItem instances, ensuring consistency with the method's return type and the new subscription item model.

packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (1)

36-79: LGTM: Test mocks consistently updated for new subscription API.

The test mocks are properly updated from getSubscriptions to getSubscription with the new data structure. The single subscription object now includes comprehensive fields (activeAt, createdAt, nextPayment, etc.) and contains subscriptionItems array, which aligns with the API refactor from paginated subscription lists to subscription objects containing subscription items.

Also applies to: 129-172, 222-265, 345-384, 485-523, 566-610, 699-714, 786-801, 862-890

packages/clerk-js/src/ui/contexts/components/Plans.tsx (8)

6-6: LGTM: Import and type updates align with subscription refactor.

The hook import changes from __experimental_useSubscriptionItems to __experimental_useSubscription, and the type changes from CommerceSubscriptionResource to CommerceSubscriptionItemResource, both consistent with the new subscription item model.

Also applies to: 13-13


56-68: LGTM: Hook implementation improved for new subscription model.

The useSubscription hook correctly fetches a single subscription and extracts subscriptionItems using useMemo. The return structure provides both the subscription data and subscription items, maintaining compatibility while adapting to the new API structure.


108-108: LGTM: Destructuring updated for new hook return structure.

The destructuring correctly changes from subscriptions to subscriptionItems, aligning with the updated hook return structure.


129-130: LGTM: Logic consistently updated to work with subscription items.

All references to subscriptions are properly updated to subscriptionItems throughout the callback functions and their dependencies, maintaining the existing business logic while adapting to the new data structure.

Also applies to: 135-135, 137-137, 143-143, 145-145


175-175: LGTM: Type annotations updated for subscription items.

The function parameter types are correctly updated from CommerceSubscriptionResource to CommerceSubscriptionItemResource, maintaining type safety with the new subscription item model.

Also applies to: 192-192


245-245: LGTM: Filtering logic updated to use subscription items.

The filtering logic correctly changes to use subscriptionItems instead of subscriptions, maintaining the business logic while working with the new data structure.


259-259: LGTM: Memoization dependency correctly updated.

The useMemo dependency array is properly updated from subscriptions to subscriptionItems, ensuring correct memoization behavior with the new data structure.


262-262: LGTM: Function parameter type updated for subscription items.

The captionForSubscription function parameter type is correctly updated to CommerceSubscriptionItemResource, maintaining type consistency with the new subscription item model.

packages/clerk-js/src/core/resources/CommercePayment.ts (4)

6-6: LGTM: Import types updated for resource consistency.

The imports are correctly updated to include CommercePaymentSourceResource and change to CommerceSubscriptionItemResource, aligning with the new resource type system.

Also applies to: 8-8


13-13: LGTM: Internal import updated to match class rename.

The internal import correctly changes from CommerceSubscription to CommerceSubscriptionItem, consistent with the class rename pattern throughout the codebase.


21-21: LGTM: Excellent backward-compatible property transition.

The approach maintains the deprecated subscription property while introducing the new subscriptionItem property with proper typing. This allows existing code to continue functioning while providing a clear migration path to the semantically correct property name.

Also applies to: 22-26


46-47: LGTM: Properties populated to support both old and new usage.

Both subscription and subscriptionItem properties are correctly populated with CommerceSubscriptionItem instances, ensuring backward compatibility while supporting the new property naming convention. The use of different JSON properties (data.subscription vs data.subscription_item) suggests proper API support for the transition.

packages/types/src/commerce.ts (4)

760-777: Good deprecation pattern.

The deprecation of the subscription property while introducing subscriptionItem follows good backward compatibility practices. Both properties now correctly use the CommerceSubscriptionItemResource type, maintaining consistency with the new type hierarchy.


916-926: LGTM - Well-defined parameter type.

The GetSubscriptionParams type is appropriately designed for fetching a single subscription with optional organization scoping, following established patterns in the codebase.


946-1079: Well-structured subscription item interface.

The interface provides comprehensive subscription item details with good backward compatibility through deprecated timestamp properties. The deprecation pattern using both numeric timestamps and Date objects is well-implemented.


1081-1188: Excellent aggregate subscription interface design.

The new CommerceSubscriptionResource interface provides a clean separation between aggregate subscription metadata and individual subscription items. Key strengths:

  • Logical hierarchy with subscriptionItems array containing individual items
  • Appropriate status restriction to 'active' | 'past_due' for aggregate level
  • Consistent use of Date objects throughout
  • Well-documented business logic (e.g., pastDueAt population when items are past due)

@@ -27,17 +69,18 @@ export class CommerceSubscription extends BaseResource implements CommerceSubscr
periodStart!: number;
periodEnd!: number;
canceledAt!: number | null;
//TODO(@COMMERCE): Why can this be undefined ?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Address TODO comment about undefined amount

The TODO raises a valid concern about why amount can be undefined. This should be investigated and resolved.


🏁 Script executed:

#!/bin/bash
# Search for usage of CommerceSubscriptionItem to understand when amount might be undefined
ast-grep --pattern 'amount' | rg -B5 -A5 "CommerceSubscriptionItem"

# Check if there are any subscription items without amount in the codebase
rg -A10 "amount.*undefined|amount.*null" --type ts

Length of output: 140215


🏁 Script executed:

#!/bin/bash
# Display the first 200 lines of CommerceSubscription.ts to inspect the class signature and constructor
sed -n '1,200p' packages/clerk-js/src/core/resources/CommerceSubscription.ts

Length of output: 3948


🏁 Script executed:

#!/bin/bash
# List immediate subdirectories under packages
ls -1 packages

Length of output: 234


🏁 Script executed:

#!/bin/bash
# List files in the types package
ls -1 packages/types

# Search for CommerceSubscriptionItemJSON in the types definitions
rg -n "export interface CommerceSubscriptionItemJSON" -n packages/types

Length of output: 325


🏁 Script executed:

#!/bin/bash
# Show CommerceSubscriptionItemJSON interface definition
sed -n '760,840p' packages/types/src/json.ts

Length of output: 2839


Remove TODO and document optional amount

The CommerceSubscriptionItemJSON.amount field is defined as optional in the API types (amount?: CommerceMoneyJSON), so it can legitimately be undefined (for example, on free‐plan or credit‐only subscription items). Remove the TODO and replace it with a clear explanatory comment:

export class CommerceSubscriptionItem extends BaseResource implements CommerceSubscriptionItemResource {
  // …
-  //TODO(@COMMERCE): Why can this be undefined ?
+  // `amount` is optional per API spec (e.g., free‐plan or credit‐only items)
  amount?: CommerceMoney;
  // …
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//TODO(@COMMERCE): Why can this be undefined ?
export class CommerceSubscriptionItem extends BaseResource implements CommerceSubscriptionItemResource {
// …
// `amount` is optional per API spec (e.g., free‐plan or credit‐only items)
amount?: CommerceMoney;
// …
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/CommerceSubscription.ts at line 72,
remove the TODO comment questioning why the amount can be undefined. Instead,
add a clear comment explaining that the CommerceSubscriptionItemJSON.amount
field is optional as per the API types and can be undefined for cases like
free-plan or credit-only subscription items.

Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

📝 Walkthrough

Walkthrough

This change set introduces a clear separation between "subscription" and "subscription item" concepts across the commerce-related modules, types, hooks, and UI components. The primary API for fetching subscriptions now returns a single, richer CommerceSubscriptionResource containing an array of CommerceSubscriptionItemResource objects, replacing the previous paginated list of flat subscription resources. Types and interfaces are updated to reflect this hierarchy, with deprecations and renames where appropriate. All hooks, UI components, and test suites are refactored to consume the new data shapes and APIs, including the introduction of a new useSubscription hook and the deprecation of useSubscriptionItems. Supporting infrastructure such as paginated hook factories is also renamed for clarity.

Estimated code review effort

4 (~90 minutes)

This is a broad, multi-layered refactor affecting type definitions, backend API contracts, hook implementations, UI components, and tests. The changes are medium-to-high complexity due to the need to ensure consistency and correctness across data models, API boundaries, and user-facing components, with careful attention required to verify that the new subscription hierarchy is correctly handled throughout the codebase.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🔭 Outside diff range comments (2)
packages/types/src/json.ts (1)

767-783: Consider adding deprecation notice for renamed interface

The renaming of CommerceSubscriptionJSON to CommerceSubscriptionItemJSON is a breaking change that could affect existing consumers.

Consider adding a deprecated type alias for backward compatibility:

/**
 * @deprecated Use CommerceSubscriptionItemJSON instead
 */
export type CommerceSubscriptionJSON_Legacy = CommerceSubscriptionItemJSON;

This would provide a migration path for existing code while clearly indicating the preferred new type.

Also applies to: 785-813

packages/types/src/commerce.ts (1)

760-777: Improve deprecation notice and document breaking change

The subscription property deprecation should guide users to the replacement property. Also, this is a breaking change that should be highlighted.

Update the deprecation notice to be more helpful:

   /**
-   * @deprecated
+   * @deprecated Use `subscriptionItem` instead. This property now returns CommerceSubscriptionItemResource instead of CommerceSubscriptionResource.
    * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change.

Note: This is a breaking change as the type of the subscription property has changed from CommerceSubscriptionResource to CommerceSubscriptionItemResource.

🧹 Nitpick comments (5)
packages/shared/src/react/hooks/index.ts (1)

15-15: Export change aligns with subscription refactor.

The change from useSubscriptionItems to useSubscription is consistent with the broader refactor. However, consider renaming the source file from useSubscriptionItems.tsx to useSubscription.tsx to match the exported function name and avoid confusion.

packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (1)

52-52: Clarify or address the API inconsistency comment.

The "Inconsistent API" comment lacks context about what makes this API inconsistent. Consider either:

  1. Expanding the comment to explain the specific inconsistency
  2. Creating a TODO with details about how to address it
  3. Filing an issue to track and resolve the inconsistency

This will help future developers understand the concern and potential next steps.

-  // Inconsistent API
+  // TODO: This method doesn't follow the same pattern as other methods (e.g., no pagination support)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)

72-76: Address TODO comment about optional amount field

The TODO comment questions why amount can be undefined. This should be resolved before merging to ensure type safety and proper documentation.

The optional amount field might be undefined for free plans or special subscription types. Would you like me to:

  1. Research the business logic to determine when amount is undefined
  2. Add proper type documentation explaining the cases
  3. Open an issue to track this technical debt?
packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (1)

41-42: Consider moving helper function to a utilities module

The isFreePlan helper function could be useful across the codebase and might benefit from being in a shared utilities module.

Consider moving to a shared location:

// In packages/clerk-js/src/ui/utils/commerce.ts
export const isFreePlan = (plan: CommercePlanResource) => !plan.hasBaseFee;

This would promote reusability across other commerce-related components.

packages/types/src/commerce.ts (1)

956-957: Address the TODO comment before merging

There's an unresolved TODO comment about the nullability of paymentSourceId. This should be clarified before the API is exposed.

Would you like me to help determine whether paymentSourceId should be nullable based on the usage patterns in the codebase, or create an issue to track this?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61b592e and c0c8c89.

📒 Files selected for processing (21)
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (5 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (3 hunks)
  • packages/clerk-js/src/core/resources/Organization.ts (3 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (9 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (2 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (8 hunks)
  • packages/shared/src/react/hooks/createCommerceHook.tsx (1 hunks)
  • packages/shared/src/react/hooks/index.ts (1 hunks)
  • packages/shared/src/react/hooks/useOrganization.tsx (5 hunks)
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePaymentMethods.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePlans.tsx (1 hunks)
  • packages/shared/src/react/hooks/useStatements.tsx (1 hunks)
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx (1 hunks)
  • packages/types/src/commerce.ts (7 hunks)
  • packages/types/src/json.ts (3 hunks)
  • packages/types/src/organization.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*

⚙️ CodeRabbit Configuration File

**/*: If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Whenever reviewing a pull request, if there are any changes that could impact security, always tag clerk/security in the PR.

Security-impacting changes include, but are not limited to:

  • Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
  • Any modification to access control, authorization checks, or role-based permissions
  • Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
  • Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
  • Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
  • Modifications to security headers, cookie flags, CORS policies, or CSRF protections
  • Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
  • Changes to rate limiting, abuse prevention, or input validation

If you're unsure whether a change is security-relevant, err on the side of caution and tag clerk/security.

Any time that you tag clerk/security, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.

Files:

  • packages/shared/src/react/hooks/createCommerceHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/shared/src/react/hooks/index.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/organization.ts
  • packages/shared/src/react/hooks/useOrganization.tsx
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useSubscriptionItems.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Subscriptions/badge.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
packages/**/index.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use tree-shaking friendly exports

Files:

  • packages/shared/src/react/hooks/index.ts
**/index.ts

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/shared/src/react/hooks/index.ts
🧬 Code Graph Analysis (11)
packages/shared/src/react/hooks/createCommerceHook.tsx (2)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/shared/src/react/types.ts (1)
  • PagesOrInfiniteOptions (124-144)
packages/shared/src/react/hooks/useStatements.tsx (3)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useStatements (45-54)
packages/shared/src/react/hooks/createCommerceHook.tsx (1)
  • createCommercePaginatedHook (41-105)
packages/types/src/commerce.ts (2)
  • CommerceStatementResource (837-875)
  • GetStatementsParams (816-816)
packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/shared/src/react/hooks/usePlans.tsx (3)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePlans (70-80)
packages/shared/src/react/hooks/createCommerceHook.tsx (1)
  • createCommercePaginatedHook (41-105)
packages/types/src/commerce.ts (2)
  • CommercePlanResource (241-411)
  • GetPlansParams (221-231)
packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useSubscription (56-68)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (1)
  • useSubscription (20-50)
packages/types/src/organization.ts (2)
packages/types/src/commerce.ts (2)
  • GetSubscriptionsParams (914-914)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/shared/src/react/hooks/useOrganization.tsx (3)
packages/shared/src/react/types.ts (1)
  • PaginatedResourcesWithDefault (83-85)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/clerk-js/src/core/resources/Organization.ts (4)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionItemResource (946-1079)
packages/types/src/json.ts (1)
  • CommerceSubscriptionItemJSON (767-783)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)
  • CommerceSubscriptionItem (58-122)
packages/shared/src/react/hooks/useSubscriptionItems.tsx (3)
packages/shared/src/react/hooks/index.ts (1)
  • useSubscription (15-15)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useSubscription (56-68)
packages/react/src/isomorphicClerk.ts (1)
  • organization (673-679)
packages/types/src/commerce.ts (2)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (21-30)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/types/src/json.ts (2)
packages/backend/src/api/resources/JSON.ts (1)
  • ClerkResourceJSON (70-79)
packages/types/src/commerce.ts (1)
  • CommerceSubscriptionStatus (111-111)
🪛 Biome (1.9.4)
packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx

[error] 559-559: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

🔇 Additional comments (35)
packages/clerk-js/src/ui/components/Subscriptions/badge.tsx (1)

1-1: LGTM! Type change aligns with commerce refactor.

The update from CommerceSubscriptionResource to CommerceSubscriptionItemResource is consistent with the broader refactor distinguishing between subscriptions and subscription items. The CommerceSubscriptionItemResource interface includes the status field that the component uses, ensuring functionality is preserved.

Also applies to: 22-22

packages/shared/src/react/hooks/createCommerceHook.tsx (1)

41-41: Excellent rename for clarity.

Renaming createCommerceHook to createCommercePaginatedHook better communicates the function's specific purpose of creating paginated commerce hooks. The comprehensive JSDoc documentation clearly explains the hook's capabilities and internal workings.

packages/shared/src/react/hooks/usePlans.tsx (1)

4-4: LGTM! Consistent with hook factory rename.

The updates to use createCommercePaginatedHook are consistent with the factory function rename and maintain the same functionality for the usePlans hook.

Also applies to: 9-9

packages/shared/src/react/hooks/usePaymentAttempts.tsx (1)

4-4: LGTM! Consistent with hook factory rename.

The updates to use createCommercePaginatedHook follow the same pattern as other commerce hooks and maintain functionality while aligning with the factory function rename.

Also applies to: 9-9

packages/shared/src/react/hooks/useStatements.tsx (2)

4-4: LGTM! Consistent with pagination refactor.

The update to use createCommercePaginatedHook aligns with the broader refactor to add pagination support to commerce hooks.


9-16: Hook configuration looks correct.

The hook configuration remains unchanged which indicates this is a clean rename/refactor. The hook name, resource type, and fetcher logic are all appropriate for statements functionality.

packages/shared/src/react/hooks/usePaymentMethods.tsx (2)

4-4: LGTM! Consistent pagination refactor.

The update to use createCommercePaginatedHook maintains consistency with other commerce hooks while adding pagination support.


9-21: Hook implementation remains solid.

The logic for selecting between organization and user payment sources is preserved correctly. The hook configuration parameters are appropriate.

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (3)

5-5: Import path updated correctly.

The change from relative to absolute import path for Flow improves consistency and maintainability.


7-7: Successfully migrated to new subscription data model.

The transition from useSubscriptions to useSubscription and from subscriptions to subscriptionItems aligns with the architectural change where subscription items are now the primary data structure being consumed by UI components.

Also applies to: 15-15


19-36: Logic correctly preserved in useMemo.

The logic for determining defaultPlanPeriod correctly uses subscriptionItems and maintains the same business logic for finding upcoming and active subscriptions. The dependency array is properly updated.

packages/types/src/organization.ts (2)

1-5: Import updated correctly for new subscription model.

The addition of CommerceSubscriptionItemResource to the imports aligns with the method signature change below.


66-68: Method signature correctly updated for subscription items.

The change from CommerceSubscriptionResource to CommerceSubscriptionItemResource reflects the architectural shift where organizations now directly retrieve subscription items rather than subscriptions containing items. This provides better consistency with the rest of the commerce API.

packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (4)

1-1: Good addition of useMemo import.

The import is needed for the new sorting optimization below.


10-10: Successfully migrated to new subscription hook.

The transition from useSubscriptions to useSubscription and the destructuring of subscriptionItems aligns perfectly with the architectural changes in the subscription data model.

Also applies to: 44-44


50-65: Excellent performance optimization with memoized sorting.

The addition of useMemo for sorting subscription items is a good performance improvement. The sorting logic correctly prioritizes active subscriptions, which enhances the user experience by showing the most relevant subscriptions first.


77-77: All subscription item references updated correctly.

The component consistently uses subscriptionItems throughout, maintaining the same conditional rendering and user interaction logic while working with the new data structure.

Also applies to: 199-199, 206-206

packages/clerk-js/src/core/resources/Organization.ts (4)

5-6: Import updates align with the subscription refactor.

The import changes correctly update from CommerceSubscriptionJSON and CommerceSubscriptionResource to their subscription item counterparts, which is consistent with the broader refactor that separates subscription items from subscriptions.


35-35: Internal import update is correct.

The import change from CommerceSubscription to CommerceSubscriptionItem is necessary to support the updated method implementation that now instantiates subscription item resources.


238-238: Method signature correctly updated for subscription items.

The return type change from CommerceSubscriptionResource to CommerceSubscriptionItemResource accurately reflects the new data model where this method returns subscription items rather than full subscriptions.


245-249: Implementation correctly updated to use subscription item types.

The changes properly update both the response type casting and object instantiation to use CommerceSubscriptionItemJSON and CommerceSubscriptionItem respectively, which is consistent with the method signature and the broader subscription refactor.

packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (1)

36-79: Test mocks correctly updated for new subscription data model.

The changes appropriately update the test to mock getSubscription instead of getSubscriptions and structure the data as a single subscription object with nested subscriptionItems, which aligns with the new subscription/subscription-item hierarchy.

packages/shared/src/react/hooks/useOrganization.tsx (2)

4-4: Import correctly updated for subscription item resource.

The import change from CommerceSubscriptionResource to CommerceSubscriptionItemResource is necessary and consistent with the subscription refactor across the codebase.


118-151: Type definitions consistently updated throughout the hook.

All type references have been properly updated from CommerceSubscriptionResource to CommerceSubscriptionItemResource, maintaining type safety while adapting to the new subscription item data model. The changes are consistent across all hook states and the pagination implementation.

Also applies to: 468-468

packages/clerk-js/src/core/resources/CommercePayment.ts (3)

6-8: Import and type updates are correct.

The imports have been properly updated to use CommerceSubscriptionItemResource instead of CommerceSubscriptionResource and include the necessary payment source types, which aligns with the subscription refactor and payment source type improvements.

Also applies to: 13-13


21-26: Well-implemented deprecation strategy for subscription property.

The approach correctly maintains backward compatibility by keeping the deprecated subscription property while introducing the new subscriptionItem property. The deprecation annotation helps developers migrate to the new property name, and the type updates improve type safety.


46-47: Implementation correctly handles both old and new subscription properties.

The code properly instantiates CommerceSubscriptionItem for both the deprecated subscription property (from data.subscription) and the new subscriptionItem property (from data.subscription_item), ensuring backward compatibility while supporting the new API structure.

packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (3)

11-12: Import additions support new subscription item functionality.

The new imports for subscription item types, parameters, and classes are necessary and correctly added to support the enhanced subscription handling with the separation of subscriptions and subscription items.

Also applies to: 19-19, 31-31


61-66: New getSubscription method correctly implemented.

The method properly handles both user and organization contexts, fetches from the appropriate endpoints, and returns a single CommerceSubscription instance. This provides access to the higher-level subscription object containing subscription items, complementing the paginated subscription items from getSubscriptions.


70-70: getSubscriptions method correctly updated to return subscription items.

The method has been properly updated to return CommerceSubscriptionItemResource instances instead of full subscriptions, with consistent updates to type casting and object instantiation. This creates a clear API separation between getting a single subscription (getSubscription) and getting paginated subscription items (getSubscriptions).

Also applies to: 79-79, 83-83

packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)

127-130: Consistent migration to CommerceSubscriptionItemResource

The migration from CommerceSubscriptionResource to CommerceSubscriptionItemResource has been applied consistently throughout the file. All helper functions and contexts have been updated to work with the new data structure.

Also applies to: 142-146, 174-180, 244-246, 258-260, 262-278

packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)

18-56: Well-structured implementation of CommerceSubscription class

The new CommerceSubscription class properly:

  • Implements the resource interface
  • Handles date conversions correctly
  • Maps nested subscription items
  • Provides null safety for optional fields
packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (2)

88-107: Well-implemented type-safe hook with overloads

The useGuessableSubscription hook demonstrates excellent TypeScript practices:

  • Conditional types based on options
  • Proper error handling with throw option
  • Clear return type definitions

437-547: Clean component extraction for SubscriptionCard

The extraction of SubscriptionCard as a separate component improves:

  • Code organization and readability
  • Reusability
  • Separation of concerns

The component properly handles all subscription states and edge cases.

packages/types/src/commerce.ts (1)

1081-1188: Well-designed subscription hierarchy

The new CommerceSubscriptionResource interface is well-structured with:

  • Clear hierarchical relationship containing multiple subscription items
  • Appropriate use of TypeScript's Extract utility for status constraints
  • Comprehensive property documentation
  • Logical property types and nullability

Comment on lines 26 to 39
const swr = useSWR(
user?.id
? {
type: 'commerce-subscription',
userId: user?.id,
args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
}
: null,
({ args }) => clerk.billing.getSubscription(args),
{
dedupingInterval: 1_000 * 60,
keepPreviousData: params?.keepPreviousData,
},
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle potential null organization ID gracefully

When params?.for === 'organization' but organization?.id is undefined, the API call might fail or return unexpected results.

Consider adding validation to ensure organization ID exists when fetching organization subscriptions:

   const swr = useSWR(
-    user?.id
+    user?.id && (params?.for !== 'organization' || organization?.id)
       ? {
           type: 'commerce-subscription',
           userId: user?.id,
           args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
         }
       : null,
     ({ args }) => clerk.billing.getSubscription(args),

This ensures the hook won't attempt to fetch when required data is missing.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const swr = useSWR(
user?.id
? {
type: 'commerce-subscription',
userId: user?.id,
args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
}
: null,
({ args }) => clerk.billing.getSubscription(args),
{
dedupingInterval: 1_000 * 60,
keepPreviousData: params?.keepPreviousData,
},
);
const swr = useSWR(
user?.id && (params?.for !== 'organization' || organization?.id)
? {
type: 'commerce-subscription',
userId: user?.id,
args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
}
: null,
({ args }) => clerk.billing.getSubscription(args),
{
dedupingInterval: 1_000 * 60,
keepPreviousData: params?.keepPreviousData,
},
);
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscriptionItems.tsx around lines 26 to
39, the code currently attempts to fetch subscription data using an organization
ID that might be undefined if params.for is 'organization' but organization.id
is missing. To fix this, add a validation check to ensure organization.id exists
before making the API call; if it does not exist, return null or skip the fetch
to prevent failed or unexpected API calls.

# Conflicts:
#	packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
@panteliselef panteliselef merged commit cd59c0e into main Jul 23, 2025
81 of 84 checks passed
@panteliselef panteliselef deleted the elef/com-959-useSubscription branch July 23, 2025 16:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants