-
Notifications
You must be signed in to change notification settings - Fork 372
feat(clerk-js,themes,shared): Add theme-usage telemetry #6529
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
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
|
||
if (typeof theme === 'object' && theme !== null) { | ||
// Check for explicit theme name | ||
if ('__themeName' in theme && typeof theme.__themeName === 'string') { |
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.
is this an ai hallucination?
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.
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.
sorry, I wasn't understanding why we needed __themeName
, but I think I get it now! I thought we supplied the shadcn theme via appearance.theme = 'shadcn'
, so I was confused why we needed __themeName
.
@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: |
📝 WalkthroughWalkthroughAdds theme-usage telemetry: introduces eventThemeUsage and unit tests in shared telemetry, and re-exports it. Emits the telemetry event from Clerk.load (packages/clerk-js) when telemetry is enabled and appearance is provided, and from the React Clerk context effect when options.appearance changes. Extends theme creation params with an optional name and adds name properties to built-in themes (dark, neobrutalism, shadcn, shadesOfPurple, simple). Adjusts a bundle size threshold. No other public function signatures were changed. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (2)**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Files:
**/*⚙️ CodeRabbit Configuration File
Files:
⏰ 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)
🔇 Additional comments (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
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: 3
🔭 Outside diff range comments (1)
packages/themes/src/createTheme.ts (1)
20-28
: Avoid leaking __themeName and ensure excess-property safety withsatisfies
Two issues:
- Adding
__themeName
directly in the returned object can (a) surface an internal field to consumers and (b) trigger excess property checks depending on howBaseTheme
is defined.- Prefer making the internal field non-enumerable and using
satisfies
to validate shape without widening.Refactor as below.
export const experimental_createTheme = (appearance: Appearance<CreateClerkThemeParams>): BaseTheme => { - // Placeholder method that might hande more transformations in the future - return { - ...appearance, - __type: 'prebuilt_appearance', - // Include the name in the theme object for telemetry - ...(appearance.name && { __themeName: appearance.name }), - }; + // Placeholder method that might handle more transformations in the future + const base = { + ...appearance, + __type: 'prebuilt_appearance', + } satisfies BaseTheme; + + // Add internal-only metadata for telemetry without exposing it via enumeration + if (appearance.name) { + Object.defineProperty(base as object, '__themeName', { + value: appearance.name, + enumerable: false, + configurable: false, + writable: false, + }); + } + + return base; };
🧹 Nitpick comments (6)
packages/themes/src/createTheme.ts (2)
8-12
: Make the theme name param immutableMark
name
as readonly to align with the repo’s immutability guidance and signal intent./** * Optional name for the theme, used for telemetry and debugging. * @example 'shadcn', 'neobrutalism', 'custom-dark' */ - name?: string; + readonly name?: string;
21-21
: Typo: “hande” → “handle”- // Placeholder method that might hande more transformations in the future + // Placeholder method that might handle more transformations in the futurepackages/shared/src/telemetry/events/theme-usage.ts (1)
35-63
: Optional: Avoid sending undefined payload fieldsReturning { themeName: undefined } increases payload size without information. Consider omitting the field entirely when not present.
- return { themeName }; + return themeName ? { themeName } : {};packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (3)
15-19
: Make assertions resilient to future event fields using objectContaining (or a helper)Asserting deep equality on the entire event object is brittle; adding non-breaking fields (e.g., timestamp, sdkVersion) will cause test failures. Prefer objectContaining, and optionally DRY with a small helper.
Apply this diff to introduce a helper and replace the assertions:
import { eventThemeUsage } from '../theme-usage'; +type ThemeUsageResult = ReturnType<typeof eventThemeUsage>; +const expectThemeUsageEvent = (result: ThemeUsageResult, payload: Record<string, unknown>) => { + expect(result).toEqual( + expect.objectContaining({ + event: 'THEME_USAGE', + eventSamplingRate: 0.1, + payload, + }), + ); +}; + describe('eventThemeUsage', () => { it('should create telemetry event with shadcn theme name', () => { @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: 'shadcn' }, - }); + expectThemeUsageEvent(result, { themeName: 'shadcn' }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: 'clerk' }, - }); + expectThemeUsageEvent(result, { themeName: 'clerk' }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: 'clerk' }, - }); + expectThemeUsageEvent(result, { themeName: 'clerk' }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: undefined }, - }); + expectThemeUsageEvent(result, { themeName: undefined }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: 'clerk' }, - }); + expectThemeUsageEvent(result, { themeName: 'clerk' }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: { themeName: 'shadcn' }, - }); + expectThemeUsageEvent(result, { themeName: 'shadcn' }); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: {}, - }); + expectThemeUsageEvent(result, {}); }); @@ - expect(result).toEqual({ - event: 'THEME_USAGE', - eventSamplingRate: 0.1, - payload: {}, - }); + expectThemeUsageEvent(result, {}); });Also applies to: 29-33, 49-53, 66-70, 85-88, 101-105, 111-115, 121-125
23-26
: Avoid explicit any in tests; safely cast via Parameters[0]This keeps tests aligned with the “no any” guideline while still exercising runtime-only shapes.
it('should handle string themes', () => { - const appearance = { - theme: 'clerk' as any, // String themes are valid at runtime - }; + // String themes are valid at runtime + const appearance = { + theme: 'clerk', + } as unknown as Parameters<typeof eventThemeUsage>[0]; @@ it('should handle array of themes', () => { - const appearance = { - theme: [ - 'clerk' as any, // String themes are valid at runtime - { - __type: 'prebuilt_appearance' as const, - __themeName: 'shadcn', - }, - ] as any, - }; + // String themes are valid at runtime + const appearance = { + theme: [ + 'clerk', + { + __type: 'prebuilt_appearance' as const, + __themeName: 'shadcn', + }, + ], + } as unknown as Parameters<typeof eventThemeUsage>[0]; @@ it('should prioritize theme over deprecated baseTheme', () => { - const appearance = { - theme: 'clerk' as any, // String themes are valid at runtime - baseTheme: { - __type: 'prebuilt_appearance' as const, - __themeName: 'shadcn', - }, - }; + // String themes are valid at runtime + const appearance = { + theme: 'clerk', + baseTheme: { + __type: 'prebuilt_appearance' as const, + __themeName: 'shadcn', + }, + } as unknown as Parameters<typeof eventThemeUsage>[0]; @@ it('should handle null appearance', () => { - const result = eventThemeUsage(null as any); + const result = eventThemeUsage(null as unknown as Parameters<typeof eventThemeUsage>[0]);Also applies to: 36-45, 73-80, 119-119
127-127
: Consider a couple more edge cases to harden behaviorOptional, but these catch edge shapes we’ve seen in the wild: empty theme arrays and non-object/non-string theme values.
it('should handle null appearance', () => { const result = eventThemeUsage(null as unknown as Parameters<typeof eventThemeUsage>[0]); expectThemeUsageEvent(result, {}); }); }); + + it('should handle empty theme array by emitting without themeName', () => { + const appearance = { + theme: [], + } as unknown as Parameters<typeof eventThemeUsage>[0]; + + const result = eventThemeUsage(appearance); + expectThemeUsageEvent(result, {}); + }); + + it('should tolerate invalid theme shapes (number) without throwing', () => { + const appearance = { + // @ts-expect-error runtime can be messy; ensure we don’t throw + theme: 123, + } as unknown as Parameters<typeof eventThemeUsage>[0]; + + const result = eventThemeUsage(appearance); + expectThemeUsageEvent(result, {}); + });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
packages/clerk-js/src/core/clerk.ts
(2 hunks)packages/react/src/contexts/ClerkContextProvider.tsx
(2 hunks)packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
(1 hunks)packages/shared/src/telemetry/events/index.ts
(1 hunks)packages/shared/src/telemetry/events/theme-usage.ts
(1 hunks)packages/themes/src/createTheme.ts
(2 hunks)packages/themes/src/themes/dark.ts
(1 hunks)packages/themes/src/themes/neobrutalism.ts
(1 hunks)packages/themes/src/themes/shadcn.ts
(1 hunks)packages/themes/src/themes/shadesOfPurple.ts
(1 hunks)packages/themes/src/themes/simple.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.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/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/telemetry/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.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/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.ts
packages/**/index.{js,ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use tree-shaking friendly exports
Files:
packages/shared/src/telemetry/events/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/shared/src/telemetry/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.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/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.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/shared/src/telemetry/events/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.
Files:
packages/shared/src/telemetry/events/index.ts
packages/themes/src/themes/shadesOfPurple.ts
packages/react/src/contexts/ClerkContextProvider.tsx
packages/clerk-js/src/core/clerk.ts
packages/themes/src/themes/neobrutalism.ts
packages/shared/src/telemetry/events/theme-usage.ts
packages/themes/src/themes/shadcn.ts
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts
packages/themes/src/themes/dark.ts
packages/themes/src/themes/simple.ts
packages/themes/src/createTheme.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/react/src/contexts/ClerkContextProvider.tsx
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/contexts/ClerkContextProvider.tsx
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/telemetry/events/__tests__/theme-usage.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/telemetry/events/__tests__/theme-usage.test.ts
🧬 Code Graph Analysis (4)
packages/react/src/contexts/ClerkContextProvider.tsx (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
eventThemeUsage
(20-28)
packages/clerk-js/src/core/clerk.ts (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
eventThemeUsage
(20-28)
packages/shared/src/telemetry/events/theme-usage.ts (2)
packages/types/src/appearance.ts (2)
Appearance
(991-1057)BaseTheme
(814-814)packages/types/src/telemetry.ts (1)
TelemetryEventRaw
(40-44)
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (1)
packages/shared/src/telemetry/events/theme-usage.ts (1)
eventThemeUsage
(20-28)
🔇 Additional comments (10)
packages/shared/src/telemetry/events/index.ts (1)
4-4
: No circular dependency detected – barrel re-export is safeI ran a scan against
packages/shared/src/telemetry/events/theme-usage.ts
and confirmed it does not import from the newindex.ts
barrel (neither directly via./index
nor via@clerk/shared/telemetry
). All existing call sites import from the telemetry barrel but don’t create a cycle back intotheme-usage.ts
. You’re clear to merge.packages/themes/src/themes/shadesOfPurple.ts (1)
5-5
: LGTM: Theme name included for telemetry consistencyName is aligned with file/export and supports the new telemetry flow.
packages/themes/src/themes/neobrutalism.ts (1)
23-23
: LGTM: Added theme name matches export and file nameThis keeps naming consistent across built-in themes for telemetry.
packages/themes/src/themes/shadcn.ts (1)
4-4
: LGTM: Telemetry-friendly theme name addedConsistent with other themes and the new createTheme contract.
packages/themes/src/themes/dark.ts (1)
4-4
: Adding a stable theme name is correct and aligned with telemetry usageIncluding name: 'dark' ensures consistent theme identification for telemetry and debugging. No issues spotted.
packages/themes/src/themes/simple.ts (1)
4-7
: Theme name addition looks goodAdding name: 'simple' is consistent with other themes and enables correct telemetry attribution.
packages/clerk-js/src/core/clerk.ts (1)
13-15
: Importing eventThemeUsage is correctThe import is scoped to telemetry and maintains existing structure. No concerns here.
packages/react/src/contexts/ClerkContextProvider.tsx (1)
9-9
: Telemetry import is appropriateRe-using the shared event factory keeps event shape consistent across packages.
packages/shared/src/telemetry/events/theme-usage.ts (1)
20-28
: Public telemetry event factory looks goodClear event naming, sampling, and payload construction; type-only imports and explicit return type comply with guidelines.
packages/shared/src/telemetry/events/__tests__/theme-usage.test.ts (1)
3-127
: Solid coverage of theme-name derivation casesGood breadth: prebuilt theme names, string themes, arrays, deprecated baseTheme precedence, and undefined/null appearance. This gives confidence the telemetry event wiring won’t regress.
|
||
// Record theme usage telemetry when appearance is provided | ||
if (this.#options.appearance) { | ||
this.telemetry.record(eventThemeUsage(this.#options.appearance)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Potential duplicate THEME_USAGE events (core load vs React provider); add simple de-duplication
Clerk.load records theme usage when appearance is provided. The React Provider also records on appearance changes. On initial mount, both can fire for the same theme, producing duplicates. Add a simple guard to skip recording the same theme name twice in a row.
Proposed change:
- // Record theme usage telemetry when appearance is provided
- if (this.#options.appearance) {
- this.telemetry.record(eventThemeUsage(this.#options.appearance));
- }
+ // Record theme usage telemetry when appearance is provided (dedupe consecutive identical names)
+ if (this.#options.appearance) {
+ const evt = eventThemeUsage(this.#options.appearance);
+ const currentThemeName = evt.payload?.themeName;
+ if (currentThemeName !== this.#lastThemeUsageName) {
+ this.telemetry.record(evt);
+ this.#lastThemeUsageName = currentThemeName;
+ }
+ }
Add this private field to the class (near other private fields):
// Tracks last emitted theme usage to avoid duplicates
#lastThemeUsageName?: string;
Verification suggestion:
- In a React app, initialize Clerk with appearance and mount ClerkProvider with the same appearance. Confirm only one THEME_USAGE event is emitted on boot, and another only when theme changes.
🏁 Script executed:
#!/bin/bash
set -e
# 1. Locate all occurrences of eventThemeUsage across the repo
rg "eventThemeUsage" -n
# 2. Identify where telemetry.record is called with eventThemeUsage (including in React provider)
rg "record.*eventThemeUsage" -n
Length of output: 2277
Add de-duplication for consecutive THEME_USAGE events
In packages/clerk-js/src/core/clerk.ts
(around lines 447–451), wrap the existing call to telemetry.record(eventThemeUsage…)
with a guard that skips recording if the theme name hasn’t changed since the last emission:
--- a/packages/clerk-js/src/core/clerk.ts
+++ b/packages/clerk-js/src/core/clerk.ts
@@ -447,7 +447,14 @@ export class Clerk {
// Record theme usage telemetry when appearance is provided
if (this.#options.appearance) {
- this.telemetry.record(eventThemeUsage(this.#options.appearance));
+ const evt = eventThemeUsage(this.#options.appearance);
+ const currentTheme = evt.payload.themeName;
+ if (currentTheme !== this.#lastThemeUsageName) {
+ this.telemetry.record(evt);
+ this.#lastThemeUsageName = currentTheme;
+ }
}
Add this private field alongside the other #
-prefixed members of the class:
// Tracks the last emitted theme name to prevent back-to-back duplicates
#lastThemeUsageName?: string;
Why?
- Both
Clerk.load
and the React<ClerkProvider>
will fire aTHEME_USAGE
event on mount with the sameappearance
. - Without this guard you’ll see two identical events at boot; with it, you get exactly one per theme and still record on real theme changes.
How to verify:
- In a test app call
Clerk.load({ appearance: { /*…*/ } })
. - Mount
<ClerkProvider appearance={/* same */}>
. - Confirm only one
THEME_USAGE
is emitted on startup, and a second only after you changeappearance
.
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 447–451, add a private field
on the class (next to the other # members) to track the last emitted theme name
(e.g. #lastThemeUsageName?: string) and wrap the
telemetry.record(eventThemeUsage(...)) call with a guard that compares the
current appearance name to #lastThemeUsageName; if they are equal, skip
recording, otherwise call telemetry.record(...) and update #lastThemeUsageName
to the current theme name. This prevents back-to-back duplicate THEME_USAGE
events while still recording on real theme changes.
// Record theme usage telemetry when appearance changes | ||
React.useEffect(() => { | ||
if (options.appearance && isomorphicClerkRef.current.telemetry) { | ||
isomorphicClerkRef.current.telemetry.record(eventThemeUsage(options.appearance)); | ||
} | ||
}, [options.appearance]); | ||
|
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
Guard against repeated emissions when appearance object identity changes without an actual theme change
The effect emits an event whenever options.appearance reference changes. In practice, this can emit duplicates on re-renders. Track the last emitted theme name and only record when it changes.
Note: This does not fully avoid a possible duplicate with the core Clerk.load emission; combine with the core-side dedupe proposed in clerk.ts for complete coverage.
// Record theme usage telemetry when appearance changes
- React.useEffect(() => {
- if (options.appearance && isomorphicClerkRef.current.telemetry) {
- isomorphicClerkRef.current.telemetry.record(eventThemeUsage(options.appearance));
- }
- }, [options.appearance]);
+ const lastThemeNameRef = React.useRef<string | undefined>(undefined);
+ React.useEffect(() => {
+ const telemetry = isomorphicClerkRef.current.telemetry;
+ if (!telemetry) {
+ return;
+ }
+ const evt = eventThemeUsage(options.appearance);
+ const nextName = evt.payload?.themeName;
+ if (nextName === lastThemeNameRef.current) {
+ return;
+ }
+ telemetry.record(evt);
+ lastThemeNameRef.current = nextName;
+ }, [options.appearance]);
🤖 Prompt for AI Agents
In packages/react/src/contexts/ClerkContextProvider.tsx around lines 123 to 129,
the effect records telemetry on every options.appearance reference change which
can emit duplicates; add a local ref (e.g., lastEmittedThemeRef) to store the
last emitted theme name, derive the current theme name from options.appearance
(handle strings and appearance objects), compare it to
lastEmittedThemeRef.current and only call
isomorphicClerkRef.current.telemetry.record(...) when they differ, then update
lastEmittedThemeRef.current to the new name; keep the same dependency on
options.appearance so it runs on changes but prevents repeated emissions for
identical theme names.
function extractThemeName(theme: BaseTheme): string | undefined { | ||
if (typeof theme === 'string') { | ||
return theme; | ||
} | ||
|
||
if (typeof theme === 'object' && theme !== null) { | ||
// Check for explicit theme name | ||
if ('__themeName' in theme && typeof theme.__themeName === 'string') { | ||
return theme.__themeName; | ||
} | ||
} | ||
|
||
return undefined; | ||
} |
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
Fix TypeScript safety when reading __themeName from BaseTheme
BaseTheme does not declare a __themeName property. The current check uses '__themeName' in theme
and then accesses theme.__themeName
, which can fail type-checking under strict settings. Prefer narrowing with a type guard and accepting unknown input.
-function extractThemeName(theme: BaseTheme): string | undefined {
- if (typeof theme === 'string') {
- return theme;
- }
-
- if (typeof theme === 'object' && theme !== null) {
- // Check for explicit theme name
- if ('__themeName' in theme && typeof theme.__themeName === 'string') {
- return theme.__themeName;
- }
- }
-
- return undefined;
-}
+function hasThemeName(t: unknown): t is { __themeName: string } {
+ return typeof t === 'object' && t !== null && '__themeName' in t && typeof (t as any).__themeName === 'string';
+}
+
+function extractThemeName(theme: unknown): string | undefined {
+ if (typeof theme === 'string') {
+ return theme;
+ }
+ if (hasThemeName(theme)) {
+ return theme.__themeName;
+ }
+ return undefined;
+}
📝 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.
function extractThemeName(theme: BaseTheme): string | undefined { | |
if (typeof theme === 'string') { | |
return theme; | |
} | |
if (typeof theme === 'object' && theme !== null) { | |
// Check for explicit theme name | |
if ('__themeName' in theme && typeof theme.__themeName === 'string') { | |
return theme.__themeName; | |
} | |
} | |
return undefined; | |
} | |
function hasThemeName(t: unknown): t is { __themeName: string } { | |
return ( | |
typeof t === 'object' && | |
t !== null && | |
'__themeName' in t && | |
typeof (t as any).__themeName === 'string' | |
); | |
} | |
function extractThemeName(theme: unknown): string | undefined { | |
if (typeof theme === 'string') { | |
return theme; | |
} | |
if (hasThemeName(theme)) { | |
return theme.__themeName; | |
} | |
return undefined; | |
} |
🤖 Prompt for AI Agents
packages/shared/src/telemetry/events/theme-usage.ts around lines 70 to 83: the
current code uses a raw "'__themeName' in theme" and then accesses
theme.__themeName which can fail TS strict checks because BaseTheme doesn't
declare that property; add a proper type guard or narrow to unknown before
reading the property. Implement a small type-guard like hasThemeName(x:
unknown): x is { __themeName: unknown } that checks x is non-null object and
'__themeName' in x, then inside that guarded branch check typeof x.__themeName
=== 'string' and return it; alternatively narrow theme to unknown and cast
safely (e.g. const maybe = theme as unknown as { __themeName?: unknown } and
then check typeof maybe.__themeName === 'string') before returning the string.
…k/javascript into alexcarpenter/theme-usage-telemetry
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Chores
Tests