npm package: @peeranat-dan/analytics
Description: A centralized analytics library supporting Google Analytics, and PostHog
Author: peeranat-dan
Latest version: 0.0.1

# Centralized Analytics Library

A TypeScript ESModule library that provides a unified interface for analytics providers including Google Analytics and PostHog.

## Features

- **Universal Interface**: Single API for multiple analytics providers
- **TypeScript Support**: Full type safety and IntelliSense
- **ESModule**: Modern ES modules support
- **Async/Await**: Promise-based APIs
- **Error Handling**: Built-in error handling and logging
- **Flexible Configuration**: Easy to configure and extend

## Installation

```bash
npm install @peeranat-dan/analytics
```

Install the peer dependencies for the analytics providers you want to use:

```bash
# For Google Analytics
npm install gtag

# For PostHog
npm install posthog-js
```

## Usage

### Basic Setup

```typescript
import {
  createAnalyticsManager,
  GoogleAnalyticsAdapter,
  PostHogAdapter,
} from "@analytics/analytics";

// Create adapters
const googleAnalytics = new GoogleAnalyticsAdapter({
  measurementId: "G-XXXXXXXXXX",
  config: {
    send_page_view: false, // We'll handle page views manually
  },
});

const posthog = new PostHogAdapter({
  apiKey: "your-posthog-api-key",
  options: {
    api_host: "https://app.posthog.com",
  },
});

// Create analytics manager
const analytics = createAnalyticsManager({
  adapters: [googleAnalytics, posthog],
  enableConsoleLogging: true,
  enableErrorHandling: true,
});

// Initialize
await analytics.initialize();
```

### Tracking Events

```typescript
// Track a simple event
await analytics.track({
  name: "button_clicked",
  properties: {
    button_id: "signup",
    page: "homepage",
  },
});

// Track with user context
await analytics.track({
  name: "purchase_completed",
  properties: {
    product_id: "prod_123",
    price: 29.99,
    currency: "USD",
  },
  userId: "user_456",
});
```

### Identifying Users

```typescript
await analytics.identify({
  id: "user_123",
  properties: {
    email: "user@example.com",
    name: "John Doe",
    subscription_tier: "premium",
  },
});
```

### Page Views

```typescript
// Track current page
await analytics.page();

// Track specific page
await analytics.page("Homepage", {
  section: "landing",
  experiment: "variant_a",
});
```

### Resetting User Data

```typescript
// Reset user data (useful for logout)
await analytics.reset();
```

### Managing Adapters

```typescript
// Add adapter dynamically
const newAdapter = new PostHogAdapter({ apiKey: "another-key" });
analytics.addAdapter(newAdapter);

// Remove adapter
analytics.removeAdapter(posthog);

// Get all adapters
const adapters = analytics.getAdapters();
```

### Cleanup

```typescript
// Clean up resources when done
await analytics.cleanup();
```

## Configuration Options

### AnalyticsConfig

```typescript
interface AnalyticsConfig {
  adapters: AnalyticsAdapter[];
  enableConsoleLogging?: boolean; // Default: false
  enableErrorHandling?: boolean; // Default: false
}
```

### Google Analytics Config

```typescript
interface GoogleAnalyticsConfig {
  measurementId: string;
  config?: {
    custom_map?: Record<string, string>;
    send_page_view?: boolean;
    [key: string]: unknown;
  };
}
```

### PostHog Config

```typescript
interface PostHogConfig {
  apiKey: string;
  options?: {
    api_host?: string;
    ui_host?: string;
    loaded?: (posthog: unknown) => void;
    [key: string]: unknown;
  };
}
```

## Event Structure

```typescript
interface AnalyticsEvent {
  name: string;
  properties?: Record<string, unknown>;
  userId?: string;
  timestamp?: Date;
}

interface AnalyticsUser {
  id: string;
  properties?: Record<string, unknown>;
}
```

## Error Handling

The library includes built-in error handling. When `enableErrorHandling` is true, individual adapter failures won't crash the entire analytics system:

```typescript
const analytics = createAnalyticsManager({
  adapters: [googleAnalytics, posthog],
  enableErrorHandling: true, // Prevents individual adapter failures from throwing
  enableConsoleLogging: true, // Logs errors to console
});
```

## Building

```bash
npm run build
```

## Development

```bash
npm run dev  # Watch mode
```

## License

MIT