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

# Node SDK

> TypeScript/Node.js client for the pre.dev Architect API - Generate comprehensive software specifications

A TypeScript/Node.js client library for the pre.dev Architect API. Generate comprehensive software specifications using AI-powered analysis.

## Features

* 🚀 **Fast Spec**: Generate comprehensive specifications quickly - perfect for MVPs and prototypes
* 🔍 **Deep Spec**: Generate ultra-detailed specifications for complex systems with enterprise-grade depth
* ⚡ **Async Spec**: Non-blocking async methods for long-running requests
* 📊 **Status Tracking**: Check the status of async specification generation requests
* 💳 **Credits Management**: Check your remaining prototype credits balance
* ✨ **Full TypeScript Support**: Complete type definitions for better IDE support
* 🛡️ **Error Handling**: Custom exceptions for different error scenarios
* 🌐 **Modern ES Modules**: Uses ES6+ import/export syntax

## Installation

Install the pre.dev Node SDK using npm:

```bash theme={null}
npm install predev-api
```

## Quick Start

```typescript theme={null}
import { PredevAPI } from 'predev-api';

// Initialize the predev client with your API key
const predev = new PredevAPI({ apiKey: 'your_api_key_here' });

// Generate a fast specification
const result = await predev.fastSpec({
  input: 'Build a SaaS project management tool with team collaboration'
});

console.log(result);
```

## Authentication

The Pre.dev API uses API key authentication. Get your API key from the [pre.dev dashboard](https://pre.dev/projects/playground) under Settings → API Keys:

```typescript theme={null}
const predev = new PredevAPI({ apiKey: 'your_api_key' });
```

## API Methods

### Synchronous Methods

#### fastSpec()

Generate a fast specification (30-40 seconds, \~5-10 credits).

```typescript theme={null}
const result = await predev.fastSpec({
  input: 'Build a SaaS project management tool with real-time collaboration'
});
```

**Parameters:**

* `options.input` **(required)**: `string` - Description of what you want to build
* `options.currentContext` **(optional)**: `string` - Existing project context
* `options.docURLs` **(optional)**: `string[]` - Documentation URLs to reference

**Returns:** `Promise<SpecResponse>` object with complete specification data

#### deepSpec()

Generate a deep specification (2-3 minutes, \~10-50 credits).

```typescript theme={null}
const result = await predev.deepSpec({
  input: 'Build a healthcare platform with HIPAA compliance'
});
```

**Parameters:** Same as `fastSpec()`

**Returns:** `Promise<SpecResponse>` object with comprehensive specification data

### Asynchronous Methods

#### fastSpecAsync()

Generate a fast specification asynchronously (returns immediately).

```typescript theme={null}
const result = await predev.fastSpecAsync({
  input: 'Build a comprehensive e-commerce platform'
});
// Returns: { specId: "spec_123", status: "pending" }
```

**Parameters:** Same as `fastSpec()`

**Returns:** `Promise<AsyncResponse>` object with `specId` for polling

#### deepSpecAsync()

Generate a deep specification asynchronously (returns immediately).

```typescript theme={null}
const result = await predev.deepSpecAsync({
  input: 'Build a fintech platform with regulatory compliance'
});
// Returns: { specId: "spec_456", status: "pending" }
```

**Parameters:** Same as `fastSpec()`

**Returns:** `Promise<AsyncResponse>` object with `specId` for polling

### Status Checking

#### getSpecStatus()

Check the status of an async specification generation request.

```typescript theme={null}
const status = await predev.getSpecStatus('spec_123');
// Returns full SpecResponse with status: "pending" | "processing" | "completed" | "failed"
```

**Parameters:**

* `specId` **(required)**: `string` - The specification ID from async methods

**Returns:** `Promise<SpecResponse>` object with current status and data (when completed)

### Credits Management

#### getCreditsBalance()

Get the remaining prototype credits balance for your API key.

```typescript theme={null}
const balance = await predev.getCreditsBalance();
// Returns: { success: true, creditsRemaining: 450 }
```

**Parameters:** None

**Returns:** `Promise<CreditsBalanceResponse>` object with credits remaining

**Example:**

```typescript theme={null}
const balance = await predev.getCreditsBalance();
if (balance.creditsRemaining < 50) {
  console.log(`Low credits: ${balance.creditsRemaining} remaining`);
} else {
  console.log(`Credits available: ${balance.creditsRemaining}`);
}
```

### Listing and Searching Specs

#### listSpecs()

List all specs with optional filtering and pagination.

```typescript theme={null}
// Get first 20 specs
const result = await predev.listSpecs();

// Get completed specs only
const completed = await predev.listSpecs({ status: 'completed' });

// Paginate: get specs 20-40
const page2 = await predev.listSpecs({ skip: 20, limit: 20 });

// Filter by endpoint type
const fastSpecs = await predev.listSpecs({ endpoint: 'fast_spec' });
```

**Parameters:**

* `params.limit` **(optional)**: `number` - Results per page (1-100, default: 20)
* `params.skip` **(optional)**: `number` - Offset for pagination (default: 0)
* `params.endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type
* `params.status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status

**Returns:** `Promise<ListSpecsResponse>` object with specs array and pagination metadata

#### findSpecs()

Search for specs using regex patterns.

```typescript theme={null}
// Search for "payment" specs
const paymentSpecs = await predev.findSpecs({ query: 'payment' });

// Search for specs starting with "Build"
const buildSpecs = await predev.findSpecs({ query: '^Build' });

// Search: only completed specs mentioning "auth"
const authSpecs = await predev.findSpecs({ 
  query: 'auth', 
  status: 'completed' 
});

// Complex regex: find SaaS or SASS projects
const saasSpecs = await predev.findSpecs({ query: 'saas|sass' });
```

**Parameters:**

* `params.query` **(required)**: `string` - Regex pattern (case-insensitive)
* `params.limit` **(optional)**: `number` - Results per page (1-100, default: 20)
* `params.skip` **(optional)**: `number` - Offset for pagination (default: 0)
* `params.endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type
* `params.status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status

**Returns:** `Promise<ListSpecsResponse>` object with matching specs and pagination metadata

**Regex Pattern Examples:**

|| Pattern | Matches |
||---------|---------|
|| `payment` | "payment", "Payment", "make payment" |
|| `^Build` | Specs starting with "Build" |
|| `platform$` | Specs ending with "platform" |
|| `(API\|REST)` | Either "API" or "REST" |
|| `auth.*system` | "auth" then anything then "system" |
|| `\\d{3,}` | 3+ digits (budgets, quantities) |
|| `saas\|sass` | SaaS or SASS |

## File Upload Support

All `fastSpec`, `deepSpec`, `fastSpecAsync`, and `deepSpecAsync` methods support optional file uploads. This allows you to provide architecture documents, requirements files, design mockups, RFPs (Request for Proposals), or other context files to improve specification generation.

### Browser/Web Environment

```typescript theme={null}
// Using File input from HTML form
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

const result = await predev.fastSpec({
  input: 'Generate specs based on this design document',
  file: file // Pass the File object directly
});
```

### Node.js Environment

```typescript theme={null}
import fs from 'fs';

// Method 1: Using file path (simplest)
const result = await predev.fastSpec({
  input: 'Build based on these requirements',
  file: {
    data: fs.readFileSync('requirements.pdf'),
    name: 'requirements.pdf'
  }
});

// Method 2: Using file object
const fileContent = fs.readFileSync('architecture.doc');
const result = await predev.deepSpec({
  input: 'Create comprehensive specs',
  file: {
    data: fileContent,
    name: 'architecture.doc'
  }
});
```

### Supported File Types

* PDF documents (`*.pdf`)
* Word documents (`*.doc`, `*.docx`)
* Text files (`*.txt`)
* Images (`*.jpg`, `*.png`, `*.jpeg`)

### Response with File Upload

When you upload a file, the response includes:

```typescript theme={null}
{
  uploadedFileName?: string;      // Name of the uploaded file
  uploadedFileShortUrl?: string;  // URL to access the file
  codingAgentSpecUrl?: string;    // Spec optimized for AI systems
  humanSpecUrl?: string;          // Spec optimized for humans
  // ... other fields
}
```

## Response Types

### AsyncResponse

```typescript theme={null}
{
  specId: string;      // Unique ID for polling (e.g., "spec_abc123")
  status: "pending" | "processing" | "completed" | "failed";
}
```

### SpecResponse

```typescript theme={null}
interface SpecResponse {
  // Basic info
  _id?: string;                    // Internal ID
  created?: string;                // ISO timestamp
  endpoint: "fast_spec" | "deep_spec";
  input: string;                   // Original input text
  status: "pending" | "processing" | "completed" | "failed";
  success: boolean;
  uploadedFileShortUrl?: string;   // URL to input file
  uploadedFileName?: string;       // Name of input file

  // Output data (when completed)
  humanSpecUrl?: string;           // URL to human-readable spec
  humanSpecMarkdown?: string;      // Full markdown SOW for humans/clients
  humanSpecJson?: HumanSpecJson;   // Full structured SOW JSON (hours/personas/roles)
  totalHumanHours?: number;        // Estimated hours for human implementation
  codingAgentSpecUrl?: string;         // URL to coding agent spec format
  codingAgentSpecMarkdown?: string;    // Direct markdown SOW for AI tools
  codingAgentSpecJson?: CodingAgentSpecJson; // Direct structured SOW JSON for AI tools
  executionTime?: number;          // Processing time in milliseconds

  // Integration URLs (when completed)
  predevUrl?: string;              // Link to pre.dev project

  // Error handling
  errorMessage?: string;           // Error details if failed
  progress?: number;               // Overall progress percentage (0-100)
  progressMessage?: string;        // Detailed progress message (e.g., "Generating User Stories...")
}

interface CodingAgentSpecJson {
  title?: string;
  executiveSummary: string;
  coreFunctionalities: SpecCoreFunctionality[];
  techStack: SpecTechStackItem[];
  techStackGrouped: Record<string, string[]>;
  milestones: CodingAgentMilestone[];
}

interface CodingAgentMilestone {
  milestoneNumber: number;
  description: string;
  stories: CodingAgentStory[];
}

interface CodingAgentStory {
  id?: string;
  title: string;
  description?: string;
  acceptanceCriteria?: string[];
  complexity?: string;
  subTasks: CodingAgentSubTask[];
}

interface CodingAgentSubTask {
  id?: string;
  description: string;
  complexity: string; // "S" | "M" | "L" | "XL"
}

interface HumanSpecJson {
  title?: string;
  executiveSummary: string;
  coreFunctionalities: SpecCoreFunctionality[];
  personas: SpecPersona[];
  techStack: SpecTechStackItem[];
  techStackGrouped: Record<string, string[]>;
  milestones: HumanSpecMilestone[];
  totalHours: number;
  roles: SpecRole[];
}

interface HumanSpecMilestone {
  milestoneNumber: number;
  description: string;
  hours: number;
  stories: HumanSpecStory[];
}

interface HumanSpecStory {
  id?: string;
  title: string;
  description?: string;
  acceptanceCriteria?: string[];
  hours: number;
  complexity?: string;
  subTasks: HumanSpecSubTask[];
}

interface HumanSpecSubTask {
  id?: string;
  description: string;
  hours: number;
  complexity: string;
  roles?: SpecRole[];
}

interface SpecPersona {
  title: string;
  description: string;
  primaryGoals?: string[];
  painPoints?: string[];
  keyTasks?: string[];
}

interface SpecRole {
  name: string;
  shortHand: string;
}

interface SpecCoreFunctionality {
  name: string;
  description: string;
  priority?: string; // "High" | "Medium" | "Low"
}

interface SpecTechStackItem {
  name: string;
  category: string;
}
```

### ListSpecsResponse

```typescript theme={null}
{
  specs: SpecResponse[];  // Array of spec objects
  total: number;          // Total count of matching specs
  hasMore: boolean;       // Whether more results are available
}
```

### CreditsBalanceResponse

```typescript theme={null}
{
  success: boolean;
  creditsRemaining: number;
}
```

## Examples

### Generate Fast Spec

````typescript theme={null}
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

const result = await predev.fastSpec({
  input: 'Build a SaaS project management tool with team collaboration',
});

console.log(`Specification URL: ${result.humanSpecUrl}`);
```### Generate Deep Spec with Context

```typescript
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

const result = await predev.deepSpec({
  input: 'Add advanced analytics dashboard',
  currentContext: 'Existing e-commerce platform with user auth and product catalog',
});

console.log(result.codingAgentSpecUrl);
````

### With Documentation URLs

```typescript theme={null}
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

const result = await predev.fastSpec({
  input: 'Build a customer support ticketing system',
  docURLs: ['https://docs.pre.dev', 'https://docs.stripe.com'],
});
```

### Async Workflow with Polling

````typescript theme={null}
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

async function generateSpec() {
  // Start async generation
  const asyncResult = await predev.fastSpecAsync({
    input: 'Build a social media platform',
  });

  console.log(`Spec ID: ${asyncResult.specId}`);

  // Poll for completion
  let status;
  while (true) {
    status = await predev.getSpecStatus(asyncResult.specId);
    console.log(`Status: ${status.status}`);
    
    if (status.status === 'completed' || status.status === 'failed') {
      break;
    }
    
    await new Promise(resolve => setTimeout(resolve, 5000));
  }

  if (status.status === 'completed') {
    console.log(`Specification URL: ${status.codingAgentSpecUrl}`);
  }
}

generateSpec();
```### List and Filter Specs

```typescript
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

// Get all completed specs
const completed = await predev.listSpecs({ 
  status: 'completed',
  limit: 50 
});

console.log(`Total completed specs: ${completed.total}`);
completed.specs.forEach(spec => {
  console.log(`- ${spec.input} (${spec.endpoint})`);
});
````

### Search Specs with Regex

```typescript theme={null}
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

// Find all payment-related specs
const paymentSpecs = await predev.findSpecs({
  query: 'payment|checkout|billing',
  status: 'completed',
  limit: 20
});

console.log(`Found ${paymentSpecs.total} payment-related specs`);
```

### Check Credits Balance

```typescript theme={null}
import { PredevAPI } from 'predev-api';

const predev = new PredevAPI({ apiKey: 'your_api_key' });

// Get current credit balance
const balance = await predev.getCreditsBalance();
console.log(`Credits remaining: ${balance.creditsRemaining}`);

// Check before making expensive request
if (balance.creditsRemaining >= 50) {
  const result = await predev.deepSpec({
    input: 'Build an enterprise platform'
  });
  console.log(`Spec ready: ${result.codingAgentSpecUrl}`);
} else {
  console.log(`Insufficient credits. Need 50, have ${balance.creditsRemaining}`);
}
```

## Documentation

For more information about the Pre.dev Architect API, visit:

* [API Documentation](https://docs.pre.dev/)
* [pre.dev Website](https://pre.dev/)
* [npm Package](https://www.npmjs.com/package/predev-api)

## Support

For issues, questions, or contributions:

* [GitHub Repository](https://github.com/predotdev/predev-api)
* [Discord Community](https://discord.com/invite/ejVTRJ6WXS)
