# Context and Scope Management

Functions for managing context data, user information, tags, and scopes throughout your application.

## Capabilities

### User Context

Set and manage user information for error tracking.

```typescript { .api }
/**
 * Set user information for the current scope
 * @param user - User object with identification and metadata
 */
function setUser(user: User): void;
```

**Usage Examples:**

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

// Set basic user information
Sentry.setUser({
  id: "123",
  email: "user@example.com",
});

// Set comprehensive user information
Sentry.setUser({
  id: "user-456",
  username: "johndoe",
  email: "john.doe@example.com",
  ip_address: "127.0.0.1",
  segment: "premium",
  subscription: "pro",
  company: "Acme Corp",
  role: "admin",
});

// Clear user information
Sentry.setUser(null);
```

### Tags

Add tags for filtering and searching events.

```typescript { .api }
/**
 * Set a single tag for the current scope
 * @param key - Tag key
 * @param value - Tag value (must be primitive)
 */
function setTag(key: string, value: Primitive): void;

/**
 * Set multiple tags for the current scope
 * @param tags - Object containing key-value pairs of tags
 */
function setTags(tags: { [key: string]: Primitive }): void;
```

**Usage Examples:**

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

// Set individual tags
Sentry.setTag("component", "payment");
Sentry.setTag("version", "1.2.3");
Sentry.setTag("feature_flag", "new_checkout");

// Set multiple tags at once
Sentry.setTags({
  environment: "production",
  server: "web-01",
  region: "us-east-1",
  build: "build-456",
});
```

### Context Data

Set structured context data for events.

```typescript { .api }
/**
 * Set context data for the current scope
 * @param key - Context key/namespace
 * @param context - Context data object
 */
function setContext(key: string, context: Context): void;
```

**Usage Examples:**

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

// Set application context
Sentry.setContext("app", {
  name: "my-node-app",
  version: "1.0.0",
  build: "123",
});

// Set device/runtime context
Sentry.setContext("runtime", {
  name: "node",
  version: process.version,
  platform: process.platform,
  arch: process.arch,
});

// Set business context
Sentry.setContext("order", {
  id: "order-789",
  total: 99.99,
  currency: "USD",
  items: 3,
  customer_tier: "premium",
});

// Set custom context
Sentry.setContext("feature_flags", {
  new_ui: true,
  beta_feature: false,
  experimental_api: true,
});
```

### Extra Data

Add unstructured extra data to events.

```typescript { .api }
/**
 * Set extra data for the current scope
 * @param key - Extra data key
 * @param extra - Extra data value (can be any type)
 */
function setExtra(key: string, extra: Extra): void;

/**
 * Set multiple extra data values for the current scope
 * @param extras - Object containing key-value pairs of extra data
 */
function setExtras(extras: Extras): void;
```

**Usage Examples:**

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

// Set individual extra data
Sentry.setExtra("request_id", "req-123456");
Sentry.setExtra("user_preferences", userPrefs);
Sentry.setExtra("debug_info", {
  memory_usage: process.memoryUsage(),
  uptime: process.uptime(),
});

// Set multiple extra values
Sentry.setExtras({
  api_response: apiResponse,
  processing_time: processingTime,
  cache_hit: true,
  batch_size: 50,
});
```

### Performance Measurements

Set custom performance measurements.

```typescript { .api }
/**
 * Set a performance measurement
 * @param name - Measurement name
 * @param value - Measurement value
 * @param unit - Measurement unit (optional)
 */
function setMeasurement(name: string, value: number, unit?: MeasurementUnit): void;
```

**Usage Examples:**

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

// Set timing measurements
Sentry.setMeasurement("database_query_time", 145, "millisecond");
Sentry.setMeasurement("file_processing_time", 2.5, "second");

// Set size measurements
Sentry.setMeasurement("payload_size", 1024, "byte");
Sentry.setMeasurement("memory_used", 512, "megabyte");

// Set count measurements
Sentry.setMeasurement("processed_records", 1000);
Sentry.setMeasurement("cache_hits", 85);
```

### Scope Management

Manage and isolate context using scopes.

```typescript { .api }
/**
 * Get the current scope
 * @returns Current scope instance
 */
function getCurrentScope(): Scope;

/**
 * Get the isolation scope
 * @returns Isolation scope instance
 */
function getIsolationScope(): Scope;

/**
 * Get the global scope
 * @returns Global scope instance
 */
function getGlobalScope(): Scope;

/**
 * Execute a callback with a new scope
 * @param callback - Function to execute with the new scope
 * @returns Return value of the callback
 */
function withScope<T>(callback: (scope: Scope) => T): T;

/**
 * Execute a callback with a new isolation scope
 * @param callback - Function to execute with the new isolation scope
 * @returns Return value of the callback
 */
function withIsolationScope<T>(callback: (scope: Scope) => T): T;
```

**Usage Examples:**

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

// Work with current scope
const scope = Sentry.getCurrentScope();
scope.setTag("component", "user-service");
scope.setLevel("warning");

// Use withScope for isolated context
function processUser(user) {
  return Sentry.withScope((scope) => {
    scope.setUser(user);
    scope.setTag("operation", "user-processing");
    scope.setContext("processing", {
      startTime: Date.now(),
      userId: user.id,
    });
    
    try {
      return performUserProcessing(user);
    } catch (error) {
      // Error will include the scope context set above
      Sentry.captureException(error);
      throw error;
    }
  });
}

// Use isolation scope for request-level context
function handleRequest(req, res, next) {
  Sentry.withIsolationScope((scope) => {
    scope.setTag("request_id", req.id);
    scope.setUser({ id: req.user?.id });
    scope.setContext("request", {
      method: req.method,
      url: req.url,
      userAgent: req.headers["user-agent"],
    });
    
    next();
  });
}
```

### Scope Manipulation

Direct scope manipulation methods.

```typescript { .api }
/**
 * Clear all context data from the current scope
 */
function clearScope(): void;

/**
 * Push a new scope onto the scope stack
 * @returns New scope instance
 */
function pushScope(): Scope;

/**
 * Pop the current scope from the scope stack
 */
function popScope(): void;
```

**Usage Examples:**

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

// Clear all scope data
Sentry.setUser({ id: "123" });
Sentry.setTag("component", "test");
Sentry.clearScope(); // All context cleared

// Manual scope stack management
const originalScope = Sentry.pushScope();
Sentry.setTag("temporary", "true");
// ... do work with temporary context
Sentry.popScope(); // Back to original scope
```

## Types

### User Type

```typescript { .api }
interface User {
  /** Unique identifier for the user */
  id?: string;
  /** Username */
  username?: string;
  /** Email address */
  email?: string;
  /** IP address */
  ip_address?: string;
  /** User segment/group */
  segment?: string;
  /** Additional user properties */
  [key: string]: any;
}
```

### Context Types

```typescript { .api }
type Context = { [key: string]: any };
type Extra = any;
type Extras = { [key: string]: Extra };
type Primitive = string | number | boolean | null | undefined;

interface MeasurementUnit {
  /** Unit name (e.g., "millisecond", "byte", "count") */
  unit: string;
}
```

### Scope Interface

```typescript { .api }
interface Scope {
  /** Add a breadcrumb to this scope */
  addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): Scope;
  
  /** Set user information for this scope */
  setUser(user: User | null): Scope;
  
  /** Set a tag for this scope */
  setTag(key: string, value: Primitive): Scope;
  
  /** Set multiple tags for this scope */
  setTags(tags: { [key: string]: Primitive }): Scope;
  
  /** Set context data for this scope */
  setContext(key: string, context: Context | null): Scope;
  
  /** Set extra data for this scope */
  setExtra(key: string, extra: Extra): Scope;
  
  /** Set multiple extra values for this scope */
  setExtras(extras: Extras): Scope;
  
  /** Set the severity level for this scope */
  setLevel(level: SeverityLevel): Scope;
  
  /** Set the fingerprint for this scope */
  setFingerprint(fingerprint: string[]): Scope;
  
  /** Clear all data from this scope */
  clear(): Scope;
  
  /** Add an event processor to this scope */
  addEventProcessor(callback: EventProcessor): Scope;
  
  /** Update scope data with a callback function */
  update<T>(updater: (scope: Scope) => T): T;
  
  /** Clone this scope */
  clone(): Scope;
}
```

### Event Processor

```typescript { .api }
type EventProcessor = (event: Event, hint?: EventHint) => Event | null | PromiseLike<Event | null>;
```