npm package: @flowsight/js
Description: FlowSight Payment Observability SDK — instrument your payments in 3 lines
Author: FlowSight
Latest version: 1.1.1

# @flowsight/js

> **FlowSight Payment Observability SDK** — instrument your payments in 3 lines.

The official JavaScript/TypeScript SDK for [FlowSight](https://flowsight.pro), the payment observability platform. Track payment events, monitor processor health, and debug failures in real-time.

## Installation

```bash
npm install @flowsight/js
```

## Quick Start

```typescript
import { FlowSight } from '@flowsight/js';

// 1. Initialize
const flowsight = FlowSight.init({
  apiKey: 'fs_live_abc123def456ghi789jkl012',
});

// 2. Track a payment
flowsight.trackEvent({
  event_type: 'payment.started',
  flow_id: '550e8400-e29b-41d4-a716-446655440000',
  transaction_id: 'pi_3ABC123DEF456',
  processor: 'stripe', // or 'paypal', 'adyen', 'redsys'
  amount: 9999,
  currency: 'USD',
});

// 3. Shut down gracefully before exit
await flowsight.shutdown();
```

That's it. Three lines to value.

## Features

- **TypeScript-first** — Full type definitions, strict mode, JSDoc on every public API
- **Zero dependencies** — Uses native `fetch()`, no external HTTP libraries
- **Node.js + Browser** — Works everywhere (Node 18+, modern browsers, Deno, Bun)
- **Fire-and-forget** — Tracking calls never throw; errors route to `onError` callback
- **Smart batching** — Buffers events, flushes every 5s or when batch reaches 50 events
- **Automatic retry** — Exponential backoff with jitter, max 3 retries on transient failures
- **Tiny bundle** — 7KB minified (UMD), 14KB (ESM), tree-shakeable
- **Three output formats** — ESM, CJS, and UMD with source maps

## API

### `FlowSight.init(config)`

Initialize the SDK. Returns a `FlowSight` client instance.

```typescript
const flowsight = FlowSight.init({
  apiKey: 'fs_live_...',         // Required. Your FlowSight API key.
  environment: 'production',      // Optional. Auto-detected from apiKey prefix.
  endpoint: 'https://...',        // Optional. Custom ingestion endpoint URL.
  maxBatchSize: 50,               // Optional. Events per batch (default: 50).
  flushIntervalMs: 5000,          // Optional. Auto-flush interval (default: 5000ms).
  maxRetries: 3,                  // Optional. Retry attempts (default: 3).
  timeoutMs: 10000,               // Optional. Request timeout (default: 10000ms).
  debug: false,                   // Optional. Log internal activity (default: false).
  onError: (error) => {           // Optional. Error callback.
    console.error('[FlowSight]', error.code, error.message);
  },
});
```

### `flowsight.trackEvent(event)`

Track a single payment event. Fire-and-forget — never throws.

```typescript
flowsight.trackEvent({
  event_type: 'payment.completed',
  flow_id: '550e8400-e29b-41d4-a716-446655440000',
  transaction_id: 'pi_3ABC123DEF456',
  processor: 'stripe',
  amount: 9999,
  currency: 'USD',
  status: 'succeeded',
  latency_ms: 234,
  payment_method: {
    type: 'card',
    brand: 'visa',
    last4: '4242',
    country: 'US',
    funding: 'credit',
  },
  processor_response: {
    processor_transaction_id: 'ch_3ABC123DEF456',
    processor_status: 'succeeded',
    raw_code: 'approved',
  },
  context: {
    checkout_session: 'cs_abc123',
    customer_tier: 'premium',
  },
});
```

Auto-generated fields (if omitted):
- `event_id` — UUID v4
- `timestamp` — Current ISO 8601 timestamp
- `sdk` — SDK name, version, and runtime

### `flowsight.trackBatch(events)`

Track multiple events in a single call. More efficient than calling `trackEvent()` in a loop.

```typescript
flowsight.trackBatch([
  { event_type: 'payment.started', ... },
  { event_type: 'payment.completed', ... },
]);
```

### `flowsight.flush()`

Force-send all buffered events immediately.

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

### `flowsight.shutdown()`

Gracefully shut down — flushes remaining events, stops timers, rejects future calls.

```typescript
await flowsight.shutdown();
```

### `flowsight.bufferedCount`

Number of events currently buffered (read-only).

## Event Types

| Event Type | Description | `status` Required |
|---|---|---|
| `payment.started` | Payment attempt initiated | No |
| `payment.completed` | Payment attempt finished | Yes |
| `payment.failed` | Payment attempt failed | Yes (`'failed'`) |
| `payment.retried` | Retry of a failed payment | No |
| `refund.started` | Refund initiated | No |
| `refund.completed` | Refund finished | Yes |
| `refund.failed` | Refund failed | Yes (`'failed'`) |

## Error Handling

The SDK never throws on tracking calls. All errors are routed to the `onError` callback:

```typescript
const flowsight = FlowSight.init({
  apiKey: 'fs_live_...',
  onError: (error) => {
    // error.code: 'NETWORK_ERROR' | 'TIMEOUT' | 'AUTH_ERROR' | 'RATE_LIMITED' | ...
    // error.message: Human-readable description
    // error.statusCode: HTTP status (if applicable)
    // error.retryCount: Retries attempted before giving up
    // error.events: The events that failed to send
    myLogger.warn('FlowSight error', error);
  },
});
```

## Tracking Failed Payments

```typescript
flowsight.trackEvent({
  event_type: 'payment.failed',
  flow_id: flowId,
  transaction_id: 'pi_3ABC123DEF456',
  processor: 'stripe',
  amount: 9999,
  currency: 'USD',
  status: 'failed',
  latency_ms: 1234,
  error: {
    code: 'card_declined',
    category: 'card_declined',
    message: 'Your card was declined.',
    processor_code: 'do_not_honor',
    retriable: false,
  },
});
```

## Environment Detection

The SDK auto-detects the target environment from the API key prefix:

| Key Prefix | Environment | Endpoint |
|---|---|---|
| `fs_live_` | Production | `https://ingest.flowsight.pro` |
| `fs_test_` | Test/Sandbox | `https://sandbox.api.flowsight.pro` |

Override with `environment` or `endpoint` in config.

## Bundle Targets

| Format | File | Platform | Size |
|---|---|---|---|
| ESM | `dist/esm/index.js` | Node.js / Bundlers | 14.4 KB |
| CJS | `dist/cjs/index.cjs` | Node.js (require) | 15.4 KB |
| UMD | `dist/umd/flowsight.umd.js` | Browsers (script tag) | 7.0 KB |

All bundles include source maps and are tree-shakeable.

### Browser (script tag)

```html
<script src="https://unpkg.com/@flowsight/js/dist/umd/flowsight.umd.js"></script>
<script>
  const flowsight = FlowSight.FlowSight.init({ apiKey: 'fs_live_...' });
</script>
```

## Requirements

- **Node.js** 18+ (uses native `fetch()`)
- **Browsers**: Any browser with `fetch()` and `crypto.getRandomValues()` support

## License

MIT © FlowSight