npm package: @giftfeud/learning-bite-sdk
Description: Official SDK for embedding GiftFeud learning bites in any application
Author: GiftFeud
Latest version: 1.8.44

# @giftfeud/learning-bite-sdk

Official SDK for embedding GiftFeud learning bites in any application.

[![npm version](https://img.shields.io/npm/v/@giftfeud/learning-bite-sdk.svg)](https://www.npmjs.com/package/@giftfeud/learning-bite-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## 🚀 Features

- **✅ Complete Rendering** - All content types (video, article, audio, questions)
- **✅ Progress Tracking** - Automatic backend synchronization
- **✅ Answer Submission** - Real-time answer saving
- **✅ Theme Support** - Respects campaign themes or custom styling
- **✅ Mobile-Friendly** - Touch gestures, swipe navigation
- **✅ TypeScript** - Full type definitions included
- **✅ Framework Agnostic** - Works with React, Vue, vanilla JS
- **✅ Security** - API key authentication, domain whitelisting

## 📦 Installation

```bash
npm install @giftfeud/learning-bite-sdk
```

## 🎯 Quick Start

### Basic Usage

```typescript
import { GiftFeudSDK } from '@giftfeud/learning-bite-sdk';

// Initialize SDK
const sdk = new GiftFeudSDK({
  apiKey: 'your-api-key',
  environment: 'production',
  userToken: 'user-auth-token', // For progress tracking
  debug: true, // Enable logging
});

// Load a learning bite
const learningBite = await sdk.loadLearningBite('share-token-123');

console.log(learningBite.title);
console.log(learningBite.slides.length);
```

### With Progress Tracking

```typescript
const sdk = new GiftFeudSDK({
  apiKey: 'your-api-key',
  userToken: 'user-auth-token',
});

// Load learning bite
const bite = await sdk.loadLearningBite('share-token-123');

// Start progress tracking
await sdk.startProgress(bite.id, 'campaign-id');

// Submit answers as user progresses
await sdk.submitAnswer(bite.id, 'slide-id', 5); // Rating scale answer

// Mark slides as completed
await sdk.completeSlide(bite.id, 'slide-id', 30); // 30 seconds

// Complete entire learning bite
await sdk.complete(bite.id, 180); // 180 seconds total
```

## 📚 API Reference

### Constructor

```typescript
new GiftFeudSDK(config: SDKConfig)
```

**Config Options:**

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `apiKey` | `string` | ✅ | Your GiftFeud API key |
| `userToken` | `string` | ❌ | User's auth token for progress tracking |
| `environment` | `'development' \| 'production'` | ❌ | Environment (default: `'production'`) |
| `baseUrl` | `string` | ❌ | Custom API URL |
| `domain` | `string` | ❌ | Domain (auto-detected) |
| `debug` | `boolean` | ❌ | Enable debug logging |
| `onError` | `(error: SDKError) => void` | ❌ | Error handler |

### Methods

#### `loadLearningBite(shareToken: string, pin?: string): Promise<LearningBite>`

Load a learning bite by its share token.

```typescript
const bite = await sdk.loadLearningBite('share-token-123');
```

#### `startProgress(learningElementId: string, campaignId?: string): Promise<any>`

Start tracking progress for a learning bite.

```typescript
await sdk.startProgress(bite.id, 'campaign-id');
```

#### `submitAnswer(learningElementId: string, slideId: string, answer: any, campaignId?: string): Promise<any>`

Submit user's answer to a question slide.

```typescript
// Rating scale answer
await sdk.submitAnswer(bite.id, 'slide-1', 5);

// Multiple choice answer
await sdk.submitAnswer(bite.id, 'slide-2', ['option-a', 'option-b']);

// Text response
await sdk.submitAnswer(bite.id, 'slide-3', 'My answer here');
```

#### `completeSlide(learningElementId: string, slideId: string, timeSpent: number, campaignId?: string): Promise<any>`

Mark a slide as completed with time tracking.

```typescript
await sdk.completeSlide(bite.id, 'slide-1', 45); // 45 seconds
```

#### `complete(learningElementId: string, totalTime: number, score?: number, campaignId?: string): Promise<any>`

Mark entire learning bite as completed.

```typescript
await sdk.complete(bite.id, 180); // 180 seconds total
```

#### `setUserToken(token: string | null): void`

Update the user token (for authentication changes).

```typescript
sdk.setUserToken('new-user-token');
```

## 🎨 Data Types

### LearningBite

```typescript
interface LearningBite {
  id: string;
  title: string;
  description?: string;
  slides: Slide[];
  timeLimitSeconds?: number;
  shareSettings?: ShareSettings;
}
```

### Slide

```typescript
interface Slide {
  id: string;
  type: 'intro' | 'content' | 'question';
  order: number;
  title?: string;
  description?: string;
  coverImage?: string;
  backgroundColor?: string;
  backgroundImage?: string;
  textColor?: string;
  useThemeColors?: boolean;
  useIntroBiteSettings?: boolean;
  contentType?: 'video' | 'article' | 'web_link' | 'audio';
  contentData?: any;
  question?: LearningQuestion;
}
```

### LearningQuestion

```typescript
interface LearningQuestion {
  id?: string;
  type: string; // 'RATING_SCALE', 'MULTIPLE_CHOICE', 'TEXT_RESPONSE', etc.
  questionText?: string;
  description?: string;
  options?: QuestionOption[];
  minValue?: number;
  maxValue?: number;
  leftLabel?: string;
  rightLabel?: string;
}
```

## 🔐 Getting an API Key

1. Contact GiftFeud to request an API key
2. Provide your domain(s) for whitelisting
3. Receive your API key and secret
4. Add to your environment variables:

```bash
GIFTFEUD_API_KEY=your-api-key
```

## 🎮 Framework Examples

### React

```typescript
import { useState, useEffect } from 'react';
import { GiftFeudSDK } from '@giftfeud/learning-bite-sdk';

function LearningBitePlayer({ shareToken, userToken }) {
  const [sdk] = useState(() => new GiftFeudSDK({
    apiKey: process.env.GIFTFEUD_API_KEY,
    userToken,
  }));
  
  const [bite, setBite] = useState(null);

  useEffect(() => {
    sdk.loadLearningBite(shareToken).then(setBite);
  }, [shareToken]);

  if (!bite) return <div>Loading...</div>;

  return (
    <div>
      <h1>{bite.title}</h1>
      {/* Render slides */}
    </div>
  );
}
```

### Vanilla JavaScript

```html
<script src="https://unpkg.com/@giftfeud/learning-bite-sdk"></script>
<script>
  const sdk = new GiftFeudSDK.GiftFeudSDK({
    apiKey: 'your-api-key',
    debug: true,
  });

  sdk.loadLearningBite('share-token-123').then(bite => {
    console.log('Loaded:', bite.title);
    // Render UI
  });
</script>
```

## 🐛 Error Handling

```typescript
try {
  const bite = await sdk.loadLearningBite('invalid-token');
} catch (error) {
  if (error.code === 'AUTHORIZATION_FAILED') {
    console.error('Invalid API key');
  } else if (error.code === 'FETCH_FAILED') {
    console.error('Learning bite not found');
  }
}
```

## 🧪 Testing

Set `environment: 'development'` to test against local API:

```typescript
const sdk = new GiftFeudSDK({
  apiKey: 'test-key',
  environment: 'development', // Points to localhost:3000
  debug: true,
});
```

## 📖 Complete Documentation

- [API Reference](./docs/API.md)
- [Examples](./examples/)
- [Architecture](./docs/ARCHITECTURE.md)
- [Changelog](./CHANGELOG.md)

## 🤝 Support

- 📧 Email: support@giftfeud.com
- 💬 Slack: [GiftFeud Community](https://giftfeud.slack.com)
- 🐛 Issues: [GitHub Issues](https://github.com/giftfeud/learning-bite-sdk/issues)

## 📄 License

MIT © GiftFeud

---

Made with ❤️ by the GiftFeud team