npm package: @orbit-js/sdk
Description: Official Orbit SDK for JavaScript/TypeScript
Author: Orbit Team
Latest version: 1.1.5

# @orbit-js/sdk

Official Orbit SDK for JavaScript/TypeScript

**✨ Funciona com Next.js e REST APIs** - Integração simplificada para aplicações Next.js e APIs REST em geral.

## Installation

```bash
npm install @orbit-js/sdk
# or
yarn add @orbit-js/sdk
# or
pnpm add @orbit-js/sdk
```

## Quick Start

### Environment Variables

First, add these environment variables to your `.env` file:

```bash
ORBIT_API_KEY=your-api-key-here
ORBIT_API_URL=https://orbit.vercel.app

# Optional
ORBIT_DEBUG=false
```

### Basic Usage

```typescript
import { OrbitClient } from '@orbit-js/sdk';

const orbit = new OrbitClient({
  apiKey: process.env.ORBIT_API_KEY!,
  apiUrl: process.env.ORBIT_API_URL!,
});

// Track an event
orbit.event('user_signup', {
  plan: 'premium',
  source: 'landing_page',
});

// Track a metric
orbit.metric('revenue', 99.99, {
  currency: 'USD',
  plan: 'premium',
});

// Track an error
try {
  // your code
} catch (error) {
  orbit.error(error as Error, {
    userId: user.id,
  });
}
```

## Configuration

```typescript
const orbit = new OrbitClient({
  apiKey: 'your-api-key',              // Required - Your Orbit API key
  apiUrl: 'https://orbit.vercel.app',  // Required - Orbit API URL
  bufferSize: 100,                     // Optional (default: 100)
  flushInterval: 30000,                // Optional (default: 30000ms)
  debug: false,                        // Optional (default: false)
  disabled: false,                     // Optional (default: false)
});
```

### Configuration Options

- **`apiKey`** (required): Your Orbit API key. Get it from your Orbit dashboard.
- **`apiUrl`** (required): The Orbit API URL where events will be sent. Use `https://orbit.vercel.app` for production.
- **`bufferSize`**: Maximum number of events to buffer before auto-flushing.
- **`flushInterval`**: Time in milliseconds between automatic flushes.
- **`debug`**: Enable debug logging to console.
- **`disabled`**: Disable all tracking (useful for development).

## API

### `event(name: string, properties?: object)`

Track a custom event.

```typescript
orbit.event('button_clicked', {
  button_id: 'cta-signup',
  page: '/pricing',
});
```

### `metric(name: string, value: number, dimensions?: object)`

Track a numeric metric.

```typescript
orbit.metric('api_response_time', 245, {
  endpoint: '/api/users',
  method: 'GET',
});
```

### `error(error: Error, context?: object)`

Track an error.

```typescript
orbit.error(new Error('Payment failed'), {
  userId: '123',
  amount: 99.99,
});
```

### `performance(name: string, duration: number, metadata?: object)`

Track a performance metric.

```typescript
orbit.performance('page_load', 1250, {
  page: '/dashboard',
});
```

### `flush(): Promise<void>`

Manually flush all pending events.

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

### `shutdown(): Promise<void>`

Stop the client and flush pending events.

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

## Automatic Tracking (Middleware)

**New in v1.1.4+** - Automatically track all HTTP requests with Next.js middleware.

### Quick Setup

Create `middleware.ts` in your project root:

```typescript
import { createOrbitMiddleware, defaultMatcher } from '@orbit-js/sdk/middleware';

export const middleware = createOrbitMiddleware({
  apiKey: process.env.ORBIT_API_KEY!,
  apiUrl: 'https://orbit.yourdomain.com', // Required
  workspaceId: process.env.ORBIT_WORKSPACE_ID,
});

export const config = {
  matcher: defaultMatcher,
};
```

### What's Tracked Automatically

- ✅ All page views
- ✅ All API calls
- ✅ Response times
- ✅ Status codes
- ✅ Geographic data (country, city, region)
- ✅ User agent information
- ✅ IP addresses (anonymized)

### Edge Runtime Compatible

The middleware is fully compatible with Next.js Edge Runtime and Vercel Edge Functions.

**📖 Full Documentation:** See [MIDDLEWARE_SETUP.md](./MIDDLEWARE_SETUP.md) for complete setup guide and advanced configuration.

## TypeScript

The SDK is written in TypeScript and includes full type definitions.

```typescript
import { OrbitClient, OrbitConfig, Metric } from '@orbit-js/sdk';
import { createOrbitMiddleware, defaultMatcher } from '@orbit-js/sdk/middleware';
```

## License

MIT © Orbit Team