> ## Documentation Index
> Fetch the complete documentation index at: https://docs.browsertest.in/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Types

> Complete TypeScript type definitions for BrowserTest SDK

## Core Types

### BrowserTestConfig

Configuration options for the BrowserTest client.

```typescript theme={null}
interface BrowserTestConfig {
  /** API key for authentication */
  apiKey: string;
  /** Base URL for API calls (default: https://api.browsertest.in) */
  baseUrl?: string;
  /** Request timeout in milliseconds (default: 30000) */
  timeout?: number;
  /** Number of retries for failed requests (default: 3) */
  retries?: number;
}
```

### QuotaInfo

Usage and quota information.

```typescript theme={null}
interface QuotaInfo {
  plan: string;
  usage: {
    screenshot: {
      used: number;
      limit: number;
      remaining: number;
    };
    agentic: {
      used: number;
      limit: number;
      remaining: number;
    };
    total: {
      screenshot: number;
      agentic: number;
    };
  };
}
```

## Screenshot Types

### ScreenshotOptions

Configuration options for screenshot capture.

```typescript theme={null}
interface ScreenshotOptions {
  /** URL to screenshot */
  url: string;
  /** Capture full page (default: false) */
  fullPage?: boolean;
  /** Viewport width (default: 1280) */
  width?: number;
  /** Viewport height (default: 720) */
  height?: number;
  /** Image format: 'png' | 'jpeg' (default: 'png') */
  format?: 'png' | 'jpeg';
  /** Image quality for JPEG (default: 80) */
  quality?: number;
  /** Wait time in milliseconds before screenshot (default: 0) */
  waitFor?: number;
  /** CSS selector for element screenshot (optional) */
  selector?: string | null;
  /** Request timeout in milliseconds (default: 10000) */
  timeout?: number;
  /** Block ads and trackers (default: true) */
  blockAds?: boolean;
}
```

### ScreenshotResult

Result of a screenshot operation.

```typescript theme={null}
interface ScreenshotResult {
  success: boolean;
  data: {
    screenshot: string; // base64 encoded image
    url: string;
    title: string;
    width: number;
    height: number;
    format: string;
    fullPage: boolean;
  };
  meta: {
    timeMs: number;
    size: number;
  };
}
```

### BatchScreenshotOptions

Options for batch screenshot operations.

```typescript theme={null}
interface BatchScreenshotOptions extends Omit<ScreenshotOptions, 'url'> {
  /** Array of URLs to screenshot */
  urls: string[];
}
```

### BatchScreenshotResult

Result of a batch screenshot operation.

```typescript theme={null}
interface BatchScreenshotResult {
  success: boolean;
  results: Array<{
    url: string;
    success: boolean;
    data?: ScreenshotResult['data'];
    error?: string;
  }>;
  meta: {
    total: number;
    successful: number;
    timeMs: number;
  };
}
```

## Testing Types

### TestOptions

Configuration options for test execution.

```typescript theme={null}
interface TestOptions {
  /** Natural language test instructions */
  instructions: string;
  /** URL to test */
  url: string;
  /** JSON schema for structured output (optional) */
  outputSchema?: object;
  /** Test configuration */
  config?: TestConfig;
}
```

### TestConfig

Browser and test configuration.

```typescript theme={null}
interface TestConfig {
  /** Viewport width (default: 1280) */
  width?: number;
  /** Viewport height (default: 720) */
  height?: number;
  /** Wait time before starting test (default: 0) */
  waitFor?: number;
  /** Test timeout in milliseconds (default: 30000) */
  timeout?: number;
  /** Block ads and trackers (default: true) */
  blockAds?: boolean;
  /** User agent string (optional) */
  userAgent?: string;
}
```

### TestResult

Result of a test execution.

```typescript theme={null}
interface TestResult {
  success: boolean;
  results: {
    /** Agent actions performed during test */
    actions: Array<{
      type: string;
      description: string;
      timestamp: string;
    }>;
    /** Structured data if outputSchema was provided */
    structuredData?: any;
    /** Raw test output */
    output: string;
  };
  meta: {
    timeMs: number;
    url: string;
  };
}
```

### TestJob

Information about an async test job.

```typescript theme={null}
interface TestJob {
  jobId: string;
  status: 'pending' | 'running' | 'completed' | 'failed';
  createdAt: string;
  url: string;
}
```

### TestJobStatus

Detailed status of a test job.

```typescript theme={null}
interface TestJobStatus {
  job: {
    id: string;
    status: 'pending' | 'running' | 'completed' | 'failed';
    createdAt: string;
    startedAt?: string;
    completedAt?: string;
    url: string;
    config?: TestConfig;
    results?: TestResult['results'];
    error?: string;
    progress?: string;
  };
}
```

### ListTestsOptions

Options for listing test jobs.

```typescript theme={null}
interface ListTestsOptions {
  /** Filter by status */
  status?: 'pending' | 'running' | 'completed' | 'failed';
  /** Filter by template ID */
  templateId?: string;
  /** Maximum number of results */
  limit?: number;
  /** Number of results to skip */
  offset?: number;
  /** Sort order (default: 'desc') */
  sortOrder?: 'asc' | 'desc';
}
```

### TestJobsList

List of test jobs.

```typescript theme={null}
interface TestJobsList {
  jobs: Array<{
    id: string;
    status: string;
    createdAt: string;
    completedAt?: string;
    url: string;
    templateId?: string;
    results?: TestResult['results'];
    error?: string;
  }>;
  total: number;
  hasMore: boolean;
}
```

## Template Types

### TemplateOptions

Options for creating a test template.

```typescript theme={null}
interface TemplateOptions {
  /** Template name */
  name: string;
  /** Template description */
  description: string;
  /** Test instructions */
  instructions: string;
  /** JSON schema for structured output */
  outputSchema: object;
  /** Template tags for organization */
  tags?: string[];
}
```

### TemplateResponse

Response from template creation/update.

```typescript theme={null}
interface TemplateResponse {
  template: {
    id: string;
    name: string;
    description: string;
    instructions: string;
    outputSchema: object;
    tags: string[];
    createdAt: string;
    updatedAt: string;
  };
}
```

### TemplateInvocationOptions

Options for invoking a template.

```typescript theme={null}
interface TemplateInvocationOptions {
  /** URL to test */
  url: string;
  /** Test configuration overrides */
  config?: TestConfig;
  /** Parameter values for template variables */
  parameters?: Record<string, any>;
}
```

### TemplateJobResponse

Response from template invocation.

```typescript theme={null}
interface TemplateJobResponse {
  jobId: string;
  status: 'pending' | 'running' | 'completed' | 'failed';
  createdAt: string;
  url: string;
}
```

### TemplateListOptions

Options for listing templates.

```typescript theme={null}
interface TemplateListOptions {
  /** Search query for template names */
  search?: string;
  /** Filter by tags */
  tags?: string[];
  /** Maximum number of results */
  limit?: number;
  /** Number of results to skip */
  offset?: number;
  /** Sort order */
  sortOrder?: 'asc' | 'desc';
}
```

### TemplateListResponse

List of templates.

```typescript theme={null}
interface TemplateListResponse {
  templates: Array<{
    id: string;
    name: string;
    description: string;
    tags: string[];
    createdAt: string;
    updatedAt: string;
  }>;
  total: number;
  hasMore: boolean;
}
```

## Batch Types

### ScreenshotRequest

Request configuration for a single screenshot in a batch.

```typescript theme={null}
interface ScreenshotRequest {
  /** URL to screenshot */
  url: string;
  /** Full page capture (default: false) */
  fullPage?: boolean;
  /** Viewport width (default: 1280) */
  width?: number;
  /** Viewport height (default: 720) */
  height?: number;
  /** Image format: 'png' | 'jpeg' (default: 'png') */
  format?: 'png' | 'jpeg';
  /** Image quality for JPEG (default: 80) */
  quality?: number;
  /** Wait time before screenshot (default: 0) */
  waitFor?: number;
  /** CSS selector for element screenshot */
  selector?: string | null;
  /** Request timeout in milliseconds (default: 10000) */
  timeout?: number;
  /** Block ads and trackers (default: true) */
  blockAds?: boolean;
}
```

### TestRequest

Request configuration for a single test in a batch.

```typescript theme={null}
interface TestRequest {
  /** Test instructions */
  instructions: string;
  /** URL to test */
  url: string;
  /** JSON schema for structured output */
  outputSchema?: object;
  /** Test configuration */
  config?: TestConfig;
}
```

### BatchOptions

Options for batch processing.

```typescript theme={null}
interface BatchOptions {
  /** Maximum concurrent operations (default: 3) */
  concurrency?: number;
  /** Continue processing on individual failures (default: true) */
  continueOnError?: boolean;
  /** Overall batch timeout in milliseconds */
  timeout?: number;
}
```

### BatchScreenshotResults

Results from batch screenshot processing.

```typescript theme={null}
interface BatchScreenshotResults {
  successful: number;
  total: number;
  results: Array<{
    url: string;
    success: boolean;
    data?: ScreenshotResult['data'];
    error?: string;
    timeMs?: number;
  }>;
  meta: {
    totalTimeMs: number;
    averageTimeMs: number;
    concurrencyUsed: number;
  };
}
```

### BatchTestResults

Results from batch test processing.

```typescript theme={null}
interface BatchTestResults {
  successful: number;
  total: number;
  results: Array<{
    instructions: string;
    url: string;
    success: boolean;
    data?: TestResult['results'];
    error?: string;
    timeMs?: number;
  }>;
  meta: {
    totalTimeMs: number;
    averageTimeMs: number;
    concurrencyUsed: number;
  };
}
```

### BatchJobResults

Results from batch job creation.

```typescript theme={null}
interface BatchJobResults {
  jobs: Array<{
    jobId: string;
    status: 'pending' | 'running' | 'completed' | 'failed';
    url: string;
    instructions: string;
  }>;
  meta: {
    total: number;
    created: number;
    failed: number;
  };
}
```

## Error Types

### BrowserTestError

Base error class for SDK errors.

```typescript theme={null}
class BrowserTestError extends Error {
  constructor(message: string, public status?: number) {
    super(message);
    this.name = 'BrowserTestError';
  }
}
```

### BrowserTestAuthError

Authentication-related errors.

```typescript theme={null}
class BrowserTestAuthError extends BrowserTestError {
  constructor(message = 'Authentication failed') {
    super(message);
    this.name = 'BrowserTestAuthError';
  }
}
```

### BrowserTestQuotaError

Quota and billing-related errors.

```typescript theme={null}
class BrowserTestQuotaError extends BrowserTestError {
  constructor(message = 'Quota exceeded', public quotaInfo?: QuotaInfo) {
    super(message);
    this.name = 'BrowserTestQuotaError';
  }
}
```

### BrowserTestAPIError

API-related errors.

```typescript theme={null}
class BrowserTestAPIError extends BrowserTestError {
  constructor(message: string, status: number) {
    super(message, status);
    this.name = 'BrowserTestAPIError';
  }
}
```

### BrowserTestTimeoutError

Timeout-related errors.

```typescript theme={null}
class BrowserTestTimeoutError extends BrowserTestError {
  constructor(message = 'Request timed out') {
    super(message);
    this.name = 'BrowserTestTimeoutError';
  }
}
```

## Utility Types

### ApiResponse

Generic API response wrapper.

```typescript theme={null}
interface ApiResponse<TData = unknown, TError = string> {
  success: boolean;
  data?: TData;
  error?: TError;
  meta?: {
    timeMs: number;
    requestId?: string;
  };
}
```

### Successful Results

Type helpers for extracting successful results.

```typescript theme={null}
// Extract successful screenshot results
type SuccessfulScreenshot = ScreenshotResult & { success: true };

// Extract successful test results
type SuccessfulTest = TestResult & { success: true };

// Extract data from successful results
type ScreenshotData = SuccessfulScreenshot['data'];
type TestResults = SuccessfulTest['results'];
```

### Batch Result Types

Type helpers for batch operations.

```typescript theme={null}
// Generic batch result
type BatchResult<TData, TError = string> = Array<{
  success: true;
  data: TData;
} | {
  success: false;
  error: TError;
}>;

// Specific batch types
type ScreenshotBatchResult = BatchResult<ScreenshotResult['data']>;
type TestBatchResult = BatchResult<TestResult['results']>;
```

### Configuration Types

Environment-based configuration types.

```typescript theme={null}
type Environment = 'development' | 'staging' | 'production';

interface EnvironmentConfig extends BrowserTestConfig {
  environment: Environment;
}

// Union type for all possible config variations
type BrowserTestConfigUnion =
  | BrowserTestConfig
  | EnvironmentConfig;
```

## Advanced Types

### Generic Test Types

```typescript theme={null}
// Generic test result with typed structured data
interface TypedTestResult<TOutput = any> extends Omit<TestResult, 'results'> {
  results: Omit<TestResult['results'], 'structuredData'> & {
    structuredData: TOutput;
  };
}

// Usage with specific output types
interface LoginTestOutput {
  loginSuccessful: boolean;
  userName?: string;
  errorMessage?: string;
}

type LoginTestResult = TypedTestResult<LoginTestOutput>;
```

### Template Types

```typescript theme={null}
// Generic template with typed output
interface TypedTemplate<TOutput = any> extends Omit<TemplateOptions, 'outputSchema'> {
  outputSchema: object; // JSON schema for TOutput
  outputType?: TOutput; // Type hint (not used at runtime)
}

// Template invocation with typed parameters
interface TypedTemplateInvocation<TPayload = any> extends TemplateInvocationOptions {
  parameters: TPayload;
}
```

### Batch Processing Types

```typescript theme={null}
// Batch processor configuration
interface BatchProcessorConfig {
  concurrency: number;
  timeout: number;
  retryPolicy: {
    maxRetries: number;
    backoffMs: number;
  };
}

// Batch processing result
interface BatchProcessingResult<TData, TError = string> {
  successful: TData[];
  failed: Array<{
    item: unknown;
    error: TError;
    retries: number;
  }>;
  stats: {
    total: number;
    successful: number;
    failed: number;
    durationMs: number;
    throughput: number; // items per second
  };
}
```

### Event Types

```typescript theme={null}
// Event types for monitoring
type BatchEvent =
  | { type: 'batch_started'; batchId: string; totalItems: number }
  | { type: 'item_completed'; batchId: string; itemIndex: number; success: boolean }
  | { type: 'batch_completed'; batchId: string; stats: BatchProcessingResult<any>['stats'] }
  | { type: 'batch_failed'; batchId: string; error: string };

// Job event types
type JobEvent =
  | { type: 'job_created'; jobId: string; templateId?: string }
  | { type: 'job_started'; jobId: string }
  | { type: 'job_progress'; jobId: string; progress: string }
  | { type: 'job_completed'; jobId: string; results: TestResult['results'] }
  | { type: 'job_failed'; jobId: string; error: string };
```

## Type Guards

Runtime type checking functions.

```typescript theme={null}
// Check if result is successful
function isSuccessfulScreenshot(result: ScreenshotResult): result is SuccessfulScreenshot {
  return result.success;
}

function isSuccessfulTest(result: TestResult): result is SuccessfulTest {
  return result.success;
}

// Check error types
function isBrowserTestAuthError(error: unknown): error is BrowserTestAuthError {
  return error instanceof Error && error.name === 'BrowserTestAuthError';
}

function isBrowserTestQuotaError(error: unknown): error is BrowserTestQuotaError {
  return error instanceof Error && error.name === 'BrowserTestQuotaError';
}

function isBrowserTestAPIError(error: unknown): error is BrowserTestAPIError {
  return error instanceof Error && error.name === 'BrowserTestAPIError';
}

function isBrowserTestTimeoutError(error: unknown): error is BrowserTestTimeoutError {
  return error instanceof Error && error.name === 'BrowserTestTimeoutError';
}
```

## Type Utilities

### Extract and Transform

```typescript theme={null}
// Extract URL from various request types
type ExtractUrl<T> = T extends { url: string } ? T['url'] : never;

// Extract instructions from test requests
type ExtractInstructions<T> = T extends { instructions: string } ? T['instructions'] : never;

// Create union of all possible result data types
type ResultData = ScreenshotResult['data'] | TestResult['results'];

// Extract error messages
type ErrorMessage = string;
```

### Conditional Types

```typescript theme={null}
// Create result type based on operation type
type OperationResult<TOperation extends string, TData> =
  TOperation extends 'screenshot' ? ScreenshotResult :
  TOperation extends 'test' ? TestResult :
  TOperation extends 'batch' ? BatchScreenshotResults | BatchTestResults :
  never;

// Check if type has specific property
type HasProperty<T, K extends string> = K extends keyof T ? true : false;

// Make specific properties optional
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
```

## Migration Types

Types for handling API changes and versioning.

```typescript theme={null}
// Version-specific types
interface ScreenshotResultV1 {
  success: boolean;
  screenshot: string;
  url: string;
  width: number;
  height: number;
}

// Migration helper
type MigrateScreenshotResultV1ToV2 = (v1: ScreenshotResultV1) => ScreenshotResult;

// Backwards compatibility types
type ScreenshotResultLatest = ScreenshotResult;
type ScreenshotResultLegacy = ScreenshotResultV1 | ScreenshotResult;

// Version detection
function isLatestScreenshotResult(result: ScreenshotResultLegacy): result is ScreenshotResultLatest {
  return 'data' in result && 'meta' in result;
}
```

## Best Practices

### Type Safety

1. **Always use strict TypeScript settings**
2. **Define interfaces for structured output**
3. **Use discriminated unions for results**
4. **Create type guards for runtime checks**
5. **Leverage generic types for reusable code**

### Development Experience

```typescript theme={null}
// Enable comprehensive TypeScript configuration
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noUncheckedIndexedAccess": true
  }
}
```

### IntelliSense Optimization

```typescript theme={null}
// Use JSDoc comments for better IntelliSense
/**
 * Takes a screenshot of the specified URL with customizable options
 * @param options - Screenshot configuration options
 * @returns Promise resolving to screenshot result with type safety
 */
async function takeScreenshot(options: ScreenshotOptions): Promise<ScreenshotResult> {
  return bt.screenshot.take(options);
}

// IntelliSense will show parameter descriptions and types
const result = await takeScreenshot({
  url: 'https://example.com',
  fullPage: true, // Shows: "Capture full page (default: false)"
  format: 'png'   // Shows: "'png' | 'jpeg'"
});
```

### Error Type Narrowing

```typescript theme={null}
// Type-safe error handling
async function handleBrowserTestOperation() {
  try {
    const result = await bt.screenshot.take({ url: 'https://example.com' });
    return result; // TypeScript knows result is ScreenshotResult
  } catch (error) {
    if (isBrowserTestAuthError(error)) {
      // TypeScript knows error is BrowserTestAuthError
      console.error('Auth failed:', error.message);
      throw error;
    }

    if (isBrowserTestQuotaError(error)) {
      // TypeScript knows error has quotaInfo property
      console.error('Quota exceeded:', error.quotaInfo);
      throw error;
    }

    // Handle other errors
    throw error;
  }
}
```
