> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mlm-platform.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Official TypeScript SDK for the MLM Platform API

# TypeScript SDK

The official TypeScript SDK provides a type-safe, easy-to-use client for the MLM Platform API.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @mlm-platform/sdk
  ```

  ```bash yarn theme={null}
  yarn add @mlm-platform/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @mlm-platform/sdk
  ```
</CodeGroup>

## Quick Start

```typescript theme={null}
import { MLMPlatformClient } from '@mlm-platform/sdk';

const client = new MLMPlatformClient({
  apiKey: 'mlm_live_your_api_key_here'
});

// Create a user
const user = await client.createUser({
  email: 'user@example.com',
  membershipTier: 'ORDINARY'
});

// Record a purchase
const result = await client.recordPurchase({
  userId: user.id,
  amount: 99.99
});
```

## Configuration

```typescript theme={null}
const client = new MLMPlatformClient({
  apiKey: 'mlm_live_your_api_key_here',
  baseUrl: 'https://app.mlm-platform.com',
  timeout: 30000,
  retries: 3,
  retryDelay: 1000
});
```

| Option       | Type     | Default        | Description                        |
| ------------ | -------- | -------------- | ---------------------------------- |
| `apiKey`     | `string` | Required       | Your tenant API key                |
| `baseUrl`    | `string` | Production URL | API base URL                       |
| `timeout`    | `number` | `30000`        | Request timeout (ms)               |
| `retries`    | `number` | `3`            | Retry attempts for failed requests |
| `retryDelay` | `number` | `1000`         | Initial retry delay (ms)           |

## Methods

### Users

<Accordion title="createUser">
  Create a new member in the hierarchy.

  ```typescript theme={null}
  const user = await client.createUser({
    email: 'user@example.com',
    membershipTier: 'ORDINARY',
    parentId: 'sponsor-uuid',
    referralCode: 'ABC123'
  });
  ```

  **Parameters:**

  * `email` (required): User's email address
  * `membershipTier`: `'ORDINARY'` | `'SENIOR'` | `'MANAGER'` | `'DIRECTOR'`
  * `parentId`: Sponsor's user ID
  * `referralCode`: Referral code for attribution
  * `isActive`: Whether user is active (default: `true`)
  * `canRecruit`: Whether user can recruit (default: `true`)
  * `metadata`: Custom metadata object
</Accordion>

<Accordion title="getUserStatus">
  Get user status and commission balance.

  ```typescript theme={null}
  const status = await client.getUserStatus('user-uuid');

  console.log(status.commissionBalance);
  // { pending: 100, cleared: 500, paid: 1000, total: 1600 }
  ```
</Accordion>

### Purchases

<Accordion title="recordPurchase">
  Record a purchase event and trigger commission calculation.

  ```typescript theme={null}
  const result = await client.recordPurchase({
    userId: 'buyer-uuid',
    amount: 99.99,
    currency: 'USD',
    idempotencyKey: 'order_123'
  });

  console.log(result.commissionsCreated); // 3
  console.log(result.commissionDetails);
  // [{ beneficiaryId: '...', level: 1, rate: 0.1, amount: 9.99 }]
  ```
</Accordion>

### Leads

<Accordion title="captureLead">
  Capture a lead with optional referral attribution.

  ```typescript theme={null}
  const lead = await client.captureLead({
    email: 'lead@example.com',
    name: 'John Doe',
    referralCode: 'ABC123',
    source: 'landing_page'
  });
  ```
</Accordion>

### Referrals

<Accordion title="getReferralLink">
  Get a user's referral link and code.

  ```typescript theme={null}
  const referral = await client.getReferralLink('user-uuid');

  console.log(referral.referralCode);  // 'ABC123'
  console.log(referral.referralUrl);   // 'https://...'
  ```
</Accordion>

### Widgets

<Accordion title="createWidgetSession">
  Create a widget access token for embedding.

  ```typescript theme={null}
  const session = await client.createWidgetSession({
    userId: 'user-uuid'
  });

  // Use token in iframe src
  const src = `https://widget.mlm-platform.example.com/referral?token=${session.token}`;
  ```
</Accordion>

## Error Handling

The SDK provides typed error classes:

```typescript theme={null}
import {
  MLMPlatformError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  NotFoundError,
  ConflictError,
  ForbiddenError
} from '@mlm-platform/sdk';

try {
  await client.createUser({ email: 'invalid' });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation failed:', error.details);
  } else if (error instanceof RateLimitError) {
    console.log(`Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof MLMPlatformError) {
    console.log(`Error: ${error.code} - ${error.message}`);
  }
}
```

| Error Class           | Status Code | When Thrown                |
| --------------------- | ----------- | -------------------------- |
| `AuthenticationError` | 401         | Invalid or missing API key |
| `ForbiddenError`      | 403         | Action not allowed         |
| `NotFoundError`       | 404         | Resource not found         |
| `ValidationError`     | 400         | Invalid request data       |
| `ConflictError`       | 409         | Resource already exists    |
| `RateLimitError`      | 429         | Rate limit exceeded        |

## TypeScript Types

All types are exported for use in your application:

```typescript theme={null}
import type {
  User,
  Lead,
  Commission,
  CreateUserRequest,
  RecordPurchaseRequest,
  PurchaseEventResponse,
  MembershipTier,
  CommissionStatus
} from '@mlm-platform/sdk';

function processUser(user: User) {
  // Fully typed
}
```

## Request Cancellation

Cancel requests using `AbortController`:

```typescript theme={null}
const controller = new AbortController();

setTimeout(() => controller.abort(), 5000);

try {
  const user = await client.createUser(
    { email: 'user@example.com' },
    { signal: controller.signal }
  );
} catch (error) {
  if (error.message === 'Request timeout') {
    console.log('Request was cancelled');
  }
}
```

## Environment Variables

Store API keys securely:

```bash theme={null}
# .env
MLM_LIVE_API_KEY=mlm_live_abc123...
MLM_SANDBOX_API_KEY=mlm_sandbox_xyz789...
```

```typescript theme={null}
const client = new MLMPlatformClient({
  apiKey: process.env.NODE_ENV === 'production'
    ? process.env.MLM_LIVE_API_KEY!
    : process.env.MLM_SANDBOX_API_KEY!
});
```
