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

# Node.js SDK

> Official Node.js/TypeScript SDK for the Audixa text-to-speech API

The Audixa Node.js SDK provides a type-safe client for the Audixa text-to-speech API, with full TypeScript support and built-in error handling.

## Installation

```bash theme={null}
npm install audixa
```

## Quick Start

<CodeGroup>
  ```typescript TypeScript theme={null}
  import Audixa from 'audixa';

  const audixa = new Audixa('YOUR_API_KEY');

  // Generate TTS and wait for completion
  const audioUrl = await audixa.generateTTS({
    text: 'Hello! Welcome to Audixa.',
    voice_id: 'am_ethan',
    model: 'base'
  });

  console.log('Audio URL:', audioUrl);
  ```

  ```javascript JavaScript (ESM) theme={null}
  import Audixa from 'audixa';

  const audixa = new Audixa('YOUR_API_KEY');

  const audioUrl = await audixa.generateTTS({
    text: 'Hello! Welcome to Audixa.',
    voice_id: 'am_ethan',
    model: 'base'
  });

  console.log('Audio URL:', audioUrl);
  ```

  ```javascript JavaScript (CommonJS) theme={null}
  const { Audixa } = require('audixa');

  const audixa = new Audixa('YOUR_API_KEY');

  async function main() {
    const audioUrl = await audixa.generateTTS({
      text: 'Hello! Welcome to Audixa.',
      voice_id: 'am_ethan',
      model: 'base'
    });

    console.log('Audio URL:', audioUrl);
  }

  main();
  ```
</CodeGroup>

## Configuration

```typescript theme={null}
import Audixa from 'audixa';

const audixa = new Audixa('YOUR_API_KEY', {
  baseUrl: 'https://api.audixa.ai/v3',   // Default
  timeout: 30000,                          // Request timeout in ms (default: 30s)
  customEndpointSlug: 'my-custom-slug',    // Optional: route TTS to custom endpoint
});
```

## API Reference

### `startTTS(payload, options?)`

Starts an async TTS generation job. Returns immediately with a `generation_id`.

```typescript theme={null}
const response = await audixa.startTTS({
  text: 'Hello from Audixa!',
  voice_id: 'am_ethan',
  model: 'base',
  speed: 1.0,
  audio_format: 'wav'
});

console.log(response.generation_id); // "gen_abc123"
console.log(response.status);        // "IN_QUEUE"
```

**Parameters:**

| Parameter      | Type                   | Required | Description                                |
| -------------- | ---------------------- | -------- | ------------------------------------------ |
| `text`         | `string`               | ✅        | Text to convert (min 30 chars)             |
| `voice_id`     | `string`               | ✅        | Voice identifier                           |
| `model`        | `'base' \| 'advanced'` | ❌        | Model to use (default: `'base'`)           |
| `speed`        | `number`               | ❌        | Speed multiplier, 0.5–2.0 (default: `1.0`) |
| `cfg_weight`   | `number`               | ❌        | Advanced model: guidance strength, 1.0–5.0 |
| `exaggeration` | `number`               | ❌        | Advanced model: expressiveness, 0.0–1.0    |
| `audio_format` | `'wav' \| 'mp3'`       | ❌        | Output format (default: `'wav'`)           |

**Options:**

| Option               | Type          | Description                             |
| -------------------- | ------------- | --------------------------------------- |
| `signal`             | `AbortSignal` | Cancel the request                      |
| `customEndpointSlug` | `string`      | Override endpoint slug for this request |

***

### `getStatus(generationId, options?)`

Check the status of a generation.

```typescript theme={null}
const status = await audixa.getStatus('gen_abc123');

if (status.status === 'COMPLETED') {
  console.log('Audio:', status.audio_url);
}
```

**Returns:** `TTSResponse` with `status`, `audio_url`, `voice_id`, `model`, etc.

***

### `generateTTS(payload, options?)`

Convenience method: starts TTS and polls until completion. Returns the audio URL.

```typescript theme={null}
const audioUrl = await audixa.generateTTS({
  text: 'Hello! This will wait for completion.',
  voice_id: 'am_ethan',
  model: 'advanced',
  cfg_weight: 3.5,
  exaggeration: 0.7,
  audio_format: 'mp3'
}, {
  pollInterval: 1000,  // Poll every 1 second (default: 1000ms)
  maxWaitTime: 120000  // Max wait 2 minutes (default: 120000ms)
});

console.log('Audio URL:', audioUrl);
```

**Additional Options (besides `signal`, `customEndpointSlug`):**

| Option         | Type     | Default  | Description                        |
| -------------- | -------- | -------- | ---------------------------------- |
| `pollInterval` | `number` | `1000`   | Milliseconds between status checks |
| `maxWaitTime`  | `number` | `120000` | Maximum wait time in milliseconds  |

***

### `getVoices(params?, options?)`

List available voices with optional filtering.

```typescript theme={null}
const { voices } = await audixa.getVoices({
  model: 'base',
  limit: 50
});

for (const voice of voices) {
  console.log(`${voice.name} (${voice.voice_id}) - ${voice.gender}`);
}
```

**Parameters:**

| Parameter | Type                   | Default | Description         |
| --------- | ---------------------- | ------- | ------------------- |
| `model`   | `'base' \| 'advanced'` | —       | Filter by model     |
| `limit`   | `number`               | `100`   | Max results (1–500) |
| `offset`  | `number`               | `0`     | Skip results        |

***

### `getHistory(params?, options?)`

Retrieve generation history.

```typescript theme={null}
const { history } = await audixa.getHistory({
  limit: 10,
  status: 'COMPLETED'
});

for (const item of history) {
  console.log(`${item.generation_id}: ${item.status} - ${item.voice_id}`);
}
```

**Parameters:**

| Parameter | Type     | Default | Description                                                        |
| --------- | -------- | ------- | ------------------------------------------------------------------ |
| `limit`   | `number` | `20`    | Max results (1–100)                                                |
| `offset`  | `number` | `0`     | Skip results                                                       |
| `status`  | `string` | —       | Filter: `IN_QUEUE`, `GENERATING`, `COMPLETED`, `FAILED`, `EXPIRED` |

## TypeScript Types

The SDK exports all types for full type safety:

```typescript theme={null}
import Audixa, {
  // Request/Response types
  StartTTSRequest,
  StartTTSResponse,
  TTSResponse,
  TTSStatusResponse,
  VoicesResponse,
  Voice,
  HistoryResponse,
  HistoryItem,

  // Enums
  TTSModel,         // "base" | "advanced"
  TTSAudioFormat,   // "wav" | "mp3"
  TTSStatus,        // "IN_QUEUE" | "GENERATING" | "COMPLETED" | "FAILED"

  // Configuration
  AudixaOptions,
  RequestOptions,

  // Errors
  AudixaError,
} from 'audixa';
```

### Key Type Definitions

```typescript theme={null}
interface StartTTSRequest {
  text: string;
  voice_id: string;
  model?: 'base' | 'advanced';
  speed?: number;
  cfg_weight?: number;
  exaggeration?: number;
  audio_format?: 'wav' | 'mp3';
}

interface TTSResponse {
  generation_id: string;
  status: 'IN_QUEUE' | 'GENERATING' | 'COMPLETED' | 'FAILED';
  input_text: string;
  voice_id: string;
  voice_name?: string | null;
  model: 'base' | 'advanced';
  tokens: number;
  credits_cost: number;
  dollar_cost?: number | null;
  method?: string | null;
  audio_url?: string | null;
  error_message?: string | null;
  created_at: string;
  started_at?: string | null;
  completed_at?: string | null;
}

interface Voice {
  voice_id: string;
  name: string;
  model: 'base' | 'advanced';
  gender?: string;
  accent?: string;
  description?: string;
  free: boolean;
  is_custom: boolean;
}

interface AudixaOptions {
  baseUrl?: string;           // Default: "https://api.audixa.ai/v3"
  timeout?: number;           // Default: 30000ms
  customEndpointSlug?: string;
}
```

## Error Handling

The SDK provides typed errors for all API failures:

```typescript theme={null}
import Audixa, { AudixaError } from 'audixa';

const audixa = new Audixa('YOUR_API_KEY');

try {
  const audioUrl = await audixa.generateTTS({
    text: 'Hello from Audixa!',
    voice_id: 'am_ethan',
    model: 'base'
  });
} catch (error) {
  if (error instanceof AudixaError) {
    console.error('Code:', error.code);           // e.g. "AUTHENTICATION_ERROR"
    console.error('Status:', error.statusCode);   // e.g. 401
    console.error('Message:', error.message);
    
    switch (error.code) {
      case 'AUTHENTICATION_ERROR':
        // Invalid or missing API key (401)
        break;
      case 'INSUFFICIENT_BALANCE':
        // Account balance too low (402)
        break;
      case 'RATE_LIMITED':
        // Too many requests (429)
        break;
      case 'VALIDATION_ERROR':
        // Invalid parameters (400/422)
        break;
      case 'NETWORK_ERROR':
        // Network connectivity issue
        break;
      case 'TIMEOUT_ERROR':
        // Request timed out
        break;
      case 'GENERATION_ERROR':
        // TTS generation failed
        break;
    }
  }
}
```

### Error Codes

| Code                   | HTTP Status | Description                    |
| ---------------------- | ----------- | ------------------------------ |
| `AUTHENTICATION_ERROR` | 401         | Invalid or missing API key     |
| `INSUFFICIENT_BALANCE` | 402         | Account has insufficient funds |
| `RATE_LIMITED`         | 429         | Rate limit exceeded            |
| `VALIDATION_ERROR`     | 400/422     | Invalid request parameters     |
| `API_ERROR`            | 500+        | Server-side error              |
| `NETWORK_ERROR`        | —           | Network connectivity issue     |
| `TIMEOUT_ERROR`        | —           | Request timed out              |
| `GENERATION_ERROR`     | —           | TTS generation failed          |

## Request Cancellation

Use `AbortSignal` to cancel in-flight requests:

```typescript theme={null}
const controller = new AbortController();

// Set a 10-second timeout
setTimeout(() => controller.abort(), 10000);

try {
  const audioUrl = await audixa.generateTTS({
    text: 'This might take a while...',
    voice_id: 'am_ethan',
    model: 'advanced'
  }, {
    signal: controller.signal
  });
} catch (error) {
  if (error instanceof AudixaError && error.code === 'TIMEOUT_ERROR') {
    console.log('Request cancelled due to timeout');
  }
}
```

## Custom Endpoints

Route TTS requests through a custom endpoint:

```typescript theme={null}
// Set globally in constructor
const audixa = new Audixa('YOUR_API_KEY', {
  customEndpointSlug: 'my-custom-slug'
});

// Or per-request
const audioUrl = await audixa.generateTTS({
  text: 'Using custom endpoint...',
  voice_id: 'custom_voice_123',
  model: 'advanced'
}, {
  customEndpointSlug: 'my-custom-slug'
});
```

## Environment Variables

Set your API key via environment variable instead of passing it directly:

```bash theme={null}
export AUDIXA_API_KEY=your_api_key_here
```

```typescript theme={null}
// Will automatically use AUDIXA_API_KEY env variable
const audixa = new Audixa();
```
