Skip to content

Conversation

brkalow
Copy link
Member

@brkalow brkalow commented Sep 25, 2025

Description

This improves error handling during clerk-js loading. Specifically, it uses our ClerkRuntimeError class and ensures we are propagating underlying errors up so we can see the cause. Previously, we swallowed errors and only threw a generic error with a generic message ("Clerk: Failed to load Clerk").

Additionally, I've added an optional cause option to ClerkRuntimeError that allows us to pass along the original, unwrapped error for additional introspect (h/t @jacekradko)

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

  • New Features

    • Added an option to configure the package name used in Clerk.js loading error messages.
  • Bug Fixes

    • Improved error handling when loading Clerk.js: structured errors with distinct timeout codes and clearer messages.
    • Original underlying errors are preserved for diagnostics (included as error causes).
    • Script loading now surfaces meaningful Error objects instead of generic/missing values.
  • Chores

    • Bumped minor version of shared package dependency.

Copy link

changeset-bot bot commented Sep 25, 2025

🦋 Changeset detected

Latest commit: be1530f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 19 packages
Name Type
@clerk/shared Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue Patch

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

Copy link

vercel bot commented Sep 25, 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 Sep 25, 2025 9:16pm

Copy link
Contributor

coderabbitai bot commented Sep 25, 2025

Walkthrough

Adds a cause property to ClerkRuntimeError, changes Clerk JS loading and script loader to throw/propagate ClerkRuntimeError with codes (including timeout) and preserved causes, exposes a helper to set package name for load errors, updates tests, and adds a changeset entry.

Changes

Cohort / File(s) Summary
Runtime error structure
packages/shared/src/errors/runtimeError.ts
Adds optional cause?: Error to ClerkRuntimeError; updates constructor signature to accept { code, cause? }, assigns this.cause, and documents the property with JSDoc.
Clerk JS loader updates
packages/shared/src/loadClerkJsScript.ts
Replaces generic Errors with ClerkRuntimeError, introduces error codes (including timeout), preserves original errors as cause and appends their messages, and adds public setClerkJsLoadingErrorPackageName(packageName: string).
Script loader adjustments
packages/shared/src/loadScript.ts
Converts NO_DOCUMENT_ERROR to an Error object; script error handler accepts the event and rejects with event.error when present or a new Error describing the failed script load.
Tests
packages/shared/src/__tests__/loadClerkJsScript.test.ts
Tests updated to expect ClerkRuntimeError instances and to assert message containment rather than exact equality.
Changeset metadata
.changeset/tangy-bees-follow.md
Adds a changeset bumping @clerk/shared minor version with note: "Improve error handling when loading clerk-js."

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App as Application
  participant LCS as loadClerkJsScript
  participant LS as loadScript
  participant Net as Network/CDN

  App->>LCS: loadClerkJsScript(...)
  note right of LCS: optional setClerkJsLoadingErrorPackageName
  LCS->>LS: loadScript(src, opts)
  LS->>Net: request script
  alt Success
    Net-->>LS: script loaded
    LS-->>LCS: resolve(script)
    LCS-->>App: resolve(clerk)
  else Script load error
    Net-->>LS: error event (may include event.error)
    LS-->>LCS: reject(event.error or Error("Failed to load script"))
    LCS-->>App: reject(ClerkRuntimeError{ code, cause: event.error })
  else Timeout
    LCS-->>App: reject(ClerkRuntimeError{ code: TIMEOUT, cause: Error("timeout") })
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

I nibbled at stacks where the scripts come to play,
Tucked original causes so failures can say,
Codes on my whiskers, timeouts in sight,
I hop through the loader to make errors right. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly conveys the primary change by indicating a new feature in the shared package to improve error handling for Clerk JS loading. It follows a conventional commit style, is specific enough to understand the focus of the PR, and avoids unnecessary details. This phrasing clearly informs reviewers and future readers of the main intent without being overly verbose.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch brk.feat/improve-clerk-js-load-errors

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 81d9f0d and be1530f.

📒 Files selected for processing (1)
  • packages/shared/src/__tests__/loadClerkJsScript.test.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/__tests__/loadClerkJsScript.test.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/__tests__/loadClerkJsScript.test.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/__tests__/loadClerkJsScript.test.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/__tests__/loadClerkJsScript.test.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/shared/src/__tests__/loadClerkJsScript.test.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/shared/src/__tests__/loadClerkJsScript.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/shared/src/__tests__/loadClerkJsScript.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__/loadClerkJsScript.test.ts
⏰ 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: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/shared/src/__tests__/loadClerkJsScript.test.ts (2)

90-92: Good upgrade to assert the new runtime error shape

Checking for ClerkRuntimeError here covers the updated loader contract while keeping the message assertion resilient to appended cause details.


141-143: Thanks for aligning the malformed Clerk branch with the new error type

Verifying the thrown instance is ClerkRuntimeError and keeping the message guard ensures the validation path still fails with the expected loader error prefix.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

pkg-pr-new bot commented Sep 25, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: be1530f

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/shared/src/loadScript.ts (1)

22-28: Avoid continuing after reject; add early returns.

Currently the code rejects but continues to create/append a script, risking multiple settle attempts and unexpected DOM mutations.

Apply:

       if (!src) {
-        reject(new Error(NO_SRC_ERROR));
+        reject(new Error(NO_SRC_ERROR));
+        return;
       }

       if (!document || !document.body) {
-        reject(new Error(NO_DOCUMENT_ERROR));
+        reject(new Error(NO_DOCUMENT_ERROR));
+        return;
       }
packages/shared/src/loadClerkJsScript.ts (2)

71-119: Fix TDZ bug when Clerk is already loaded before pollInterval is defined.

Calling checkAndResolve() before pollInterval is initialized can cause a ReferenceError if Clerk is already loaded.

Apply:

 function waitForClerkWithTimeout(timeoutMs: number): Promise<HTMLScriptElement | null> {
   return new Promise((resolve, reject) => {
     let resolved = false;
 
-    const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {
-      clearTimeout(timeoutId);
-      clearInterval(pollInterval);
-    };
+    let pollInterval: ReturnType<typeof setInterval> | undefined;
+    const cleanup = (timeoutId: ReturnType<typeof setTimeout>) => {
+      clearTimeout(timeoutId);
+      if (pollInterval) {
+        clearInterval(pollInterval);
+      }
+    };
 
     const checkAndResolve = () => {
       if (resolved) {
         return;
       }
 
       if (isClerkProperlyLoaded()) {
         resolved = true;
-        cleanup(timeoutId, pollInterval);
+        cleanup(timeoutId);
         resolve(null);
       }
     };
 
     const handleTimeout = () => {
       if (resolved) {
         return;
       }
 
       resolved = true;
-      cleanup(timeoutId, pollInterval);
+      cleanup(timeoutId);
 
       if (!isClerkProperlyLoaded()) {
         reject(new ClerkRuntimeError(FAILED_TO_LOAD_ERROR, { code: ERROR_CODE_TIMEOUT }));
       } else {
         resolve(null);
       }
     };
 
     const timeoutId = setTimeout(handleTimeout, timeoutMs);
-
-    checkAndResolve();
-
-    const pollInterval = setInterval(() => {
+    pollInterval = setInterval(() => {
       if (resolved) {
-        clearInterval(pollInterval);
+        if (pollInterval) clearInterval(pollInterval);
         return;
       }
       checkAndResolve();
     }, 100);
+    // Run one immediate check after pollInterval is initialized
+    checkAndResolve();
   });
 }

160-175: Propagate underlying loadScript errors and avoid unhandled rejections.

Current code fires loadScript(...).catch(throw ...) without awaiting or returning it, leading to an unhandled rejection and causing the caller to only see a timeout. Also, error.message access will throw if error is undefined.

Apply:

-  const loadPromise = waitForClerkWithTimeout(timeout);
-
-  loadScript(clerkJsScriptUrl(opts), {
-    async: true,
-    crossOrigin: 'anonymous',
-    nonce: opts.nonce,
-    beforeLoad: applyClerkJsScriptAttributes(opts),
-  }).catch(error => {
-    throw new ClerkRuntimeError(FAILED_TO_LOAD_ERROR + (error.message ? `, ${error.message}` : ''), {
-      code: ERROR_CODE,
-      cause: error,
-    });
-  });
-
-  return loadPromise;
+  try {
+    await loadScript(clerkJsScriptUrl(opts), {
+      async: true,
+      crossOrigin: 'anonymous',
+      nonce: opts.nonce,
+      beforeLoad: applyClerkJsScriptAttributes(opts),
+    });
+  } catch (error: unknown) {
+    const msg =
+      error && typeof error === 'object' && 'message' in error ? String((error as any).message) : '';
+    throw new ClerkRuntimeError(FAILED_TO_LOAD_ERROR + (msg ? `, ${msg}` : ''), {
+      code: ERROR_CODE,
+      cause: error instanceof Error ? error : undefined,
+    });
+  }
+
+  return waitForClerkWithTimeout(timeout);
🧹 Nitpick comments (6)
packages/shared/src/loadScript.ts (2)

17-19: Make opts optional to match usage and avoid forcing callers to pass {}.

You already guard with opts || {}.

Apply:

-export async function loadScript(src = '', opts: LoadScriptOptions): Promise<HTMLScriptElement> {
+export async function loadScript(src = '', opts?: LoadScriptOptions): Promise<HTMLScriptElement> {

48-51: Only set nonce when provided.

Avoid assigning undefined to a DOM string property.

Apply:

-      script.src = src;
-      script.nonce = nonce;
+      script.src = src;
+      if (nonce) {
+        script.nonce = nonce;
+      }
packages/shared/src/loadClerkJsScript.ts (1)

162-167: Avoid setting nonce twice.

Nonce is set both via loadScript’s nonce option and again in beforeLoad through attributes. Pick one to prevent churn.

Proposed: drop the nonce: opts.nonce here and keep it in applyClerkJsScriptAttributes, or vice‑versa.

packages/shared/src/errors/runtimeError.ts (3)

21-25: Broaden cause type to unknown for interoperability.

Callers may pass non-Error causes (e.g., DOM Events). Using unknown avoids type mismatches while encouraging narrowing at use sites.

Apply:

-  /**
-   * The original error that was caught to throw an instance of ClerkRuntimeError.
-   */
-  cause?: Error;
+  /**
+   * The original error that triggered this runtime error.
+   */
+  cause?: unknown;

26-26: Accept unknown cause in constructor for the same reason.

Apply:

-  constructor(message: string, { code, cause }: { code: string; cause?: Error }) {
+  constructor(message: string, { code, cause }: { code: string; cause?: unknown }) {

27-36: Optionally pass cause to Error for native chaining (when supported).

If your TS lib target includes ES2022.Error, consider chaining cause to preserve stacks.

Example:

// Replace super(_message) with:
// super(_message, cause ? { cause } : undefined as any);

Gate behind lib support to avoid type errors.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 33efaad and 151c46c.

📒 Files selected for processing (4)
  • .changeset/tangy-bees-follow.md (1 hunks)
  • packages/shared/src/errors/runtimeError.ts (2 hunks)
  • packages/shared/src/loadClerkJsScript.ts (3 hunks)
  • packages/shared/src/loadScript.ts (3 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/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.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/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.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/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.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/shared/src/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.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/errors/runtimeError.ts
  • packages/shared/src/loadClerkJsScript.ts
  • packages/shared/src/loadScript.ts
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/tangy-bees-follow.md
🧬 Code graph analysis (1)
packages/shared/src/loadClerkJsScript.ts (1)
packages/shared/src/errors/runtimeError.ts (1)
  • ClerkRuntimeError (9-50)
⏰ 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: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
.changeset/tangy-bees-follow.md (1)

1-6: Changeset scope and bump look appropriate.

Minor bump matches the addition of a new exported helper and enhanced error behavior.

packages/shared/src/loadClerkJsScript.ts (1)

3-3: Import path is correct: ClerkRuntimeError is re-exported from ‘./error’ barrel.

Comment on lines 14 to 16
/**
*
*/
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Replace placeholder JSDoc with real API docs.

Document params, return type, and error cases. This is a public utility.

Apply:

-/**
- *
- *
- */
+/**
+ * Dynamically injects a <script> tag and resolves when it loads.
+ *
+ * Errors:
+ * - Rejects with Error(NO_SRC_ERROR) when src is empty.
+ * - Rejects with Error(NO_DOCUMENT_ERROR) when document/body is unavailable (SSR).
+ * - Rejects with a descriptive Error on script load failure.
+ *
+ * @param src - Script URL to load.
+ * @param opts - Script attributes and lifecycle hooks.
+ * @returns A promise resolving with the created script element after it loads.
+ */
📝 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.

Suggested change
/**
*
*/
/**
* Dynamically injects a <script> tag and resolves when it loads.
*
* Errors:
* - Rejects with Error(NO_SRC_ERROR) when src is empty.
* - Rejects with Error(NO_DOCUMENT_ERROR) when document/body is unavailable (SSR).
* - Rejects with a descriptive Error on script load failure.
*
* @param src - Script URL to load.
* @param opts - Script attributes and lifecycle hooks.
* @returns A promise resolving with the created script element after it loads.
*/
🤖 Prompt for AI Agents
In packages/shared/src/loadScript.ts around lines 14 to 16, the current
placeholder JSDoc must be replaced with a complete API docblock: add
descriptions for each parameter (name, type, purpose, optional/defaults), the
exact return type and shape (including Promise if async), and list possible
error cases/conditions that callers should handle (including thrown errors and
rejection reasons). Keep wording concise, use standard JSDoc tags (@param,
@returns, @throws/@rejects), mention side effects (DOM/script insertion) and
intended audience (public utility), and ensure examples or usage notes are
included if helpful.

Comment on lines 14 to 16
/**
*
*/
Copy link
Member Author

Choose a reason for hiding this comment

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

Not sure how this ended up here 🙃

Comment on lines +10 to +11
const ERROR_CODE = 'failed_to_load_clerk_js';
const ERROR_CODE_TIMEOUT = 'failed_to_load_clerk_js_timeout';
Copy link
Member

Choose a reason for hiding this comment

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

Is this helping because we want to better track why an error is thrown ?

Copy link
Member Author

Choose a reason for hiding this comment

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

Correct 👍

@brkalow brkalow merged commit 5546352 into main Sep 26, 2025
40 checks passed
@brkalow brkalow deleted the brk.feat/improve-clerk-js-load-errors branch September 26, 2025 20:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants