Skip to content

Conversation

@jsendo
Copy link
Contributor

@jsendo jsendo commented Apr 15, 2025

WHY

Summary by CodeRabbit

  • New Features
    • Introduced a debug mode for API requests using the PD_SDK_DEBUG environment variable, allowing sanitized debug logs for troubleshooting.
  • Documentation
    • Added a changelog entry for version 1.5.2, detailing the new debug feature and usage precautions.
  • Chores
    • Updated TypeScript configuration and type declarations to improve support for environment variables.
    • Reordered a development dependency for consistency.

@linear
Copy link

linear bot commented Apr 15, 2025

@vercel
Copy link

vercel bot commented Apr 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Apr 15, 2025 10:47pm
pipedream-docs ⬜️ Ignored (Inspect) Apr 15, 2025 10:47pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Apr 15, 2025 10:47pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 15, 2025

Walkthrough

The changes introduce a new debugging utility and environment variable to the SDK, enabling conditional logging of sanitized debug information for API requests. The BaseClient class's request handling is updated to improve error reporting and ensure response bodies are handled correctly. TypeScript typings are enhanced to support the use of environment variables in browser contexts by declaring a global process object. Additionally, the TypeScript configuration is updated to include the new typings. A changelog entry documents these updates, and a minor reordering of a development dependency occurs in the root package configuration.

Changes

File(s) Change Summary
packages/sdk/src/shared/index.ts Introduced a DEBUG utility function for conditional, sanitized debug logging; updated BaseClient.makeRequest to improve response body handling, error reporting, and debug output.
packages/sdk/src/shared/shims.d.ts Added a global process type declaration with optional env property for browser compatibility with environment variables.
packages/sdk/tsconfig.browser.json Included src/shared/shims.d.ts in the TypeScript compilation context for the browser SDK.
packages/sdk/CHANGELOG.md Added an entry for version 1.5.2 describing the new PD_SDK_DEBUG environment variable and debugging features.
package.json Reordered the "@next/eslint-plugin-next" entry within devDependencies without changing its version or presence.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SDK (BaseClient)
    participant API

    User->>SDK (BaseClient): makeRequest(url, options)
    SDK (BaseClient)->>API: Send HTTP request
    API-->>SDK (BaseClient): Respond with status, headers, body
    SDK (BaseClient)->>SDK (BaseClient): Read response as raw text
    alt PD_SDK_DEBUG is true
        SDK (BaseClient)->>SDK (BaseClient): Sanitize and log debug info using DEBUG()
    end
    alt Response is OK and JSON
        SDK (BaseClient)->>User: Return parsed JSON
    else Response is OK and not JSON
        SDK (BaseClient)->>User: Return raw text
    else Response is not OK
        SDK (BaseClient)->>User: Throw error with raw body
    end
Loading

Poem

In the warren of code, a debug flag appears,
Sanitizing secrets, allaying our fears.
With logs that are careful, and typings anew,
The SDK grows smarter for rabbits—and you!
A hop and a skip, through requests we go,
Now errors and bodies are easy to know.
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/sdk/src/shared/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@jsendo jsendo requested a review from danhsiung April 15, 2025 22:03
@jsendo jsendo marked this pull request as ready for review April 15, 2025 22:03
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 (2)
packages/sdk/src/shared/index.ts (2)

892-901: Good implementation of conditional debug logging.

The DEBUG function:

  1. Checks if the PD_SDK_DEBUG environment variable is set to "true"
  2. Sanitizes all arguments to prevent leaking sensitive information
  3. Prefixes logged messages with [PD_SDK_DEBUG] for easy identification

Consider adding documentation about this feature in user-facing documentation to help developers troubleshoot SDK issues.

 export function DEBUG(...args: any[]) {
+  // Only logs when PD_SDK_DEBUG=true environment variable is set
+  // Sanitizes sensitive information before logging
   if (
     typeof process !== "undefined" &&
     typeof process.env !== "undefined" &&
     process.env.PD_SDK_DEBUG === "true"
   ) {
     const safeArgs = args.map((arg) => sanitize(arg));
     console.log("[PD_SDK_DEBUG]", ...safeArgs);
   }
 }

1025-1034: Improved JSON parsing with proper error handling.

The implementation now:

  1. Attempts to parse JSON only if the content type indicates JSON
  2. Uses a try-catch block to handle JSON parsing errors gracefully
  3. Logs debug information when parsing fails
  4. Falls back to returning raw text when JSON parsing fails

This makes the API client more robust when dealing with unexpected or malformed responses.

Consider using the optional chaining operator as suggested by the static analysis tool:

-if (contentType && contentType.includes("application/json")) {
+if (contentType?.includes("application/json")) {
   try {
     const json = JSON.parse(rawBody);
     return json as T;
   } catch (err) {
     DEBUG("Couldn't parse json, falling back to raw", err)
   }
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 1025-1025: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ddb081 and 74e8eec.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • package.json (1 hunks)
  • packages/sdk/CHANGELOG.md (1 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/src/shared/index.ts (2 hunks)
  • packages/sdk/src/shared/shims.d.ts (1 hunks)
  • packages/sdk/tsconfig.browser.json (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/sdk/src/shared/index.ts

[error] 1025-1025: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (8)
package.json (1)

44-44: Reordering of devDependency looks good.

The dependency @next/eslint-plugin-next has been reordered within the devDependencies section without changing its version. This is likely due to automatic sorting or code formatting.

packages/sdk/src/shared/shims.d.ts (1)

1-5: Good addition of TypeScript declaration for environment variable access.

This TypeScript declaration provides proper type information for accessing environment variables via process.env in browser environments where process might be undefined. This supports the new debugging feature that needs to check for the PD_SDK_DEBUG environment variable.

packages/sdk/tsconfig.browser.json (1)

17-17: Correctly included declaration file in TypeScript configuration.

The new src/shared/shims.d.ts declaration file has been properly added to the TypeScript compiler's include list, ensuring that the browser build has access to the process type declarations.

packages/sdk/src/shared/index.ts (3)

850-859: Good list of sensitive keys for redaction.

This comprehensive list of sensitive key patterns ensures that sensitive information like tokens, passwords, and keys will be properly redacted in debug output.


862-889: Well-implemented sanitization function with circular reference handling.

The sanitize function effectively:

  1. Handles null/undefined values
  2. Detects and marks circular references to prevent infinite recursion
  3. Processes arrays recursively
  4. Redacts values for sensitive keys
  5. Recursively processes nested objects

This implementation carefully handles edge cases that could occur in complex API requests and responses.


1017-1023: Fixed response body handling to prevent multiple consumption issues.

This change addresses a critical issue where attempting to read a response body multiple times could fail. By:

  1. Reading the raw body text once and storing it
  2. Including this raw body in error messages for better debugging
  3. Logging sanitized debug information about the request and response

This improves error reporting and fixes potential runtime errors that could occur when trying to access response data multiple times.

packages/sdk/package.json (1)

4-4: Version bump is appropriate and aligns with new feature addition.

The version update to 1.5.1 is correct for introducing the debug mode feature.

packages/sdk/CHANGELOG.md (1)

5-12: Changelog entry is clear and accurate.

The new entry documents the debug feature and its risks well.

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 (2)
packages/sdk/src/shared/index.ts (2)

897-906: Safe implementation of debug logging.

The DEBUG function correctly:

  • Checks for the existence of the process object and environment variables
  • Only logs when explicitly enabled via PD_SDK_DEBUG environment variable
  • Applies sanitization to all arguments before logging
  • Provides a clear prefix for easy identification of debug logs

One improvement could be handling variations of "true" like "1" or "yes".

-  if (
-    typeof process !== "undefined" &&
-    typeof process.env !== "undefined" &&
-    process.env.PD_SDK_DEBUG === "true"
-  ) {
+  if (
+    typeof process !== "undefined" &&
+    typeof process.env !== "undefined" &&
+    ["true", "1", "yes"].includes(process.env.PD_SDK_DEBUG?.toLowerCase() || "")
+  ) {

1029-1040: Safer response handling with fallback mechanism.

This approach addresses a common Fetch API issue where response bodies can only be consumed once. The implementation:

  1. Captures the raw text first
  2. Attempts to parse JSON when appropriate
  3. Falls back to the raw text with proper debug logging if parsing fails

Based on the static analysis hint, consider using optional chaining for the Content-Type header check:

-    const contentType = response.headers.get("Content-Type");
-    if (contentType && contentType.includes("application/json")) {
+    const contentType = response.headers.get("Content-Type");
+    if (contentType?.includes("application/json")) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 1030-1030: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74e8eec and 6f905b9.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • packages/sdk/CHANGELOG.md (1 hunks)
  • packages/sdk/src/shared/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/sdk/CHANGELOG.md
🧰 Additional context used
🪛 Biome (1.9.4)
packages/sdk/src/shared/index.ts

[error] 1030-1030: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
packages/sdk/src/shared/index.ts (4)

855-864: Good selection of sensitive keys for redaction.

The array of sensitive keys covers common patterns for credentials and private information, which will help ensure sensitive data is not accidentally logged.


867-894: Well-implemented sanitization function with circular reference handling.

The sanitize function effectively:

  • Recursively processes objects and arrays
  • Detects and handles circular references with WeakSet
  • Performs case-insensitive matching of sensitive keys
  • Properly redacts sensitive values

This approach ensures debug logs won't leak credentials or sensitive data.


1022-1026: Improved error handling with response body capture.

Capturing the raw body text before checking response status improves error messages by including the response content, which is essential for debugging API issues.


1028-1028: Effective debug logging of request and response details.

The DEBUG function is used appropriately to log all relevant information for troubleshooting: status code, request URL, options, and the raw response body.

// Attempt to parse JSON, fall back to raw text if it fails
DEBUG(response.status, url.toString(), requestOptions, rawBody)
const contentType = response.headers.get("Content-Type");
if (contentType && contentType.includes("application/json")) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

This should have used optional chaining I guess.

@jsendo jsendo merged commit ecb9960 into master Apr 16, 2025
12 checks passed
@jsendo jsendo deleted the je/dj-3197-add-sdk-debug-mode branch April 16, 2025 15:44
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