npm package: @mosano-product-framework/public-sdk
Description: MPF Public SDK for auth, storage, and payments services
Latest version: 0.0.1

# @mosano-product-framework/public-sdk

TypeScript SDK for MPF services. Provides typed clients for authentication, storage, and payments.

## Installation

```bash
npm install @mosano-product-framework/public-sdk
# or
pnpm add @mosano-product-framework/public-sdk
```

## Quick Start

```typescript
import { createAuthClient } from '@mosano-product-framework/public-sdk';

const auth = createAuthClient({
  baseUrl: 'https://api.example.com/auth',
});

// Sign in
const { access_token } = await auth.signInEmailPassword({
  email: 'user@example.com',
  password: 'secret123',
});

// Use token for authenticated requests
const authenticatedAuth = createAuthClient({
  baseUrl: 'https://api.example.com/auth',
  headers: { Authorization: `Bearer ${access_token}` },
});

const profile = await authenticatedAuth.getMe();
```

## Service Clients

### Auth Client (REST)

The auth client provides user authentication, session management, and multi-tenancy support.

```typescript
import { createAuthClient } from '@mosano-product-framework/public-sdk';

const auth = createAuthClient({
  baseUrl: 'https://api.example.com/auth',
});

// Sign up a new user
const { access_token, refresh_token, user } = await auth.signUpEmailPassword({
  name: 'John Doe',
  email: 'john@example.com',
  password: 'securePassword123',
});

// Sign in existing user
const tokens = await auth.signInEmailPassword({
  email: 'john@example.com',
  password: 'securePassword123',
});

// Get current user profile (requires auth header)
const me = await auth.getMe();

// Update profile
await auth.updateMe({ name: 'John Updated' });

// Refresh session
const newTokens = await auth.renewSession({ refresh_token });

// Sign out
await auth.signOut({ refresh_token });
```

#### Session Management

```typescript
// List active sessions
const sessions = await auth.listSessions();

// Revoke a specific session
await auth.revokeSession('session-id');

// Revoke all other sessions
await auth.revokeOtherSessions();
```

#### Multi-tenancy

```typescript
// Create a tenant
const tenant = await auth.createTenant({
  name: 'My Organization',
  slug: 'my-org',
});

// Invite a member
await auth.inviteMember({
  tenant_id: tenant.id,
  email: 'member@example.com',
  role: 'member',
});

// Accept invitation
await auth.acceptInvitation({ token: 'invitation-token' });
```

### Storage Client (GraphQL)

The storage client manages files and folders.

```typescript
import { createStorageClient } from '@mosano-product-framework/public-sdk';

const storage = createStorageClient({
  baseUrl: 'https://api.example.com/storage',
  headers: { Authorization: `Bearer ${token}` },
});

// Create a folder
const folder = await storage.createFolder({
  name: 'Documents',
  parentId: null, // root level
});

// List folders
const folders = await storage.listFolders({ parentId: null });

// List files in a folder
const files = await storage.listFiles({ folderId: folder.id, limit: 20 });

// Get a file
const file = await storage.getFile('file-id');

// Get file download URL
const url = await storage.getFileUrl('file-id', {
  expiresIn: 3600, // 1 hour
  download: true,
});

// Delete a file
await storage.deleteFile('file-id');

// Delete a folder
await storage.deleteFolder('folder-id');
```

### Payments Client (GraphQL)

The payments client handles customers, payment methods, payments, and subscriptions.

```typescript
import { createPaymentsClient } from '@mosano-product-framework/public-sdk';

const payments = createPaymentsClient({
  baseUrl: 'https://api.example.com/payments',
  headers: { Authorization: `Bearer ${token}` },
});

// Create a customer
const customer = await payments.createCustomer({
  email: 'customer@example.com',
  name: 'Jane Doe',
});

// Add a payment method
const paymentMethod = await payments.addPaymentMethod({
  customerId: customer.id,
  type: 'card',
  token: 'stripe_token_xxx', // from payment processor
  setAsDefault: true,
});

// List payment methods
const methods = await payments.listPaymentMethods(customer.id);

// Create a one-time payment
const payment = await payments.createPayment({
  customerId: customer.id,
  amount: 2999, // $29.99 in cents
  currency: 'usd',
  paymentMethodId: paymentMethod.id,
  description: 'Product purchase',
});

// Create a subscription
const subscription = await payments.createSubscription({
  customerId: customer.id,
  priceId: 'price_monthly_pro',
  paymentMethodId: paymentMethod.id,
});

// Update subscription
await payments.updateSubscription(subscription.id, {
  priceId: 'price_monthly_enterprise',
});

// Cancel subscription
await payments.cancelSubscription(subscription.id);

// Refund a payment
const refund = await payments.refundPayment(payment.id, {
  amount: 1000, // partial refund of $10.00
  reason: 'Customer request',
});
```

## Middlewares

The SDK includes built-in middlewares for common patterns.

### Auth Middleware

Automatically injects authorization headers and handles token expiry.

```typescript
import { createAuthClient, createAuthMiddleware } from '@mosano-product-framework/public-sdk';

const authMiddleware = createAuthMiddleware({
  getAccessToken: () => localStorage.getItem('access_token'),
  onTokenExpired: async () => {
    // Refresh the token
    const newToken = await refreshToken();
    localStorage.setItem('access_token', newToken);
  },
});

const auth = createAuthClient({
  baseUrl: 'https://api.example.com/auth',
  middlewares: [authMiddleware],
});
```

### Retry Middleware

Automatically retries failed requests with exponential backoff.

```typescript
import { createStorageClient, createRetryMiddleware } from '@mosano-product-framework/public-sdk';

const retryMiddleware = createRetryMiddleware({
  maxRetries: 3,
  retryDelay: 1000, // base delay in ms
  retryOn: [500, 502, 503, 504, 429], // status codes to retry
});

const storage = createStorageClient({
  baseUrl: 'https://api.example.com/storage',
  middlewares: [retryMiddleware],
});
```

### Logging Middleware

Logs requests and responses for debugging.

```typescript
import { createPaymentsClient, createLoggingMiddleware } from '@mosano-product-framework/public-sdk';

const loggingMiddleware = createLoggingMiddleware({
  logRequest: true,
  logResponse: true,
  logErrors: true,
});

const payments = createPaymentsClient({
  baseUrl: 'https://api.example.com/payments',
  middlewares: [loggingMiddleware],
});
```

### Combining Middlewares

```typescript
import {
  createAuthClient,
  createAuthMiddleware,
  createRetryMiddleware,
  createLoggingMiddleware,
} from '@mosano-product-framework/public-sdk';

const auth = createAuthClient({
  baseUrl: 'https://api.example.com/auth',
  middlewares: [
    createLoggingMiddleware({ logErrors: true }),
    createRetryMiddleware({ maxRetries: 3 }),
    createAuthMiddleware({ getAccessToken: () => getToken() }),
  ],
});
```

## Error Handling

The SDK provides typed error classes for different failure scenarios.

```typescript
import {
  createAuthClient,
  MPFAPIError,
  MPFNetworkError,
  MPFAuthError,
  MPFValidationError,
} from '@mosano-product-framework/public-sdk';

const auth = createAuthClient({ baseUrl: 'https://api.example.com/auth' });

try {
  await auth.signInEmailPassword({
    email: 'user@example.com',
    password: 'wrong',
  });
} catch (error) {
  if (error instanceof MPFAuthError) {
    // 401 Unauthorized - invalid credentials
    console.error('Invalid credentials:', error.message);
  } else if (error instanceof MPFValidationError) {
    // 400 Bad Request - validation failed
    console.error('Validation error:', error.errors);
  } else if (error instanceof MPFNetworkError) {
    // Network failure - no response received
    console.error('Network error:', error.message);
  } else if (error instanceof MPFAPIError) {
    // Other API error (4xx, 5xx)
    console.error(`API error ${error.status}:`, error.message);
  }
}
```

## TypeScript

All types are exported and can be imported directly.

```typescript
import type { AuthTypes, StorageTypes, PaymentsTypes } from '@mosano-product-framework/public-sdk';

// Auth types
const user: AuthTypes.User = { ... };
const signInRequest: AuthTypes.SignInEmailPasswordRequest = { ... };

// Storage types
const file: StorageTypes.File = { ... };
const folder: StorageTypes.Folder = { ... };

// Payments types
const customer: PaymentsTypes.Customer = { ... };
const payment: PaymentsTypes.Payment = { ... };
```

Or import from subpaths for tree-shaking:

```typescript
import { createAuthClient } from '@mosano-product-framework/public-sdk/auth';
import { createStorageClient } from '@mosano-product-framework/public-sdk/storage';
import { createPaymentsClient } from '@mosano-product-framework/public-sdk/payments';
```

## License

MIT