Skip to content

Conversation

aeliox
Copy link
Contributor

@aeliox aeliox commented Sep 29, 2025

Description

Passes current standardized localization value to Stripe Elements.

Screenshot 2025-09-29 at 10 45 53 AM

Checklist

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

Type of change

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

Summary by CodeRabbit

  • New Features

    • Payment UI now passes locale to Stripe Elements, defaults to “en,” and normalizes region variants (e.g., fr-FR → fr).
  • Refactor

    • Consolidated options update flow to ensure consistent internal state before emitting updates.
  • Tests

    • Added comprehensive tests for locale propagation, defaults when undefined, and normalization across input formats.
  • Chores

    • Patch version bumps for JS/shared packages.

Copy link

changeset-bot bot commented Sep 29, 2025

🦋 Changeset detected

Latest commit: a7f50d0

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

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

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

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

Copy link

vercel bot commented Sep 29, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 29, 2025 6:03pm

Copy link
Contributor

coderabbitai bot commented Sep 29, 2025

Walkthrough

Core update flow now merges and initializes internal options before emitting props. Sandbox builds an intermediate options object (maps localization to a resource and sets sessionStorage) then calls a single Clerk.__unstable__updateProps. Adds useLocalization hook and tests to normalize and pass locale to Stripe Elements.

Changes

Cohort / File(s) Summary
Sandbox options construction
packages/clerk-js/sandbox/app.ts
Build an intermediate options object (map localization to a localization resource, perform sessionStorage.setItem during mapping) and call a single Clerk.__unstable__updateProps({ options }) instead of previous chained updates.
Core options merge behavior
packages/clerk-js/src/core/clerk.ts
__unstable__updateProps now merges incoming _props.options with this.#options, runs the merged result through #initOptions, assigns this.#options = processedOptions, and emits props that use the processed/merged options.
PaymentElement localization and tests
packages/shared/src/react/commerce.tsx, packages/shared/src/react/__tests__/commerce.test.tsx
Add useLocalization hook to read/default/normalize locale (defaults to en, normalizes variants like fr-FRfr, en-USen), pass locale into Stripe Elements options, and add tests mocking Stripe/Clerk to verify propagation, defaults, and normalization.
Release metadata
.changeset/cold-bottles-watch.md
Document that current localization is passed to Stripe Elements; bump patch versions for related packages.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Sandbox as sandbox/app.ts
  participant Clerk as Clerk Core
  note over Sandbox: Construct intermediate options\n(map localization -> resource, set sessionStorage)
  App->>Sandbox: user updates settings
  Sandbox->>Clerk: __unstable__updateProps({ options })
  activate Clerk
  Clerk->>Clerk: mergedOptions = merge(this.#options, _props.options)
  Clerk->>Clerk: processedOptions = this.#initOptions(mergedOptions)
  Clerk->>Clerk: this.#options = processedOptions
  Clerk-->>Sandbox: updated props emitted
  deactivate Clerk
Loading
sequenceDiagram
  autonumber
  actor User
  participant App as React App
  participant Hook as useLocalization
  participant Clerk as OptionsContext
  participant Stripe as Stripe Elements
  note over Hook: read localization, default to "en", normalize to 2-letter code
  User->>App: open checkout
  App->>Hook: request locale
  Hook->>Clerk: read options.localization
  Clerk-->>Hook: localization value (or undefined)
  Hook->>App: locale (e.g., "en", "fr")
  App->>Stripe: mount Elements { locale }
  Stripe-->>App: Elements container (data-locale)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit taps keys with a hop and a twirl,
Merges options tidy, gives props a whirl.
Locale trims to two letters — bonjour, hi!
Stripe reads the language and greets the UI.
Tests nibble carrots, all set to fly. 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title “feat(clerk-js): Pass locale to Stripe elements” succinctly describes the core enhancement made in this changeset by indicating a new feature scoped to the clerk-js package and specifically calling out the propagation of localization to Stripe Elements. It follows a conventional commit style, is concise, and directly reflects the primary objective of the pull request. There is no extraneous detail or unrelated noise.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch keiran/bill-1069

Comment @coderabbitai help to get the list of available commands and usage tips.

const mergedOptions = { ...this.#options, ..._props.options };

// Update the Clerk instance's internal options
this.#options = mergedOptions;
Copy link
Contributor Author

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

@aeliox aeliox requested a review from panteliselef September 29, 2025 17:45
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 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 set

Splitting 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: Remove as any and pass a typed Stripe locale

as any hides 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 any and 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 updates

Building options once and calling __unstable__updateProps({ options }) is cleaner. To reduce needless work, consider bailing if the computed options.localization hasn’t changed from Clerk.__internal_getOption('localization'). Also, if l[input.value] is ever undefined, fall back to l.enUS to stay robust.

packages/shared/src/react/__tests__/commerce.test.tsx (2)

64-67: SWR mock may not match both call sites; make it key‑aware

The same useSWR mock 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

mockGetOption is 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 37028ca and a9a2589.

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

Files:

  • packages/clerk-js/sandbox/app.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/shared/src/react/commerce.tsx
  • 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/clerk-js/sandbox/app.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/shared/src/react/commerce.tsx
  • 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/commerce.tsx
  • 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/commerce.tsx
  • 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
**/*.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)

Copy link

pkg-pr-new bot commented Sep 29, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: a7f50d0

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
packages/shared/src/react/__tests__/commerce.test.tsx (6)

10-24: Stripe mock: narrow option typing for clarity

Use a minimal options type instead of any to 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 leakage

Mocks 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 place

Guard against residual implementations when renderWithLocale is 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.each yields 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 case

Strengthen defaults with an invalid locale (e.g., xx-YY) asserting fallback to en.

 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 fixtures

This 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 9f50354 and a7f50d0.

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

Files:

  • packages/shared/src/react/__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 good

Asserting fallback to en when no localization is present is appropriate and aligns with the intended behavior.


252-283: ClerkProvider-style resource case is valid

Normalizing fr-FR to fr here is reasonable since Stripe accepts fr and there’s no region-specific variant for France to preserve.


171-173: Annotate options with the actual context value type
I couldn’t locate an OptionsContextValue export in packages/shared/src/react. Please verify the correct context-value type exported by your contexts module, import it, and then declare:

const options: Partial<YourContextType> = {
  localization: { locale },
};

Comment on lines +285 to +321
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();
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Normalization may drop supported regional locales (risk of worse UX)

The test enforces unconditional 2-letter normalization (e.g., pt-BRpt). 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 en as 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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants