npm package: @saastoast/web
Description: Official JavaScript/TypeScript SDK for SaasToast - simple event tracking
Author: SaasToast Team
Latest version: 1.0.1

# @saastoast/web

Official JavaScript/TypeScript SDK for SaasToast - simple event tracking for web applications.

## Features

- 🎯 **Simple Event Tracking** - Track custom events with metadata
- 📊 **Revenue Tracking** - Track purchases, subscriptions, and monetary events
- 🔒 **Type Safe** - Full TypeScript support
- ⚡ **Performance Optimized** - Minimal bundle size with automatic retries
- 📦 **Zero Dependencies** - No external dependencies
- 🌐 **Browser Compatible** - Works in all modern browsers and IE 11+

## Installation

```bash
npm install @saastoast/web
# or
yarn add @saastoast/web
```

### CDN Usage

For direct browser usage without a build system:

```html
<script src="https://unpkg.com/@saastoast/web@latest/dist/index.min.js"></script>
```

## Quick Start

### ES6 Modules

```typescript
import { SaasToast } from '@saastoast/web';

const saastoast = new SaasToast({
  apiKey: 'api_live_your_api_key_here', // Get this from your SaasToast dashboard
  debug: true // Enable debug logging in development
});

// Track an event
await saastoast.track({
  type: 'button_click',
  metadata: {
    button: 'signup',
    location: 'header'
  }
});
```

### Script Tag

```html
<script src="https://unpkg.com/@saastoast/web@latest/dist/index.min.js"></script>
<script>
  const saastoast = new SaasToast({
    apiKey: 'api_live_your_api_key_here'
  });

  saastoast.track({
    type: 'page_view',
    metadata: { page: window.location.pathname }
  });
</script>
```

### Static Factory Method

```typescript
// Create client with just an API key
const saastoast = SaasToast.create('api_live_your_api_key_here');

await saastoast.track({
  type: 'user_signup',
  userId: 'user_123',
  metadata: { plan: 'premium' }
});
```

## Configuration Options

```typescript
const saastoast = new SaasToast({
  /** API key for authentication (required) */
  apiKey: 'api_live_your_key_here',

  /** Base URL for the API (default: 'https://api.saastoast.com') */
  baseUrl: 'https://api.saastoast.com',

  /** Maximum number of retry attempts (default: 3) */
  maxRetries: 3,

  /** Request timeout in milliseconds (default: 10000) */
  timeout: 10000,

  /** Enable debug logging (default: false) */
  debug: false
});
```

## Event Tracking

### Basic Event

```typescript
await saastoast.track({
  type: 'page_view',
  metadata: {
    page: window.location.pathname,
    referrer: document.referrer,
    title: document.title
  }
});
```

### Revenue Event

```typescript
await saastoast.track({
  type: 'purchase_completed',
  userId: 'user_123',
  revenue: 2999, // $29.99 in cents
  currency: 'USD',
  metadata: {
    product_id: 'prod_456',
    payment_method: 'stripe',
    plan: 'premium'
  }
});
```

### Custom Event with Value

```typescript
await saastoast.track({
  type: 'feature_used',
  userId: 'user_123',
  value: 10, // Custom scoring/importance value
  metadata: {
    feature: 'advanced_search',
    query_length: 25,
    results_found: 42
  }
});
```

## Event Interface

```typescript
interface Event {
  /** Event type identifier */
  type: string;

  /** User identifier */
  userId?: string;

  /** Revenue amount in cents */
  revenue?: number;

  /** Currency code (ISO 4217) */
  currency?: string;

  /** Event value for scoring/importance */
  value?: number;

  /** Custom properties */
  metadata?: Record<string, any>;

  /** Event timestamp (defaults to now) */
  timestamp?: Date | string;
}
```

## Response Interface

```typescript
interface TrackResponse {
  /** Whether the request was successful */
  success: boolean;

  /** Event ID from the server */
  eventId?: string;

  /** Error message if failed */
  error?: string;
}
```

## Framework Integration Examples

### React

```tsx
import React, { useEffect } from 'react';
import { SaasToast } from '@saastoast/web';

// Initialize once at app level
const saastoast = new SaasToast({
  apiKey: process.env.REACT_APP_SAASTOAST_API_KEY,
  debug: process.env.NODE_ENV === 'development'
});

function App() {
  const handleSignup = async (userData) => {
    const result = await saastoast.track({
      type: 'user_signup',
      userId: userData.id,
      metadata: {
        source: 'website',
        plan: userData.plan
      }
    });

    if (result.success) {
      console.log('Signup tracked:', result.eventId);
    }
  };

  const handlePurchase = async (orderId: string, amount: number) => {
    await saastoast.track({
      type: 'purchase',
      userId: 'user_123',
      revenue: Math.round(amount * 100), // Convert to cents
      currency: 'USD',
      metadata: {
        order_id: orderId,
        payment_method: 'credit_card'
      }
    });
  };

  return (
    <div>
      <button onClick={() => handleSignup({ id: 'user_123', plan: 'premium' })}>
        Sign Up
      </button>
      <button onClick={() => handlePurchase('order_456', 29.99)}>
        Purchase
      </button>
    </div>
  );
}
```

### Vue.js

```vue
<template>
  <div>
    <button @click="trackFeature">Use Feature</button>
    <button @click="trackPurchase">Purchase</button>
  </div>
</template>

<script>
import { SaasToast } from '@saastoast/web';

export default {
  name: 'Analytics',

  data() {
    return {
      saastoast: null
    };
  },

  created() {
    this.saastoast = new SaasToast({
      apiKey: process.env.VUE_APP_SAASTOAST_API_KEY,
      debug: process.env.NODE_ENV === 'development'
    });
  },

  methods: {
    async trackFeature() {
      await this.saastoast.track({
        type: 'feature_used',
        metadata: {
          feature: 'advanced_search',
          user_type: 'premium'
        }
      });
    },

    async trackPurchase() {
      await this.saastoast.track({
        type: 'purchase_intent',
        metadata: {
          product: 'premium',
          source: 'feature_page'
        }
      });
    }
  }
};
</script>
```

### Angular

```typescript
import { Injectable } from '@angular/core';
import { SaasToast } from '@saastoast/web';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  private saastoast: SaasToast;

  constructor() {
    this.saastoast = new SaasToast({
      apiKey: environment.saastoastApiKey,
      debug: !environment.production
    });
  }

  async track(eventType: string, metadata?: any): Promise<void> {
    const result = await this.saastoast.track({
      type: eventType,
      metadata
    });

    if (!result.success) {
      console.error('Failed to track event:', result.error);
    }
  }
}

// Usage in component:
@Component({
  selector: 'app-dashboard',
  template: '<button (click)="trackAction()">Action</button>'
})
export class DashboardComponent {
  constructor(private analytics: AnalyticsService) {}

  trackAction(): void {
    this.analytics.track('button_click', {
      button: 'dashboard_action',
      location: 'main_content'
    });
  }
}
```

## E-commerce Tracking Examples

### Shopping Cart Events

```typescript
// Product view
await saastoast.track({
  type: 'product_viewed',
  userId: 'user_123',
  metadata: {
    product_id: 'prod_789',
    category: 'electronics',
    price: 299.99,
    name: 'Wireless Headphones'
  }
});

// Add to cart
await saastoast.track({
  type: 'add_to_cart',
  userId: 'user_123',
  value: 1,
  metadata: {
    product_id: 'prod_789',
    quantity: 1,
    price: 299.99
  }
});

// Purchase
await saastoast.track({
  type: 'purchase',
  userId: 'user_123',
  revenue: 29999, // $299.99 in cents
  currency: 'USD',
  metadata: {
    order_id: 'order_456',
    products: ['prod_789'],
    tax: 25.00,
    shipping: 10.00,
    total: 334.99
  }
});
```

### SaaS Application Events

```typescript
// Feature usage
await saastoast.track({
  type: 'feature_used',
  userId: 'user_123',
  metadata: {
    feature: 'export_data',
    format: 'csv',
    rows_exported: 1500
  }
});

// Subscription upgrade
await saastoast.track({
  type: 'subscription_upgraded',
  userId: 'user_123',
  revenue: 4999, // $49.99 monthly
  currency: 'USD',
  value: 12, // Expected months
  metadata: {
    from_plan: 'basic',
    to_plan: 'professional',
    billing_cycle: 'monthly'
  }
});
```

## Error Handling

The SDK handles errors gracefully and returns a response object:

```typescript
const result = await saastoast.track({
  type: 'test_event',
  metadata: { test: true }
});

if (result.success) {
  console.log('Success! Event ID:', result.eventId);
} else {
  console.error('Failed:', result.error);
  // Handle the error appropriately
  // The SDK will have already retried based on your configuration
}
```

### Retry Logic

The SDK automatically retries failed requests for:
- Network errors
- Server errors (5xx)
- Rate limiting (429)

Non-retryable errors:
- Invalid API key (401)
- Bad request data (400)
- Missing permissions (403)

## Browser Compatibility

- **Chrome/Edge**: 63+
- **Firefox**: 58+
- **Safari**: 11.1+
- **Internet Explorer**: 11+ (with polyfills)

### IE 11 Polyfills

```html
<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,Promise"></script>
```

## Bundle Size

- **Minified**: ~4KB
- **Gzipped**: ~1.5KB
- **No dependencies**: Zero external dependencies

## TypeScript Support

Full TypeScript definitions are included:

```typescript
import type { Event, SaasToastConfig, TrackResponse } from '@saastoast/web';

const config: SaasToastConfig = {
  apiKey: 'api_live_your_key',
  debug: true
};

const event: Event = {
  type: 'user_action',
  userId: 'user_123',
  metadata: {
    action: 'button_click'
  }
};

const response: TrackResponse = await saastoast.track(event);
```

## Environment Variables

Set up environment variables for different stages:

```bash
# .env.development
REACT_APP_SAASTOAST_API_KEY=api_live_dev_your_key
REACT_APP_SAASTOAST_DEBUG=true

# .env.production
REACT_APP_SAASTOAST_API_KEY=api_live_your_key
REACT_APP_SAASTOAST_DEBUG=false
```

## Support

- Documentation: [https://docs.saastoast.com](https://docs.saastoast.com)
- Issues: [GitHub Issues](https://github.com/saastoast/saastoast/issues)
- Email: support@saastoast.com

## License

MIT License - see LICENSE file for details.