npm package: @noalia/code-titan-api-client
Description: CodeTitan API Client - TypeScript client library for CodeTitan REST API
Author: CodeTitan Team
Latest version: 1.0.1

# CodeTitan API Client

TypeScript client library for the CodeTitan REST API.

**✅ Fully compatible with CodeTitan API Server v1.0.0**

## Installation

```bash
npm install @codetitan/api-client
```

## Quick Start

```typescript
import { CodeTitanClient } from '@codetitan/api-client';

// Initialize client with API key
const client = new CodeTitanClient({
  apiKey: 'ct_key_your_api_key_here',
  baseURL: 'http://localhost:3001'  // optional, defaults to localhost:3001
});

// Start analysis
const response = await client.analyze({
  projectPath: '/path/to/your/project',
  level: 6,
  quick: false
});

console.log(`Analysis started: ${response.run_id}`);

// Wait for completion
const result = await client.waitForAnalysis(response.run_id, {
  onProgress: (run) => {
    console.log(`Status: ${run.status}`);
  }
});

console.log('Analysis complete:', result.report);
```

## Features

- ✅ Full TypeScript support with type definitions
- ✅ Promise-based API
- ✅ Comprehensive error handling
- ✅ Automatic polling for async operations
- ✅ Rate limiting support
- ✅ Matches actual API server endpoints

## API Reference

### Client Configuration

```typescript
interface CodeTitanClientConfig {
  apiKey: string;        // Required: Your API key
  baseURL?: string;      // Optional: API server URL (default: http://localhost:3001)
  timeout?: number;      // Optional: Request timeout in ms (default: 30000)
  retries?: number;      // Optional: Number of retries (default: 3)
}
```

### Public Methods (No Auth Required)

#### `health()`
Check API server health status.

```typescript
const health = await client.health();
console.log(health.status); // 'healthy'
```

#### `CodeTitanClient.generateApiKey()` (static)
Generate a new API key.

```typescript
const result = await CodeTitanClient.generateApiKey(
  { email: 'user@example.com', name: 'My Key' },
  'http://localhost:3001',
  'provisioning-token'  // Required in production
);

console.log(result.api_key); // 'ct_key_...'
```

### Authenticated Methods

#### `getStatus()`
Get API status and user capabilities.

```typescript
const status = await client.getStatus();
console.log(status.capabilities.levels); // [1, 2, 3, 4, 5, 6, 7, 8]
```

#### `analyze(request)`
Start code analysis.

```typescript
const response = await client.analyze({
  projectPath: '/path/to/project',
  level: 6,                    // Analysis level (1-8)
  quick: false,                // Quick mode
  format: 'json',              // Output format: json | markdown | console
  applyFixes: false            // Apply automatic fixes
});

console.log(response.run_id);
console.log(response.estimated_time);
```

#### `getRun(runId)`
Get analysis run status and results.

```typescript
const run = await client.getRun('run-id-here');
console.log(run.status);      // 'started' | 'completed' | 'failed'

if (run.status === 'completed') {
  console.log(run.report);    // Analysis results
}
```

#### `waitForAnalysis(runId, options?)`
Poll for analysis completion.

```typescript
const result = await client.waitForAnalysis('run-id', {
  pollInterval: 2000,           // Poll every 2 seconds
  maxAttempts: 150,             // Max 5 minutes
  onProgress: (run) => {
    console.log(`Status: ${run.status}`);
  }
});

console.log(result.report);
```

#### `analyzeAndWait(request, options?)`
Convenience method: analyze and wait for results.

```typescript
const result = await client.analyzeAndWait({
  projectPath: '/path/to/project',
  level: 6
}, {
  onProgress: (run) => console.log(run.status)
});

console.log(result.report);
```

#### `listProjects()`
List user's projects.

```typescript
const response = await client.listProjects();
console.log(response.projects);
console.log(response.count);
```

## Error Handling

All methods throw `CodeTitanError` on failure:

```typescript
import { CodeTitanError } from '@codetitan/api-client';

try {
  const result = await client.analyze({ projectPath: '/invalid/path' });
} catch (error) {
  if (error instanceof CodeTitanError) {
    console.error(`Error: ${error.code}`);
    console.error(`Message: ${error.message}`);
    console.error(`Status: ${error.statusCode}`);

    if (error.code === 'RATE_LIMIT_EXCEEDED') {
      console.log(`Retry after ${error.retryAfter} seconds`);
    }
  }
}
```

### Error Codes

- `RATE_LIMIT_EXCEEDED` - Rate limit exceeded (429)
- `UNAUTHORIZED` - Invalid API key (401)
- `FORBIDDEN` - Access denied (403)
- `NOT_FOUND` - Resource not found (404)
- `BAD_REQUEST` - Invalid request (400)
- `SERVER_ERROR` - Server error (500+)
- `NETWORK_ERROR` - Network failure
- `ANALYSIS_FAILED` - Analysis failed
- `TIMEOUT` - Operation timeout
- `UNKNOWN_ERROR` - Unknown error

## TypeScript Types

All request/response types are exported:

```typescript
import {
  AnalyzeRequest,
  AnalyzeResponse,
  AnalysisRun,
  AnalysisReport,
  Finding,
  Project,
  ProjectsResponse,
  ApiStatus,
  HealthResponse,
  GenerateKeyRequest,
  GenerateKeyResponse,
  CodeTitanError
} from '@codetitan/api-client';
```

## Requirements

- Node.js >= 18.0.0
- npm >= 9.0.0

## Support

Visit https://codetitan.dev/docs for documentation.