-
Notifications
You must be signed in to change notification settings - Fork 370
feat(clerk-js): Introduce debugLogger #6452
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?
Conversation
🦋 Changeset detectedLatest commit: 5ff7b86 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 ↗︎
|
📝 WalkthroughWalkthroughThis change introduces a comprehensive debug logging system to the Clerk JavaScript SDK. The main Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15–25 minutes Complexity label: Moderate
Assessment against linked issues
Assessment against linked issues: Out-of-scope changesNo out-of-scope or unrelated code changes were detected. All modifications pertain directly to the implementation of the debugLogger feature and its integration with the Clerk SDK environment and core classes. 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. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
🪧 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: 9
🧹 Nitpick comments (10)
packages/types/src/json.ts (1)
74-82
: Consider the necessity of property reordering.The addition of
client_debug_mode: boolean
is correct and follows proper naming conventions. However, the reordering of existing properties (auth_config
,user_settings
,organization_settings
) appears unnecessary and could potentially cause confusion without providing functional benefits.While TypeScript interfaces don't enforce property order, maintaining consistent ordering can help with code readability and reduce unnecessary diffs in version control.
packages/clerk-js/src/core/modules/debug/transports/console.ts (1)
3-32
: Solid console transport implementation.The
ConsoleTransport
class provides a clean implementation of theDebugTransport
interface with proper message formatting and appropriate console method routing based on log levels.Consider adding error handling for
JSON.stringify
to prevent issues with circular references:- const context = entry.context ? ` ${JSON.stringify(entry.context)}` : ''; + const context = entry.context ? ` ${JSON.stringify(entry.context, null, 2)}` : '';Or use a safer stringify approach:
- const context = entry.context ? ` ${JSON.stringify(entry.context)}` : ''; + let context = ''; + if (entry.context) { + try { + context = ` ${JSON.stringify(entry.context)}`; + } catch (err) { + context = ` [Circular/Non-serializable context]`; + } + }packages/clerk-js/src/core/modules/debug/transports/composite.ts (2)
3-10
: Interface includes unused properties.The
CompositeLoggerOptions
interface defineslogLevel
andfilters
properties that aren't used by theCompositeTransport
class. Consider either implementing these features or removing them from the interface to avoid confusion.The
options
property in the transport configuration is also unused.
12-27
: Well-designed composite transport with minor logging concern.The
CompositeTransport
implementation properly handles multiple transports with good error isolation usingPromise.allSettled
. However, the error logging on line 22 usesconsole.error
, which could create noise or conflicts if one of the transports is aConsoleTransport
.Consider using a different error handling approach or making the error logging configurable:
- console.error('Failed to send to transport:', err); + // Only log if not in browser environment or if no console transport is present + if (typeof window === 'undefined' || !this.transports.some(t => t.constructor.name === 'ConsoleTransport')) { + console.error('Failed to send to transport:', err); + }packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (2)
16-22
: Consider lazy timer initialization to avoid unnecessary resource usage.Starting the flush timer immediately in the constructor creates a timer even if the transport is never used for logging. Consider starting the timer on the first
send()
call instead.Apply this diff for lazy timer initialization:
constructor(endpoint = 'https://telemetry.clerk.com/v1/debug', batchSize = 50, flushInterval = 10000) { this.batchSize = batchSize; this.endpoint = endpoint; this.flushInterval = flushInterval; - this.startFlushTimer(); }
Then modify the
send
method to start the timer if not already running:async send(entry: DebugLogEntry): Promise<void> { + if (!this.flushTimer) { + this.startFlushTimer(); + } this.batchBuffer.push(entry);
32-66
: Add response validation and consider retry logic for production robustness.The flush implementation correctly batches and sends data, but could be more robust for production use.
Consider adding response validation:
await fetch(this.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(debugDataArray), -}); +}).then(response => { + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } +});Also consider making the
eventType
configurable rather than hardcoded as'custom_event'
.packages/clerk-js/src/core/clerk.ts (2)
209-216
: Improve error handling and type safety.The implementation is good but could be enhanced:
- Type safety: The imported module should be type-checked
- Error logging: Consider using the existing
logger
from '@clerk/shared/logger' for consistency- Error details: The error message could be more specific
Apply this diff to improve the implementation:
async #initializeDebugModule(): Promise<void> { try { - const { getDebugLogger } = await import('./modules/debug'); - this.debugLogger = await getDebugLogger({}); + const debugModule = await import('./modules/debug'); + if ('getDebugLogger' in debugModule && typeof debugModule.getDebugLogger === 'function') { + this.debugLogger = await debugModule.getDebugLogger({}); + } } catch (error) { - console.error('Failed to initialize debug module:', error); + logger.warn('Failed to initialize debug module:', error); } }
858-865
: Add error handling and consider access modifier.The method implementation is correct but could be improved:
- Error handling: Add try-catch around the dynamic import
- Access modifier: Consider making this method private if it's truly internal
Apply this diff to improve robustness:
/** * @internal */ - public static async __internal_resetDebugLogger(): Promise<void> { + private static async __internal_resetDebugLogger(): Promise<void> { - // This method is now handled by the debug module itself - const { __internal_resetDebugLogger } = await import('./modules/debug'); - __internal_resetDebugLogger(); + try { + const { __internal_resetDebugLogger } = await import('./modules/debug'); + __internal_resetDebugLogger(); + } catch (error) { + logger.warn('Failed to reset debug logger:', error); + } }If this method needs to be public for external testing, keep it public but add the error handling.
packages/clerk-js/src/core/modules/debug/index.ts (1)
1-171
: Add comprehensive test coverage for the debug module.The coding guidelines specify that tests should be added to cover changes. This debug module needs extensive testing for:
- Singleton behavior
- Logger initialization with various options
- Error handling during initialization
- Factory function behaviors
- Reset functionality
Would you like me to generate comprehensive unit tests for this debug module to ensure proper functionality and prevent regressions?
packages/clerk-js/src/core/modules/debug/types.ts (1)
1-140
: Add comprehensive test coverage for type definitions.The type guards and utility functions need test coverage to ensure they work correctly with various input scenarios.
Would you like me to generate unit tests for the type guard functions and utility types to ensure they properly validate objects and handle edge cases?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
packages/clerk-js/src/core/clerk.ts
(5 hunks)packages/clerk-js/src/core/modules/debug/index.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/logger.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/composite.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/console.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/types.ts
(1 hunks)packages/clerk-js/src/core/resources/Environment.ts
(3 hunks)packages/types/src/environment.ts
(1 hunks)packages/types/src/json.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.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/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.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/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.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/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.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.Whenever reviewing a pull request, if there are any changes that could impact security, always tag
@clerk/security
in the PR.Security-impacting changes include, but are not limited to:
- Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
- Any modification to access control, authorization checks, or role-based permissions
- Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
- Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
- Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
- Modifications to security headers, cookie flags, CORS policies, or CSRF protections
- Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
- Changes to rate limiting, abuse prevention, or input validation
If you're unsure whether a change is security-relevant, err on the side of caution and tag
@clerk/security
.Any time that you tag
@clerk/security
, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.
Files:
packages/types/src/environment.ts
packages/clerk-js/src/core/resources/Environment.ts
packages/types/src/json.ts
packages/clerk-js/src/core/modules/debug/transports/console.ts
packages/clerk-js/src/core/modules/debug/transports/composite.ts
packages/clerk-js/src/core/modules/debug/logger.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/clerk-js/src/core/clerk.ts
packages/clerk-js/src/core/modules/debug/types.ts
packages/**/index.{js,ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use tree-shaking friendly exports
Files:
packages/clerk-js/src/core/modules/debug/index.ts
**/index.ts
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
Use index.ts files for clean imports but avoid deep barrel exports
Avoid barrel files (index.ts re-exports) as they can cause circular dependencies
Files:
packages/clerk-js/src/core/modules/debug/index.ts
🧬 Code Graph Analysis (5)
packages/types/src/json.ts (4)
packages/types/src/commerceSettings.ts (1)
CommerceSettingsJSON
(6-21)packages/types/src/displayConfig.ts (1)
DisplayConfigJSON
(10-48)packages/types/src/organizationSettings.ts (1)
OrganizationSettingsJSON
(6-20)packages/types/src/userSettings.ts (1)
UserSettingsJSON
(112-130)
packages/clerk-js/src/core/modules/debug/transports/console.ts (2)
packages/clerk-js/src/core/modules/debug/index.ts (1)
ConsoleTransport
(9-9)packages/clerk-js/src/core/modules/debug/types.ts (2)
DebugTransport
(43-48)DebugLogEntry
(14-24)
packages/clerk-js/src/core/modules/debug/logger.ts (1)
packages/clerk-js/src/core/modules/debug/types.ts (4)
DebugTransport
(43-48)DebugLogLevel
(4-4)DebugLogFilter
(79-86)DebugLogEntry
(14-24)
packages/clerk-js/src/core/modules/debug/index.ts (6)
packages/clerk-js/src/core/modules/debug/types.ts (2)
DebugLogFilter
(79-86)DebugLogLevel
(4-4)packages/clerk-js/src/core/modules/debug/transports/console.ts (1)
ConsoleTransport
(3-32)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (2)
TelemetryTransport
(9-83)TelemetryLoggerOptions
(3-7)packages/clerk-js/src/core/modules/debug/transports/composite.ts (2)
CompositeTransport
(12-27)CompositeLoggerOptions
(3-10)packages/clerk-js/src/core/modules/debug/logger.ts (2)
DebugLogger
(6-116)error
(17-19)packages/clerk-js/src/core/clerk.ts (1)
__internal_resetDebugLogger
(2861-2865)
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (1)
packages/clerk-js/src/core/modules/debug/types.ts (4)
DebugLogFilter
(79-86)DebugTransport
(43-48)DebugLogEntry
(14-24)DebugData
(29-38)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (17)
packages/types/src/environment.ts (1)
22-22
: LGTM! Clean addition of debug mode flag.The new
clientDebugMode
boolean property is appropriately named and fits well within the existingEnvironmentResource
interface structure.packages/clerk-js/src/core/resources/Environment.ts (3)
23-23
: Property declaration looks good.The
clientDebugMode
property is properly initialized with a sensible default value offalse
.
52-52
: Proper initialization pattern.The use of
withDefault
helper ensures safe initialization from JSON data, following the established pattern used by other properties in this class.
93-93
: Consistent serialization.The property is correctly included in the snapshot serialization with proper snake_case naming convention for the JSON field.
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (4)
24-30
: LGTM! Clean batching implementation.The batching logic is straightforward and correctly triggers a flush when the batch size is reached. The async/await usage ensures proper error propagation.
68-73
: LGTM! Proper cleanup implementation.The destroy method correctly clears the timer and flushes any remaining buffered entries, preventing data loss during cleanup.
75-82
: Verify browser environment compatibility.The method uses
window.setTimeout
which is browser-specific. Ensure this transport is only used in browser environments or consider using a more universal timer approach.The timer implementation is otherwise correct with proper error handling and recursive restart pattern.
1-83
: Security review required for telemetry data transmission.This transport sends debug log entries to external endpoints, which may contain sensitive information including user IDs, session IDs, organization IDs, and arbitrary context data. The debug entries are transmitted without apparent sanitization.
@clerk/security Please review this telemetry transport implementation for:
- Potential PII leakage in debug context data
- Data sanitization requirements before external transmission
- Endpoint security and authentication requirements
- Whether debug data should be filtered before sending to telemetry
packages/clerk-js/src/core/modules/debug/logger.ts (4)
3-15
: LGTM! Well-designed class with proper dependency injection.The class follows good practices with dependency injection for the transport mechanism, appropriate default values, and proper TypeScript typing.
17-35
: LGTM! Consistent and clean logging method interface.All logging methods follow the same pattern with consistent signatures and proper delegation to the private log method. The API design is intuitive for developers.
37-58
: Verify crypto.randomUUID() browser compatibility.The implementation is solid with proper early returns and error handling. However,
crypto.randomUUID()
requires modern browser support (Chrome 92+, Firefox 95+, Safari 15.4+).Consider a fallback for older browsers or verify minimum browser requirements:
id: crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,Otherwise, the logging logic and error handling are well implemented.
60-65
: LGTM! Correct log level hierarchy implementation.The level checking logic correctly implements the standard logging hierarchy where error is the highest priority and trace is the lowest. The array-based approach is clean and efficient.
packages/clerk-js/src/core/clerk.ts (2)
202-207
: Consider the implications of fire-and-forget async call.The debug module initialization is called without awaiting, which creates a fire-and-forget pattern. This might be intentional for lazy loading, but consider:
- Potential race conditions if
debugLogger
is accessed immediately afterupdateEnvironment
- Error handling is delegated to the private method
If this behavior is intentional, consider adding a comment explaining the design decision.
1484-1484
: LGTM! Good use of optional chaining for debug logging.The debug logging implementation is well done:
- Safe optional chaining prevents runtime errors
- Consistent with existing router debug pattern
- Provides valuable debugging information
packages/clerk-js/src/core/modules/debug/types.ts (3)
4-4
: LGTM! Well-defined debug log levels.The debug log levels follow standard logging conventions and provide appropriate granularity for debugging purposes.
130-132
: Consider if mutable utility types are necessary.The
MutableDebugLogEntry
andMutableDebugData
types remove readonly constraints, which goes against the immutable design principle established by the readonly properties in the base interfaces.Could you clarify the use case for these mutable utility types? If they're needed for specific scenarios, consider adding JSDoc comments explaining when they should be used, as removing readonly constraints could lead to unintended mutations.
Also applies to: 137-139
14-24
: LGTM! Well-structured interfaces with proper readonly properties.The interfaces are well-designed with:
- Proper use of readonly properties for immutability
- Comprehensive field coverage for debug logging needs
- Optional properties marked appropriately
- Good separation between log entries and debug data structures
Also applies to: 29-38
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
Outdated
Show resolved
Hide resolved
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (3)
packages/clerk-js/src/core/modules/debug/index.ts (3)
58-144
: Well-implemented singleton with race condition protection.The promise caching mechanism effectively prevents concurrent initialization issues, and the error handling properly clears state for retries. The implementation follows TypeScript best practices.
However, the telemetry endpoint security validation mentioned in past reviews appears to still be missing.
252-254
: Add environment guard for internal reset function.As mentioned in previous reviews, this internal function should be protected with environment checks to prevent misuse in production environments.
export function __internal_resetDebugLogger(): void { + if (process.env.NODE_ENV === 'production') { + throw new Error('[Clerk] __internal_resetDebugLogger is disabled in production'); + } DebugLoggerManager.getInstance().reset(); }
106-106
: Security concern: Telemetry endpoints lack validation.As mentioned in previous reviews, the telemetry endpoints are used without validation, which could enable data exfiltration to malicious endpoints. This affects multiple locations where TelemetryTransport is instantiated.
@clerk/security - Please review the telemetry endpoint configuration as it poses a data exfiltration risk.
Consider implementing endpoint validation as suggested in previous reviews:
+function isValidTelemetryEndpoint(endpoint?: string): boolean { + if (!endpoint) return true; // Use default + try { + const url = new URL(endpoint); + return url.hostname.endsWith('.clerk.com') || url.hostname === 'clerk.com'; + } catch { + return false; + } +}And validate before creating TelemetryTransport instances.
Also applies to: 172-172, 215-215
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
packages/clerk-js/src/core/modules/debug/index.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/logger.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/console.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/types.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
- packages/clerk-js/src/core/modules/debug/transports/console.ts
- packages/clerk-js/src/core/modules/debug/logger.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.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/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.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/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.ts
packages/**/index.{js,ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use tree-shaking friendly exports
Files:
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.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/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.ts
**/index.ts
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
Use index.ts files for clean imports but avoid deep barrel exports
Avoid barrel files (index.ts re-exports) as they can cause circular dependencies
Files:
packages/clerk-js/src/core/modules/debug/index.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.Whenever reviewing a pull request, if there are any changes that could impact security, always tag
@clerk/security
in the PR.Security-impacting changes include, but are not limited to:
- Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
- Any modification to access control, authorization checks, or role-based permissions
- Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
- Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
- Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
- Modifications to security headers, cookie flags, CORS policies, or CSRF protections
- Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
- Changes to rate limiting, abuse prevention, or input validation
If you're unsure whether a change is security-relevant, err on the side of caution and tag
@clerk/security
.Any time that you tag
@clerk/security
, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.
Files:
packages/clerk-js/src/core/modules/debug/index.ts
packages/clerk-js/src/core/modules/debug/types.ts
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/modules/debug/index.ts (1)
packages/clerk-js/src/core/modules/debug/types.ts (4)
DebugLogLevel
(4-4)isValidLogLevel
(96-98)VALID_LOG_LEVELS
(9-9)DebugLogFilter
(84-91)
⏰ 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). (22)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Static analysis
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (7)
packages/clerk-js/src/core/modules/debug/index.ts (3)
1-11
: LGTM!Clean imports and appropriate default log level configuration.
18-25
: Well-implemented validation with helpful error messaging.The generic constraint and comprehensive error message make this validation function both flexible and developer-friendly.
27-47
: Excellent use of type-only exports and well-documented interfaces.Follows coding guidelines for clean imports and comprehensive JSDoc documentation.
packages/clerk-js/src/core/modules/debug/types.ts (4)
1-15
: Well-defined type system with proper const assertions.The union types and readonly constant array follow TypeScript best practices for type safety.
19-91
: Comprehensive interface definitions with excellent documentation.The interfaces properly use readonly properties for immutable data structures and include thorough JSDoc documentation, following the coding guidelines.
96-136
: Type guards properly enhanced based on previous feedback.The type guards now correctly validate enum values against their union types, addressing the security and type safety concerns from previous reviews.
141-155
: Well-implemented utility types using advanced TypeScript features.The mapped types properly handle readonly constraint removal while maintaining type safety.
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: 0
♻️ Duplicate comments (4)
packages/clerk-js/src/core/modules/debug/index.ts (4)
171-172
: Security concern: Same telemetry endpoint validation needed here.This function also creates a TelemetryTransport without endpoint validation, which has the same security implications as flagged in the performInitialization method.
215-215
: Security concern: Same telemetry endpoint validation needed here.This function also creates a TelemetryTransport without endpoint validation, which has the same security implications as flagged in the performInitialization method.
254-256
: Security concern: Internal reset function lacks environment protection.This internal function can still be called in production environments, potentially clearing important debug state. The environment guard suggested in previous reviews has not been implemented.
Add environment protection:
export function __internal_resetDebugLogger(): void { + if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') { + throw new Error('[Clerk] __internal_resetDebugLogger is disabled in production'); + } DebugLoggerManager.getInstance().reset(); }
106-106
: Security concern: Telemetry endpoint validation still missing.The telemetry endpoint is used without validation, which poses a security risk for data exfiltration. This was flagged in previous reviews but remains unaddressed.
@clerk/security - Please review the telemetry endpoint configuration as debug data could be sent to arbitrary endpoints.
Consider implementing endpoint validation:
+// Add endpoint validation helper +function isValidTelemetryEndpoint(endpoint?: string): boolean { + if (!endpoint) return true; // Use default + try { + const url = new URL(endpoint); + // Only allow clerk.com domains for security + return url.hostname.endsWith('.clerk.com') || url.hostname === 'clerk.com'; + } catch { + return false; + } +} - const transports = [{ transport: new ConsoleTransport() }, { transport: new TelemetryTransport(endpoint) }]; + if (endpoint && !isValidTelemetryEndpoint(endpoint)) { + console.warn('Invalid telemetry endpoint provided, using default'); + endpoint = undefined; + } + const transports = [{ transport: new ConsoleTransport() }, { transport: new TelemetryTransport(endpoint) }];
🧹 Nitpick comments (1)
packages/clerk-js/src/core/modules/debug/index.ts (1)
237-239
: Simplify explicit type annotation.The explicit type annotation is unnecessary since TypeScript can infer the type from the CompositeLoggerOptions interface.
- const transportInstances = transports.map( - (t: { transport: DebugTransport; options?: Record<string, unknown> }) => t.transport, - ); + const transportInstances = transports.map(t => t.transport);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (1)
packages/clerk-js/src/core/modules/debug/index.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/modules/debug/index.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/modules/debug/index.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/index.ts
packages/**/index.{js,ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use tree-shaking friendly exports
Files:
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/index.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/modules/debug/index.ts
**/index.ts
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
Use index.ts files for clean imports but avoid deep barrel exports
Avoid barrel files (index.ts re-exports) as they can cause circular dependencies
Files:
packages/clerk-js/src/core/modules/debug/index.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.Whenever reviewing a pull request, if there are any changes that could impact security, always tag
@clerk/security
in the PR.Security-impacting changes include, but are not limited to:
- Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
- Any modification to access control, authorization checks, or role-based permissions
- Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
- Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
- Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
- Modifications to security headers, cookie flags, CORS policies, or CSRF protections
- Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
- Changes to rate limiting, abuse prevention, or input validation
If you're unsure whether a change is security-relevant, err on the side of caution and tag
@clerk/security
.Any time that you tag
@clerk/security
, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.
Files:
packages/clerk-js/src/core/modules/debug/index.ts
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/modules/debug/index.ts (6)
packages/clerk-js/src/core/modules/debug/types.ts (5)
DebugLogLevel
(4-4)isValidLogLevel
(96-98)VALID_LOG_LEVELS
(9-9)DebugLogFilter
(84-91)DebugTransport
(48-53)packages/clerk-js/src/core/modules/debug/logger.ts (2)
DebugLogger
(11-121)error
(22-24)packages/clerk-js/src/core/modules/debug/transports/console.ts (1)
ConsoleTransport
(31-69)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (2)
TelemetryTransport
(9-83)TelemetryLoggerOptions
(3-7)packages/clerk-js/src/core/modules/debug/transports/composite.ts (2)
CompositeTransport
(12-27)CompositeLoggerOptions
(3-10)packages/clerk-js/src/core/clerk.ts (1)
__internal_resetDebugLogger
(2892-2896)
⏰ 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: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/clerk-js/src/core/modules/debug/index.ts (4)
1-31
: LGTM! Clean imports and exports structure.The imports are well-organized with proper type-only imports where appropriate. The exports follow tree-shaking friendly patterns and properly separate runtime code from type definitions.
8-25
: LGTM! Well-implemented validation with helpful error messages.The validation function uses proper generic constraints and provides clear, actionable error messages that include the invalid value and list of valid options.
32-47
: LGTM! Clean interface definitions with proper documentation.The interfaces are well-structured and provide clear contracts for logger configuration options.
58-144
: LGTM! Singleton pattern with proper race condition handling.The implementation correctly addresses the race condition concerns from previous reviews by using a promise cache pattern. The type safety issues have also been resolved with proper TypeScript types throughout.
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: 4
🔭 Outside diff range comments (1)
packages/clerk-js/src/core/modules/debug/index.ts (1)
1-260
: Consider adding comprehensive tests for this core module.This is a critical module that manages the entire debug logging system, but no tests are included in this PR. The complexity and importance of this module warrant comprehensive test coverage.
Would you like me to help create a comprehensive test suite for the
DebugLoggerManager
and factory functions?
♻️ Duplicate comments (1)
packages/clerk-js/src/core/modules/debug/index.ts (1)
256-259
: Add environment protection for internal reset function.Based on the past review comments, this internal function should be protected from production use to prevent accidental state clearing.
🧹 Nitpick comments (3)
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts (1)
20-46
: Consider adding more comprehensive test coverage.While the basic functionality is tested, consider adding tests for:
- Handling of all DebugLogEntry properties
- Error scenarios in the collector's recordLog method
- Validation of the exact data transformation between DebugLogEntry and TelemetryLogEntry
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (1)
5-9
: Consider removing unused TelemetryLoggerOptions interface.The
TelemetryLoggerOptions
interface is defined but doesn't appear to be used in this file. It might belong in the main debug module or could be removed if unused.packages/clerk-js/src/core/modules/debug/index.ts (1)
51-55
: Consider making CompositeLoggerOptions more flexible.The transport array is constrained to only
ConsoleTransport | TelemetryTransport
, but theCompositeTransport
class accepts anyDebugTransport
. This limits extensibility.Apply this diff to make it more flexible:
export interface CompositeLoggerOptions { - transports: Array<{ transport: ConsoleTransport | TelemetryTransport }>; + transports: Array<{ transport: DebugTransport }>; logLevel?: DebugLogLevel; filters?: DebugLogFilter[]; }You'll need to import
DebugTransport
from'./types'
.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
packages/clerk-js/bundlewatch.config.json
(1 hunks)packages/clerk-js/src/core/modules/debug/index.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
(1 hunks)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
(1 hunks)packages/shared/src/telemetry/collector.ts
(5 hunks)packages/types/src/telemetry.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/bundlewatch.config.json
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.ts
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/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.ts
**/__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/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.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/modules/debug/transports/__tests__/telemetry.test.ts
packages/clerk-js/src/core/modules/debug/transports/telemetry.ts
packages/types/src/telemetry.ts
packages/shared/src/telemetry/collector.ts
packages/clerk-js/src/core/modules/debug/index.ts
packages/**/index.{js,ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use tree-shaking friendly exports
Files:
packages/clerk-js/src/core/modules/debug/index.ts
**/index.ts
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
Use index.ts files for clean imports but avoid deep barrel exports
Avoid barrel files (index.ts re-exports) as they can cause circular dependencies
Files:
packages/clerk-js/src/core/modules/debug/index.ts
🧬 Code Graph Analysis (3)
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts (4)
packages/types/src/telemetry.ts (1)
TelemetryCollector
(61-66)packages/shared/src/telemetry/collector.ts (1)
TelemetryCollector
(73-383)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (1)
TelemetryTransport
(11-35)packages/clerk-js/src/core/modules/debug/types.ts (1)
DebugLogEntry
(19-29)
packages/shared/src/telemetry/collector.ts (3)
packages/types/src/telemetry.ts (2)
TelemetryLogEntry
(49-59)TelemetryEvent
(8-35)packages/clerk-js/src/core/clerk.ts (2)
sdkMetadata
(297-299)sdkMetadata
(301-303)packages/react/src/isomorphicClerk.ts (1)
sdkMetadata
(265-267)
packages/clerk-js/src/core/modules/debug/index.ts (8)
packages/clerk-js/src/core/modules/debug/types.ts (2)
DebugLogLevel
(4-4)DebugLogFilter
(84-91)packages/types/src/telemetry.ts (1)
TelemetryCollector
(61-66)packages/shared/src/telemetry/collector.ts (1)
TelemetryCollector
(73-383)packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (2)
TelemetryLoggerOptions
(5-9)TelemetryTransport
(11-35)packages/clerk-js/src/core/modules/debug/transports/composite.ts (2)
CompositeLoggerOptions
(3-10)CompositeTransport
(12-27)packages/clerk-js/src/core/modules/debug/transports/console.ts (1)
ConsoleTransport
(31-69)packages/clerk-js/src/core/modules/debug/logger.ts (2)
DebugLogger
(11-139)error
(22-24)packages/clerk-js/src/core/clerk.ts (1)
__internal_resetDebugLogger
(2899-2903)
🪛 ESLint
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
[error] 1-3: Run autofix to sort these imports!
(simple-import-sort/imports)
[error] 2-2: All imports in the declaration are only used as types. Use import type
.
(@typescript-eslint/consistent-type-imports)
⏰ 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: semgrep-cloud-platform/scan
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
packages/types/src/telemetry.ts (2)
46-59
: LGTM - Well-structured debug log entry interface.The
TelemetryLogEntry
interface is well-designed with:
- Readonly properties for immutability
- Proper typing with constrained log levels
- Appropriate optional fields for metadata
- Good alignment with the debug logging system requirements
65-65
: LGTM - Clean extension of TelemetryCollector interface.The addition of the
recordLog
method to theTelemetryCollector
interface is clean and follows the existing pattern established by therecord
method.packages/clerk-js/src/core/modules/debug/transports/telemetry.ts (1)
11-35
: LGTM - Clean and robust transport implementation.The
TelemetryTransport
class is well-implemented with:
- Proper null-checking for optional collector
- Clean property mapping between log entry types
- Graceful handling of missing dependencies
- Appropriate async/await usage
packages/shared/src/telemetry/collector.ts (2)
163-190
: LGTM - Well-structured log recording implementation.The
recordLog
method follows good patterns:
- Proper filtering with
#shouldRecordLog
- Consistent metadata enrichment using
#getSDKMetadata
- Appropriate data transformation and buffering
- Integration with scheduling logic
294-313
: LGTM - Robust log flushing implementation.The
#flushLogs
method is well-implemented with:
- Proper empty buffer check
- Safe buffer copying and clearing
- Appropriate error handling with console.error
- Correct endpoint usage
packages/clerk-js/src/core/modules/debug/index.ts (2)
14-18
: LGTM - Proper input validation.The
validateLoggerOptions
function provides essential runtime validation to prevent configuration errors.
60-148
: LGTM - Well-implemented singleton pattern with race condition protection.The
DebugLoggerManager
class properly implements:
- Thread-safe singleton pattern
- Race condition protection with promise caching
- Proper error handling and cleanup
- Clear separation of concerns
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
Outdated
Show resolved
Hide resolved
packages/clerk-js/src/core/modules/debug/transports/__tests__/telemetry.test.ts
Outdated
Show resolved
Hide resolved
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: 0
🧹 Nitpick comments (1)
packages/shared/src/telemetry/collector.ts (1)
190-358
: Consider adding unit tests for the new logging functionalityThe new logging capabilities represent a significant feature addition. Based on the coding guidelines, tests should be added to cover the new functionality.
Key areas that should be tested include:
recordLog
method behavior with various log entries- Log filtering logic in
#shouldRecordLog
- Log flush scheduling and execution
- Error handling in log flush operations
- Integration with existing telemetry functionality
Would you like me to help generate unit tests for the new logging functionality?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/shared/src/telemetry/collector.ts
(5 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/telemetry/collector.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/shared/src/telemetry/collector.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/telemetry/collector.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/telemetry/collector.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/shared/src/telemetry/collector.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/shared/src/telemetry/collector.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/shared/src/telemetry/collector.ts
🧬 Code Graph Analysis (1)
packages/shared/src/telemetry/collector.ts (3)
packages/types/src/telemetry.ts (1)
TelemetryLogEntry
(49-59)packages/clerk-js/src/core/clerk.ts (2)
sdkMetadata
(297-299)sdkMetadata
(301-303)packages/react/src/isomorphicClerk.ts (1)
sdkMetadata
(265-267)
⏰ 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 (9)
packages/shared/src/telemetry/collector.ts (9)
19-19
: LGTM - Import addition is correctThe
TelemetryLogEntry
import is properly added to support the new logging functionality.
64-87
: Well-structured type definition with clear documentationThe
TelemetryLogData
type is properly defined with comprehensive JSDoc comments explaining each field. This addresses the previous concern about usingany[]
by providing a specific type for log buffer entries.
102-106
: Log buffer fields properly typed and protectedThe log buffer and flush promise fields are correctly typed using the new
TelemetryLogData[]
type, and the pending flush protection has been added as suggested in previous reviews.
190-217
: Robust log recording implementation with proper error boundariesThe
recordLog
method is well-implemented with:
- Clear JSDoc documentation
- Proper filtering via
#shouldRecordLog
- Correct data transformation using SDK metadata
- Safe null handling for optional fields
The implementation correctly follows the existing pattern established by the
record
method.
223-225
: Consider more granular log filtering logicThe current
#shouldRecordLog
implementation only checks if telemetry is enabled, but unlike events, it doesn't respect the debug mode check. This means logs will be recorded even in debug mode, which may or may not be intended.Should logs be filtered out in debug mode like events are? The current logic differs from
#shouldRecord
which excludes debug mode:// Events are filtered out in debug mode #shouldRecord(preparedPayload: TelemetryEvent, eventSamplingRate?: number) { return this.isEnabled && !this.isDebug && this.#shouldBeSampled(preparedPayload, eventSamplingRate); } // But logs are not #shouldRecordLog(_entry: TelemetryLogEntry): boolean { return this.isEnabled; }If logs should also be filtered in debug mode, apply this diff:
#shouldRecordLog(_entry: TelemetryLogEntry): boolean { - return this.isEnabled; + return this.isEnabled && !this.isDebug; }
268-277
: Consistent flush cleanup implementationThe addition of
this.#pendingFlush = null;
properly cleans up the pending flush state after completion, maintaining consistency with the new log flush implementation.
279-310
: Well-implemented log flush scheduling with proper concurrency protectionThe
#scheduleLogFlush
method correctly implements:
- Server-side immediate flushing
- Buffer size-based immediate flushing with pending flush cancellation
- Duplicate flush prevention
- Proper cleanup of pending flush state
This addresses the previous concern about missing pending flush protection for logs.
312-333
: Improved event flush logic with better concurrency handlingThe modifications to
#flush
add proper:
- Duplicate flush prevention via
#flushPromise
check- Empty buffer early return
- Promise cleanup in finally block
These improvements enhance the robustness of the existing event flushing mechanism.
335-358
: Comprehensive log flush implementation with proper error handlingThe
#flushLogs
method is well-implemented with:
- Duplicate flush prevention
- Empty buffer early return
- Correct endpoint (
/v1/logs
)- Proper JSON serialization of log entries array
- Exception handling with console error logging
- Promise cleanup in both catch and finally blocks
The error handling is more comprehensive than the event flush, which is appropriate given that log flushing is a new feature.
…og flush, Clerk core state+debug logger
Description
Create a debugLogger module that will be lazy instantiated when environment shows we are in a client debug mode.
Fixes: USER-2540
Related: https://github.com/clerk/cloudflare-workers/pull/672
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Tests
Documentation