npm package: @hangarx/helix-js
Description: Helix Analytics JavaScript SDK for browser environments
Author: Helix SDK Team
Latest version: 1.0.0

# Helix SDK JavaScript Tracking Library

A lightweight, high-performance JavaScript tracking library with **Tinybird integration** for ultra-fast analytics. Events are automatically stored in Tinybird for 10-25x faster queries while maintaining reliability through dual storage.

## ⚡ Tinybird Integration

All events tracked by the Helix SDK are automatically stored in **Tinybird** for high-performance analytics:

- **🚀 10-25x faster** analytics queries vs traditional databases
- **📊 Real-time ingestion** without processing delays  
- **🔄 Automatic partitioning** by month for optimal performance
- **📈 Unlimited scalability** for growing event volumes
- **🛡️ Dual storage** with Supabase fallback for reliability

## 🚀 Quick Start

### Option 1: Script Tag (Recommended)

Add this to your HTML `<head>` or before closing `</body>`:

```html
<script>
  // Configuration
  window.helixConfig = {
    apiKey: 'your-api-key-here',
    endpoint: 'https://api.helix.com/v1/track',
    debug: false // Set to true for development
  };
</script>
<script src="https://cdn.helix.com/helix.min.js"></script>
```

### Option 2: Self-Hosted

1. Download `helix.min.js` from this repository
2. Host it on your CDN or server
3. Include it in your HTML:

```html
<script>
  window.helixConfig = {
    apiKey: 'your-api-key-here',
    endpoint: 'https://api.helix.com/v1/track'
  };
</script>
<script src="/path/to/helix.min.js"></script>
```

### Option 3: NPM Module

```bash
npm install @helix/analytics-js
```

```javascript
import HelixAnalytics from '@helix/analytics-js';

const helix = new HelixAnalytics({
  apiKey: 'your-api-key-here',
  endpoint: 'https://api.helix.com/v1/track'
});
```

## 📊 Usage

Once loaded, the global `helix` object is available:

### Track Events
```javascript
// Basic event tracking
helix.track('Button Clicked', {
  button: 'signup',
  page: 'homepage',
  campaign: 'summer-sale'
});

// E-commerce tracking
helix.track('Purchase Completed', {
  product: 'Premium Plan',
  amount: 99.99,
  currency: 'USD',
  transaction_id: 'txn_123456'
});
```

### Identify Users
```javascript
helix.identify('user123', {
  email: 'user@example.com',
  plan: 'premium',
  signup_date: '2025-01-15'
});
```

### Track Page Views
```javascript
// Manual page tracking
helix.page('Homepage', {
  section: 'hero',
  campaign: 'summer-sale'
});

// Automatic page tracking is enabled by default
// Tracks initial page load and SPA navigation
```

### Reset Session
```javascript
// Clear user data and start new session
helix.reset();
```

## ⚙️ Configuration Options

```javascript
window.helixConfig = {
  // Required
  apiKey: 'your-api-key-here',
  
  // Optional
  endpoint: 'https://api.helix.com/v1/track', // Default endpoint
  debug: false,                               // Enable debug logging
  batchSize: 20,                             // Events per batch
  flushInterval: 10000,                      // Flush interval in ms
  
  // Multi-destination support
  destinations: [
    {
      type: 'ga4',
      config: {
        measurementId: 'G-XXXXXXXXXX',
        apiSecret: 'your-ga4-api-secret'
      }
    },
    {
      type: 'mixpanel',
      config: {
        token: 'your-mixpanel-token'
      }
    }
  ]
};
```

## 🎯 Features

### ⚡ High-Performance Analytics
- **Tinybird Integration**: Events automatically stored in Tinybird for 10-25x faster queries
- **Real-time Ingestion**: Instant event processing without delays
- **Dual Storage**: Primary Tinybird storage with Supabase fallback for reliability
- **Columnar Storage**: Optimized for analytical workloads and complex queries

### ✅ Automatic Tracking
- **Page Views**: Automatically tracks initial page load and SPA navigation
- **Session Management**: Generates and maintains session IDs
- **Context Collection**: Automatically captures page, screen, and browser data
- **SPA Support**: Intelligent single-page application navigation tracking

### ✅ Performance Optimized
- **Batch Processing**: Groups events for efficient network usage (20 events/batch)
- **Async Operations**: Non-blocking event tracking
- **Error Handling**: Robust retry logic for failed requests
- **Lightweight**: Only 5.18 KB minified and gzipped

### ✅ Multi-Destination Support
- **Helix API + Tinybird**: Primary high-performance analytics destination
- **Google Analytics 4**: Direct GA4 integration
- **Mixpanel**: Direct Mixpanel integration
- **Extensible**: Easy to add more destinations

### ✅ Developer Friendly
- **TypeScript Support**: Full type definitions included
- **Debug Mode**: Detailed logging for development
- **Browser Compatibility**: Works in all modern browsers
- **No Dependencies**: Zero external dependencies

## 🔧 Advanced Usage

### Custom Event Context
```javascript
helix.track('Video Played', {
  video_id: 'intro-video',
  duration: 120,
  quality: '1080p'
});
```

### User Properties
```javascript
helix.identify('user123', {
  email: 'user@example.com',
  plan: 'premium',
  company: 'Acme Corp',
  signup_date: '2025-01-15',
  total_purchases: 5
});
```

### Page Properties
```javascript
helix.page('Product Page', {
  product_id: 'prod_123',
  category: 'software',
  price: 99.99,
  in_stock: true
});
```

## 🛠️ Development

### Building from Source

```bash
# Install dependencies
npm install

# Build minified version
npm run build

# Development build with watching
npm run dev

# Run tests
npm test
```

### File Structure
```
sdk/javascript/
├── src/
│   └── index.ts          # Main SDK source
├── dist/
│   ├── helix.min.js      # Minified production build
│   └── index.d.ts        # TypeScript definitions
├── example.html          # Demo page
├── webpack.config.js     # Build configuration
├── tsconfig.json         # TypeScript configuration
└── package.json          # Package configuration
```

## 🔄 Tinybird Data Flow

Events flow seamlessly from your website to Tinybird for high-performance analytics:

```
JavaScript SDK → Helix API Backend → Tinybird Primary Storage
                                  ↘ Supabase Fallback Storage
```

### Event Processing Pipeline:
1. **SDK Collection**: Events collected in browser with automatic context
2. **Batch Processing**: Events batched for efficient network usage
3. **API Authentication**: Secure Bearer token authentication
4. **Event Enrichment**: IP address, timestamps, and context enhancement
5. **Tinybird Storage**: Primary storage in Tinybird analytics_events datasource
6. **Fallback Protection**: Automatic Supabase storage if Tinybird unavailable

### Tinybird Schema Mapping:
```javascript
// SDK Event → Tinybird Transformation
{
  event_id: "company_timestamp_random",     // Unique event identifier
  company_id: "your-company-id",            // Company context
  type: "track",                            // Event type (track/identify/page/screen)
  user_id: "user123",                       // User identifier
  session_id: "sess_abc123",                // Session identifier
  event_name: "Button Clicked",             // Event name
  properties: "{\"button\":\"signup\"}",    // JSON-encoded properties
  traits: "{}",                             // JSON-encoded user traits
  context: "{\"page\":{...}}",              // JSON-encoded context
  timestamp: "2025-09-15T20:00:00Z",        // Event timestamp
  received_at: "2025-09-15T20:00:00Z",      // Server receipt time
  processed: "false",                       // Processing status
  ip_address: "192.168.1.100",             // Client IP address
  user_agent: "Mozilla/5.0...",            // Browser user agent
  url: "https://example.com/page",          // Page URL
  referrer: "https://google.com",           // Page referrer
  page_title: "Page Title",                 // Page title
  screen_width: 1920,                       // Screen width
  screen_height: 1080                       // Screen height
}
```

## 📈 Event Data Structure

All events include this automatic context:

```javascript
{
  type: 'track',           // Event type
  event: 'Button Clicked', // Event name
  properties: { ... },     // Custom properties
  userId: 'user123',       // User ID (if identified)
  sessionId: 'sess_...',   // Auto-generated session ID
  timestamp: '2025-01-15T10:30:00.000Z',
  context: {
    page: {
      url: 'https://example.com/page',
      title: 'Page Title',
      path: '/page',
      referrer: 'https://google.com'
    },
    screen: {
      width: 1920,
      height: 1080
    },
    library: {
      name: '@helix/analytics-js',
      version: '1.0.0'
    },
    userAgent: 'Mozilla/5.0...'
  }
}
```

## 🔒 Privacy & Security

- **No PII Collection**: Only collects data you explicitly send
- **Secure Transport**: All data sent over HTTPS
- **Configurable**: Full control over what data is tracked
- **GDPR Compliant**: Respects user privacy preferences

## 📱 Browser Support

- **Chrome**: 60+
- **Firefox**: 55+
- **Safari**: 12+
- **Edge**: 79+
- **Mobile**: iOS Safari 12+, Chrome Mobile 60+

## 🐛 Debugging

Enable debug mode to see detailed logging:

```javascript
window.helixConfig = {
  apiKey: 'your-api-key',
  debug: true // Enable debug logging
};
```

Debug logs will show