-
Notifications
You must be signed in to change notification settings - Fork 401
feat(clerk-js,types): Make payment method optional for free trials #7068
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
base: main
Are you sure you want to change the base?
feat(clerk-js,types): Make payment method optional for free trials #7068
Conversation
🦋 Changeset detectedLatest commit: 8095cff The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
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 |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds a boolean Changes
Sequence DiagramsequenceDiagram
participant User
participant CheckoutUI as "CheckoutForm / Components"
participant API as "Backend / Mutations"
rect #F0F4C3
note left of CheckoutUI: Decision based on needsPaymentMethod
end
alt needsPaymentMethod == true
User->>CheckoutUI: Open checkout
CheckoutUI->>User: Show payment-method UI
User->>CheckoutUI: Select/add payment method
User->>CheckoutUI: Submit (Pay)
CheckoutUI->>API: confirmCheckout(payment_method_id)
API-->>CheckoutUI: success
CheckoutUI-->>User: Confirmation
else needsPaymentMethod == false
User->>CheckoutUI: Open checkout
CheckoutUI->>User: Show Start Trial (no payment UI)
User->>CheckoutUI: Click Start Trial
CheckoutUI->>API: confirmCheckout() / payWithoutPaymentMethod()
API-->>CheckoutUI: trial started
CheckoutUI-->>User: Confirmation
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used📓 Path-based instructions (13)packages/clerk-js/src/ui/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
Files:
**/*.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{ts,tsx,d.ts}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{jsx,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{test,spec}.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/*.{js,ts,tsx,jsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/*.tsx📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
Files:
**/*.test.{jsx,tsx}📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
Files:
**/__tests__/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
Files:
🧬 Code graph analysis (2)packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)
⏰ 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). (4)
🔇 Additional comments (13)
Comment |
ec36e8d to
db232df
Compare
db232df to
f122be2
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)
352-366: Remove unused variable_for.The variable destructured on line 353 is never used in the component. Consider removing it to keep the code clean.
Apply this diff:
const FreeTrialButton = withCardStateProvider(() => { - const { for: _for } = useCheckoutContext(); const { payWithoutPaymentMethod } = useCheckoutMutations(); const card = useCardState();
413-489: Consider simplifyingshowPaymentMethodslogic.In
ExistingPaymentMethodForm, line 438 setsshowPaymentMethods = needsPaymentMethod. However, this component is only rendered whenneedsPaymentMethodis already true (line 264). This means:
showPaymentMethodsis alwaystrueinside this component- The else branch (lines 479-483) is unreachable
You have two options:
- Remove the conditional and always render the Select component
- If the hidden input fallback serves a purpose, document why it's needed
Option 1 - Remove redundant conditional:
const ExistingPaymentMethodForm = withCardStateProvider( ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => { const { checkout } = useCheckout(); - const { paymentMethod, needsPaymentMethod } = checkout; + const { paymentMethod } = checkout; const { payWithExistingPaymentMethod } = useCheckoutMutations(); const card = useCardState(); const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<BillingPaymentMethodResource | undefined>( paymentMethod || paymentMethods.find(p => p.isDefault), ); const options = useMemo(() => { return paymentMethods.map(method => { const label = method.paymentType !== 'card' ? `${capitalize(method.paymentType)}` : `${capitalize(method.cardType)} ⋯ ${method.last4}`; return { value: method.id, label, }; }); }, [paymentMethods]); - const showPaymentMethods = needsPaymentMethod; return ( <Form onSubmit={payWithExistingPaymentMethod} sx={formProps} > - {showPaymentMethods ? ( - <Select - elementId='paymentMethod' - options={options} - value={selectedPaymentMethod?.id || null} - onChange={option => { - const paymentMethod = paymentMethods.find(source => source.id === option.value); - setSelectedPaymentMethod(paymentMethod); - }} - portal - > - {/*Store value inside an input in order to be accessible as form data*/} - <input - name={HIDDEN_INPUT_NAME} - type='hidden' - value={selectedPaymentMethod?.id} - /> - <SelectButton - icon={ChevronUpDown} - sx={t => ({ - justifyContent: 'space-between', - backgroundColor: t.colors.$colorBackground, - })} - > - {selectedPaymentMethod && <PaymentMethodRow paymentMethod={selectedPaymentMethod} />} - </SelectButton> - <SelectOptionList - sx={t => ({ - paddingBlock: t.space.$1, - color: t.colors.$colorForeground, - })} - /> - </Select> - ) : ( + <Select + elementId='paymentMethod' + options={options} + value={selectedPaymentMethod?.id || null} + onChange={option => { + const paymentMethod = paymentMethods.find(source => source.id === option.value); + setSelectedPaymentMethod(paymentMethod); + }} + portal + > + {/*Store value inside an input in order to be accessible as form data*/} <input name={HIDDEN_INPUT_NAME} type='hidden' value={selectedPaymentMethod?.id} /> - )} + <SelectButton + icon={ChevronUpDown} + sx={t => ({ + justifyContent: 'space-between', + backgroundColor: t.colors.$colorBackground, + })} + > + {selectedPaymentMethod && <PaymentMethodRow paymentMethod={selectedPaymentMethod} />} + </SelectButton> + <SelectOptionList + sx={t => ({ + paddingBlock: t.space.$1, + color: t.colors.$colorForeground, + })} + /> + </Select> <Card.Alert>{card.error}</Card.Alert> <CheckoutSubmitButton /> </Form> ); }, );
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
.changeset/bumpy-glasses-eat.md(1 hunks)packages/clerk-js/bundlewatch.config.json(1 hunks)packages/clerk-js/src/core/resources/BillingCheckout.ts(2 hunks)packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx(2 hunks)packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(12 hunks)packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx(1 hunks)packages/types/src/billing.ts(1 hunks)packages/types/src/json.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{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/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/bundlewatch.config.jsonpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/types/src/json.tspackages/types/src/billing.tspackages/clerk-js/src/core/resources/BillingCheckout.tspackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
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/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/bumpy-glasses-eat.md
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
Drawer(561-570)packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
Checkout(12-62)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
useCheckoutContext(10-37)packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
withCardStateProvider(72-81)useCardState(42-70)packages/types/src/billing.ts (1)
BillingPaymentMethodResource(277-332)packages/shared/src/react/hooks/useCheckout.ts (1)
useCheckout(70-147)
🔇 Additional comments (19)
packages/clerk-js/bundlewatch.config.json (1)
27-27: LGTM! Reasonable bundle size increase.The ~1.23KB increase in the checkout bundle size is expected given the addition of:
- New
needsPaymentMethodflag and related logic- New internal components (
FreeTrialButton,CheckoutSubmitButton)- Enhanced conditional rendering for free trial flows
.changeset/bumpy-glasses-eat.md (1)
1-6: LGTM! Changeset follows conventions.The changeset correctly specifies minor version bumps for both packages and provides a clear description of the feature.
packages/types/src/json.ts (1)
818-818: LGTM! JSON DTO field addition follows conventions.The
needs_payment_methodfield follows the snake_case naming convention used throughout the JSON DTOs and aligns with the camelCaseneedsPaymentMethodin the TypeScript interface.packages/types/src/billing.ts (1)
782-786: LGTM! Well-documented public API addition.The
needsPaymentMethodfield is properly documented with clear JSDoc explaining its purpose and usage. The addition is straightforward and follows the existing interface patterns.packages/clerk-js/src/core/resources/BillingCheckout.ts (2)
32-32: LGTM! Property declaration follows class conventions.The property declaration is consistent with other boolean flags in the class.
56-56: LGTM! Deserialization follows existing patterns.The mapping from
data.needs_payment_methodtothis.needsPaymentMethodis consistent with how other fields are deserialized in thefromJSONmethod.packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2)
164-164: LGTM! New field destructured for conditional UI logic.The
needsPaymentMethodfield is appropriately extracted from the checkout object to drive subsequent rendering decisions.
431-451: LGTM! Clearer conditional logic withneedsPaymentMethod.The refactored conditionals using
needsPaymentMethodare more explicit and maintainable than the previous logic based ontotals.totalDueNow.amount > 0 || freeTrialEndsAt !== null. The code properly handles the case whenpaymentMethodis undefined with a fallback to '–'.packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (5)
934-937: LGTM! Minor test improvement.Extracting the button to a variable before assertion improves readability and follows good testing practices.
939-1042: LGTM! Comprehensive free trial test coverage.This test effectively verifies the "Add payment method" tab behavior during free trials, including:
- Proper button text ("Start free trial")
- Tab switching behavior
- UI state when payment methods exist but aren't required
1044-1133: LGTM! Edge case properly tested.This test validates the scenario where no payment methods exist but the free trial requires adding one, ensuring the UI correctly prompts the user while hiding unnecessary controls.
1135-1229: LGTM! Important edge case covered.This test confirms that when
needsPaymentMethodis false, the payment method UI is completely hidden (no segmented controls, no hidden inputs), and only the "Start free trial" button is shown.
1231-1339: LGTM! Critical test for free trial isolation.This test ensures that even when stored payment methods exist, they are not displayed or used when
needsPaymentMethodis false. This properly validates that free trials can proceed without payment method collection when configured that way.packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)
2-2: LGTM! Unused import removed.Good cleanup removing the
BillingMoneyAmounttype that is no longer used in the file.
176-179: LGTM! New mutation handler for free trials without payment methods.The
payWithoutPaymentMethodhandler correctly confirms checkout without requiring payment data, enabling free trials that don't need upfront payment method collection.
241-258: LGTM! Segmented control properly gated byneedsPaymentMethod.The conditional ensures the payment method source selector is only shown when:
- Payment methods exist
- Payment method is actually needed
- RHC (React Headless Components) is not disabled
262-269: LGTM! Clear branching logic based onneedsPaymentMethod.The refactored conditional is straightforward:
- When payment method is needed: show existing or new payment method forms
- When not needed: show free trial button
This is much clearer than the previous totals-based logic.
387-405: LGTM! Reusable submit button component.The
CheckoutSubmitButtoncomponent appropriately consolidates the common submit button configuration (localization, loading state, full width) used across multiple forms.
407-411: LGTM! Shared styling helper.The
formPropshelper provides consistent vertical layout styling across all checkout forms.
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (7)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (7)
639-640: Good coverage for needsPaymentMethod; consider DRYing the fixtures.Adding
needsPaymentMethodin mocks across scenarios is correct and aligns tests with the new API surface. To reduce duplication and maintenance, extract a small builder (e.g.,buildCheckout(overrides)andbuildPlan(overrides)) and reuse across tests.Also applies to: 752-753, 892-893, 1109-1110, 1199-1200, 1303-1304, 1435-1436
937-939: Avoid brittle exact currency label match.Exact "Pay $10.00" can fail under locale/spacing differences. Prefer a regex and case-insensitive match.
- const payButton = getByRole('button', { name: 'Pay $10.00' }); - expect(payButton).toBeInTheDocument(); + expect(getByRole('button', { name: /pay\s*\$?\s*10\.00/i })).toBeInTheDocument();
942-1045: Move userEvent outside waitFor to reduce flakiness.Trigger events first, then wait for resulting assertions. Avoid invoking
userEventinsidewaitFor.- await waitFor(async () => { - expect(getByRole('heading', { name: 'Checkout' })).toBeVisible(); - const addPaymentMethodButton = getByText('Add payment method'); - expect(addPaymentMethodButton).toBeVisible(); - await userEvent.click(addPaymentMethodButton); - }); + expect(getByRole('heading', { name: 'Checkout' })).toBeVisible(); + const addPaymentMethodButton = getByText('Add payment method'); + expect(addPaymentMethodButton).toBeVisible(); + await userEvent.click(addPaymentMethodButton); + await waitFor(() => { + expect(getByRole('button', { name: 'Start free trial' })).toBeInTheDocument(); + });
1138-1232: Solid scenarios for “free trial, not required” with/without stored PMs; minor robustness nits.These cover the no-prompt path well. For resilience:
- Prefer case-insensitive queries for brand strings when present/absent checks: use
/visa/i.- Where asserting absence of tabs, also assert
queryByRole('tablist')is null to decouple from labels.Also applies to: 1234-1341
1330-1334: Card brand match should be case-insensitive.UI may render “Visa” vs “visa”. Use a regex.
- const visaPaymentMethod = queryByText('visa'); + const visaPaymentMethod = queryByText(/visa/i); expect(visaPaymentMethod).toBeNull(); - const last4Digits = queryByText('⋯ 4242'); + const last4Digits = queryByText(/⋯\s*4242/) expect(last4Digits).toBeNull();
942-1045: Reduce fixture duplication with small builders.The large repeated
startCheckoutandplanpayloads make updates error-prone. Extract a builder to keep tests concise and consistent.// top of file (outside tests) const basePlan = { id: 'plan_trial', name: 'Pro', description: 'Pro plan', features: [], fee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, annualFee: { amount: 12000, amountFormatted: '120.00', currency: 'USD', currencySymbol: '$' }, annualMonthlyFee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, slug: 'pro', avatarUrl: '', publiclyVisible: true, isDefault: true, isRecurring: true, hasBaseFee: false, forPayerType: 'user', freeTrialDays: 7, freeTrialEnabled: true, } as const; const baseCheckout = { externalClientSecret: 'cs_test', externalGatewayId: 'gw_test', totals: { subtotal: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, grandTotal: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' }, taxTotal: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' }, credit: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' }, pastDue: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' }, totalDueNow: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' }, }, isImmediatePlanChange: true, planPeriod: 'month', plan: basePlan, paymentMethod: undefined, confirm: vi.fn(), } as const; function buildCheckout(overrides: Partial<typeof baseCheckout> = {}) { return { id: 'chk_test', status: 'needs_confirmation', freeTrialEndsAt: null, ...baseCheckout, ...overrides }; }Also applies to: 1047-1136, 1138-1232, 1234-1341
639-640: I need to check the test file structure to understand whyas anyis being used and whether it's necessary:Based on my verification of the codebase:
The
needsPaymentMethodproperty is correctly integrated across all layers:
- ✅ Public types:
packages/types/src/billing.ts:786- ✅ JSON wire shape:
packages/types/src/json.ts:818(needs_payment_method)- ✅ Resource mapping:
packages/clerk-js/src/core/resources/BillingCheckout.ts:56(properly maps from wire format)- ✅ Hook state:
packages/shared/src/react/hooks/useCheckout.ts:116- ✅ UI components: properly destructured and used in
CheckoutComplete.tsxandCheckoutForm.tsxHowever, the underlying concern in your review is valid from a testing best practice perspective: using
anytype on mocks is a poor choice as there would be no relationship between mock and its actual type. TypeScript's Partial utility type allows you to create mock objects while keeping all properties optional, which is particularly useful when working with partial updates or constructing objects incrementally.Refactor test fixture objects to use
Partial<BillingCheckout>with a factory function instead ofas any.This improves type safety and maintains type checking while allowing partial mocking. The pattern is used throughout the test file at lines 639–640, 752–753, 892–893, 1109–1110, 1199–1200, 1303–1304, and 1435–1436.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(12 hunks)packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧰 Additional context used
📓 Path-based instructions (13)
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/Checkout/__tests__/Checkout.test.tsx
**/*.{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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
Drawer(561-570)packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
Checkout(12-62)
⏰ 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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)
393-417: LGTM: Well-refactored submit button and shared form styling.
CheckoutSubmitButtonextracts repeated logic with proper typing viaPropsOfComponentformPropsensures consistent vertical layout across all checkout forms- Both follow coding guidelines for reusable components and styling patterns
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(12 hunks)packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx(5 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
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/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
Drawer(561-570)packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
Checkout(12-62)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (5)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
useCheckoutContext(10-37)packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
withCardStateProvider(72-81)useCardState(42-70)packages/clerk-js/src/ui/styledSystem/types.ts (2)
PropsOfComponent(58-58)ThemableCssProp(58-58)packages/shared/src/react/hooks/useCheckout.ts (1)
useCheckout(70-148)packages/shared/src/react/hooks/index.ts (1)
useCheckout(16-16)
⏰ 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: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (4)
639-639: LGTM: needsPaymentMethod fixtures align with test scenarios.The additions of
needsPaymentMethod: trueto these test fixtures correctly reflect scenarios where payment methods are required.Also applies to: 752-752, 892-892
937-940: LGTM: Minor test refactor for clarity.Storing the Pay button in a variable before asserting is a good practice for test readability.
942-1136: LGTM: Comprehensive free trial test coverage.These two tests effectively cover the "Add payment method" flow for free trials:
- First test: When PMs exist, user can switch to "Add payment method" tab
- Second test: When no PMs exist and PM is required, the payment form is shown directly
The previous issue flagged in review comments has been resolved (needsPaymentMethod correctly set to
true).
1138-1342: Test expectations define important behavioral distinction.These tests establish that when
needsPaymentMethod: false:
- Free trials (Line 1234,
isImmediatePlanChange: true): Should NOT collect payment method at all—no hidden input (Line 1337)- Downgrades (Line 1344,
isImmediatePlanChange: false): Should silently collect payment method via hidden input (Line 1474)Ensure the implementation in
CheckoutForm.tsxcorrectly differentiates these scenarios.packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)
2-2: LGTM: Import additions support new functionality.The new type imports are properly utilized:
ConfirmCheckoutParamsat Line 151PropsOfComponentandThemableCssPropat Lines 393 and 413Also applies to: 18-18
176-179: LGTM: payWithoutPaymentMethod mutation correctly implements no-PM flow.The implementation correctly handles free-trial checkout when no payment method is required by calling
confirmCheckout({})with no parameters.Also applies to: 193-193
358-372: LGTM: FreeTrialButton component follows established patterns.The component is well-structured, using:
withCardStateProviderfor state managementCard.Alertfor error display- Shared
formPropsstyling for consistency- Reusable
CheckoutSubmitButtonAs per coding guidelines.
420-495: Conditional approval: ExistingPaymentMethodForm refactoring is sound IF rendering logic is fixed.The refactoring is well-executed:
- Destructured props signature (Line 420)
showPaymentMethods = needsPaymentMethodcleanly controls UI visibility (Line 444)- Hidden input at Lines 485-489 supports downgrade scenario
- Shared
formPropsstyling andCheckoutSubmitButtonmaintain consistencyHowever, this component assumes it's only rendered when appropriate. The critical bug at Lines 262-278 must be fixed first to ensure this component is never rendered for free trials when
needsPaymentMethod: false.
1635921 to
9c68ff1
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (7)
packages/clerk-js/src/core/resources/BillingCheckout.ts(2 hunks)packages/clerk-js/src/test/fixture-helpers.ts(1 hunks)packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx(2 hunks)packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(12 hunks)packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx(8 hunks)packages/types/src/billing.ts(1 hunks)packages/types/src/json.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/types/src/json.ts
- packages/clerk-js/src/core/resources/BillingCheckout.ts
- packages/types/src/billing.ts
🧰 Additional context used
📓 Path-based instructions (13)
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/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsxpackages/clerk-js/src/test/fixture-helpers.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsxpackages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (5)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
useCheckoutContext(10-37)packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
usePaymentMethods(32-40)packages/shared/src/react/hooks/usePaymentMethods.tsx (1)
usePaymentMethods(9-21)packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
withCardStateProvider(72-81)useCardState(42-70)packages/clerk-js/src/ui/styledSystem/types.ts (2)
PropsOfComponent(58-58)ThemableCssProp(58-58)
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)
packages/clerk-js/src/ui/elements/LineItems.tsx (1)
LineItems(289-294)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
Drawer(561-570)packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
Checkout(12-62)
⏰ 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: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (9)
packages/clerk-js/src/test/fixture-helpers.ts (1)
365-380: LGTM! Enhanced test fixture flexibility.The parameterized
withBillingfunction provides better control over billing configuration in tests, allowing selective enablement of user/organization billing and paid plans. The default values (alltrue) maintain backward compatibility for existing tests while enabling more granular scenarios.packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2)
164-164: LGTM! New flag integrated correctly.The
needsPaymentMethodflag is properly destructured and used to control the completion screen display logic.
431-451: LGTM! Conditional rendering handles both free trial and payment flows.The logic correctly switches between:
- Payment method details when
needsPaymentMethodis true- Subscription start date when
needsPaymentMethodis falseAppropriate fallbacks ('–') are provided when data is unavailable.
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (3)
176-179: LGTM! Simple mutation for free trials without payment methods.The
payWithoutPaymentMethodfunction correctly confirms checkout without a payment source, enabling frictionless free trial activation.
358-372: LGTM! Free trial button properly integrated.The
FreeTrialButtoncomponent correctly:
- Wraps submission in a form with
payWithoutPaymentMethodhandler- Uses shared
CheckoutSubmitButtonfor consistency- Displays errors via
Card.Alert- Applies shared
formPropsstyling
393-417: LGTM! Reusable submit button with shared styling.The
CheckoutSubmitButtonandformPropsprovide consistent styling and behavior across all checkout forms.packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (3)
312-394: LGTM! Comprehensive free trial confirmation stage test.Properly validates:
- Free trial badge display
- "Total Due after trial ends in N days" line item
- "Start free trial" button presence
- All with
needsPaymentMethod: false
945-1139: LGTM! Extensive free trial flow coverage.These three new tests comprehensively validate:
- Add payment method tab shows "Start free trial" for trials requiring PM
- Free trial prompts for PM when none exists and PM is required
- Free trial bypasses PM collection when PM is not required
The assertions correctly verify tab visibility, button labels, and absence of hidden
payment_method_idinputs when PM is not needed.
1141-1347: LGTM! Critical free trial scenarios validated.These tests verify:
- No PM prompts when
needsPaymentMethod: false(Lines 1141-1236)- No PM prompts even with stored PMs when not required (Lines 1238-1347)
Both correctly assert:
- Segmented controls are hidden
- No hidden
payment_method_idinput- "Start free trial" button renders
Note: These tests likely pass because
__BUILD_DISABLE_RHC__defaults totruein the test environment, which makespaymentMethodSourcedefault to'existing'(Line 226 in CheckoutForm.tsx). The rendering bug I flagged would surface in production when RHC is enabled.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)
265-271: LGTM: Rendering logic correctly handles all checkout scenarios.The conditional logic properly prioritizes
needsPaymentMethodto determine the checkout flow:
- When
false: Always rendersFreeTrialButton(no payment collection)- When
true: Renders appropriate payment method form based onpaymentMethodSourceThis addresses the free-trial-without-payment-method requirement and maintains backward compatibility for downgrades and immediate plan changes.
Optional: Add inline comments for complex conditional.
Consider adding brief comments explaining each branch to improve maintainability:
- {!needsPaymentMethod ? ( + {/* Free trials: no payment method required */} + {!needsPaymentMethod ? ( <FreeTrialButton /> + {/* Payment required: show appropriate form based on source */} ) : paymentMethodSource === 'existing' ? ( <ExistingPaymentMethodForm paymentMethods={paymentMethods} /> ) : ( !__BUILD_DISABLE_RHC__ && paymentMethodSource === 'new' && <AddPaymentMethodForCheckout /> )}
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(12 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
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/Checkout/CheckoutForm.tsx
**/*.{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/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/CheckoutForm.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
useCheckoutContext(10-37)packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
usePaymentMethods(32-40)packages/shared/src/react/hooks/usePaymentMethods.tsx (1)
usePaymentMethods(9-21)packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
withCardStateProvider(72-81)useCardState(42-70)packages/clerk-js/src/ui/styledSystem/types.ts (2)
PropsOfComponent(58-58)ThemableCssProp(58-58)packages/shared/src/react/hooks/useCheckout.ts (1)
useCheckout(70-148)
⏰ 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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)
2-2: LGTM: Import updates are necessary and properly typed.The added type imports are correctly used later in the file and follow TypeScript best practices for type-only imports.
Also applies to: 18-18
141-195: LGTM: Payment without payment method flow is correctly implemented.The new
payWithoutPaymentMethodmutation follows the established pattern and correctly callsconfirmCheckoutwith an empty params object, enabling free trials without requiring payment method collection.
389-413: LGTM: New components follow best practices.
CheckoutSubmitButtonandformPropsare well-designed:
- Proper TypeScript typing with
PropsOfComponentandThemableCssProp- Consistent use of theme tokens and localization
- Appropriate spread operator usage for prop forwarding
- Follows coding guidelines for UI components
415-492: Edge case confirmed as real but not a code defect.The edge case (empty payment methods with RHC disabled + payment required) is theoretically possible but doesn't require frontend fixes:
- Form submission handler extracts whatever value is in the form (line 169)
- Backend validation is responsible for rejecting invalid/empty payment source IDs
- This aligns with the minimal validation pattern in the component
- RHC-disabled + zero payment methods is an extremely rare legacy scenario
- Test coverage exists for related payment method scenarios
The updates to
ExistingPaymentMethodFormcorrectly implement theneedsPaymentMethodflag and properly handle both rendering paths (downgrades vs. immediate changes). No additional frontend safeguards are needed.
| const FreeTrialButton = withCardStateProvider(() => { | ||
| const { for: _for } = useCheckoutContext(); | ||
| const { payWithoutPaymentMethod } = useCheckoutMutations(); | ||
| const card = useCardState(); | ||
|
|
||
| return ( | ||
| <Form | ||
| onSubmit={payWithoutPaymentMethod} | ||
| sx={formProps} | ||
| > | ||
| <Card.Alert>{card.error}</Card.Alert> | ||
| <CheckoutSubmitButton /> | ||
| </Form> | ||
| ); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove unused destructured variable.
Line 355 destructures for: _for from the context but never uses it. This appears to be leftover from refactoring.
Apply this diff:
const FreeTrialButton = withCardStateProvider(() => {
- const { for: _for } = useCheckoutContext();
const { payWithoutPaymentMethod } = useCheckoutMutations();
const card = useCardState();📝 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.
| const FreeTrialButton = withCardStateProvider(() => { | |
| const { for: _for } = useCheckoutContext(); | |
| const { payWithoutPaymentMethod } = useCheckoutMutations(); | |
| const card = useCardState(); | |
| return ( | |
| <Form | |
| onSubmit={payWithoutPaymentMethod} | |
| sx={formProps} | |
| > | |
| <Card.Alert>{card.error}</Card.Alert> | |
| <CheckoutSubmitButton /> | |
| </Form> | |
| ); | |
| }); | |
| const FreeTrialButton = withCardStateProvider(() => { | |
| const { payWithoutPaymentMethod } = useCheckoutMutations(); | |
| const card = useCardState(); | |
| return ( | |
| <Form | |
| onSubmit={payWithoutPaymentMethod} | |
| sx={formProps} | |
| > | |
| <Card.Alert>{card.error}</Card.Alert> | |
| <CheckoutSubmitButton /> | |
| </Form> | |
| ); | |
| }); |
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around lines
354 to 368, the destructured variable `for: _for` is unused; remove the `for:
_for` from the useCheckoutContext() destructure so the context is accessed
without extracting an unused binding, leaving the const as `const { } =
useCheckoutContext();` or simply `useCheckoutContext();` (prefer keeping any
needed hook call) and ensure no other references depend on `_for`.
Description
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
UI Changes
Types
Tests
Chores