-
Notifications
You must be signed in to change notification settings - Fork 370
chore(nextjs, shared) adjust telemetry sampling for keyless #6488
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: 1a19920 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 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 set introduces support for enhanced telemetry handling in keyless mode for a Next.js and Clerk integration. It adds a global flag Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (6)
.changeset/sad-pianos-pull.md (1)
1-7
: LGTM! Consider more descriptive changeset message.The changeset format is correct and properly identifies the affected packages with patch versions. The description could be more specific about the telemetry sampling rate override for keyless applications to better document the change.
packages/nextjs/src/app-router/client/ClerkProvider.tsx (1)
46-51
: Consider type-safe approach for global flag setting.The logic is correct, but using
(window as any)
bypasses TypeScript's type safety. Consider defining a proper interface extension or using a more type-safe approach.Apply this diff to improve type safety:
+declare global { + interface Window { + __clerk_keyless?: boolean; + } +} + // Set global keyless flag for telemetry boosting useEffect(() => { if (canUseKeyless && typeof window !== 'undefined') { - (window as any).__clerk_keyless = true; + window.__clerk_keyless = true; } }, []);packages/shared/src/telemetry/collector.ts (1)
289-289
: Improve type safety consistency.The keyless detection logic is correct, but consider using the same type-safe approach across the codebase instead of
(window as any)
.If you implement the global interface extension suggested in ClerkProvider.tsx, you can improve this line:
-const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true; +const isKeyless = typeof window !== 'undefined' && window.__clerk_keyless === true;packages/shared/src/telemetry/events/component-mounted.ts (3)
27-29
: Consider extracting keyless detection logic.The keyless detection and sampling rate calculation logic is duplicated between this function and
eventComponentMounted
. Consider extracting it to a utility function for better maintainability.+function getEffectiveSamplingRate(samplingRateOverride?: number): number { + const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true; + return samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE); +} + function createPrebuiltComponentEvent(event: typeof EVENT_COMPONENT_MOUNTED | typeof EVENT_COMPONENT_OPENED) { return function ( component: string, props?: Record<string, any>, additionalPayload?: TelemetryEventRaw['payload'], samplingRateOverride?: number, ): TelemetryEventRaw<EventPrebuiltComponent> { - // Check for keyless mode and boost sampling rate if no override provided - const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true; - const effectiveSamplingRate = samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE); + const effectiveSamplingRate = getEffectiveSamplingRate(samplingRateOverride);
113-115
: Code duplication: Same keyless detection logic.This is the same keyless detection logic as in
createPrebuiltComponentEvent
. The earlier suggestion to extract this to a utility function would eliminate this duplication.Apply the same refactor here:
- // Check for keyless mode and boost sampling rate if no override provided - const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true; - const effectiveSamplingRate = samplingRateOverride ?? (isKeyless ? 1.0 : EVENT_SAMPLING_RATE); + const effectiveSamplingRate = getEffectiveSamplingRate(samplingRateOverride);
28-28
: Consider improving type safety for global window property.The
(window as any).__clerk_keyless
access could be more type-safe. Consider adding a type declaration for the global property.You could add a type declaration at the top of the file or in a types file:
declare global { interface Window { __clerk_keyless?: boolean; } }Then use:
-const isKeyless = typeof window !== 'undefined' && (window as any).__clerk_keyless === true; +const isKeyless = typeof window !== 'undefined' && window.__clerk_keyless === true;Also applies to: 114-114
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
.changeset/sad-pianos-pull.md
(1 hunks)packages/nextjs/src/app-router/client/ClerkProvider.tsx
(1 hunks)packages/nextjs/src/types.ts
(1 hunks)packages/shared/src/__tests__/component-mounted.test.ts
(1 hunks)packages/shared/src/__tests__/telemetry.test.ts
(1 hunks)packages/shared/src/telemetry/collector.ts
(2 hunks)packages/shared/src/telemetry/events/component-mounted.ts
(6 hunks)
🧰 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/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.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/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.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/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.ts
**/*.{jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/nextjs/src/app-router/client/ClerkProvider.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.ts
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/nextjs/src/app-router/client/ClerkProvider.tsx
**/*
⚙️ 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/nextjs/src/app-router/client/ClerkProvider.tsx
packages/shared/src/telemetry/collector.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/nextjs/src/types.ts
packages/shared/src/__tests__/component-mounted.test.ts
packages/shared/src/telemetry/events/component-mounted.ts
.changeset/**
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/sad-pianos-pull.md
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/shared/src/__tests__/telemetry.test.ts
packages/shared/src/__tests__/component-mounted.test.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/shared/src/__tests__/telemetry.test.ts
packages/shared/src/__tests__/component-mounted.test.ts
🧬 Code Graph Analysis (3)
packages/nextjs/src/app-router/client/ClerkProvider.tsx (2)
packages/nextjs/src/utils/feature-flags.ts (1)
canUseKeyless
(12-12)packages/shared/src/telemetry/collector.ts (1)
window
(179-213)
packages/nextjs/src/types.ts (1)
packages/types/src/utils.ts (1)
Without
(105-107)
packages/shared/src/telemetry/events/component-mounted.ts (1)
packages/types/src/telemetry.ts (1)
TelemetryEventRaw
(40-44)
🪛 ESLint
packages/shared/src/__tests__/component-mounted.test.ts
[error] 1-1: 'TelemetryEventRaw' is defined but never used. Allowed unused vars must match /^_/u.
(@typescript-eslint/no-unused-vars)
[error] 1-1: 'TelemetryEventRaw' is defined but never used.
(unused-imports/no-unused-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: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
packages/shared/src/telemetry/collector.ts (1)
299-299
: LGTM! Efficient conditional property inclusion.The conditional spreading approach is clean and efficiently adds the keyless flag only when needed.
packages/nextjs/src/types.ts (1)
4-21
: LGTM! Well-structured type definition.The type definition properly excludes the original
telemetry
property and redefines it with Next.js-specific options. The JSDoc documentation clearly explains the purpose and behavior. The union type withfalse
or an object with optionaldisabled
/debug
properties provides good flexibility.packages/shared/src/__tests__/telemetry.test.ts (1)
321-402
: LGTM! Comprehensive test coverage for keyless mode detection.The test suite thoroughly covers all scenarios:
- Keyless flag present and true
- Keyless flag absent or false
- Server environment (no window object)
The test structure is well-organized with proper setup/cleanup, and the mocking approach correctly simulates different environments. The use of debug mode to verify payload contents is a smart testing strategy.
packages/shared/src/__tests__/component-mounted.test.ts (3)
10-13
: LGTM!Good test cleanup pattern to ensure isolation between tests by removing any existing window mock.
15-61
: Excellent test coverage for keyless mode detection.The test suite comprehensively covers all scenarios:
- Default behavior when not in keyless mode
- Sampling rate boost in keyless mode
- Explicit override precedence
- Server environment handling
- Invalid flag type handling
134-179
: Comprehensive payload structure validation.The tests properly verify:
- Appearance property tracking with boolean flags
- Handling of both present and absent appearance properties
- Additional payload data inclusion
packages/shared/src/telemetry/events/component-mounted.ts (1)
25-26
: LGTM! Consistent function signature updates.The addition of the optional
samplingRateOverride
parameter is consistent across all functions and maintains backward compatibility. JSDoc comments are properly updated.Also applies to: 52-52, 61-61, 77-77, 86-86, 103-103, 111-111
@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: |
- Added `KeylessTelemetryEnhancer` component to boost telemetry sampling rates in keyless mode. - Introduced `NextJSTelemetryCollector` to manage telemetry events with keyless support. - Updated global `Window` interface to include `__clerk_keyless` flag. - Created tests for keyless telemetry integration, ensuring proper functionality and error handling. - Refactored existing telemetry event functions to respect explicit sampling rate overrides.
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
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
packages/nextjs/src/__tests__/telemetry-collector.test.ts
(1 hunks)packages/nextjs/src/app-router/client/ClerkProvider.tsx
(2 hunks)packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
(1 hunks)packages/nextjs/src/global.d.ts
(1 hunks)packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
(1 hunks)packages/nextjs/src/utils/telemetry-collector.ts
(1 hunks)packages/shared/src/__tests__/component-mounted.test.ts
(1 hunks)packages/shared/src/telemetry/events/component-mounted.ts
(6 hunks)
✅ Files skipped from review due to trivial changes (1)
- packages/nextjs/src/global.d.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/nextjs/src/app-router/client/ClerkProvider.tsx
- packages/shared/src/tests/component-mounted.test.ts
- packages/shared/src/telemetry/events/component-mounted.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/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/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/telemetry-collector.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/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/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/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/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/telemetry-collector.ts
**/*.{jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/telemetry-collector.ts
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
**/*
⚙️ 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/nextjs/src/app-router/client/keyless-creator-reader.tsx
packages/nextjs/src/__tests__/telemetry-collector.test.ts
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
packages/nextjs/src/utils/telemetry-collector.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/nextjs/src/__tests__/telemetry-collector.test.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/nextjs/src/__tests__/telemetry-collector.test.ts
🪛 ESLint
packages/nextjs/src/__tests__/telemetry-collector.test.ts
[error] 70-70: A require()
style import is forbidden.
(@typescript-eslint/no-require-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: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/nextjs/src/__tests__/telemetry-collector.test.ts (2)
9-19
: LGTM! Comprehensive interface verification.The test properly verifies that the NextJSTelemetryCollector implements the expected telemetry collector interface with all required methods and properties.
21-47
: Good error handling test with proper cleanup.The test correctly simulates keyless mode, verifies the collector handles events without throwing, and properly cleans up the global flag.
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx (3)
16-50
: Excellent implementation of telemetry enhancement logic.The component properly:
- Detects keyless runtime using the global flag
- Prevents double wrapping with instanceof checks
- Includes cleanup for HMR support
- Uses appropriate exit conditions
52-52
: LGTM! Proper null rendering for utility component.Returning null is appropriate for a utility component that only provides side effects without rendering UI.
37-38
: Ensure PACKAGE_NAME and PACKAGE_VERSION are defined and importedI searched the repo but didn’t find any exports for these constants. To prevent runtime errors, please:
- Define
PACKAGE_NAME
andPACKAGE_VERSION
(e.g. in a newconstants.ts
alongside your util).- Import them at the top of
packages/nextjs/src/utils/keyless-telemetry-enhancer.tsx
, for example:'use client'; import { useEffect } from 'react'; import { useClerk } from '../client-boundary/hooks'; import { canUseKeyless } from './feature-flags'; import { NextJSTelemetryCollector } from './telemetry-collector'; + import { PACKAGE_NAME, PACKAGE_VERSION } from './constants';
- Adjust the import path if your constants live elsewhere.
packages/nextjs/src/utils/telemetry-collector.ts (3)
9-14
: LGTM! Proper TypeScript class structure.Excellent use of private fields, interface implementation, and clean constructor pattern.
16-22
: LGTM! Clean delegation pattern.The getters properly delegate to the internal collector, maintaining the interface contract.
24-39
: Excellent sampling rate boosting logic with comprehensive edge case handling.The implementation correctly:
- Detects keyless mode via global flag
- Identifies COMPONENT_MOUNTED events
- Respects existing 100% sampling rates
- Only boosts when sampling is undefined or below 1.0
- Creates new event object to avoid mutation
The logic handles all the necessary edge cases and maintains immutability by creating a new event object when boosting is needed.
test('boosts sampling for component-mounted events in keyless mode', () => { | ||
(window as any).__clerk_keyless = true; | ||
|
||
// Spy on underlying collector | ||
const records: any[] = []; | ||
vi.doMock('@clerk/shared/telemetry', async () => { | ||
const actual = await vi.importActual<any>('@clerk/shared/telemetry'); | ||
return { | ||
...actual, | ||
TelemetryCollector: class { | ||
isEnabled = true; | ||
isDebug = false; | ||
record(ev: any) { | ||
records.push(ev); | ||
} | ||
}, | ||
}; | ||
}); | ||
|
||
// Re-require after mock | ||
// eslint-disable-next-line @typescript-eslint/no-var-requires | ||
const { NextJSTelemetryCollector: Collector } = require('../utils/telemetry-collector'); | ||
const collector = new Collector({ publishableKey: 'pk_test_123' }); | ||
|
||
collector.record({ event: 'COMPONENT_MOUNTED', payload: { component: 'SignIn' } }); | ||
collector.record({ event: 'COMPONENT_MOUNTED', payload: { component: 'SignUp' }, eventSamplingRate: 0.1 }); | ||
collector.record({ event: 'OTHER_EVENT', payload: {} }); | ||
|
||
expect(records[0].eventSamplingRate).toBe(1); | ||
expect(records[1].eventSamplingRate).toBe(1); | ||
expect(records[2].eventSamplingRate).toBeUndefined(); | ||
|
||
delete (window as any).__clerk_keyless; | ||
vi.resetModules(); | ||
}); | ||
}); |
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
Address ESLint violation while maintaining test functionality.
The test logic for verifying sampling rate boosting is sound, but the require()
usage violates the ESLint rule. Since this is needed for dynamic re-importing after mocking, consider using dynamic import with proper typing.
- // Re-require after mock
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { NextJSTelemetryCollector: Collector } = require('../utils/telemetry-collector');
+ // Re-import after mock
+ const { NextJSTelemetryCollector: Collector } = await import('../utils/telemetry-collector');
You'll need to make the test function async
and add await
before the import statement to maintain the same functionality while adhering to ESLint rules.
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 ESLint
[error] 70-70: A require()
style import is forbidden.
(@typescript-eslint/no-require-imports)
🤖 Prompt for AI Agents
In packages/nextjs/src/__tests__/telemetry-collector.test.ts between lines 49
and 84, the test uses a synchronous require() call which violates ESLint rules.
To fix this, convert the test function to async and replace the require() call
with an awaited dynamic import statement, ensuring proper typing is used. This
change maintains the test functionality while adhering to ESLint standards.
if (typeof window !== 'undefined') { | ||
(window as any).__clerk_keyless = true; | ||
} |
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
Improve type safety for global keyless flag.
Instead of using (window as any)
, leverage the declared Window interface property to maintain type safety.
- if (typeof window !== 'undefined') {
- (window as any).__clerk_keyless = true;
- }
+ if (typeof window !== 'undefined') {
+ window.__clerk_keyless = true;
+ }
This assumes the property is properly declared in the global.d.ts file as mentioned in the AI summary.
📝 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.
if (typeof window !== 'undefined') { | |
(window as any).__clerk_keyless = true; | |
} | |
if (typeof window !== 'undefined') { | |
window.__clerk_keyless = true; | |
} |
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/client/keyless-creator-reader.tsx around lines
13 to 15, replace the use of (window as any).__clerk_keyless with a properly
typed property on the Window interface. First, ensure that the global.d.ts file
declares __clerk_keyless on the Window interface. Then, access
window.__clerk_keyless directly without casting to any to maintain type safety.
Description
This adds a sampling rate override for telemetry on keyless applications to help us better troubleshoot keyless issues. It creates a global keyless flag which is then used to override the sample rate for the
COMPONENT_MOUNTED
event.Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit