npm package: @memoreco/memoreco-embed
Description: Lightweight SDK to embed and control Memoreco Player iframes
Author: Memoreco
Latest version: 0.1.13

# @memoreco/memoreco-embed

A comprehensive, framework-agnostic SDK to embed and control Memoreco Player iframes with **enterprise-grade media player capabilities**. It provides both programmatic embedding and advanced iframe control through full integration with the @memoreco/media-player.

## Installation

```bash
npm install @memoreco/memoreco-embed
```

Or include via CDN:

```html
<script src="https://cdn.memoreco.com/memoreco-embed.js" async></script>
```

## Configuration

```javascript
import { configure } from '@memoreco/memoreco-embed';

// Configure the SDK (optional)
configure({
  apiKey: 'your-api-key',
  apiBaseUrl: 'https://api.memoreco.com',
  playerBaseUrl: 'https://player.memoreco.com'
});
```

## Usage Examples

### Programmatic Embedding

```javascript
import * as memoreco from '@memoreco/memoreco-embed';

// Get embed metadata and HTML (calls actual oEmbed API)
const embedData = await memoreco.oembed('https://memoreco.com/v/ASSET_ID', { 
  width: 600, 
  autoplay: false 
});
document.getElementById('video-container').innerHTML = embedData.html;

// Replace all Memoreco URLs in a container with embedded players
memoreco.linkReplace('#content', { width: 800, controls: true });

// Replace Memoreco URLs in text with embed HTML
const textWithEmbeds = memoreco.textReplace(blogContent, { width: 600 });
```

### Direct Player Control

```javascript
import { MemorecoPlayer } from '@memoreco/memoreco-embed';

// Create a controllable player instance with enterprise features
const player = MemorecoPlayer.create("#player", {
  assetId: "ASSET_ID",
  token: "JWT_TOKEN", // optional for protected assets
  autoplay: false,
  controls: true,
  theme: { primaryColor: "#C15B3F", darkMode: true }
});

// Enhanced event system with 19 comprehensive events
player.on("ready", (data) => {
  console.log('Player capabilities:', data.capabilities);
  console.log('Media player available:', data.mediaPlayerAvailable);
  player.play();
});

player.on("timeupdate", (data) => console.log(data.currentTime));

// Advanced events from integrated media player
player.on("urlrefresh", (data) => console.log('Signed URL refreshed:', data));
player.on("qualitychange", (data) => console.log('Quality changed:', data.newQuality));
player.on("networkchange", (data) => console.log('Network condition:', data.quality));

// Full playback control
await player.pause();
await player.seek(42);
await player.setVolume(0.8);
await player.setQuality('1080p');
```

## API Reference

### Embedding Methods

#### `oembed(url, options)`
Fetch embed metadata and HTML for a Memoreco URL.

```javascript
const embedData = await oembed('https://memoreco.com/v/ASSET_ID', {
  width: 640,
  height: 360,
  autoplay: false,
  controls: true,
  theme: { primaryColor: '#C15B3F' }
});

console.log(embedData.html); // <iframe src="..."></iframe>
console.log(embedData.title); // Video title
console.log(embedData.thumbnail); // Thumbnail URL
```

#### `linkReplace(selector, options)`
Replace Memoreco URLs with embedded players in DOM elements.

```javascript
// Replace all Memoreco links in articles
linkReplace('article', { width: 800, controls: true });

// Replace in specific container
linkReplace('#video-content', { 
  width: '100%', 
  height: 400,
  theme: { darkMode: true }
});
```

#### `textReplace(text, options)`
Replace Memoreco URLs in text with embed HTML.

```javascript
const blogPost = "Check out this demo: https://memoreco.com/v/abc123";
const withEmbeds = textReplace(blogPost, { width: 600 });
// Returns: "Check out this demo: <iframe src='...'></iframe>"
```

### Player Control Methods

#### `MemorecoPlayer.create(container, options)`
Create a controllable player instance.

```javascript
const player = MemorecoPlayer.create("#player-container", {
  assetId: "ASSET_ID",
  token: "JWT_TOKEN", // optional
  autoplay: false,
  controls: true,
  width: 800,
  height: 450,
  theme: {
    primaryColor: "#C15B3F",
    backgroundColor: "#000000",
    textColor: "#ffffff",
    darkMode: true
  }
});
```

#### Player Methods

**Event Management:**
- `player.on(event, handler)` - Add event listener
- `player.off(event, handler)` - Remove event listener  
- `player.destroy()` - Destroy player and cleanup

**Playback Control:**
- `player.play()` - Start playback
- `player.pause()` - Pause playback
- `player.seek(seconds)` - Seek to specific time

**Audio Control:**
- `player.setVolume(0.8)` - Set volume (0-1)
- `player.setPlaybackRate(1.5)` - Set playback speed

**Display Control:**
- `player.enterFullscreen()` - Enter fullscreen mode
- `player.exitFullscreen()` - Exit fullscreen mode

**State Queries:**
- `player.getState()` - Get current player state
- `player.getCurrentTime()` - Get current playback time
- `player.getDuration()` - Get total video duration

**Quality Control:**
- `player.getQualities()` - Get available quality levels (including HLS levels)
- `player.setQuality('720p')` - Set video quality (supports HLS and manual switching)
- `player.enableAdaptiveStreaming(true)` - Enable/disable adaptive bitrate streaming

**Network & Performance:**
- `player.getNetworkCondition()` - Get current network quality assessment
- `player.getAvailableQualities()` - Get detailed quality information with bitrates
- `player.getCurrentQuality()` - Get currently selected quality level

**UI Control:**
- `player.setTheme(theme)` - Update player theme dynamically
- `player.showCaptions(true)` - Show/hide captions
- `player.enterFullscreen()` - Enter fullscreen mode
- `player.exitFullscreen()` - Exit fullscreen mode

**Advanced Features:**
- `player.setTranscriptLanguage('en')` - Set transcript language
- `player.goToChapter('chapter-1')` - Jump to specific chapter
- `player.setToken('new-jwt')` - Update access token (refreshes signed URLs)

**Enterprise Security:**
- Automatic signed URL refresh before expiration
- JWT token-based authentication for protected content
- Network condition monitoring and quality adaptation
- Comprehensive error handling and recovery

## Events

The enhanced event system provides 19 comprehensive events from the integrated media player:

```javascript
// Core playback events
player.on('ready', (data) => {
  console.log('Player capabilities:', data.capabilities);
  console.log('Media player available:', data.mediaPlayerAvailable);
});
player.on('play', () => console.log('Playback started'));
player.on('pause', () => console.log('Playback paused'));
player.on('ended', () => console.log('Playback finished'));

// Progress and seeking
player.on('timeupdate', (data) => console.log('Time:', data.currentTime));
player.on('seeking', (data) => console.log('Seeking to:', data.currentTime));
player.on('seeked', (data) => console.log('Seeked to:', data.currentTime));
player.on('progress', (data) => console.log('Buffered:', data.buffered));
player.on('durationchange', (data) => console.log('Duration:', data.duration));

// Loading and media states
player.on('loadstart', () => console.log('Started loading'));
player.on('loadedmetadata', () => console.log('Metadata loaded'));
player.on('canplay', () => console.log('Can start playback'));
player.on('waiting', () => console.log('Waiting for data'));

// Quality and streaming
player.on('qualitychange', (data) => {
  console.log('Quality changed:', {
    oldQuality: data.oldQuality,
    newQuality: data.newQuality,
    reason: data.reason,
    networkCondition: data.networkCondition
  });
});

// Enterprise features (signed URLs)
player.on('urlrefresh', (data) => {
  console.log('Signed URL refreshed:', {
    assetId: data.assetId,
    qualityId: data.qualityId,
    expiresAt: new Date(data.expiresAt),
    refreshCount: data.refreshCount
  });
});

player.on('urlexpired', (data) => {
  console.error('Signed URL expired:', {
    assetId: data.assetId,
    qualityId: data.qualityId,
    error: data.error
  });
});

// Audio/video controls
player.on('volumechange', (data) => console.log('Volume:', data.volume));
player.on('ratechange', (data) => console.log('Playback rate:', data.rate));
player.on('fullscreenchange', (data) => console.log('Fullscreen:', data.isFullscreen));

// Error handling
player.on('error', (error) => console.error('Player error:', error));
```

**Available Events:**
- **Core:** `ready`, `play`, `pause`, `ended`, `error`
- **Progress:** `timeupdate`, `seeking`, `seeked`, `progress`, `durationchange`
- **Loading:** `loadstart`, `loadedmetadata`, `canplay`, `waiting`
- **Quality:** `qualitychange` (with network condition data)
- **Controls:** `volumechange`, `ratechange`, `fullscreenchange`
- **Enterprise:** `urlrefresh`, `urlexpired` (signed URL management)
- **Advanced:** `transcript.update`, `chapter.change`, `highlight.click`

## Options

### EmbedOptions / PlayerOptions

```typescript
interface EmbedOptions {
  width?: number | string;     // Player width
  height?: number | string;    // Player height  
  autoplay?: boolean;          // Auto-start playback
  controls?: boolean;          // Show player controls
  muted?: boolean;             // Mute audio
  loop?: boolean;              // Loop playback
  className?: string;          // CSS class for iframe
  token?: string;              // Access token for protected assets
  theme?: PlayerTheme;         // Visual theme
}

interface PlayerTheme {
  primaryColor?: string;       // Primary UI color
  backgroundColor?: string;    // Background color
  textColor?: string;          // Text color
  darkMode?: boolean;          // Use dark theme
}
```

## Security

- **Token-based access:** Use JWT tokens for protected assets
- **Origin validation:** PostMessage communication validates iframe origins
- **Sandbox attributes:** Iframes use appropriate sandbox restrictions
- **HTTPS only:** All communication uses secure protocols

## Browser Support

- Modern browsers with postMessage support
- ES2020+ JavaScript features
- No external dependencies

## Iframe Runtime

The package includes a comprehensive iframe runtime that integrates the full **@memoreco/media-player** within iframe embeds:

```html
<!-- Automatically included in Memoreco Player iframes -->
<script src="/path/to/memoreco-player-runtime.js"></script>
```

### Enterprise Features in Iframe:

**🎥 Full Media Player Integration:**
- Complete @memoreco/media-player instance with all enterprise features
- HLS.js adaptive streaming with automatic quality switching
- Network condition monitoring and bandwidth optimization
- Signed URL management with automatic refresh

**🔒 Security & Authentication:**
- JWT token authentication for protected content
- Automatic signed URL refresh before expiration
- Secure API integration with Memoreco backend services
- Comprehensive error handling and recovery

**⚡ Advanced Capabilities:**
- Quality control (manual and adaptive)
- Theme system with CSS custom properties
- Fullscreen support with native APIs
- Resource management and cleanup

**📊 Comprehensive Event System:**
- 19 detailed events forwarded to parent window
- Network condition monitoring
- Signed URL lifecycle events
- Quality change events with reasons

**🛠️ Developer Experience:**
- Type-safe PostMessage API
- URL parameter parsing for configuration
- Automatic container creation and management
- Fallback mechanisms for reliability

## Build Outputs

The build process generates several optimized files:

**Embed SDK:**
- `dist/index.js` - CommonJS build (185.34 kB, 31.77 kB gzipped)
- `dist/index.mjs` - ES Module build (267.77 kB, 37.89 kB gzipped)  
- `dist/index.umd.js` - UMD build for direct browser inclusion

**Iframe Runtime:**
- `dist/iframe/memoreco-player-runtime.js` - **Enterprise runtime** (702.86 kB, 189.10 kB gzipped)
  - Includes full @memoreco/media-player
  - HLS.js streaming capabilities
  - Complete API client integration
  - Signed URL management system

### Bundle Size Comparison:

| Component | Uncompressed | Gzipped | Features |
|-----------|-------------|---------|----------|
| **Embed SDK** | 267.77 kB | 37.89 kB | Lightweight iframe creator |
| **Iframe Runtime** | 702.86 kB | 189.10 kB | **Full enterprise media player** |

The iframe runtime is significantly larger due to the integration of enterprise features, but this provides complete feature parity between direct player integration and iframe embedding.

## Development

```bash
# Install dependencies
npm install

# Build both embed SDK and iframe runtime
npm run build

# Build only embed SDK
npm run build:embed

# Build only iframe runtime  
npm run build:iframe

# Run tests
npm test

# Type checking
npm run typecheck
```

## License

MIT