npm package: @preapi.net/sdk
Description: Official JavaScript/TypeScript SDK for the PreAPI AI API Gateway
Author: VectorLabs LLC
Latest version: 1.0.0

# @preapi.net/sdk

Official JavaScript/TypeScript SDK for the [PreAPI](https://preapi.net) AI API Gateway.

Access 1000+ AI models through a single, unified API — image generation, video generation, audio, upscaling, and more.

## Installation

```bash
npm install @preapi.net/sdk
```

## Quick Start

```typescript
import PreAPI from "@preapi.net/sdk";

const client = new PreAPI("your-api-key");

// Generate an image
const result = await client.generate({
  model: "flux-pro",
  input: {
    prompt: "a cat astronaut floating in space, digital art",
    width: 1024,
    height: 1024,
  },
});

console.log(result.output_url); // CDN URL of the generated image
console.log(result.credits_used); // Credits consumed
console.log(result.duration_ms); // Processing time
```

## Features

- **Zero dependencies** — uses native `fetch` (Node 18+, browsers, edge runtimes)
- **Full TypeScript support** — complete type definitions included
- **Dual format** — ESM and CommonJS supported
- **Typed errors** — specific error classes for each error type
- **Configurable** — custom base URL, timeout, and fetch implementation

## API Reference

### `new PreAPI(apiKey)`

Create a client with just an API key:

```typescript
const client = new PreAPI("your-api-key");
```

### `new PreAPI(config)`

Create a client with full configuration:

```typescript
const client = new PreAPI({
  apiKey: "your-api-key",
  baseUrl: "https://preapi.net", // default
  timeout: 120000, // 2 minutes, default
});
```

### `client.generate(input)`

Generate output from an AI model.

```typescript
const result = await client.generate({
  model: "flux-pro", // model slug
  input: {
    prompt: "a beautiful sunset over mountains",
  },
});
```

**Returns:** `GenerateOutput`

| Field          | Type                     | Description                    |
| -------------- | ------------------------ | ------------------------------ |
| `output_url`   | `string \| null`         | CDN URL of the generated file  |
| `output`       | `Record<string, unknown>`| Full model output data         |
| `credits_used` | `number`                 | Credits consumed               |
| `duration_ms`  | `number`                 | Processing time in ms          |

### `client.models.list()`

List all available models.

```typescript
const models = await client.models.list();

for (const model of models) {
  console.log(`${model.name} (${model.slug}) - ${model.category}`);
}
```

**Returns:** `Model[]`

| Field           | Type             | Description              |
| --------------- | ---------------- | ------------------------ |
| `id`            | `string`         | Unique model ID          |
| `slug`          | `string`         | Model slug for API calls |
| `name`          | `string`         | Display name             |
| `description`   | `string`         | Model description        |
| `category`      | `string`         | Category (e.g. "text-to-image") |
| `input_type`    | `string`         | Input type               |
| `output_type`   | `string`         | Output type              |
| `base_cost`     | `number`         | Base credit cost         |
| `pricing_type`  | `string`         | Pricing model            |
| `thumbnail_url` | `string \| null` | Thumbnail image          |
| `tags`          | `string[]`       | Tags                     |

## Error Handling

The SDK throws typed errors that you can catch and handle:

```typescript
import { PreAPI, InsufficientCreditsError, ModelNotFoundError } from "@preapi.net/sdk";

const client = new PreAPI("your-api-key");

try {
  const result = await client.generate({
    model: "flux-pro",
    input: { prompt: "hello world" },
  });
} catch (error) {
  if (error instanceof InsufficientCreditsError) {
    console.log("Not enough credits! Add more at https://preapi.net/dashboard");
  } else if (error instanceof ModelNotFoundError) {
    console.log("Model not found. Check available models with client.models.list()");
  }
}
```

### Error Classes

| Class                      | Code                    | HTTP | Description                    |
| -------------------------- | ----------------------- | ---- | ------------------------------ |
| `AuthenticationError`      | `UNAUTHORIZED`          | 401  | Invalid or missing API key     |
| `InsufficientCreditsError` | `INSUFFICIENT_CREDITS`  | 402  | Not enough credits             |
| `ModelNotFoundError`       | `MODEL_NOT_FOUND`       | 404  | Model slug not found           |
| `RateLimitError`           | `RATE_LIMITED`          | 429  | Too many requests              |
| `ProviderError`            | `PROVIDER_ERROR`        | 502  | Upstream AI provider error     |
| `PreAPIError`              | *(varies)*              | *    | Base error class               |

All errors include `status`, `code`, `message`, and `requestId` properties.

## CommonJS

```javascript
const { PreAPI } = require("@preapi.net/sdk");

const client = new PreAPI("your-api-key");
```

## Requirements

- Node.js 18+ (or any environment with native `fetch`)
- PreAPI API key — get one at [preapi.net](https://preapi.net)

## License

MIT — VectorLabs LLC