npm package: @feedinbox/sdk
Description: Secure TypeScript SDK for FeedInbox - API client for feedback collection and user engagement
Author: FeedInbox Team
Latest version: 2.0.2

# @feedinbox/sdk

[![npm version](https://img.shields.io/npm/v/@feedinbox/sdk.svg)](https://www.npmjs.com/package/@feedinbox/sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8+-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/Node.js-16+-green.svg)](https://nodejs.org/)

Secure TypeScript SDK for FeedInbox - Complete API client for feedback collection, user engagement, and customer data management.

## Installation

```bash
npm install @feedinbox/sdk
```

## Quick Start

```typescript
import { FeedInboxSDK } from '@feedinbox/sdk';

// Initialize with API key from environment
const feedinbox = new FeedInboxSDK();

// Create feedback
const result = await feedinbox.createFeedback({
  userEmail: 'user@example.com',
  message: 'Great product! Love the new features.',
  priority: 'high',
  subject: 'Product Feedback'
});

if (result.success) {
  console.log('Feedback submitted:', result.data);
} else {
  console.error('Error:', result.error);
}
```

## Configuration

Set your API key as an environment variable:

```bash
export FEEDINBOX_API_KEY="fb_your_api_key_here"
```

Or pass it directly to the constructor:

```typescript
const feedinbox = new FeedInboxSDK({
  apiKey: 'fb_your_api_key_here',
  timeout: 15000,
  retries: 3
});
```

### Config Options

- `apiKey` - Your FeedInbox API key (uses `FEEDINBOX_API_KEY` env var if not provided)
- `apiUrl` - Custom API endpoint URL
- `timeout` - Request timeout in milliseconds (default: 10000)
- `retries` - Number of retries for failed requests (default: 2)
- `customBackendUrl` - Override the API URL completely

## API Methods

All methods return `Promise<ApiResponse<T>>` with consistent error handling:

```typescript
interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
}
```

### Feedback

#### Create Feedback

```typescript
await sdk.createFeedback({
  userEmail: 'user@example.com',     // Required
  message: 'Your feedback message',  // Required (max 10,000 chars)
  subject: 'Optional subject',       // Optional
  priority: 'low' | 'medium' | 'high', // Optional (default: 'medium')
  workspaceId: 'workspace_id',       // Optional
  metadata: { key: 'value' }         // Optional
});
```

#### Get Feedback

```typescript
await sdk.getFeedback({
  userEmail: 'user@example.com',     // Optional filter
  limit: 10,                         // Optional (1-100)
  page: 1,                          // Optional
  status: 'open' | 'responded' | 'closed' // Optional filter
});
```

#### Update Feedback

```typescript
await sdk.updateFeedback('feedback_id', {
  message: 'Updated message',
  priority: 'high',
  status: 'responded'
});
```

#### Delete Feedback

```typescript
await sdk.deleteFeedback('feedback_id');
```

### Subscribers

#### Create Subscriber

```typescript
await sdk.createSubscriber({
  email: 'user@example.com',        // Required
  subscriptions: [                  // Required
    { 
      id: 'newsletter', 
      title: 'Weekly Newsletter', 
      description: 'Weekly updates' 
    }
  ],
  consent: true,                    // Optional
  workspaceId: 'workspace_id',      // Optional
  metadata: { source: 'website' }  // Optional
});
```

#### Get Subscriber

```typescript
await sdk.getSubscriber('user@example.com');
```

#### Update Subscriber

```typescript
await sdk.updateSubscriber('user@example.com', [
  { 
    id: 'newsletter', 
    title: 'Weekly Newsletter', 
    description: 'Weekly updates' 
  }
]);
```

#### Delete Subscriber

```typescript
await sdk.deleteSubscriber('user@example.com');
```

### Contacts

#### Create Contact

```typescript
await sdk.createContact({
  firstName: 'John',                // Required
  lastName: 'Doe',                  // Optional
  email: 'user@example.com',        // Required
  message: 'Your message here',     // Required
  subject: 'Optional subject',      // Optional
  workspaceId: 'workspace_id',      // Optional
  metadata: { source: 'contact_form' } // Optional
});
```

#### Get Contacts

```typescript
await sdk.getContacts({
  userEmail: 'user@example.com',    // Optional filter
  limit: 50,                        // Optional (1-100)
  page: 1                          // Optional
});
```

#### Update Contact

```typescript
await sdk.updateContact('contact_id', {
  firstName: 'Jane',
  lastName: 'Smith',
  message: 'Updated message'
});
```

#### Delete Contact

```typescript
await sdk.deleteContact('contact_id');
```

### User Preferences

#### Create Preferences

```typescript
await sdk.createPreferences('user@example.com', {
  preferences: [                    // Required
    { 
      id: 'email_frequency', 
      title: 'Email Frequency', 
      description: 'How often to receive emails',
      value: 'weekly'
    }
  ],
  workspaceId: 'workspace_id',      // Optional
  metadata: { theme: 'dark' }       // Optional
});
```

#### Get Preferences

```typescript
await sdk.getPreferences('user@example.com');
```

#### Update Preferences

```typescript
await sdk.updatePreferences('user@example.com', {
  preferences: [
    { 
      id: 'email_frequency', 
      title: 'Email Frequency', 
      description: 'How often to receive emails',
      value: 'daily'  // Updated value
    }
  ]
});
```

#### Delete Preferences

```typescript
await sdk.deletePreferences('user@example.com');
```

### Helper Methods

#### Toggle Subscription

```typescript
await sdk.toggleSubscription(
  'user@example.com',
  'newsletter_id',
  true,  // true to subscribe, false to unsubscribe
  { source: 'user_dashboard' }  // Optional metadata
);
```

#### Get Complete User Profile

```typescript
const profile = await sdk.getUserProfile('user@example.com', {
  includePreferences: true,         // Optional
  includeSubscriptions: true,       // Optional
  includeMetadata: true            // Optional
});
```

#### Check User Data Existence

```typescript
const dataCheck = await sdk.hasUserData('user@example.com');
// Returns: { hasPreferences: boolean, hasSubscriptions: boolean, hasAnyData: boolean }
```

## Error Handling

Always check the `success` property of API responses:

```typescript
const result = await feedinbox.createFeedback(data);

if (result.success) {
  console.log('Success:', result.data);
} else {
  console.error('Error:', result.error);
  // Handle error appropriately
}
```

## Deprecated Methods

These methods are still supported but deprecated. Use the newer equivalents:

```typescript
// Deprecated
await sdk.subscribe(data);      // Use createSubscriber() instead
await sdk.submitContact(data);  // Use createContact() instead
```

## Security Features

- API key validation (must start with `fb_`)
- Input sanitization against XSS attacks
- Email and URL validation
- Rate limiting (100 requests/minute per instance)
- Automatic retry with exponential backoff
- Request timeout protection

## Examples

### Newsletter Subscription

```typescript
async function subscribeUser(email: string) {
  const result = await feedinbox.createSubscriber({
    email,
    subscriptions: [
      { id: 'newsletter', title: 'Weekly Newsletter', description: 'Product updates' }
    ],
    consent: true
  });
  
  if (result.success) {
    console.log('Successfully subscribed');
  } else {
    console.error('Subscription failed:', result.error);
  }
}
```

### Contact Form Submission

```typescript
async function submitContact(formData) {
  const result = await feedinbox.createContact({
    firstName: formData.firstName,
    lastName: formData.lastName,
    email: formData.email,
    message: formData.message,
    subject: formData.subject,
    metadata: {
      source: 'contact_page',
      timestamp: new Date().toISOString()
    }
  });

  return result;
}
```

## Requirements

- Node.js 16+
- TypeScript 5.8+

## License

MIT © FeedInbox