npm package: @product-intelligence-hub/sdk-core
Description: Core SDK internals for Product Intelligence Hub
Latest version: 0.4.2

# @product-intelligence-hub/sdk-core

Core SDK internals for Product Intelligence Hub. This package provides the base implementation used by platform-specific SDKs.

## Overview

This package is not intended for direct use. Instead, use one of the platform-specific SDKs:

- [@product-intelligence-hub/sdk-web](https://www.npmjs.com/package/@product-intelligence-hub/sdk-web) - Browser SDK
- [@product-intelligence-hub/sdk-react-native](https://www.npmjs.com/package/@product-intelligence-hub/sdk-react-native) - React Native SDK
- [@product-intelligence-hub/sdk-node](https://www.npmjs.com/package/@product-intelligence-hub/sdk-node) - Node.js/Server SDK

## Architecture

```
sdk-core/
├── client.ts       # PIHClient base class
├── identity.ts     # IdentityManager - user/anonymous ID management
├── session.ts      # SessionManager - session tracking
├── transport.ts    # Transport - HTTP communication
├── queue.ts        # EventQueue - batching and retry logic
├── errors.ts       # PIHError - error handling
├── types.ts        # TypeScript interfaces
└── utils.ts        # Utility functions
```

## Core Components

### PIHClient

Base client class that platform SDKs extend:

```typescript
import { PIHClient, StorageAdapter } from "@product-intelligence-hub/sdk-core";

class MyPlatformClient extends PIHClient {
  constructor(config: PIHConfig, storage: StorageAdapter) {
    super(config, storage);
  }

  async initialize(): Promise<void> {
    await super.initialize();
    // Platform-specific initialization
  }

  // Override to auto-collect platform-specific context
  protected getContext(): Record<string, unknown> {
    return {
      screenWidth: ...,
      locale: ...,
      // Platform-specific fields
    };
  }
}
```

### StorageAdapter

Interface for platform-specific storage:

```typescript
interface StorageAdapter {
  getItem(key: string): Promise<string | null>;
  setItem(key: string, value: string): Promise<void>;
  removeItem(key: string): Promise<void>;
}
```

### IdentityManager

Manages user identity:

- Anonymous ID generation and persistence
- User ID tracking after identify()
- User traits storage

### SessionManager

Manages session lifecycle:

- Session ID generation
- Automatic session rotation on timeout
- Session start/end callbacks
- **Session enrichment**: `sessionNumber` (incrementing counter, persisted) and `eventIndex` (position within session, resets each session)

### EventQueue

Handles event batching:

- Configurable flush interval and batch size
- Automatic retry with exponential backoff
- Persistent queue storage

### Transport

HTTP transport layer:

- Track and identify endpoints
- Feature flag fetch and evaluation endpoints
- Retry logic
- Error handling
- Sends `X-SDK-Name` / `X-SDK-Version` headers (from `SDKMeta`) on every request

## Exports

```typescript
// Types
export type {
  PIHConfig,
  AutocaptureConfig,
  TrackEvent,
  TrackOptions,
  IdentifyPayload,
  TrackResponse,
  IdentifyResponse,
  QueuedEvent,
  StorageAdapter,
  TransportOptions,
  ClientState,
  SDKMeta,
  FeatureFlags,
  FeatureFlagConfig,
} from "./types.js";

// Errors
export { PIHError } from "./errors.js";
export type { PIHErrorCode } from "./errors.js";

// Core classes
export { PIHClient } from "./client.js";
export { IdentityManager } from "./identity.js";
export { SessionManager } from "./session.js";
export { Transport } from "./transport.js";
export { EventQueue } from "./queue.js";

// Utilities
export {
  generateUUID,
  getTimestamp,
  dateToTimestamp,
  getBackoffDelay,
  STORAGE_PREFIX,
  STORAGE_KEYS,
  DEFAULTS,
} from "./utils.js";
```

## AutocaptureConfig

The `AutocaptureConfig` type defines all autocapture options:

```typescript
interface AutocaptureConfig {
  pageViews?: boolean;       // default: true
  clicks?: boolean;          // default: false
  clickSelector?: string;    // default: "[data-track]"
  forms?: boolean;           // 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)
}
```

## Extending

To create a new platform SDK:

1. Create a storage adapter implementing `StorageAdapter`
2. Extend `PIHClient` with platform-specific features
3. Override `initialize()` for platform setup
4. Override `getContext()` to auto-collect platform-specific device/browser context
5. Add platform-specific tracking methods

## Related

- [SDK Spec](https://github.com/maxivarela/product-intelligence-hub/blob/main/docs/06_SDK_SPEC.md) - Full SDK specification