-
Notifications
You must be signed in to change notification settings - Fork 393
chore(backend): Add extend trial endpoint #6714
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
🦋 Changeset detectedLatest commit: 32a8460 The changes in this PR will be included in the next version bump. This PR includes changesets to release 11 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 |
WalkthroughAdds 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
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 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/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (3)
.changeset/public-goats-sort.md (1)
1-5
: Optional: Call out experimental status in the noteSince 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 exampleAdd 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 forextendTo
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.
📒 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
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/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 summaryMinor bump for a new public API is appropriate; message is clear.
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; | ||
}; |
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
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.
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.
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, | ||
}); | ||
} | ||
|
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
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 withbasePath
.
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', …)
withjoinPaths(billingBasePath, …)
. - Pass
options: { deepSnakecaseBodyParamKeys: true }
on therequest
call so keys are snake_cased andJSON.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.
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Documentation