Skip to content

Conversation

heatlikeheatwave
Copy link
Contributor

@heatlikeheatwave heatlikeheatwave commented Aug 15, 2025

Description

Fixes build error in playground/nextjs action (see here) by import fs methods with nodeFsOrThrow rather than direct import.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • Bug Fixes

    • Improved telemetry reliability by only recording flags when the environment supports it, avoiding unnecessary filesystem access and reducing noise.
    • Enforced single-write semantics for telemetry flags to prevent duplicate events.
    • Reduced error logs in unsupported scenarios while preserving drift-detection behavior.
  • Chores

    • Prepared a patch release documenting the internal migration of filesystem handling.

Copy link

changeset-bot bot commented Aug 15, 2025

⚠️ No Changeset found

Latest commit: 19a504c

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Aug 15, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 15, 2025 8:57pm

Copy link

pkg-pr-new bot commented Aug 15, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: d013b46

Copy link
Contributor

coderabbitai bot commented Aug 15, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Updates keyless-telemetry.ts to replace direct fs.promises usage with nodeFsOrThrow from ./fs/utils. Adds a canUseKeyless guard in tryMarkTelemetryEventAsFired: if canUseKeyless is false, returns false immediately; otherwise ensures the telemetry flag directory exists and attempts an atomic write (flag 'wx') of a JSON payload { firedAt, event } to the flag file. EEXIST results in false; other errors are logged and return false. detectKeylessEnvDrift remains functionally the same but now uses the filesystem abstraction. A changeset file registering the import migration was added.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 19a504c and d013b46.

📒 Files selected for processing (1)
  • .changeset/itchy-queens-cough.md (1 hunks)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
packages/nextjs/src/server/keyless-telemetry.ts (6)

6-6: Prefer dynamic import for nodeFsOrThrow to avoid pulling Node-only code into non-Node bundles

This aligns with “Use dynamic imports for optional features” and reduces the risk of bundlers including Node-only code in edge/client targets.

Apply this diff to drop the static import:

-import { nodeFsOrThrow } from './fs/utils';

46-63: Good fix; simplify control flow and dynamically import fs utilities inside the guarded branch

  • Use early return to reduce nesting.
  • Dynamically import fs utilities only when needed (further guards edge/client bundles).
  • Keep atomic create with 'wx' and return semantics unchanged.
   try {
-    if (canUseKeyless) {
-      const { mkdir, writeFile } = nodeFsOrThrow();
-      const flagFilePath = getTelemetryFlagFilePath();
-      const flagDirectory = dirname(flagFilePath);
-
-      // Ensure the directory exists before attempting to write the file
-      await mkdir(flagDirectory, { recursive: true });
-
-      const flagData = {
-        firedAt: new Date().toISOString(),
-        event: EVENT_KEYLESS_ENV_DRIFT_DETECTED,
-      };
-      await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx' });
-      return true;
-    } else {
-      return false;
-    }
+    if (!canUseKeyless) {
+      return false;
+    }
+    const { nodeFsOrThrow } = await import('./fs/utils');
+    const { mkdir, writeFile } = nodeFsOrThrow();
+    const flagFilePath = getTelemetryFlagFilePath();
+    const flagDirectory = dirname(flagFilePath);
+
+    // Ensure the directory exists before attempting to write the file
+    await mkdir(flagDirectory, { recursive: true });
+
+    const flagData = {
+      firedAt: new Date().toISOString(),
+      event: EVENT_KEYLESS_ENV_DRIFT_DETECTED,
+    };
+    await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx', mode: 0o600 });
+    return true;

58-58: Harden file permissions for the flag file

The flag contents aren’t sensitive, but it’s inexpensive to set restrictive permissions on creation to avoid permissive defaults (umask-dependent).

If you don’t adopt the bigger refactor above, minimally update the write options:

-      await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx' });
+      await writeFile(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx', mode: 0o600 });

63-69: Tighten error typing for EEXIST check

Prefer using Node’s ErrnoException type for clearer intent and better editor support.

-  } catch (error: unknown) {
-    if ((error as { code?: string })?.code === 'EEXIST') {
+  } catch (error: unknown) {
+    const err = error as NodeJS.ErrnoException;
+    if (err?.code === 'EEXIST') {
       return false;
     }
     console.warn('Failed to create telemetry flag file:', error);
     return false;
   }

175-178: Avoid duplication: reuse EVENT_SAMPLING_RATE for client telemetry config

You already have EVENT_SAMPLING_RATE = 1; reuse it to keep sampling consistent and prevent drift if the constant changes later.

-      telemetry: {
-        samplingRate: 1,
-      },
+      telemetry: {
+        samplingRate: EVENT_SAMPLING_RATE,
+      },

44-60: Add unit tests for the new fs abstraction and gating behavior

Given the bugfix nature of this PR, please add tests that cover:

  • returns false when canUseKeyless is false (and doesn’t attempt FS ops)
  • creates directory and file when allowed, returns true on first attempt
  • returns false on EEXIST without logging an error
  • logs and returns false on other fs errors

I can provide Jest tests that mock ./fs/utils and the feature flag if helpful.

Would you like me to scaffold these tests with Jest + ts-jest and module mocks for nodeFsOrThrow and feature-flags?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 01c8bcc and 19a504c.

📒 Files selected for processing (1)
  • packages/nextjs/src/server/keyless-telemetry.ts (2 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/nextjs/src/server/keyless-telemetry.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/server/keyless-telemetry.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/nextjs/src/server/keyless-telemetry.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/server/keyless-telemetry.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

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

Files:

  • packages/nextjs/src/server/keyless-telemetry.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/nextjs/src/server/keyless-telemetry.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/nextjs/src/server/keyless-telemetry.ts
🧬 Code Graph Analysis (1)
packages/nextjs/src/server/keyless-telemetry.ts (2)
packages/nextjs/src/utils/feature-flags.ts (1)
  • canUseKeyless (12-12)
packages/nextjs/src/server/fs/utils.ts (1)
  • nodeFsOrThrow (33-33)
⏰ 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: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/nextjs/src/server/keyless-telemetry.ts (1)

1-3: Sanity check: top-level Node 'path' import in server code

This file imports 'path' at module scope. It’s fine for Node runtimes, but if this module ever leaks into an edge/client bundle, it could break. Not blocking, but please verify bundling boundaries.

If needed, we can also lazily import 'path' inside tryMarkTelemetryEventAsFired (and inline join/dirname usage) to isolate Node-only deps.

@heatlikeheatwave heatlikeheatwave enabled auto-merge (squash) August 15, 2025 20:57
@heatlikeheatwave heatlikeheatwave merged commit 6daa584 into main Aug 15, 2025
36 checks passed
@heatlikeheatwave heatlikeheatwave deleted the heat/fix/playground-build-error-keyless-telemetry branch August 15, 2025 20:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants