npm package: @orville-wang/nomos-sdk
Description: Official Nomos SDK for event tracking and analytics.
Author: Nomos Team
Latest version: 0.1.2

# @nomos/sdk

Official Nomos SDK for event tracking and analytics. Track user behavior, events, and analytics data with ease.

## Features

- 🚀 Simple and intuitive API
- 🔒 Secure HMAC-SHA256 request signing
- 📦 Automatic event batching and queuing
- 🔄 Automatic retry with exponential backoff
- 🌐 Works in both browser and Node.js environments
- 📝 Full TypeScript support
- ⚡ Lightweight with minimal dependencies

## Installation

```bash
npm install @nomos/sdk
```

Or with yarn:

```bash
yarn add @nomos/sdk
```

Or with pnpm:

```bash
pnpm add @nomos/sdk
```

## Quick Start

```typescript
import NomosSDK from '@nomos/sdk';

// Initialize the SDK
const nomos = new NomosSDK({
  projectId: 'your_project_id',
  secretKey: 'your_secret_key',
  apiUrl: 'http://localhost:8504', // Optional, defaults to production
});

// Track an event
await nomos.track('page_view', {
  page: '/home',
  referrer: 'google',
});

// Identify a user after login
nomos.identify('user_01HXXX');

// Track user events
await nomos.track('button_click', {
  button_name: 'subscribe',
  plan: 'premium',
});
```

## API Reference

### Constructor

```typescript
new NomosSDK(config: NomosConfig)
```

**Configuration Options:**

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `projectId` | string | Yes | - | Your project ID from Nomos dashboard |
| `secretKey` | string | Yes | - | Secret key for HMAC signature |
| `apiUrl` | string | No | `https://api.nomos.com` | API base URL (base only; trailing `/` is trimmed) |
| `batchSize` | number | No | `10` | Number of events to batch before auto-flush |
| `flushInterval` | number | No | `5000` | Auto-flush interval in milliseconds |
| `maxRetries` | number | No | `3` | Maximum retry attempts for failed requests |
| `debug` | boolean | No | `false` | Enable debug logging |

### Methods

#### `track(eventName, properties?, metadata?)`

Track a single event.

```typescript
await nomos.track('event_name', {
  // Custom properties
  key: 'value',
}, {
  // Optional metadata
  platform: 'web',
  browser: 'Chrome',
});
```

**Parameters:**
- `eventName` (string): Name of the event
- `properties` (object, optional): Custom event properties
- `metadata` (object, optional): Device and session metadata

#### `trackBatch(events)`

Track multiple events in a batch.

```typescript
await nomos.trackBatch([
  { event_name: 'event1', properties: { a: 1 } },
  { event_name: 'event2', properties: { b: 2 } },
]);
```

#### `identify(userId)`

Identify a logged-in user.

```typescript
nomos.identify('user_01HXXX');
```

**Parameters:**
- `userId` (string): User ID in ULID format (26 characters)

#### `setDistinctId(distinctId)`

Set an anonymous user ID.

```typescript
nomos.setDistinctId('anon_01HXXX');
```

**Parameters:**
- `distinctId` (string): Anonymous user ID in ULID format (26 characters)

#### `flush()`

Manually flush the event queue.

```typescript
await nomos.flush();
```

#### `destroy()`

Clean up and destroy the SDK instance.

```typescript
nomos.destroy();
```

## Usage Examples

### Basic Event Tracking

```typescript
import NomosSDK from '@nomos/sdk';

const nomos = new NomosSDK({
  projectId: 'proj_01HXXX',
  secretKey: 'sk_xxxxxxxxxxxxxxxx',
});

// Track page views
await nomos.track('page_view', {
  page: '/products',
  category: 'electronics',
});

// Track button clicks
await nomos.track('button_click', {
  button_id: 'checkout',
  location: 'header',
});
```

### User Identification

```typescript
// Anonymous user tracking
nomos.track('product_view', {
  product_id: 'prod_123',
});

// User logs in
nomos.identify('user_01HXXX');

// Now events are associated with the user
nomos.track('add_to_cart', {
  product_id: 'prod_123',
  quantity: 1,
});
```

### Batch Tracking

```typescript
// Track multiple events at once
await nomos.trackBatch([
  {
    event_name: 'page_view',
    properties: { page: '/home' },
  },
  {
    event_name: 'button_click',
    properties: { button: 'signup' },
  },
  {
    event_name: 'form_submit',
    properties: { form: 'newsletter' },
  },
]);
```

### Custom Configuration

```typescript
const nomos = new NomosSDK({
  projectId: 'proj_01HXXX',
  secretKey: 'sk_xxxxxxxxxxxxxxxx',
  apiUrl: 'https://analytics.example.com',
  batchSize: 20,           // Batch 20 events before auto-flush
  flushInterval: 10000,    // Flush every 10 seconds
  maxRetries: 5,           // Retry up to 5 times
  debug: true,             // Enable debug logging
});
```

### Error Handling

```typescript
try {
  await nomos.track('event_name', { key: 'value' });
} catch (error) {
  console.error('Failed to track event:', error);
}

// Or use flush to ensure events are sent
await nomos.flush();
```

### Cleanup

```typescript
// When done, clean up the SDK
nomos.destroy();
```

## Event Structure

Events sent to Nomos have the following structure:

```typescript
{
  event_id: string;        // Unique event ID (auto-generated)
  event_name: string;      // Event name
  project_id: string;      // Your project ID
  user_id?: string;        // Logged-in user ID (ULID, 26 chars)
  distinct_id?: string;    // Anonymous user ID (ULID, 26 chars)
  timestamp: number;       // Event timestamp in milliseconds
  properties?: object;     // Custom event properties
  metadata?: object;       // Device and session metadata
}
```

**Note:** Either `user_id` or `distinct_id` must be present. The SDK automatically manages this based on whether you've called `identify()`.

## TypeScript Support

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

```typescript
import NomosSDK, {
  type NomosConfig,
  type Event,
  type EventProperties
} from '@nomos/sdk';

const config: NomosConfig = {
  projectId: 'proj_01HXXX',
  secretKey: 'sk_xxxxxxxxxxxxxxxx',
};

const nomos = new NomosSDK(config);
```

## Development

### Install Dependencies

```bash
npm install
```

### Run Tests

```bash
npm run test
```

### Build

```bash
npm run build
```

### Type Check

```bash
npm run typecheck
```

## License

MIT

## Support

For issues and questions, please visit [GitHub Issues](https://github.com/nomos/sdk/issues).