npm.io
1.50.0 • Published 1 week ago

@sesamy/sdk

Licence
MIT
Version
1.50.0
Deps
1
Size
394 kB
Vulns
0
Weekly
0

@sesamy/sdk

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

Installation

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
import { client, management } from '@sesamy/sdk';
import type { User, Profile, Subscription, Entitlement } from '@sesamy/types';
Client SDK (End-user operations)
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.profile.get();
const updatedProfile: Profile = await sdkClient.profile.update({ firstName: 'New' });

// 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)
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:

// 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:

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
  • profile.get(): Promise<Profile> - Get the authenticated user's profile
  • profile.update(data: Partial<Profile>): Promise<Profile> - Update the authenticated user's 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
  • 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
  • onRequestError (optional): Called when a request never completes or ends in a 5xx response, with the URL, method, and either the status or the error fetch threw. Meant for telemetry: the request still rejects with an APIError, and anything the callback throws is ignored.

Error Handling

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

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:

# 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:

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

License

MIT

Keywords