npm package: @revhold/node
Description: Official Node.js SDK for RevHold - AI business assistant for SaaS analytics
Author: RevHold
Latest version: 1.0.0

# @revhold/node

Official Node.js SDK for [RevHold](https://www.revhold.io) - AI business assistant for SaaS analytics.

## Installation

```bash
npm install @revhold/node
# or
yarn add @revhold/node
```

## Quick Start

```typescript
import { RevHold } from '@revhold/node';

const revhold = new RevHold({
  apiKey: process.env.REVHOLD_API_KEY,
});

// Track a usage event
await revhold.trackEvent({
  userId: 'user_123',
  eventName: 'document_created',
  eventValue: 1,
});

// Ask AI a question
const insight = await revhold.askAI({
  question: 'Which users are most engaged this week?',
});
console.log(insight.answer);
```

## API Reference

### Constructor

```typescript
const revhold = new RevHold({
  apiKey: string;       // Required: Your RevHold API key
  baseURL?: string;     // Optional: Override API base URL
});
```

### trackEvent(params)

Track a single usage event.

```typescript
await revhold.trackEvent({
  userId: 'user_123',           // Required
  eventName: 'feature_used',    // Required
  eventValue: 1,                // Optional, defaults to 1
  timestamp: '2025-01-07T...',  // Optional, defaults to now
});
```

**Returns:** `Promise<TrackEventResponse>`

```typescript
{
  success: boolean;
  message: string;
  eventId: string;
}
```

### trackBatch(events)

Track multiple events efficiently.

```typescript
await revhold.trackBatch([
  { userId: 'user_1', eventName: 'feature_used' },
  { userId: 'user_2', eventName: 'document_created' },
  { userId: 'user_3', eventName: 'export_completed' },
]);
```

**Returns:** `Promise<{ success: boolean; message: string; count: number }>`

### askAI(params)

Ask the AI a question about your usage data.

```typescript
const result = await revhold.askAI({
  question: 'Which users are most engaged this week?',
});

console.log(result.answer);      // AI-generated insight
console.log(result.confidence);  // 'high' | 'medium' | 'low'
console.log(result.dataPoints);  // Number of events analyzed
```

**Returns:** `Promise<AskAIResponse>`

```typescript
{
  answer: string;
  confidence: 'high' | 'medium' | 'low';
  dataPoints: number;
}
```

### getUsage(options?)

Retrieve recent usage events.

```typescript
const usage = await revhold.getUsage({
  limit: 10,               // Optional: max 1000
  userId: 'user_123',      // Optional: filter by user
});

console.log(usage.events);
console.log(usage.total);
```

**Returns:** `Promise<GetUsageResponse>`

```typescript
{
  events: Array<{
    eventId: string;
    userId: string;
    eventName: string;
    eventValue: number;
    timestamp: string;
  }>;
  total: number;
  limit: number;
}
```

## Error Handling

The SDK throws `RevHoldError` for all API errors:

```typescript
import { RevHold, RevHoldError } from '@revhold/node';

try {
  await revhold.trackEvent({
    userId: 'user_123',
    eventName: 'feature_used',
  });
} catch (error) {
  if (error instanceof RevHoldError) {
    console.error('Status:', error.status);
    console.error('Code:', error.code);
    console.error('Message:', error.message);
    
    if (error.status === 429) {
      console.log('Rate limit - retry after 60s');
    } else if (error.status === 402) {
      console.log('Plan limit reached - upgrade');
    }
  }
}
```

### Error Properties

- `status: number` - HTTP status code (401, 402, 429, 500, etc.)
- `code: string` - Machine-readable error code
- `message: string` - Human-readable error message
- `details?: any` - Additional error context

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions.

```typescript
import type { 
  TrackEventParams,
  AskAIParams,
  TrackEventResponse,
  AskAIResponse,
  UsageEvent,
} from '@revhold/node';
```

## Examples

### Track user activity

```typescript
// When a user creates a document
await revhold.trackEvent({
  userId: req.user.id,
  eventName: 'document_created',
  eventValue: 1,
});

// When a user exports data
await revhold.trackEvent({
  userId: req.user.id,
  eventName: 'data_exported',
  eventValue: 1,
});
```

### Batch tracking

```typescript
// Track multiple events efficiently
const events = users.map(user => ({
  userId: user.id,
  eventName: 'daily_active',
  eventValue: 1,
}));

await revhold.trackBatch(events);
```

### AI insights

```typescript
// Get churn insights
const churnAnalysis = await revhold.askAI({
  question: 'Which users are at risk of churning?',
});

// Identify upsell opportunities
const upsellOpportunities = await revhold.askAI({
  question: 'Which trial users are most likely to upgrade?',
});

// Analyze feature adoption
const featureAdoption = await revhold.askAI({
  question: 'What features do power users use most?',
});
```

## Rate Limits

- **Usage events:** 1,000 requests/minute
- **AI questions:** 10 requests/minute
- **Get usage:** 100 requests/minute

Rate limit info is included in error responses:

```typescript
catch (error) {
  if (error.status === 429) {
    console.log('Retry after:', error.details?.retryAfter);
  }
}
```

## Support

- 📖 [Documentation](https://www.revhold.io/docs)
- 📚 [API Reference](https://www.revhold.io/api-reference)
- 💬 [Contact Support](https://www.revhold.io/contact)

## License

MIT