-
Notifications
You must be signed in to change notification settings - Fork 371
chore(clerk-js,types): Update PricingTable with trial info #6493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
chore(clerk-js,types): Update PricingTable with trial info #6493
Conversation
🦋 Changeset detectedLatest commit: b228074 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 Git ↗︎
|
@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: |
📝 WalkthroughWalkthroughThis change introduces support for free trial properties across multiple packages. It adds new fields such as Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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: 5
🔭 Outside diff range comments (2)
packages/types/src/localization.ts (1)
151-156
: Add ‘date’ parameter to badge__endsAtAll locales that define badge__endsAt use a
{{ date }}
placeholder, so update its type:• In packages/types/src/localization.ts (line 153):
- badge__endsAt: LocalizationValue; + badge__endsAt: LocalizationValue<'date'>;packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)
144-153
: Prioritize trial notice over plan-period mismatch to avoid suppressing itWith the current else-if ordering, when both a plan-period mismatch and an active trial are true, the mismatch branch executes first, setting shouldShowFooterNotice=false and suppressing the trial message. Trial notice should take precedence.
Apply this reordering so trial wins:
- } else if (planPeriod !== subscription.planPeriod && plan.annualMonthlyAmount > 0) { - shouldShowFooter = true; - shouldShowFooterNotice = false; - } else if (plan.freeTrialEnabled && subscription.freeTrialEndsAt !== null) { - shouldShowFooter = true; - shouldShowFooterNotice = true; + } else if (plan.freeTrialEnabled && subscription.freeTrialEndsAt) { + shouldShowFooter = true; + shouldShowFooterNotice = true; + } else if (planPeriod !== subscription.planPeriod && plan.annualMonthlyAmount > 0) { + shouldShowFooter = true; + shouldShowFooterNotice = false;This ensures the “trial ends at …” notice shows even when a mismatch exists.
🧹 Nitpick comments (8)
packages/localizations/src/en-US.ts (1)
144-144
: New “Start free trial” label added – consider pluralization edge caseString is fine and param matches types. Minor nit: “{{days}}-day” reads a bit odd for 1 (e.g., “1-day”). If your i18n system supports it, consider singular/plural variants; otherwise this is acceptable.
Example alternatives (if desired):
- “Start your {{days}}-day free trial”
- Add plural forms: startFreeTrial_one / startFreeTrial_other
packages/clerk-js/src/core/resources/CommercePlan.ts (2)
68-91
: Snapshot omits new fields—confirm intent, or include them__internal_toSnapshot doesn’t include freeTrialDays/freeTrialEnabled. If snapshots are used for caching or devtools, consider adding them; if snapshots intentionally exclude experimental fields, ignore.
If inclusion is desired and CommercePlanJSONSnapshot supports them, update as:
slug: this.slug, avatar_url: this.avatarUrl, + free_trial_days: this.freeTrialDays, + free_trial_enabled: this.freeTrialEnabled, features: this.features.map(feature => feature.__internal_toSnapshot()),Also ensure @clerk/types CommercePlanJSONSnapshot includes these fields.
33-66
: Add unit tests for deserialization defaultsNo tests were added. Please add coverage for:
- Missing trial fields → defaults (null/false)
- Explicit values (e.g., 0 days, enabled true)
I can help scaffold tests if useful.
packages/types/src/json.ts (1)
785-788
: Document experimental fields; avoid commented-out properties
- Keep free_trial_ends_at optional for beta, but add a JSDoc explaining semantics, units, and GA plan.
- Remove the commented is_free_trial line or link to a tracking issue.
Example:
/** * UNIX epoch seconds when the free trial ends. * @experimental Optional until GA; may become required when backend guarantees presence. */ free_trial_ends_at?: number | null;packages/types/src/commerce.ts (3)
440-457
: Model the free-trial invariants more explicitly (or at least document them).Right now
freeTrialEnabled
andfreeTrialDays
can drift (e.g., enabled withnull
or disabled with a number). Either:
- Document the invariant in JSDoc: when
freeTrialEnabled === true
,freeTrialDays
is a positive integer; whenfalse
, it must benull
.- Or (preferred) encode it in the type system via a discriminated union.
Example approach (outside this range, shown for clarity):
type FreeTrialInfo = | { freeTrialEnabled: true; freeTrialDays: number } | { freeTrialEnabled: false; freeTrialDays: null }; // Then: export interface CommercePlanResource extends ClerkResource, FreeTrialInfo { // ... }
1126-1146
: Remove commented-out code and rely on tracked TODOs.The
isFreeTrial
block is commented out. Avoid commented code in types; it tends to rot and confuses consumers. Keep the TODO in an issue or a code comment without the dead code.Also,
freeTrialEndsAt: Date | null;
looks good and consistent with other date fields.- // /** - // * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. - // * It is advised to pin the SDK version and the clerk-js version to a specific version to avoid breaking changes. - // * @example - // * ```tsx - // * <ClerkProvider clerkJsVersion="x.x.x" /> - // * ``` - // */ - // isFreeTrial: boolean;
1256-1265
: Clarify semantics foreligibleForFreeTrial
(and why it’s optional).Add a short JSDoc note clarifying what “eligible” means (e.g., new subscriber with no prior trial? per-plan vs account-level?) and whether absence (
undefined
) should be interpreted as “unknown” vs “false”. This helps UI logic avoid misinterpretation.packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
271-272
: Narrow the dependency to avoid unnecessary re-creations.Depending on the entire
topLevelSubscription
object can cause needless callback invalidations. Depend only on the boolean you read.- [activeOrUpcomingSubscriptionWithPlanPeriod, canManageBilling, subscriptionItems, topLevelSubscription], + [activeOrUpcomingSubscriptionWithPlanPeriod, canManageBilling, subscriptionItems, topLevelSubscription?.eligibleForFreeTrial],
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
.changeset/sour-lemons-talk.md
(1 hunks).changeset/tender-planets-win.md
(1 hunks)packages/clerk-js/src/core/resources/CommercePlan.ts
(2 hunks)packages/clerk-js/src/core/resources/CommerceSubscription.ts
(4 hunks)packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
(2 hunks)packages/clerk-js/src/ui/contexts/components/Plans.tsx
(4 hunks)packages/localizations/src/en-US.ts
(2 hunks)packages/types/src/commerce.ts
(3 hunks)packages/types/src/json.ts
(3 hunks)packages/types/src/localization.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
.changeset/**
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/tender-planets-win.md
.changeset/sour-lemons-talk.md
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/src/core/resources/CommercePlan.ts
packages/types/src/json.ts
packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/types/src/commerce.ts
packages/localizations/src/en-US.ts
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/types/src/localization.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
**/*.{jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/contexts/components/Plans.tsx
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/localizations/**/*
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Localization files must be placed in 'packages/localizations/'.
Files:
packages/localizations/src/en-US.ts
**/localizations/**/*.ts
⚙️ CodeRabbit Configuration File
**/localizations/**/*.ts
: Review the changes to localization files with the following guidelines:
- Ensure that no existing translations are accidentally removed unless they are being replaced or fixed. If a string is removed, verify that it is intentional and justified.
- Check that all translations are friendly, formal, or semi-formal. Explicit, offensive, or inappropriate language is not allowed. If you find any potentially offensive language or are unsure, tag the @clerk/sdk-infra team in a separate comment. If you do not intend to tag the team, refer to it as "Clerk SDK Infra team" instead.
- Use the most up-to-date base localization file (https://github.com/clerk/javascript/blob/main/packages/localizations/src/en-US.ts) to validate changes, ensuring consistency and completeness.
- Confirm that new translations are accurate, contextually appropriate, and match the intent of the original English strings.
- Check for formatting issues, such as missing placeholders, incorrect variable usage, or syntax errors.
- Ensure that all keys are unique and that there are no duplicate or conflicting entries.
- If you notice missing translations for new keys, flag them for completion.
Files:
packages/localizations/src/en-US.ts
🧠 Learnings (1)
📚 Learning: 2025-07-22T08:43:52.095Z
Learnt from: panteliselef
PR: clerk/javascript#6317
File: packages/clerk-js/src/ui/contexts/components/Plans.tsx:56-68
Timestamp: 2025-07-22T08:43:52.095Z
Learning: The `useSubscription` hook exported from `packages/clerk-js/src/ui/contexts/components/Plans.tsx` is only used internally within clerk-js UI components and is not exposed to external consumers, making renames and modifications to this hook non-breaking for end users.
Applied to files:
packages/clerk-js/src/ui/contexts/components/Plans.tsx
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)
packages/clerk-js/src/ui/localization/localizationKeys.ts (1)
localizationKeys
(72-77)
⏰ 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: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (14)
packages/localizations/src/en-US.ts (1)
46-46
: Add trial-end badge: placeholder and format look correctKey and pipe formatting are consistent with existing date-based badges. No issues.
.changeset/tender-planets-win.md (1)
1-7
: Changeset looks good for trial info in PricingTablePackages and bump type are appropriate; concise description aligns with PR scope.
.changeset/sour-lemons-talk.md (1)
1-6
: Second changeset OK; confirm intended duplication of bumped packagesMultiple changesets both bumping @clerk/clerk-js and @clerk/types will coalesce to a single minor bump per package, which is fine. Just confirm this duplication is intentional.
packages/types/src/localization.ts (2)
152-152
: Type for new badge key is correctbadge__trialEndsAt: LocalizationValue<'date'>; matches its usage in en-US and other date badges.
178-179
: Type for startFreeTrial is correctParam name 'days' matches the en-US string. Good addition.
packages/clerk-js/src/core/resources/CommercePlan.ts (2)
30-31
: New free trial fields added to plan: good shapeTypes and nullability look right: number | null for days, boolean for enabled.
61-63
: Safe deserialization with sensible defaultswithDefault(null/false) guards absent fields and preserves 0 days when present. LGTM.
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)
238-244
: Confirmation: Localization keys and date param are validBoth
badge__trialEndsAt
andbadge__startsAt
are defined in packages/types/src/localization.ts as LocalizationValue<'date'> and have corresponding entries in your locale files (e.g. en-US). TheLocalizationValue<'date'>
type allows aDate
object for thedate
parameter, so your usage is correct.Optional readability tweak:
- In PricingTableDefault.tsx (lines 238–244), you could replace
plan.freeTrialEnabled && subscription.freeTrialEndsAt !== null
with
plan.freeTrialEnabled && Boolean(subscription.freeTrialEndsAt)
sincefreeTrialEndsAt
is normalized tonull
when absent.packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
30-31
: LGTM: Adds eligibleForFreeTrial with backward-compatible optional typingProperty and typing align with the new JSON field and preserve BC.
79-79
: LGTM: Adds freeTrialEndsAt on subscription itemsThe field is correctly modeled as Date | null and matches the UI usage.
packages/types/src/json.ts (2)
652-654
: LGTM: Adds plan-level free trial fieldsFields use snake_case, correct optionality, and appropriate nullability for days.
817-818
: LGTM: Adds subscription-level trial eligibility (optional)Optionality preserves BC. Consider adding a brief JSDoc for clarity similar to other experimental fields.
packages/clerk-js/src/ui/contexts/components/Plans.tsx (2)
111-111
: LGTM: exposingdata
astopLevelSubscription
.This improves readability when combined with
subscriptionItems
. No issues spotted.
258-261
: Apply the free-trial override only on the subscribe path.This is the right place to inject the trial CTA. Keep this, and remove the global override in the final return below.
Add tests to ensure:
- With no active subscription and eligible trial: CTA is “Start free trial (X days)”.
- With active subscription: CTA remains “Manage subscription”.
- With canceled subscription (period mismatch): CTA is “Switch to …”, not trial.
I can help draft tests using
@testing-library/react
and mocked hooks.
this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null; | ||
return this; |
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.
Avoid falsy checks on epoch timestamps
Using a truthy check can mis-handle 0 as a valid timestamp. Prefer an explicit type/nullish guard.
Use a robust check:
- this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null;
+ this.freeTrialEndsAt =
+ typeof data.free_trial_ends_at === 'number' ? unixEpochToDate(data.free_trial_ends_at) : null;
📝 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.
this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null; | |
return this; | |
this.freeTrialEndsAt = | |
typeof data.free_trial_ends_at === 'number' ? unixEpochToDate(data.free_trial_ends_at) : null; | |
return this; |
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/CommerceSubscription.ts at lines
110-111, replace the current truthy check on data.free_trial_ends_at with an
explicit nullish check to correctly handle 0 as a valid timestamp. Change the
condition to explicitly check if data.free_trial_ends_at is not null or
undefined before converting it with unixEpochToDate; otherwise, assign null.
// TODO(@COMMERCE): This needs to be removed. | ||
subscription: sub, |
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.
💡 Verification agent
🧩 Analysis chain
Track the TODO for removing the subscription
param.
Create an issue to remove this param and plan a small cleanup PR. I can scan for call sites to confirm it’s unused before removal.
🏁 Script executed:
#!/bin/bash
# Find direct and object-style usages of the `subscription` param passed to buttonPropsForPlan
rg -n --no-heading "buttonPropsForPlan\(" -A 5
rg -n --no-heading "subscription\s*:" -g "packages/clerk-js/**"
Length of output: 3060
Plan removal of unused subscription
prop from Plans component
The subscription
parameter in packages/clerk-js/src/ui/contexts/components/Plans.tsx
isn’t consumed by any downstream code. Please create an issue to track this cleanup and open a small PR to:
- Remove
subscription
from the component signature (around line 178). - Delete the
subscription: sub,
mapping (line 191).
- // TODO(@COMMERCE): This needs to be removed.
- subscription: sub,
📝 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.
// TODO(@COMMERCE): This needs to be removed. | |
subscription: sub, |
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 178 to
191, the subscription prop is unused and should be removed. First, remove the
subscription parameter from the Plans component signature near line 178. Then,
delete the subscription: sub, mapping at line 191. Additionally, create an issue
to track this cleanup and open a small PR to implement these removals.
const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => { | ||
if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) { | ||
return localizationKeys('commerce.startFreeTrial', { days: plan.freeTrialDays ?? 0 }); | ||
} | ||
return localizationKey; | ||
}; | ||
|
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
Don’t globally override CTAs with “Start free trial”.
As written, freeTrialOr
is later applied to the final result, so “Start free trial” can incorrectly replace “Manage subscription”, “Switch to Annual/Monthly”, etc., whenever plan.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial
. Restrict the override only to the “subscribe” path.
Also consider guarding against 0/null trial days to avoid odd UI like “Start free trial (0 days)”.
- const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => {
- if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) {
- return localizationKeys('commerce.startFreeTrial', { days: plan.freeTrialDays ?? 0 });
- }
- return localizationKey;
- };
+ const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => {
+ // Only used for initial subscribe CTA; final application must not override manage/switch CTAs.
+ if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) {
+ const days = Math.max(plan.freeTrialDays ?? 0, 0);
+ return localizationKeys('commerce.startFreeTrial', { days });
+ }
+ return localizationKey;
+ };
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 215 to
221, the freeTrialOr function currently overrides all CTAs with "Start free
trial" when freeTrialEnabled and eligibleForFreeTrial are true, which
incorrectly replaces other CTAs like "Manage subscription" or "Switch to
Annual/Monthly". To fix this, restrict the override so it only applies on the
"subscribe" path by adding a condition to check the current CTA context before
returning the free trial localization key. Additionally, add a guard to ensure
plan.freeTrialDays is greater than zero before applying the free trial text to
avoid showing "Start free trial (0 days)" or similar UI issues.
return { | ||
localizationKey: getLocalizationKey(), | ||
localizationKey: freeTrialOr(getLocalizationKey()), | ||
variant: isCompact ? 'bordered' : 'solid', | ||
colorScheme: isCompact ? 'secondary' : 'primary', | ||
isDisabled: !canManageBilling, | ||
disabled: !canManageBilling, | ||
}; |
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.
Bug: final return still overrides everything with trial CTA.
Remove the outer freeTrialOr
to avoid overriding non-subscription CTAs.
- return {
- localizationKey: freeTrialOr(getLocalizationKey()),
+ return {
+ localizationKey: getLocalizationKey(),
variant: isCompact ? 'bordered' : 'solid',
colorScheme: isCompact ? 'secondary' : 'primary',
isDisabled: !canManageBilling,
disabled: !canManageBilling,
};
📝 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.
return { | |
localizationKey: getLocalizationKey(), | |
localizationKey: freeTrialOr(getLocalizationKey()), | |
variant: isCompact ? 'bordered' : 'solid', | |
colorScheme: isCompact ? 'secondary' : 'primary', | |
isDisabled: !canManageBilling, | |
disabled: !canManageBilling, | |
}; | |
return { | |
localizationKey: getLocalizationKey(), | |
variant: isCompact ? 'bordered' : 'solid', | |
colorScheme: isCompact ? 'secondary' : 'primary', | |
isDisabled: !canManageBilling, | |
disabled: !canManageBilling, | |
}; |
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 263 to
269, the final return statement wraps the localizationKey with freeTrialOr,
which causes it to override all non-subscription CTAs incorrectly. To fix this,
remove the outer freeTrialOr call from the return statement so that only
appropriate CTAs use freeTrialOr and others remain unaffected.
@@ -43,6 +43,7 @@ export const enUS: LocalizationResource = { | |||
badge__default: 'Default', | |||
badge__endsAt: "Ends {{ date | shortDate('en-US') }}", | |||
badge__expired: 'Expired', | |||
badge__trialEndsAt: "Trial ends {{ date | shortDate('en-US') }}", |
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.
💡 Verification agent
🧩 Analysis chain
Ensure other locales add these new keys
Please verify all locale files define:
- badge__trialEndsAt
- commerce.startFreeTrial
Missing translations will fall back to English or cause gaps depending on runtime.
Run to audit locale coverage:
Also applies to: 144-144
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# List all locale files missing either key
echo "Checking for missing 'badge__trialEndsAt'..."
rg -L --no-messages -n "badge__trialEndsAt" packages/localizations/src/*.ts | sed 's/:.*//' | sort -u > /tmp/has_trialEndsAt.txt || true
echo "Checking for missing 'startFreeTrial'..."
rg -L --no-messages -n "startFreeTrial" packages/localizations/src/*.ts | sed 's/:.*//' | sort -u > /tmp/has_startFreeTrial.txt || true
ls packages/localizations/src/*.ts | sort -u > /tmp/all_locales.txt
echo "Locales missing badge__trialEndsAt:"
comm -23 /tmp/all_locales.txt /tmp/has_trialEndsAt.txt || true
echo
echo "Locales missing commerce.startFreeTrial:"
comm -23 /tmp/all_locales.txt /tmp/has_startFreeTrial.txt || true
Length of output: 6275
To handle the missing comm
utility in the sandbox, let’s directly list locales missing each key using rg -L
:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Locales missing badge__trialEndsAt:"
rg -L "badge__trialEndsAt" packages/localizations/src/*.ts || true
echo
echo "Locales missing startFreeTrial:"
rg -L "startFreeTrial" packages/localizations/src/*.ts || true
Length of output: 4024
To get an accurate list of missing translations (excluding the index.ts
file), let’s re-run the audit and filter out index.ts
:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Locales missing 'badge__trialEndsAt' (excluding index.ts):"
rg -L "badge__trialEndsAt" packages/localizations/src/*.ts | grep -v "index.ts" || true
echo
echo "Locales missing 'startFreeTrial' (excluding index.ts):"
rg -L "startFreeTrial" packages/localizations/src/*.ts | grep -v "index.ts" || true
Length of output: 4166
Ensure new localization keys are added to every locale
en-US.ts already defines both entries. All other files in packages/localizations/src (excluding index.ts) are missing them—please add:
// At the top level (alongside other keys)
badge__trialEndsAt: "Trial ends {{ date | shortDate('en-US') }}",
// Under the commerce namespace
commerce: {
…,
startFreeTrial: 'Start {{days}}-day free trial',
},
Apply this to every <locale>.ts
file in packages/localizations/src except index.ts and en-US.ts so no locale falls back to English or has missing entries.
🤖 Prompt for AI Agents
In packages/localizations/src/en-US.ts at line 46, the localization keys
badge__trialEndsAt and commerce.startFreeTrial are defined, but these keys are
missing in all other locale files except index.ts and en-US.ts. To fix this, add
the badge__trialEndsAt key at the top level and the commerce.startFreeTrial key
inside the commerce namespace in every other locale file within
packages/localizations/src, ensuring no locale falls back to English or has
missing entries.
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Localization