# Node.js System Integrations

Node.js-specific integrations for handling uncaught exceptions, unhandled rejections, and system-level monitoring.

## Capabilities

### Exception and Rejection Handlers

Automatic capture of uncaught exceptions and unhandled promise rejections.

```typescript { .api }
/**
 * Create integration for capturing uncaught exceptions
 * @param options - Uncaught exception handler configuration options
 * @returns Uncaught exception integration instance
 */
function onUncaughtExceptionIntegration(options?: UncaughtExceptionOptions): Integration;

/**
 * Create integration for capturing unhandled promise rejections
 * @param options - Unhandled rejection handler configuration options
 * @returns Unhandled rejection integration instance
 */
function onUnhandledRejectionIntegration(options?: UnhandledRejectionOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with exception handlers
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.onUncaughtExceptionIntegration({
      exitEvenIfOtherHandlersAreRegistered: false,
    }),
    Sentry.onUnhandledRejectionIntegration({
      mode: "warn", // "strict", "warn", or "none"
    }),
  ],
});

// These will be automatically captured
throw new Error("This uncaught exception will be sent to Sentry");

Promise.reject(new Error("This unhandled rejection will be sent to Sentry"));

// Async function without proper error handling
async function riskyOperation() {
  throw new Error("This error will be captured as unhandled rejection");
}
riskyOperation(); // Called without await or .catch()
```

### Node.js Context Integration

Capture Node.js-specific context information.

```typescript { .api }
/**
 * Create Node.js context integration for capturing runtime information
 * @returns Node.js context integration instance
 */
function nodeContextIntegration(): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with Node.js context
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.nodeContextIntegration(),
  ],
});

// Context automatically includes:
// - Node.js version
// - Platform information
// - Memory usage
// - Process uptime
// - Environment variables (filtered)
```

### Local Variables Integration

Capture local variables in stack traces for debugging.

```typescript { .api }
/**
 * Create local variables integration for capturing variable values in stack traces
 * @param options - Local variables configuration options
 * @returns Local variables integration instance
 */
function localVariablesIntegration(options?: LocalVariablesOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with local variables capture
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.localVariablesIntegration({
      captureAllExceptions: true, // Capture for all exceptions
      maxExceptionsPerSecond: 5, // Rate limit to avoid performance impact
    }),
  ],
});

function processUserData(userId, userData) {
  const processedData = transformData(userData);
  const validationResult = validateData(processedData);
  
  if (!validationResult.isValid) {
    // When this error is captured, local variables will be included:
    // userId, userData, processedData, validationResult
    throw new Error("Data validation failed");
  }
  
  return processedData;
}
```

### Context Lines Integration

Add source code context around stack trace lines.

```typescript { .api }
/**
 * Create context lines integration for adding source code context to stack traces
 * @param options - Context lines configuration options
 * @returns Context lines integration instance
 */
function contextLinesIntegration(options?: ContextLinesOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with context lines
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.contextLinesIntegration({
      frameContextLines: 5, // Number of lines before/after each stack frame
    }),
  ],
});

// Stack traces will include source code context around each frame
function calculateTotal(items) {
  let total = 0;
  for (const item of items) {
    total += item.price; // If error occurs here, surrounding code will be shown
  }
  return total;
}
```

### Modules Integration

Capture information about loaded Node.js modules.

```typescript { .api }
/**
 * Create modules integration for capturing loaded module information
 * @returns Modules integration instance
 */
function modulesIntegration(): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with modules integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.modulesIntegration(),
  ],
});

// Events will include information about:
// - All loaded npm packages and their versions
// - Built-in Node.js modules in use
// - Module loading order and dependencies
```

### Child Process Integration

Instrument child process operations.

```typescript { .api }
/**
 * Create child process integration for tracing subprocess operations
 * @param options - Child process configuration options
 * @returns Child process integration instance
 */
function childProcessIntegration(options?: ChildProcessOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { spawn, exec } from "child_process";

// Initialize with child process integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.childProcessIntegration({
      captureSpawns: true, // Trace child process spawns
      captureExecs: true,  // Trace exec operations
    }),
  ],
});

// These operations will create spans
const child = spawn("ls", ["-la"]);
child.on("close", (code) => {
  console.log(`Child process exited with code ${code}`);
});

exec("node --version", (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
});
```

### File System Integration

Instrument file system operations.

```typescript { .api }
/**
 * Create file system integration for tracing fs operations
 * @param options - File system configuration options
 * @returns File system integration instance
 */
function fsIntegration(options?: FsOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import fs from "fs/promises";
import path from "path";

// Initialize with fs integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.fsIntegration({
      captureAsyncOperations: true, // Trace async fs operations
      captureSyncOperations: false, // Don't trace sync operations (performance)
    }),
  ],
});

// These operations will create spans
const content = await fs.readFile("data.json", "utf8");
await fs.writeFile("output.json", JSON.stringify(data));
const stats = await fs.stat("myfile.txt");
```

### System Error Integration

Capture system-level errors and signals.

```typescript { .api }
/**
 * Create system error integration for capturing system-level errors
 * @returns System error integration instance
 */
function systemErrorIntegration(): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with system error integration
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.systemErrorIntegration(),
  ],
});

// Captures system events like:
// - SIGTERM, SIGINT signals
// - Memory limit exceeded
// - File descriptor limits
// - Network errors
```

### Context and Module Integrations

Integrations for enhanced context capture and module information.

```typescript { .api }
/**
 * Create context lines integration for capturing source code around stack frames
 * @param options - Context lines configuration options
 * @returns Context lines integration instance
 */
function contextLinesIntegration(options?: ContextLinesOptions): Integration;

/**
 * Create modules integration for capturing loaded module information
 * @returns Modules integration instance
 */
function modulesIntegration(): Integration;

/**
 * Create node context integration for capturing Node.js environment context
 * @returns Node context integration instance
 */
function nodeContextIntegration(): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with context and module integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.contextLinesIntegration({
      frameContextLines: 5, // Lines of code to show around each stack frame
    }),
    Sentry.modulesIntegration(), // Include loaded modules in error reports
    Sentry.nodeContextIntegration(), // Include Node.js runtime context
  ],
});

// Enhanced error reports will include:
// - Source code lines around each stack frame
// - List of loaded modules and versions
// - Node.js runtime information (version, platform, etc.)
```

### Third-Party Service Integrations

Integrations for popular third-party services and libraries.

```typescript { .api }
/**
 * Create Supabase integration for database and API tracing
 * @param options - Supabase integration configuration options
 * @returns Supabase integration instance
 */
function supabaseIntegration(options?: SupabaseOptions): Integration;

/**
 * Instrument Supabase client for automatic tracing
 * @param client - Supabase client instance
 * @returns Instrumented client
 */
function instrumentSupabaseClient<T>(client: T): T;

/**
 * Create Zod errors integration for enhanced validation error reporting
 * @param options - Zod errors configuration options
 * @returns Zod errors integration instance
 */
function zodErrorsIntegration(options?: ZodErrorsOptions): Integration;

/**
 * Create Winston transport for sending logs to Sentry
 * @param options - Winston transport configuration options
 * @returns Sentry Winston transport instance
 */
function createSentryWinstonTransport(options?: WinstonTransportOptions): Transport;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";
import { createClient } from "@supabase/supabase-js";
import { z } from "zod";
import winston from "winston";

// Initialize with third-party integrations
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.supabaseIntegration({
      captureQueries: true,
      captureAuth: true, // Track authentication events
    }),
    Sentry.zodErrorsIntegration({
      captureValidationErrors: true,
      enhanceErrorMessages: true,
    }),
  ],
});

// Supabase client - automatically traced
const supabase = Sentry.instrumentSupabaseClient(
  createClient("https://your-project.supabase.co", "your-anon-key")
);

// Database operations will create spans
const { data, error } = await supabase
  .from("users")
  .select("*")
  .eq("active", true);

// Zod validation errors will be enhanced
const userSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  age: z.number().min(18),
});

try {
  userSchema.parse({ name: "A", email: "invalid", age: 15 });
} catch (error) {
  // Enhanced Zod error information will be sent to Sentry
  Sentry.captureException(error);
}

// Winston logger with Sentry transport
const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    Sentry.createSentryWinstonTransport({
      level: "error", // Only send error level logs to Sentry
      silent: false,
    }),
  ],
});

logger.error("This error will be sent to both console and Sentry");
```

### Development Tools

Integration for development and debugging tools.

```typescript { .api }
/**
 * Create Spotlight integration for development debugging
 * @param options - Spotlight configuration options
 * @returns Spotlight integration instance
 */
function spotlightIntegration(options?: SpotlightOptions): Integration;
```

**Usage Examples:**

```typescript
import * as Sentry from "@sentry/node";

// Initialize with Spotlight for development
Sentry.init({
  dsn: "YOUR_DSN",
  integrations: [
    Sentry.spotlightIntegration({
      sidecarUrl: "http://localhost:8969", // Spotlight sidecar URL
    }),
  ],
});

// When running with Spotlight:
// - View real-time errors and traces in browser
// - Debug performance issues locally
// - Inspect event data before it goes to Sentry
```

## Types

### Integration Options

```typescript { .api }
interface UncaughtExceptionOptions {
  /** Exit process even if other handlers are registered */
  exitEvenIfOtherHandlersAreRegistered?: boolean;
}

interface UnhandledRejectionOptions {
  /** Mode for handling unhandled rejections */
  mode?: "strict" | "warn" | "none";
}

interface LocalVariablesOptions {
  /** Capture local variables for all exceptions */
  captureAllExceptions?: boolean;
  /** Maximum number of exceptions to capture per second */
  maxExceptionsPerSecond?: number;
  /** Maximum depth for variable capture */
  maxDepth?: number;
  /** Maximum number of properties per object */
  maxProperties?: number;
}

interface ContextLinesOptions {
  /** Number of lines to include before/after each stack frame */
  frameContextLines?: number;
}

interface ChildProcessOptions {
  /** Capture child process spawn operations */
  captureSpawns?: boolean;
  /** Capture exec operations */
  captureExecs?: boolean;
  /** Maximum command length to capture */
  maxCommandLength?: number;
}

interface FsOptions {
  /** Capture asynchronous file system operations */
  captureAsyncOperations?: boolean;
  /** Capture synchronous file system operations */
  captureSyncOperations?: boolean;
  /** File path patterns to ignore */
  ignorePatterns?: string[];
}

interface SpotlightOptions {
  /** Spotlight sidecar URL */
  sidecarUrl?: string;
  /** Enable Spotlight integration */
  enabled?: boolean;
}

interface SupabaseOptions {
  /** Capture database queries in spans */
  captureQueries?: boolean;
  /** Track authentication events */
  captureAuth?: boolean;
  /** Maximum query length to capture */
  maxQueryLength?: number;
}

interface ZodErrorsOptions {
  /** Capture validation errors from Zod schemas */
  captureValidationErrors?: boolean;
  /** Enhance error messages with schema information */
  enhanceErrorMessages?: boolean;
  /** Maximum number of validation errors to include */
  maxErrors?: number;
}

interface WinstonTransportOptions {
  /** Minimum log level to send to Sentry */
  level?: string;
  /** Silent mode - don't output to console */
  silent?: boolean;
  /** Custom formatting function */
  format?: any;
}

interface Transport {
  log(info: any, next: () => void): void;
}
```