-
Notifications
You must be signed in to change notification settings - Fork 402
feat(clerk-js): Pass locale to Stripe elements #6885
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
Conversation
🦋 Changeset detectedLatest commit: 0333fce 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.
|
WalkthroughPropagate locale from ClerkProvider into Stripe PaymentElement by adding a localization hook and passing a normalized two-letter locale into Stripe Elements; make Changes
Sequence Diagram(s)sequenceDiagram
participant CP as ClerkProvider
participant UI as useLocalization
participant PE as PaymentElementInternalRoot
participant SE as Stripe Elements
CP->>UI: supply localization options
UI->>UI: normalize locale (e.g., "en-US" → "en")\ndefault "en" if missing
UI-->>PE: return normalized locale
PE->>SE: initialize Elements with locale option
SE->>SE: render PaymentElement localized UI
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20–30 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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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). (3)
Comment |
packages/clerk-js/src/core/clerk.ts
Outdated
| const mergedOptions = { ...this.#options, ..._props.options }; | ||
|
|
||
| // Update the Clerk instance's internal options | ||
| this.#options = mergedOptions; |
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.
I'm unsure if there is a reason we weren't doing this previously, but without it clerk.__internal_getOption('localization') would not work after __unstable__updateProps was called in the sandbox
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 (5)
packages/shared/src/react/commerce.tsx (2)
65-78: Locale normalization is too naive; consider BCP‑47 and Stripe’s supported setSplitting on '-' loses region variants (e.g., pt-BR, fr-CA, zh-HK, zh-TW, es-419) and ignores 'auto'. This can degrade UX vs Stripe’s localized formats. Recommend:
- Accept 'auto' if Clerk opts for auto-detection.
- Preserve known region-specific locales Stripe supports; otherwise fall back to the base language or 'en'.
- Optionally log at debug level instead of fully swallowing errors for easier diagnosis.
I can provide a small helper (toStripeLocale) to normalize and validate against a supported set while keeping your current default of 'en'.
238-239: Removeas anyand pass a typed Stripe locale
as anyhides type issues and may pass unsupported values to Stripe. Use Stripe’s locale type and a small normalizer:
- Import the type and return a properly typed value from your hook, then pass it directly.
Example minimal change (keeps current behavior while improving typing):
-import type { Stripe, StripeElements } from '@stripe/stripe-js'; +import type { Stripe, StripeElements, StripeElementsOptions } from '@stripe/stripe-js'; … -const useLocalization = () => { +const useLocalization = (): StripeElementsOptions['locale'] => { const clerk = useClerk(); let locale = 'en'; try { const localization = clerk.__internal_getOption('localization'); locale = localization?.locale || 'en'; } catch (_) {} // Normalize locale to 2-letter language code for Stripe compatibility - const normalizedLocale = locale.split('-')[0]; - return normalizedLocale; + const normalizedLocale = locale.split('-')[0] as StripeElementsOptions['locale']; + return normalizedLocale; }; … - locale: locale as any, + locale,This eliminates
anyand keeps your current two‑letter normalization. We can iterate later to preserve regional variants if desired.packages/clerk-js/sandbox/app.ts (1)
240-254: Good consolidation; add a small guard to avoid no‑op updatesBuilding
optionsonce and calling__unstable__updateProps({ options })is cleaner. To reduce needless work, consider bailing if the computedoptions.localizationhasn’t changed fromClerk.__internal_getOption('localization'). Also, ifl[input.value]is ever undefined, fall back tol.enUSto stay robust.packages/shared/src/react/__tests__/commerce.test.tsx (2)
64-67: SWR mock may not match both call sites; make it key‑awareThe same
useSWRmock services two different keys: 'clerk-stripe-sdk' (returns{ loadStripe }) and 'stripe-sdk' (returns the Stripe instance). The current mock always returns{ data: { loadStripe: fn } }, which can hide shape issues. Consider:-jest.mock('swr', () => ({ - __esModule: true, - default: () => ({ data: { loadStripe: jest.fn().mockResolvedValue({}) } }), -})); +jest.mock('swr', () => ({ + __esModule: true, + default: (key: any, fetcher?: any) => { + if (key === 'clerk-stripe-sdk') { + return { data: { loadStripe: jest.fn().mockResolvedValue({}) } }; + } + if (key?.key === 'stripe-sdk') { + // Simulate resolved Stripe instance + return { data: {} }; + } + return { data: undefined }; + }, +}));This keeps the tests closer to runtime behavior and avoids accidental truthy mismatches.
85-321: Reset mocks between tests to avoid cross‑test leakage
mockGetOptionis reconfigured in multiple tests without reset, which can cause order-dependent behavior. Add:beforeEach(() => { jest.clearAllMocks(); });Optionally also
jest.resetModules()if module state matters.
📜 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 (4)
packages/clerk-js/sandbox/app.ts(1 hunks)packages/clerk-js/src/core/clerk.ts(1 hunks)packages/shared/src/react/__tests__/commerce.test.tsx(1 hunks)packages/shared/src/react/commerce.tsx(3 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/sandbox/app.tspackages/clerk-js/src/core/clerk.tspackages/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/shared/src/react/commerce.tsxpackages/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsx
🧬 Code graph analysis (1)
packages/clerk-js/sandbox/app.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
Clerk(199-2952)
⏰ 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). (2)
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
@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 (6)
packages/shared/src/react/__tests__/commerce.test.tsx (6)
10-24: Stripe mock: narrow option typing for clarityUse a minimal options type instead of
anyto satisfy TS test guidelines and catch regressions.-jest.mock('../stripe-react', () => ({ - Elements: ({ children, options }: { children: React.ReactNode; options: any }) => ( +jest.mock('../stripe-react', () => ({ + Elements: ({ children, options }: { children: React.ReactNode; options: { locale?: string } }) => (
65-84: Module mocks: add lightweight reset to avoid cross-test leakageMocks are reconfigured per test but never reset. Add a global reset to keep tests independent and easier to extend.
describe('PaymentElement Localization', () => { + afterEach(() => { + jest.clearAllMocks(); + mockGetOption.mockReset(); + });
162-182: Helper stability: reset and set mock in one placeGuard against residual implementations when
renderWithLocaleis called multiple times.-const renderWithLocale = (locale: string) => { - // Mock the __internal_getOption to return the expected localization - mockGetOption.mockImplementation(key => { +const renderWithLocale = (locale: string) => { + mockGetOption.mockReset(); + mockGetOption.mockImplementation(key => { if (key === 'localization') { return { locale }; } return undefined; });
214-225: Iterating locales: prefer table-driven tests for better failure output
it.eachyields clearer diffs on failures and runs cases independently.-it('should handle different locale values', () => { - const locales = ['en', 'es', 'fr', 'de', 'it']; - locales.forEach(locale => { - const { unmount } = renderWithLocale(locale); - const elements = screen.getByTestId('stripe-elements'); - expect(elements).toHaveAttribute('data-locale', locale); - unmount(); - }); -}); +it.each(['en', 'es', 'fr', 'de', 'it'])( + 'should pass locale "%s" through unchanged', + locale => { + const { unmount } = renderWithLocale(locale); + expect(screen.getByTestId('stripe-elements')).toHaveAttribute('data-locale', locale); + unmount(); + }, +);
191-212: Add a negative/invalid-locale caseStrengthen defaults with an invalid locale (e.g.,
xx-YY) asserting fallback toen.it('should default to "en" when no locale is provided', () => { // ... expect(elements).toHaveAttribute('data-locale', 'en'); }); +it('should fallback to "en" for invalid/unknown locales', () => { + mockGetOption.mockReset(); + mockGetOption.mockImplementation(key => (key === 'localization' ? { locale: 'xx-YY' } : undefined)); + render( + <OptionsContext.Provider value={{ localization: { locale: 'xx-YY' } as any }}> + <__experimental_PaymentElementProvider checkout={mockCheckout}> + <__experimental_PaymentElement fallback={<div>Loading...</div>} /> + </__experimental_PaymentElementProvider> + </OptionsContext.Provider>, + ); + expect(screen.getByTestId('stripe-elements')).toHaveAttribute('data-locale', 'en'); +});Also applies to: 227-250
87-160: Consider a typed factory for checkout fixturesThis large inline object is repeated across commerce tests in this area. A small factory (with override support) improves reuse and narrows types.
// test/utils/factories.ts export function createCheckout(overrides: Partial<Checkout> = {}): Checkout { return { id: 'checkout_123', // ...defaults as above... ...overrides, }; }Then import and use
createCheckout()here to keep tests focused.
📜 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/shared/src/react/__tests__/commerce.test.tsx(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/react/__tests__/commerce.test.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/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/shared/src/react/__tests__/commerce.test.tsx (3)
191-212: Default locale case looks goodAsserting fallback to
enwhen no localization is present is appropriate and aligns with the intended behavior.
252-283: ClerkProvider-style resource case is validNormalizing
fr-FRtofrhere is reasonable since Stripe acceptsfrand there’s no region-specific variant for France to preserve.
171-173: Annotateoptionswith the actual context value type
I couldn’t locate anOptionsContextValueexport inpackages/shared/src/react. Please verify the correct context-value type exported by yourcontextsmodule, import it, and then declare:const options: Partial<YourContextType> = { localization: { locale }, };
| it('should normalize full locale strings to 2-letter codes for Stripe', () => { | ||
| const testCases = [ | ||
| { input: 'en-US', expected: 'en' }, | ||
| { input: 'fr-FR', expected: 'fr' }, | ||
| { input: 'es-ES', expected: 'es' }, | ||
| { input: 'de-DE', expected: 'de' }, | ||
| { input: 'it-IT', expected: 'it' }, | ||
| { input: 'pt-BR', expected: 'pt' }, | ||
| ]; | ||
|
|
||
| testCases.forEach(({ input, expected }) => { | ||
| // Mock the __internal_getOption to return the expected localization | ||
| mockGetOption.mockImplementation(key => { | ||
| if (key === 'localization') { | ||
| return { locale: input }; | ||
| } | ||
| return undefined; | ||
| }); | ||
|
|
||
| const options = { | ||
| localization: { locale: input }, | ||
| }; | ||
|
|
||
| const { unmount } = render( | ||
| <OptionsContext.Provider value={options}> | ||
| <__experimental_PaymentElementProvider checkout={mockCheckout}> | ||
| <__experimental_PaymentElement fallback={<div>Loading...</div>} /> | ||
| </__experimental_PaymentElementProvider> | ||
| </OptionsContext.Provider>, | ||
| ); | ||
|
|
||
| const elements = screen.getByTestId('stripe-elements'); | ||
| expect(elements).toHaveAttribute('data-locale', expected); | ||
|
|
||
| unmount(); | ||
| }); | ||
| }); |
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.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Normalization may drop supported regional locales (risk of worse UX)
The test enforces unconditional 2-letter normalization (e.g., pt-BR → pt). Stripe Elements accepts several region codes (e.g., pt-BR, fr-CA, en-GB, es-419, zh-TW). Collapsing these to base language can degrade translations.
Recommendation:
- Preserve locale if it’s in Stripe’s supported list (including region variants).
- Otherwise, try base language; finally fall back to
en.
Update tests to reflect preservation where applicable.
- const testCases = [
- { input: 'en-US', expected: 'en' },
- { input: 'fr-FR', expected: 'fr' },
- { input: 'es-ES', expected: 'es' },
- { input: 'de-DE', expected: 'de' },
- { input: 'it-IT', expected: 'it' },
- { input: 'pt-BR', expected: 'pt' },
- ];
+ const testCases = [
+ // preserve known region variants supported by Stripe
+ { input: 'en-GB', expected: 'en-GB' },
+ { input: 'fr-CA', expected: 'fr-CA' },
+ { input: 'es-419', expected: 'es-419' },
+ { input: 'pt-BR', expected: 'pt-BR' },
+ { input: 'zh-TW', expected: 'zh-TW' },
+ // collapse to base where region is not needed/supported
+ { input: 'en-US', expected: 'en' },
+ { input: 'fr-FR', expected: 'fr' },
+ { input: 'es-ES', expected: 'es' },
+ { input: 'de-DE', expected: 'de' },
+ { input: 'it-IT', expected: 'it' },
+ ];To confirm Stripe’s current supported locales list:
🌐 Web query:
What locales are supported by Stripe Elements as of September 2025? Does it accept region codes like en-GB, fr-CA, es-419, pt-BR, zh-TW?
💡 Result:
Short answer: Yes — Stripe Elements accepts specific locale codes (including region variants). The Stripe docs list the supported locales and include en-GB, fr-CA, es-419 and pt-BR. For Chinese they use region/script variants (zh-Hans for Simplified, zh-Hant-TW for Traditional Taiwan, zh-Hant-HK for Hong Kong). If you pass a locale not directly supported Stripe will pick a reasonable fallback (e.g., fr-BE → fr-FR). [1][2]
Sources:
- Stripe Elements / Connect embedded components supported locales (includes en-GB, fr-CA, es-419, pt-BR, zh-Hant-TW, zh-Hans). [1]
- Stripe Checkout / locale support & fallback behavior. [2]
Preserve Stripe-supported locale variants in normalization/tests
The current logic collapses every locale (e.g., pt-BR, en-GB) to its two-letter base, but Stripe Elements accepts region/script variants (en-GB, fr-CA, es-419, pt-BR, zh-Hans, zh-Hant-TW, zh-Hant-HK) [1][2]. Update the normalization (and corresponding tests) to:
- Use the full locale if it’s in Stripe’s supported list
- Otherwise fall back to the two-letter language tag
- Finally fall back to
enas a last resort
Example test update:
- const testCases = [
- { input: 'en-US', expected: 'en' },
- { input: 'fr-FR', expected: 'fr' },
- // …
- ];
+ const testCases = [
+ // preserve supported region/script variants
+ { input: 'en-GB', expected: 'en-GB' },
+ { input: 'fr-CA', expected: 'fr-CA' },
+ { input: 'es-419', expected: 'es-419' },
+ { input: 'pt-BR', expected: 'pt-BR' },
+ { input: 'zh-Hans', expected: 'zh-Hans' },
+ { input: 'zh-Hant-TW', expected: 'zh-Hant-TW' },
+ // collapse unsupported variants
+ { input: 'en-US', expected: 'en' },
+ { input: 'fr-FR', expected: 'fr' },
+ { input: 'es-ES', expected: 'es' },
+ // …
+ ];📝 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.
| it('should normalize full locale strings to 2-letter codes for Stripe', () => { | |
| const testCases = [ | |
| { input: 'en-US', expected: 'en' }, | |
| { input: 'fr-FR', expected: 'fr' }, | |
| { input: 'es-ES', expected: 'es' }, | |
| { input: 'de-DE', expected: 'de' }, | |
| { input: 'it-IT', expected: 'it' }, | |
| { input: 'pt-BR', expected: 'pt' }, | |
| ]; | |
| testCases.forEach(({ input, expected }) => { | |
| // Mock the __internal_getOption to return the expected localization | |
| mockGetOption.mockImplementation(key => { | |
| if (key === 'localization') { | |
| return { locale: input }; | |
| } | |
| return undefined; | |
| }); | |
| const options = { | |
| localization: { locale: input }, | |
| }; | |
| const { unmount } = render( | |
| <OptionsContext.Provider value={options}> | |
| <__experimental_PaymentElementProvider checkout={mockCheckout}> | |
| <__experimental_PaymentElement fallback={<div>Loading...</div>} /> | |
| </__experimental_PaymentElementProvider> | |
| </OptionsContext.Provider>, | |
| ); | |
| const elements = screen.getByTestId('stripe-elements'); | |
| expect(elements).toHaveAttribute('data-locale', expected); | |
| unmount(); | |
| }); | |
| }); | |
| it('should normalize full locale strings to 2-letter codes for Stripe', () => { | |
| - const testCases = [ | |
| - { input: 'en-US', expected: 'en' }, | |
| - { input: 'fr-FR', expected: 'fr' }, | |
| - { input: 'es-ES', expected: 'es' }, | |
| - { input: 'de-DE', expected: 'de' }, | |
| - { input: 'it-IT', expected: 'it' }, | |
| - { input: 'pt-BR', expected: 'pt' }, | |
| const testCases = [ | |
| // preserve Stripe-supported region/script variants | |
| { input: 'en-GB', expected: 'en-GB' }, | |
| { input: 'fr-CA', expected: 'fr-CA' }, | |
| { input: 'es-419', expected: 'es-419' }, | |
| { input: 'pt-BR', expected: 'pt-BR' }, | |
| { input: 'zh-Hans', expected: 'zh-Hans' }, | |
| { input: 'zh-Hant-TW', expected: 'zh-Hant-TW' }, | |
| // fall back to 2-letter language code for unsupported variants | |
| { input: 'en-US', expected: 'en' }, | |
| { input: 'fr-FR', expected: 'fr' }, | |
| { input: 'es-ES', expected: 'es' }, | |
| { input: 'de-DE', expected: 'de' }, | |
| { input: 'it-IT', expected: 'it' }, | |
| ]; | |
| testCases.forEach(({ input, expected }) => { | |
| // Mock the __internal_getOption to return the expected localization | |
| mockGetOption.mockImplementation(key => { | |
| if (key === 'localization') { | |
| return { locale: input }; | |
| } | |
| return undefined; | |
| }); | |
| const options = { | |
| localization: { locale: input }, | |
| }; | |
| const { unmount } = render( | |
| <OptionsContext.Provider value={options}> | |
| <__experimental_PaymentElementProvider checkout={mockCheckout}> | |
| <__experimental_PaymentElement fallback={<div>Loading...</div>} /> | |
| </__experimental_PaymentElementProvider> | |
| </OptionsContext.Provider>, | |
| ); | |
| const elements = screen.getByTestId('stripe-elements'); | |
| expect(elements).toHaveAttribute('data-locale', expected); | |
| unmount(); | |
| }); | |
| }); |
🤖 Prompt for AI Agents
In packages/shared/src/react/__tests__/commerce.test.tsx around lines 285-321,
the test and underlying normalization collapse every locale to its 2-letter base
but Stripe supports specific region/script variants; change the normalization
logic to first check against Stripe's supported-locale list and return the full
incoming locale if present, otherwise fall back to the two-letter language
subtag, and as a final fallback return 'en'; update these tests to include
supported variants (e.g., 'en-GB', 'pt-BR', 'es-419', 'zh-Hans', 'zh-Hant-TW')
asserting the full variant is preserved, keep existing cases asserting
base-language fallback for unsupported variants, and ensure the mockGetOption
and OptionsContext values reflect the exact locale strings used in each case.
3f3e4ef to
dcdb9d8
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: 3
♻️ Duplicate comments (1)
packages/shared/src/react/__tests__/commerce.test.tsx (1)
285-321: Update test cases after fixing normalization logic.The existing past review comment correctly identifies that these tests enforce overly simplistic normalization. Once the implementation in
commerce.tsxis updated to preserve Stripe-supported regional variants (en-GB, fr-CA, es-419, pt-BR, zh-Hans, zh-Hant-TW, etc.), update these test cases to verify:
- Supported regional/script variants are preserved as-is
- Unsupported variants fall back to base language
- Invalid locales default to 'en'
Example test cases to add:
const testCases = [ // Preserve supported variants { input: 'en-GB', expected: 'en-GB' }, { input: 'fr-CA', expected: 'fr-CA' }, { input: 'es-419', expected: 'es-419' }, { input: 'pt-BR', expected: 'pt-BR' }, { input: 'zh-Hans', expected: 'zh-Hans' }, { input: 'zh-Hant-TW', expected: 'zh-Hant-TW' }, // Normalize unsupported variants to base { input: 'en-US', expected: 'en' }, { input: 'fr-FR', expected: 'fr' }, { input: 'es-ES', expected: 'es' }, // Invalid/unknown locales default to 'en' { input: 'invalid-locale', expected: 'en' }, { input: 'xx-XX', expected: 'en' }, ];
🧹 Nitpick comments (2)
packages/shared/src/react/commerce.tsx (1)
65-80: Consider adding JSDoc for internal hook documentation.While not exported, documenting the hook's behavior (retrieval, defaulting, normalization, error handling) would improve maintainability for future developers working on this code.
+/** + * Retrieves and normalizes the current locale from Clerk's localization options. + * + * @returns A Stripe-compatible locale string, defaulting to 'en' on errors or when unset. + * @internal + */ const useLocalization = () => {packages/shared/src/react/__tests__/commerce.test.tsx (1)
86-321: Consider adding edge case tests for robustness.The current test suite is comprehensive, but consider adding tests for:
- Error thrown by
__internal_getOption(should default to 'en' and not crash)- Non-string locale values (should handle gracefully)
- Empty string locale (should default to 'en')
- Locales with multiple segments, e.g., 'zh-Hant-TW' (should preserve if supported)
These tests would validate the defensive coding in the implementation.
📜 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 (5)
.changeset/cold-bottles-watch.md(1 hunks)packages/clerk-js/sandbox/app.ts(1 hunks)packages/clerk-js/src/core/clerk.ts(1 hunks)packages/shared/src/react/__tests__/commerce.test.tsx(1 hunks)packages/shared/src/react/commerce.tsx(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/clerk-js/src/core/clerk.ts
- .changeset/cold-bottles-watch.md
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/sandbox/app.tspackages/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsxpackages/shared/src/react/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/sandbox/app.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
Clerk(197-2999)
packages/shared/src/react/commerce.tsx (5)
packages/nextjs/src/index.ts (1)
useClerk(50-50)packages/nextjs/src/client-boundary/hooks.ts (1)
useClerk(4-4)packages/shared/src/react/hooks/index.ts (1)
useClerk(8-8)packages/react/src/hooks/index.ts (1)
useClerk(6-6)packages/clerk-js/src/core/resources/SignUp.ts (1)
locale(650-652)
⏰ 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 (1)
packages/clerk-js/sandbox/app.ts (1)
242-256: Clean refactor: two-step option construction improves readability.The refactored flow separates option construction from application, making the code easier to follow. The explicit
localizationObjhandling and intermediateoptionsobject construction align well with the__unstable__updatePropsmerge behavior.
| jest.mock('../hooks/useUser', () => ({ | ||
| useUser: () => ({ | ||
| user: { | ||
| id: 'user_123', | ||
| initializePaymentSource: jest.fn().mockResolvedValue({ | ||
| externalGatewayId: 'acct_123', | ||
| externalClientSecret: 'seti_123', | ||
| paymentMethodOrder: ['card'], | ||
| }), | ||
| }, | ||
| }), | ||
| })); |
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.
Fix mock method name: initializePaymentSource → initializePaymentMethod.
Line 50 mocks initializePaymentSource, but the actual implementation at line 94 of commerce.tsx calls initializePaymentMethod. This mismatch could cause tests to pass while missing actual integration issues.
user: {
id: 'user_123',
- initializePaymentSource: jest.fn().mockResolvedValue({
+ initializePaymentMethod: jest.fn().mockResolvedValue({
externalGatewayId: 'acct_123',
externalClientSecret: 'seti_123',
paymentMethodOrder: ['card'],
}),
},📝 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.
| jest.mock('../hooks/useUser', () => ({ | |
| useUser: () => ({ | |
| user: { | |
| id: 'user_123', | |
| initializePaymentSource: jest.fn().mockResolvedValue({ | |
| externalGatewayId: 'acct_123', | |
| externalClientSecret: 'seti_123', | |
| paymentMethodOrder: ['card'], | |
| }), | |
| }, | |
| }), | |
| })); | |
| jest.mock('../hooks/useUser', () => ({ | |
| useUser: () => ({ | |
| user: { | |
| id: 'user_123', | |
| initializePaymentMethod: jest.fn().mockResolvedValue({ | |
| externalGatewayId: 'acct_123', | |
| externalClientSecret: 'seti_123', | |
| paymentMethodOrder: ['card'], | |
| }), | |
| }, | |
| }), | |
| })); |
🤖 Prompt for AI Agents
packages/shared/src/react/__tests__/commerce.test.tsx around lines 46 to 57: the
mocked user currently provides initializePaymentSource but the production code
calls initializePaymentMethod; update the mock to provide
initializePaymentMethod instead (i.e., replace initializePaymentSource with
initializePaymentMethod and keep the same jest.fn().mockResolvedValue(...)
payload) so tests exercise the same method name as commerce.tsx.
| const useLocalization = () => { | ||
| const clerk = useClerk(); | ||
|
|
||
| let locale = 'en'; | ||
| try { | ||
| const localization = clerk.__internal_getOption('localization'); | ||
| locale = localization?.locale || 'en'; | ||
| } catch { | ||
| // ignore errors | ||
| } | ||
|
|
||
| // Normalize locale to 2-letter language code for Stripe compatibility | ||
| const normalizedLocale = locale.split('-')[0]; | ||
|
|
||
| return normalizedLocale; | ||
| }; |
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.
🧩 Analysis chain
Normalization drops Stripe-supported regional locales, degrading translation quality.
The current implementation unconditionally normalizes all locales to 2-letter language codes (line 77), but Stripe Elements supports specific regional variants that provide better translations:
- Regional variants:
en-GB,fr-CA,es-419,pt-BR - Script variants:
zh-Hans,zh-Hant-TW,zh-Hant-HK
Collapsing pt-BR → pt or zh-Hant-TW → zh can result in incorrect or less relevant translations for users in those regions.
Additionally, line 72-74 silently swallows all errors without logging, making debugging difficult.
Based on learnings from the past review comment, update the normalization logic:
const useLocalization = () => {
const clerk = useClerk();
let locale = 'en';
try {
const localization = clerk.__internal_getOption('localization');
locale = localization?.locale || 'en';
- } catch {
+ } catch (error) {
// ignore errors
+ console.warn('Failed to retrieve localization option:', error);
}
- // Normalize locale to 2-letter language code for Stripe compatibility
- const normalizedLocale = locale.split('-')[0];
+ // Stripe supports specific regional/script variants; preserve them if valid
+ const stripeLocales = new Set([
+ 'auto', 'ar', 'bg', 'cs', 'da', 'de', 'el', 'en', 'en-GB',
+ 'es', 'es-419', 'et', 'fi', 'fil', 'fr', 'fr-CA', 'he', 'hr',
+ 'hu', 'id', 'it', 'ja', 'ko', 'lt', 'lv', 'ms', 'mt', 'nb',
+ 'nl', 'no', 'pl', 'pt', 'pt-BR', 'ro', 'ru', 'sk', 'sl', 'sv',
+ 'th', 'tr', 'vi', 'zh', 'zh-Hans', 'zh-Hant', 'zh-Hant-HK', 'zh-Hant-TW'
+ ]);
+
+ // Validate locale is a string before processing
+ if (typeof locale !== 'string') {
+ return 'en';
+ }
+
+ // Return as-is if supported; otherwise try base language; finally default to 'en'
+ if (stripeLocales.has(locale)) {
+ return locale;
+ }
+
+ const baseLanguage = locale.split('-')[0];
+ return stripeLocales.has(baseLanguage) ? baseLanguage : 'en';
-
- return normalizedLocale;
};Verify the current Stripe-supported locale list:
🌐 Web query:
What are the complete list of supported locales for Stripe Elements as of 2025?
💡 Result:
Here are the locales Stripe Elements supports (locale codes) as listed in Stripe’s docs (2025):
bg-BG, zh-Hans, zh-Hant-HK, zh-Hant-TW, hr-HR, cs-CZ, da-DK, nl-NL, en-AU, en-IN, en-IE, en-NZ, en-SG, en-GB, en-US, et-EE, fil-PH, fi-FI, fr-CA, fr-FR, de-DE, el-GR, hu-HU, id-ID, it-IT, ja-JP, ko-KR, lv-LV, lt-LT, ms-MY, mt-MT, nb-NO, pl-PL, pt-BR, pt-PT, ro-RO, sk-SK, sl-SI, es-AR, es-BR, es-419, es-MX, es-ES, sv-SE, th-TH, tr-TR, vi-VN. [1][2]
Sources:
- Stripe Connect embedded components — supported locales list (Stripe docs). [Stripe]. [2]
- Stripe JS appendix: Supported locales (Stripe docs). [2]
Corrected Stripe-supported locale list required; proposed solution includes unsupported locales.
The review comment correctly identifies that the current normalization degrades UX by collapsing regional locales, but the proposed fix contains inaccuracies:
The actual Stripe Elements 2025 supported locales use full locale codes with regions: bg-BG, zh-Hans, zh-Hant-HK, zh-Hant-TW, hr-HR, cs-CZ, da-DK, nl-NL, en-AU, en-IN, en-IE, en-NZ, en-SG, en-GB, en-US, et-EE, fil-PH, fi-FI, fr-CA, fr-FR, de-DE, el-GR, hu-HU, id-ID, it-IT, ja-JP, ko-KR, lv-LV, lt-LT, ms-MY, mt-MT, nb-NO, pl-PL, pt-BR, pt-PT, ro-RO, sk-SK, sl-SI, es-AR, es-BR, es-419, es-MX, es-ES, sv-SE, th-TH, tr-TR, vi-VN.
The proposed solution includes unsupported locales ('auto', 'ar', 'he', 'no', 'ru') and base language codes ('en', 'es', 'de') that Stripe doesn't accept as fallbacks. The corrected diff should use only validated Stripe locales and improve the fallback strategy.
# Conflicts: # packages/shared/src/react/commerce.tsx
Description
Passes current standardized localization value to Stripe Elements.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Tests
Chores