Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 5, 2025

Description

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

    • Added the ability to extend a subscription item’s free trial via the Billing API by specifying a new trial end date.
    • Supports RFC3339 timestamps; the date must be in the future and no more than 365 days beyond the current trial end.
  • Documentation

    • Marked the feature as experimental and recommended pinning the SDK version to avoid potential breaking changes.

@panteliselef panteliselef requested a review from a team September 5, 2025 15:01
@panteliselef panteliselef self-assigned this Sep 5, 2025
Copy link

changeset-bot bot commented Sep 5, 2025

🦋 Changeset detected

Latest commit: 32a8460

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

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

Adds a changeset declaring a minor release for @clerk/backend and introduces an experimental BillingAPI method to extend a subscription item's free trial via a POST to /billing/subscription_items/{subscriptionItemId}/extend_free_trial, including a new params type with an extendTo Date and validation.

Changes

Cohort / File(s) Summary
Release metadata
\.changeset/public-goats-sort.md
Adds a changeset documenting a minor release for @clerk/backend to note the new trial extension capability via BillingAPI.
Billing API extension
packages/backend/src/api/endpoints/BillingApi.ts
Adds ExtendSubscriptionItemFreeTrialParams { extendTo: Date }; adds experimental method extendSubscriptionItemFreeTrial(subscriptionItemId, params) that validates ID and POSTs to /billing/subscription_items/{id}/extend_free_trial, returning CommerceSubscriptionItem.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Caller
  participant SDK as BillingAPI
  participant HTTP as POST /billing/subscription_items/{id}/extend_free_trial
  participant Svc as Billing Service

  Dev->>SDK: extendSubscriptionItemFreeTrial(subscriptionItemId, { extendTo })
  SDK->>SDK: requireId(subscriptionItemId)
  SDK->>HTTP: body: { extendTo }
  HTTP->>Svc: Validate and process
  Svc-->>HTTP: 200 OK + CommerceSubscriptionItem
  HTTP-->>SDK: CommerceSubscriptionItem
  SDK-->>Dev: CommerceSubscriptionItem
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nudge the clock, a gentle tilt,
Trials stretched like satin quilt.
POST a wish, extendTo skies—
Billing breeze, time complies.
Hare today, more days to spend,
Subscriptions hop, their trials extend. 🐇⏳

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/update-billing-bapi

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

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

Status, Documentation and Community

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

Copy link

vercel bot commented Sep 5, 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 5, 2025 3:02pm

Copy link

pkg-pr-new bot commented Sep 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 32a8460

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: 2

🧹 Nitpick comments (3)
.changeset/public-goats-sort.md (1)

1-5: Optional: Call out experimental status in the note

Since the method is marked experimental in code, consider noting that here to set expectations for consumers.

packages/backend/src/api/endpoints/BillingApi.ts (2)

60-63: Enhance JSDoc: add @param/@returns and a short usage example

Add param tags and the return type description so API docs are complete.

Example:

/**
 * @experimental ...
 * @param subscriptionItemId The subscription item ID to extend.
 * @param params.extendTo RFC3339 timestamp (as Date) to extend the trial to.
 * @returns Updated CommerceSubscriptionItem after extension.
 *
 * @example
 * await billingApi.extendSubscriptionItemFreeTrial('si_123', { extendTo: new Date('2025-10-01T00:00:00Z') });
 */

26-32: Optional: client-side guardrails for extendTo

Consider a lightweight check to ensure extendTo is in the future before issuing the request; let the server enforce the 365-day rule.

if (!(params.extendTo instanceof Date) || Number.isNaN(params.extendTo.valueOf()) || params.extendTo <= new Date()) {
  throw new TypeError('extendTo must be a valid future Date');
}

I can add unit tests covering happy path, past-date rejection, and request payload shape if helpful.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 7926f7f and 32a8460.

📒 Files selected for processing (2)
  • .changeset/public-goats-sort.md (1 hunks)
  • packages/backend/src/api/endpoints/BillingApi.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/public-goats-sort.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/backend/src/api/endpoints/BillingApi.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/backend/src/api/endpoints/BillingApi.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/api/endpoints/BillingApi.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/api/endpoints/BillingApi.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

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

Files:

  • packages/backend/src/api/endpoints/BillingApi.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/backend/src/api/endpoints/BillingApi.ts
🧬 Code graph analysis (1)
packages/backend/src/api/endpoints/BillingApi.ts (1)
packages/backend/src/api/resources/CommerceSubscriptionItem.ts (1)
  • CommerceSubscriptionItem (11-128)
⏰ 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). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
.changeset/public-goats-sort.md (1)

1-5: LGTM on the changeset scope and summary

Minor bump for a new public API is appropriate; message is clear.

Comment on lines +26 to +32
type ExtendSubscriptionItemFreeTrialParams = {
/**
* RFC3339 timestamp to extend the free trial to.
* Must be in the future and not more than 365 days from the current trial end.
*/
extendTo: Date;
};
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

Export the public params type

This type appears in a public method signature; make it exported to avoid d.ts naming issues and to enable reuse.

Apply this diff:

-type ExtendSubscriptionItemFreeTrialParams = {
+export type ExtendSubscriptionItemFreeTrialParams = {
   /**
    * RFC3339 timestamp to extend the free trial to.
    * Must be in the future and not more than 365 days from the current trial end.
    */
   extendTo: Date;
 };
📝 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
type ExtendSubscriptionItemFreeTrialParams = {
/**
* RFC3339 timestamp to extend the free trial to.
* Must be in the future and not more than 365 days from the current trial end.
*/
extendTo: Date;
};
export type ExtendSubscriptionItemFreeTrialParams = {
/**
* RFC3339 timestamp to extend the free trial to.
* Must be in the future and not more than 365 days from the current trial end.
*/
extendTo: Date;
};
🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/BillingApi.ts around lines 26 to 32, the
ExtendSubscriptionItemFreeTrialParams type is used in a public method signature
but is declared without export; change its declaration to export the type
(export type ExtendSubscriptionItemFreeTrialParams = { extendTo: Date; }) so it
is included in emitted d.ts files and can be reused externally, and update any
local references/imports if necessary.

Comment on lines +64 to +75
public async extendSubscriptionItemFreeTrial(
subscriptionItemId: string,
params: ExtendSubscriptionItemFreeTrialParams,
) {
this.requireId(subscriptionItemId);
return this.request<CommerceSubscriptionItem>({
method: 'POST',
path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),
bodyParams: params,
});
}

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add explicit return type; ensure RFC3339 serialization; avoid hardcoded '/billing'

  • Public API should declare return type.
  • Serialize Date to RFC3339 explicitly to avoid transport ambiguity.
  • Use a billingBasePath constant for consistency with basePath.

Apply this diff within the shown lines:

-  public async extendSubscriptionItemFreeTrial(
+  public async extendSubscriptionItemFreeTrial(
     subscriptionItemId: string,
     params: ExtendSubscriptionItemFreeTrialParams,
-  ) {
+  ): Promise<CommerceSubscriptionItem> {
     this.requireId(subscriptionItemId);
     return this.request<CommerceSubscriptionItem>({
       method: 'POST',
-      path: joinPaths('/billing', 'subscription_items', subscriptionItemId, 'extend_free_trial'),
-      bodyParams: params,
+      path: joinPaths(billingBasePath, 'subscription_items', subscriptionItemId, 'extend_free_trial'),
+      bodyParams: {
+        // Ensure RFC3339 payload
+        extendTo: params.extendTo.toISOString(),
+      },
     });
   }

And add this near the other base path constants:

const billingBasePath = '/billing';

Verification script to confirm serializer expectations and path correctness:


🏁 Script executed:

#!/bin/bash
# Inspect request serialization to confirm Date handling and key-casing.
fd 'AbstractApi.ts' -t f
if [[ -f packages/backend/src/api/endpoints/AbstractApi.ts ]]; then
  sed -n '1,220p' packages/backend/src/api/endpoints/AbstractApi.ts | sed -n '1,220p'
fi
rg -nP -C3 --type=ts 'bodyParams:\s*{[^}]*toISOString\('
rg -nP -C3 --type=ts "joinPaths\('/billing'|billingBasePath" packages/backend
# Check if there is a params key transform (camelCase -> snake_case)
rg -nP -C2 --type=ts 'snake|camel.*case|serialize.*params|toSnake' packages

Length of output: 12970


Declare explicit return type, billingBasePath constant, and enable deepSnakecaseBodyParamKeys

  • Change signature to ): Promise<CommerceSubscriptionItem>.
  • Add const billingBasePath = '/billing'; alongside other base‐path constants.
  • Replace path: joinPaths('/billing', …) with joinPaths(billingBasePath, …).
  • Pass options: { deepSnakecaseBodyParamKeys: true } on the request call so keys are snake_cased and JSON.stringify emits dates as RFC3339.
🤖 Prompt for AI Agents
packages/backend/src/api/endpoints/BillingApi.ts around lines 64 to 75: the
method signature and request call need updates — change the method return type
to Promise<CommerceSubscriptionItem>, add a billingBasePath constant alongside
other base-path constants and use it in joinPaths instead of the string literal
'/billing', and pass options: { deepSnakecaseBodyParamKeys: true } into the
request call so body keys are deep-snake_cased and dates are serialized as
RFC3339.

@panteliselef panteliselef merged commit 63fa204 into main Sep 8, 2025
41 checks passed
@panteliselef panteliselef deleted the elef/update-billing-bapi branch September 8, 2025 14:01
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.

3 participants