npm package: @sesamy/sdk
Description: Pure TypeScript SDK for Sesamy API Proxy
Author: Sesamy
Latest version: 1.28.0

# @sesamy/sdk

A pure TypeScript SDK for the Sesamy API Proxy, designed for tree-shaking with separate client and management exports.

## Installation

```bash
npm install @sesamy/sdk
# or
pnpm add @sesamy/sdk
```

## Usage

The SDK is auth-agnostic and accepts a `tokenProvider` function that returns a complete Authorization header value (e.g., "Bearer token" or "Basic credentials"). This allows integration with any authentication library or method, supporting both Bearer token and Basic authentication schemes.

### Importing Types

```typescript
import { client, management } from '@sesamy/sdk';
import type { User, Profile, Subscription, Entitlement } from '@sesamy/types';
```

### Client SDK (End-user operations)

```typescript
import { client } from '@sesamy/sdk';

// Example with auth0-spa-js
import { Auth0Client } from '@auth0/auth0-spa-js';
const auth0Client = new Auth0Client({
  domain: 'your-domain.auth0.com',
  client_id: 'your-client-id',
});

const sdkClient = client({
  baseUrl: 'https://api-proxy.example.com',
  tokenProvider: async () => {
    const token = await auth0Client.getTokenSilently();
    return `Bearer ${token}`; // Return the full Authorization header
  },
  vendorId: 'your-vendor-id', // Optional, for multi-tenancy
});

// Use client methods
const profile: Profile = await sdkClient.getProfile('user-id');
const updatedProfile: Profile = await sdkClient.updateProfile('user-id', { name: 'New Name' });

// Generate checkout link
const checkoutUrl = sdkClient.checkouts.generateLink(
  { apiUrl: 'https://api-proxy.example.com' },
  {
    items: [{ sku: 'premium-monthly' }],
    email: 'user@example.com',
    language: 'en',
    redirectUrl: 'https://example.com/success',
  }
);

// Generate other links
const accountUrl = sdkClient.links.generateAccountLink(
  { baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
  { language: 'en' }
);

const changePaymentUrl = sdkClient.links.generateChangePaymentLink(
  { baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
  { contractId: 'contract-123', language: 'en' }
);
```

### Management SDK (Admin operations)

```typescript
import { management } from '@sesamy/sdk';

// Example with server-side auth (e.g., auth0-next or next-auth)
const sdkManagement = management({
  baseUrl: 'https://api-proxy.example.com',
  tokenProvider: async () => {
    // Your token retrieval logic here
    // e.g., from session, auth0-next, next-auth, etc.
    const token = await getTokenFromSession();
    return `Bearer ${token}`; // Return the full Authorization header
  },
  vendorId: 'your-vendor-id',
});

// Use management methods
const users: User[] = await sdkManagement.getUsers({ limit: 10 });
const newUser: User = await sdkManagement.createUser({ email: 'user@example.com' });
await sdkManagement.setPassword('user-id', 'new-password');
```

### Tree Shaking

Import only what you need to reduce bundle size:

```javascript
// Only client
import { client } from '@sesamy/sdk';

// Only management
import { management } from '@sesamy/sdk';

// Only specific parts
import client from '@sesamy/sdk/client';
import management from '@sesamy/sdk/management';
```

## API Reference

### Types

The SDK re-exports TypeScript type definitions from the shared `@sesamy/types` package:

```typescript
import type {
  User,
  Profile,
  Address,
  Subscription,
  Entitlement,
  EntitlementType,
  Product,
  Contract,
  Checkout,
  Bill,
  Transaction,
  Fulfillment,
  Vendor,
  Amendment,
  Tally,
  PaymentIssue,
  UserMetadata,
} from '@sesamy/types';

// SDK-specific types
import type { SDKConfig, ClientSDK, ManagementSDK } from '@sesamy/sdk';
```

### Client Methods

- `getProfile(userId: string): Promise<Profile>` - Get user profile
- `updateProfile(userId: string, data: Partial<Profile>): Promise<Profile>` - Update user profile

### Checkout Methods

- `checkouts.generateLink(config, params): string` - Generate a checkout link URL
- `checkouts.create(data): Promise<Checkout>` - Create a checkout session
- `checkouts.get(id): Promise<Checkout>` - Get checkout session by ID
- `checkouts.update(id, data): Promise<Checkout>` - Update a checkout session

### Link Generation Methods

- `links.generateCheckoutLink(config, params): string` - Generate a checkout link URL
- `links.generateAccountLink(config, params): string` - Generate an account management link
- `links.generateChangePaymentLink(config, params): string` - Generate a change payment method link
- `links.generateChangePlanLink(config, params): string` - Generate a change subscription plan link
- `links.generateConsumeLink(config, params): string` - Generate a content consumption link

### Management Methods

- `getUsers(query?: any): Promise<User[]>` - List users with optional filtering
- `createUser(data: Partial<User>): Promise<User>` - Create a new user
- `getUser(userId: string): Promise<User>` - Get a user by ID
- `updateUser(userId: string, data: Partial<User>): Promise<User>` - Update a user
- `deleteUser(userId: string): Promise<void>` - Delete a user
- `setPassword(userId: string, password: string): Promise<void>` - Set user password
- `changeLoginIdentifier(userId: string, email: string): Promise<void>` - Change user login email
- `setUserMetadata(userId: string, key: string, value: string): Promise<void>` - Set user metadata
- `deleteUserMetadata(userId: string, key: string): Promise<void>` - Delete user metadata

## Configuration

- `baseUrl` (required): Base URL for the API proxy
- `tokenProvider` (required): Async function that returns the full Authorization header value (e.g., "Bearer token", "Basic credentials")
- `vendorId` (optional): Vendor ID for multi-tenant setups

## Error Handling

The SDK throws errors for API failures. Handle token expiration by refreshing tokens in your `tokenProvider`:

```typescript
const sdk = client({
  baseUrl: 'https://api-proxy.example.com',
  tokenProvider: async () => {
    try {
      const token = await auth0Client.getTokenSilently();
      return `Bearer ${token}`; // Return the full Authorization header
    } catch (error) {
      // Handle token refresh failure
      throw new Error('Authentication failed');
    }
  },
});
```

## Development

### Using pnpm filters

From the monorepo root, you can use the `sdk` filter to run commands specifically for this package:

```bash
# Build the SDK
pnpm sdk build

# Production build (includes type definitions)
pnpm sdk build:prod

# Type checking
pnpm sdk type-check

# Development server
pnpm sdk dev
```

### Direct commands

You can also run commands directly in the package directory:

```bash
cd packages/sdk
pnpm build
pnpm build:prod
pnpm type-check
```

## License

MIT