npm package: @sadesoftware/services-sdk
Description: Official TypeScript SDK for Sade Services Platform - Email, WhatsApp, Drive, and more
Author: Sade Platform
Latest version: 1.0.0

# @sadesoftware/services-sdk

Official TypeScript SDK for Sade Services Platform - Email, WhatsApp, Drive, and more.

[![npm version](https://img.shields.io/npm/v/@sadesoftware/services-sdk.svg)](https://www.npmjs.com/package/@sadesoftware/services-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 🚀 Features

- ✅ **TypeScript First** - Full type safety with TypeScript
- ✅ **Tree-Shakeable** - Import only what you need
- ✅ **Retry Logic** - Automatic retry with exponential backoff
- ✅ **Circuit Breaker** - Fail-fast when service is down
- ✅ **Telemetry** - Built-in logging and monitoring
- ✅ **Zero Dependencies** - Only `zod` for validation
- ✅ **ESM + CJS** - Works in all environments
- ✅ **Promise-Based** - Modern async/await API

## 📦 Installation

```bash
npm install @sadesoftware/services-sdk
```

## 🔑 Quick Start

### Minimal Setup (Recommended)

**1. Install the package:**
```bash
npm install @sadesoftware/services-sdk
```

**2. Create `.env` file:**
```bash
SADE_API_KEY=sk_live_your_api_key_here

# Domain:
# - If API key has domain restriction (domain: "myapp.com") → use that domain
# - If API key allows all domains (domain: "*") → use any value (e.g., "*" or "myapp.com")
SADE_DOMAIN=myapp.com

# Optional: Custom API URL (defaults to https://api.sade.works)
# SADE_API_URL=http://localhost:8000
```

**3. Create SDK instance (once):**
```typescript
// lib/sdk.ts or services/sade.ts
import { ServicesSDK } from '@sadesoftware/services-sdk';

export const sdk = new ServicesSDK({
  apiKey: process.env.SADE_API_KEY!,
  domain: process.env.SADE_DOMAIN || '*', // Any value if API key allows all domains
  // baseURL is optional - uses https://api.sade.works by default
  baseURL: process.env.SADE_API_URL,
});
```

**4. Use anywhere in your app:**
```typescript
import { sdk } from './lib/sdk';

// Send OTP via Email
async function sendOTP(email: string) {
  const code = Math.floor(100000 + Math.random() * 900000).toString();
  
  await sdk.email.send({
    to: [email],
    subject: 'Your Login Code',
    content: `Your verification code is: ${code}`,
  });
  
  return code;
}

// Send WhatsApp notification
async function notifyUser(phone: string, message: string) {
  await sdk.whatsApp.sendText({
    number: phone, // ⚠️ Without + symbol! (e.g., 905551234567)
    text: message,
  });
}
```

### Basic Example

```typescript
import { ServicesSDK } from '@sadesoftware/services-sdk';

const sdk = new ServicesSDK({
  apiKey: 'sk_live_xxxxxxxxxxxx',
  domain: 'example.com'
});

// Send email
await sdk.email.send({
  to: ['user@example.com'],
  subject: 'Hello!',
  content: '<h1>Welcome</h1>'
});

// Send WhatsApp
await sdk.whatsApp.sendText({
  number: '905551234567', // ⚠️ Without + symbol!
  text: 'Hello from SDK!'
});

// Upload to Drive
await sdk.drive.upload(file, {
  targetPath: '/invoices'
});
```

## 📚 Services

### Email Service

```typescript
const result = await sdk.email.send({
  to: ['user@example.com', 'admin@example.com'],
  subject: 'Order Confirmation',
  content: '<h1>Your order #1234</h1>',
  content_type: 'html',
  sender_name: 'My Store'
});

console.log(`Used ${result.credits_used} credits`);
```

### WhatsApp Service

```typescript
// Text message
await sdk.whatsApp.sendText({
  number: '905551234567', // ⚠️ Without + symbol!
  text: 'Hello World!'
});

// Media message
await sdk.whatsApp.sendMedia({
  number: '905551234567', // ⚠️ Without + symbol!
  media_type: 'image',
  mimetype: 'image/jpeg',
  media: 'https://example.com/photo.jpg',
  caption: 'Check this out!'
});

// Button message
await sdk.whatsApp.sendButtons({
  number: '905551234567', // ⚠️ Without + symbol!
  title: 'Select Option',
  description: 'Choose one:',
  buttons: [
    { type: 'reply', displayText: 'Yes', id: 'yes' },
    { type: 'reply', displayText: 'No', id: 'no' }
  ]
});
```

### Drive Service

```typescript
// Upload file
const result = await sdk.drive.upload(file, {
  filename: 'invoice.pdf',
  targetPath: '/invoices/2024',
  customerSlug: 'acme-corp',
  onDuplicate: 'autoRename' // or 'replace', 'skip'
});

// List files
const files = await sdk.drive.listFiles({
  page: 1,
  limit: 20
});

// Get preview URL
const previewURL = sdk.drive.getPreviewURL(fileId, true); // thumbnail
```

### Account Service

```typescript
// Get balance
const balance = await sdk.account.getBalance();
console.log(`Credits: ${balance.data.credit_balance}`);

// Get usage stats
const usage = await sdk.account.getUsage();
console.log(`Total calls: ${usage.data.total_usage}`);
```

## ⚙️ Advanced Configuration

```typescript
const sdk = new ServicesSDK({
  apiKey: 'sk_live_xxx',
  domain: 'example.com',
  
  // Global timeout
  timeout: 30000,
  
  // Retry configuration
  retry: {
    maxRetries: 3,
    backoff: 'exponential', // 'linear', 'fixed'
    initialDelay: 1000,
    maxDelay: 30000
  },
  
  // Circuit breaker
  circuitBreaker: {
    threshold: 5,
    timeout: 60000,
    windowSize: 10000
  },
  
  // Telemetry
  telemetry: {
    enabled: true,
    logLevel: 'info', // 'debug', 'info', 'warn', 'error'
    logger: customLogger // optional custom logger
  },
  
  // Service-specific configs
  services: {
    email: {
      timeout: 60000,
      configId: 'custom-config-id'
    },
    whatsapp: {
      timeout: 45000
    },
    drive: {
      timeout: 120000
    }
  }
});
```

## 🔧 Per-Call Overrides

```typescript
// Override timeout for specific call
await sdk.email.send(
  { to: ['user@example.com'], subject: 'Test' },
  { timeout: 90000 }
);

// Use specific config
await sdk.whatsApp.sendText(
  { number: '905551234567', text: 'Hi' }, // ⚠️ Without + symbol!
  { configId: 'custom-config', instanceName: 'production' }
);
```

## 🚨 Error Handling

```typescript
import {
  InsufficientCreditsError,
  RateLimitError,
  ConfigNotFoundError,
  AuthenticationError
} from '@sadesoftware/services-sdk';

try {
  await sdk.email.send({ ... });
} catch (error) {
  if (error instanceof InsufficientCreditsError) {
    console.log(`Need ${error.creditsRequired} credits`);
    console.log(`Have ${error.creditsRemaining} credits`);
    // Redirect to billing
  } else if (error instanceof RateLimitError) {
    console.log(`Retry after ${error.retryAfter} seconds`);
    // Wait and retry
  } else if (error instanceof AuthenticationError) {
    console.log('Invalid API key');
    // Check credentials
  } else if (error instanceof ConfigNotFoundError) {
    console.log('Service not configured');
    // Contact support
  }
}
```

## 🌲 Tree-Shakeable Imports

```typescript
// Import only what you need
import { EmailClient } from '@sadesoftware/services-sdk/email';
import { WhatsAppClient } from '@sadesoftware/services-sdk/whatsapp';
```

## 🧪 Testing

The SDK includes built-in testing utilities:

```typescript
// Health check
const isHealthy = await sdk.healthCheck();
```

## 📖 API Documentation

For complete API documentation, visit: https://docs.sade.works

## 🔗 Links

- [Website](https://sade.works)
- [Documentation](https://docs.sade.works)
- [API Reference](https://api.sade.works/docs)
- [GitHub](https://github.com/sadeuckun/services-system)
- [npm](https://www.npmjs.com/package/@sadesoftware/services-sdk)

## 📄 License

MIT © Sade Platform

## 🤝 Support

- Email: support@sade.works
- Issues: https://github.com/sadeuckun/services-system/issues