npm package: @product-intelligence-hub/sdk-web
Description: Browser SDK for Product Intelligence Hub
Latest version: 0.4.2

# @product-intelligence-hub/sdk-web

Browser SDK for Product Intelligence Hub.

## Installation

```bash
npm install @product-intelligence-hub/sdk-web
# or
yarn add @product-intelligence-hub/sdk-web
# or
pnpm add @product-intelligence-hub/sdk-web
```

### Optional Peer Dependencies

For Web Vitals tracking (`performance: true`):
```bash
npm install web-vitals
```

## Quick Start

```typescript
import PIH from "@product-intelligence-hub/sdk-web";

// Initialize the SDK
const pih = PIH.init({
  apiKey: "your-api-key",
  projectId: "proj_xxx",
  environment: "production",
  tenantId: "tenant_xxx", // optional
  debug: false,
});

// Track an event
pih.track("button_clicked", {
  button_id: "signup",
  page: "/home",
});

// Identify a user
pih.identify("user_123", {
  email: "user@example.com",
  plan: "pro",
});
```

## Configuration Options

```typescript
PIH.init({
  // Required
  apiKey: string;           // Environment API key
  projectId: string;        // Project ID (proj_xxx)
  environment: string;      // Environment name

  // Optional
  apiUrl?: string;          // Ingest API URL (has default, override for self-hosted)
  tenantId?: string;        // Tenant ID for multi-tenant apps
  debug?: boolean;          // Enable debug logging (default: false)
  flushInterval?: number;   // Batch flush interval in ms (default: 10000)
  flushAt?: number;         // Flush when queue reaches this size (default: 20)
  maxQueueSize?: number;    // Max events to queue (default: 1000)
  sessionTimeout?: number;  // Session timeout in ms (default: 1800000)

  // Autocapture
  autocapture?: {
    pageViews?: boolean;    // Track page views (default: true)
    clicks?: boolean;       // Track clicks (default: false)
    forms?: boolean;        // Track form submissions (default: false)
    performance?: boolean;  // Web Vitals tracking (default: false)
    engagement?: boolean;   // Time-on-page + scroll depth (default: false)
    errorTracking?: boolean; // JS error capture (default: false)
  };

  // Callbacks
  onError?: (error: PIHError) => void;
});
```

## API

### `PIH.init(config)`

Initialize the SDK. Returns the client instance.

### `pih.track(eventName, properties?, options?)`

Track an event.

```typescript
pih.track("purchase_completed", {
  product_id: "prod_123",
  amount: 99.99,
  currency: "USD",
});

// With options
pih.track("critical_event", { ... }, {
  immediate: true,  // Send immediately, bypass queue
  timestamp: new Date("2024-01-01"),  // Custom timestamp
});
```

### `pih.identify(userId, traits?)`

Identify the current user.

```typescript
pih.identify("user_123", {
  email: "user@example.com",
  name: "John Doe",
  plan: "enterprise",
});
```

### `pih.setTenant(tenantId)`

Set the tenant ID for multi-tenant applications.

```typescript
pih.setTenant("tenant_456");
```

### `pih.trackPageView()`

Manually track a page view.

```typescript
pih.trackPageView();
```

### `pih.flush()`

Force flush the event queue.

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

### `pih.isFeatureEnabled(key, defaultValue?)`

Check if a feature flag is enabled.

```typescript
if (pih.isFeatureEnabled("new_checkout_flow")) {
  showNewCheckout();
}

// With default value
const enabled = pih.isFeatureEnabled("beta_feature", false);
```

### `pih.getFeatureFlags()`

Get all feature flag values.

```typescript
const flags = pih.getFeatureFlags();
// { new_checkout_flow: true, beta_feature: false }
```

### `pih.refreshFlags()`

Force refresh feature flags from the server.

```typescript
await pih.refreshFlags();
```

### `pih.reset()`

Reset identity (for logout).

```typescript
await pih.reset();
```

## Autocapture

Enable automatic event capture:

```typescript
PIH.init({
  // ...
  autocapture: {
    pageViews: true,       // Track page_viewed on navigation
    clicks: true,          // Track element_clicked
    forms: true,           // Track form_submitted
    performance: true,     // Track web_vital (requires web-vitals)
    engagement: true,      // Track page_engaged + scroll_depth_reached
    errorTracking: true,   // Track js_error
  }
});
```

### Auto-Tracked Events

| Event | Trigger | Key Properties |
|-------|---------|----------------|
| `page_viewed` | `pageViews: true` (default) | path, title, referrer, UTM params |
| `element_clicked` | `clicks: true` | element_tag, element_text, data_track |
| `form_submitted` | `forms: true` | form_id, form_action, form_method, field_count |
| `web_vital` | `performance: true` | metric_name (LCP/FID/CLS/INP/TTFB), value, rating |
| `page_engaged` | `engagement: true` | duration_ms (fired on visibility change) |
| `scroll_depth_reached` | `engagement: true` | depth_percent (25, 50, 75, 100) |
| `js_error` | `errorTracking: true` | message, filename, lineno, type (max 10/page) |

### Enabling/Disabling at Runtime

```typescript
// Enable
pih.enableAutocapture({ clicks: true });

// Disable
pih.disableAutocapture();
```

## Browser Context

The SDK automatically collects browser context on every event:

- `screenWidth` / `screenHeight` -- physical screen resolution
- `viewportWidth` / `viewportHeight` -- browser viewport size
- `locale` -- browser locale (e.g. `en-US`)
- `timezone` -- IANA timezone (e.g. `America/New_York`)
- `connectionType` -- network connection type
- `deviceType` -- `desktop`, `tablet`, or `mobile`
- `pageUrl`, `pagePath`, `pageTitle`, `referrer`

These fields are included in the `context` property of each event.

## Session Enrichment

Each event includes session-level metadata:

- `sessionNumber` -- incrementing counter of sessions (persists across sessions)
- `eventIndex` -- zero-based position of the event within the current session

## Feature Flag Hooks (React)

```typescript
import { useFeatureFlag, useFeatureFlags } from "@product-intelligence-hub/sdk-web/hooks";

function MyComponent() {
  // Single flag with default value
  const isNewUI = useFeatureFlag("new_ui", false);

  // All flags
  const allFlags = useFeatureFlags();

  if (isNewUI) {
    return <NewUIComponent />;
  }
  return <LegacyComponent />;
}
```

Hooks automatically re-render when flag values change (e.g. after `refreshFlags()` or `identify()`).

## TypeScript Support

Full TypeScript support included. Types are exported from the package:

```typescript
import type { PIHConfig, TrackEvent, TrackOptions, FeatureFlags } from "@product-intelligence-hub/sdk-web";
```

## Build Outputs

- ESM: `dist/index.js`
- CommonJS: `dist/index.cjs`
- Browser (IIFE): `dist/index.global.js`
- TypeScript declarations: `dist/index.d.ts`

## Related

- [@product-intelligence-hub/sdk-core](https://www.npmjs.com/package/@product-intelligence-hub/sdk-core) - Core SDK internals
- [SDK Spec](https://github.com/maxivarela/product-intelligence-hub/blob/main/docs/06_SDK_SPEC.md) - Full SDK specification