mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 10:53:24 +00:00
Compare commits
37 Commits
v0.7.3
...
5e673ac993
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e673ac993 | |||
| 511bac8033 | |||
| eb2c61bdb8 | |||
| 3139897b25 | |||
| a550641993 | |||
| 04603cfe2d | |||
| 6c2fd7952e | |||
| d6f2a10e3e | |||
| a6dc342f3b | |||
| 9486376442 | |||
| cffb092d3f | |||
| 122f211e7c | |||
| 4a6d0ee091 | |||
| b2d42fa776 | |||
| 63e14ddc5b | |||
| c9f6119148 | |||
| 15f821f08a | |||
| 895e7765f9 | |||
| 49d3984640 | |||
| 6057c3c582 | |||
| 255fe42a43 | |||
| 83fd0f84a4 | |||
| aa53d5bc3d | |||
| f5aa6e2189 | |||
| afdca83640 | |||
| c7ea1b9b8f | |||
| 660663945e | |||
| f119a42fcd | |||
| cd55072acb | |||
| 26f71e7a2b | |||
| 0ac1f94502 | |||
| 3530213870 | |||
| e052464482 | |||
| 53206d306b | |||
| c860419e66 | |||
| e22e74fb74 | |||
| 135eda73cf |
120
EVENTBUS_EXAMPLE.md
Normal file
120
EVENTBUS_EXAMPLE.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# EventBus Usage Examples
|
||||
|
||||
## Type-Safe Event Bus
|
||||
|
||||
The `EventBus` class provides fully type-safe event handling with TypeScript type inference.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```typescript
|
||||
import { EventBus } from '@xtr-dev/rondevu-client';
|
||||
|
||||
// Define your event mapping
|
||||
interface AppEvents {
|
||||
'user:connected': { userId: string; timestamp: number };
|
||||
'user:disconnected': { userId: string };
|
||||
'message:received': string;
|
||||
'connection:error': Error;
|
||||
}
|
||||
|
||||
// Create the event bus
|
||||
const events = new EventBus<AppEvents>();
|
||||
|
||||
// Subscribe to events - TypeScript knows the exact data type!
|
||||
events.on('user:connected', (data) => {
|
||||
// data is { userId: string; timestamp: number }
|
||||
console.log(`User ${data.userId} connected at ${data.timestamp}`);
|
||||
});
|
||||
|
||||
events.on('message:received', (data) => {
|
||||
// data is string
|
||||
console.log(data.toUpperCase());
|
||||
});
|
||||
|
||||
// Emit events - TypeScript validates the data type
|
||||
events.emit('user:connected', {
|
||||
userId: '123',
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
events.emit('message:received', 'Hello World');
|
||||
|
||||
// Type errors caught at compile time:
|
||||
// events.emit('user:connected', 'wrong type'); // ❌ Error!
|
||||
// events.emit('message:received', { wrong: 'type' }); // ❌ Error!
|
||||
```
|
||||
|
||||
### One-Time Listeners
|
||||
|
||||
```typescript
|
||||
// Subscribe once - handler auto-unsubscribes after first call
|
||||
events.once('connection:error', (error) => {
|
||||
console.error('Connection failed:', error.message);
|
||||
});
|
||||
```
|
||||
|
||||
### Unsubscribing
|
||||
|
||||
```typescript
|
||||
const handler = (data: string) => {
|
||||
console.log('Message:', data);
|
||||
};
|
||||
|
||||
events.on('message:received', handler);
|
||||
|
||||
// Later, unsubscribe
|
||||
events.off('message:received', handler);
|
||||
```
|
||||
|
||||
### Utility Methods
|
||||
|
||||
```typescript
|
||||
// Clear all handlers for a specific event
|
||||
events.clear('message:received');
|
||||
|
||||
// Clear all handlers for all events
|
||||
events.clear();
|
||||
|
||||
// Get listener count
|
||||
const count = events.listenerCount('user:connected');
|
||||
|
||||
// Get all event names with handlers
|
||||
const eventNames = events.eventNames();
|
||||
```
|
||||
|
||||
## Connection Events Example
|
||||
|
||||
```typescript
|
||||
interface ConnectionEvents {
|
||||
'connection:state': { state: 'connected' | 'disconnected' | 'connecting' };
|
||||
'connection:message': { from: string; data: string | ArrayBuffer };
|
||||
'connection:error': { code: string; message: string };
|
||||
}
|
||||
|
||||
class ConnectionManager {
|
||||
private events = new EventBus<ConnectionEvents>();
|
||||
|
||||
on<K extends keyof ConnectionEvents>(
|
||||
event: K,
|
||||
handler: (data: ConnectionEvents[K]) => void
|
||||
) {
|
||||
this.events.on(event, handler);
|
||||
}
|
||||
|
||||
private handleStateChange(state: 'connected' | 'disconnected' | 'connecting') {
|
||||
this.events.emit('connection:state', { state });
|
||||
}
|
||||
|
||||
private handleMessage(from: string, data: string | ArrayBuffer) {
|
||||
this.events.emit('connection:message', { from, data });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
- ✅ **Full type safety** - TypeScript validates event names and data types
|
||||
- ✅ **IntelliSense support** - Auto-completion for event names and data properties
|
||||
- ✅ **Compile-time errors** - Catch type mismatches before runtime
|
||||
- ✅ **Self-documenting** - Event interface serves as documentation
|
||||
- ✅ **Refactoring-friendly** - Rename events or change types with confidence
|
||||
547
MIGRATION.md
Normal file
547
MIGRATION.md
Normal file
@@ -0,0 +1,547 @@
|
||||
# Migration Guide: v0.8.x → v0.9.0
|
||||
|
||||
This guide helps you migrate from Rondevu Client v0.8.x to v0.9.0.
|
||||
|
||||
## Overview
|
||||
|
||||
v0.9.0 is a **breaking change** that completely replaces low-level APIs with high-level durable connections featuring automatic reconnection and message queuing.
|
||||
|
||||
### What's New
|
||||
|
||||
✅ **Durable Connections**: Automatic reconnection on network drops
|
||||
✅ **Message Queuing**: Messages sent during disconnections are queued and flushed on reconnect
|
||||
✅ **Durable Channels**: RTCDataChannel wrappers that survive connection drops
|
||||
✅ **TTL Auto-Refresh**: Services automatically republish before expiration
|
||||
✅ **Simplified API**: Direct methods on main client instead of nested APIs
|
||||
|
||||
### What's Removed
|
||||
|
||||
❌ **Low-level APIs**: `client.services.*`, `client.discovery.*`, `client.createPeer()` no longer exported
|
||||
❌ **Manual Connection Management**: No need to handle WebRTC peer lifecycle manually
|
||||
❌ **Service Handles**: Replaced with DurableService instances
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
### 1. Service Exposure
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const client = new Rondevu();
|
||||
await client.register();
|
||||
|
||||
const handle = await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
handler: (channel, peer) => {
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
channel.send(`Echo: ${e.data}`);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Unpublish
|
||||
await handle.unpublish();
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const client = new Rondevu();
|
||||
await client.register();
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
poolSize: 10, // NEW: Handle multiple concurrent connections
|
||||
handler: (channel, connectionId) => {
|
||||
// NEW: DurableChannel with event emitters
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// NEW: Start the service
|
||||
await service.start();
|
||||
|
||||
// NEW: Stop the service
|
||||
await service.stop();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.services.exposeService()` → `client.exposeService()`
|
||||
- Returns `DurableService` instead of `ServiceHandle`
|
||||
- Handler receives `DurableChannel` instead of `RTCDataChannel`
|
||||
- Handler receives `connectionId` string instead of `RondevuPeer`
|
||||
- DurableChannel uses `.on('message', ...)` instead of `.onmessage = ...`
|
||||
- Must call `service.start()` to begin accepting connections
|
||||
- Use `service.stop()` instead of `handle.unpublish()`
|
||||
|
||||
### 2. Connecting to Services
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
// Connect by username + FQN
|
||||
const { peer, channel } = await client.discovery.connect(
|
||||
'alice',
|
||||
'chat@1.0.0'
|
||||
);
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
};
|
||||
|
||||
channel.onopen = () => {
|
||||
channel.send('Hello!');
|
||||
};
|
||||
|
||||
peer.on('connected', () => {
|
||||
console.log('Connected');
|
||||
});
|
||||
|
||||
peer.on('failed', (error) => {
|
||||
console.error('Failed:', error);
|
||||
});
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
// Connect by username + FQN
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
maxReconnectAttempts: 10 // NEW: Configurable reconnection
|
||||
});
|
||||
|
||||
// NEW: Create durable channel
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
});
|
||||
|
||||
channel.on('open', () => {
|
||||
channel.send('Hello!');
|
||||
});
|
||||
|
||||
// NEW: Connection lifecycle events
|
||||
connection.on('connected', () => {
|
||||
console.log('Connected');
|
||||
});
|
||||
|
||||
connection.on('reconnecting', (attempt, max, delay) => {
|
||||
console.log(`Reconnecting (${attempt}/${max})...`);
|
||||
});
|
||||
|
||||
connection.on('failed', (error) => {
|
||||
console.error('Failed permanently:', error);
|
||||
});
|
||||
|
||||
// NEW: Must explicitly connect
|
||||
await connection.connect();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.discovery.connect()` → `client.connect()`
|
||||
- Returns `DurableConnection` instead of `{ peer, channel }`
|
||||
- Must create channels with `connection.createChannel()`
|
||||
- Must call `connection.connect()` to establish connection
|
||||
- Automatic reconnection with configurable retry limits
|
||||
- Messages sent during disconnection are automatically queued
|
||||
|
||||
### 3. Connecting by UUID
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
const { peer, channel } = await client.discovery.connectByUuid('service-uuid');
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
};
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
const connection = await client.connectByUuid('service-uuid', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
});
|
||||
|
||||
await connection.connect();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.discovery.connectByUuid()` → `client.connectByUuid()`
|
||||
- Returns `DurableConnection` instead of `{ peer, channel }`
|
||||
- Must create channels and connect explicitly
|
||||
|
||||
### 4. Multi-Connection Services (Offer Pooling)
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
const handle = await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 5,
|
||||
pollingInterval: 2000,
|
||||
handler: (channel, peer, connectionId) => {
|
||||
console.log(`Connection: ${connectionId}`);
|
||||
},
|
||||
onPoolStatus: (status) => {
|
||||
console.log('Pool status:', status);
|
||||
}
|
||||
});
|
||||
|
||||
const status = handle.getStatus();
|
||||
await handle.addOffers(3);
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 5, // SAME: Pool size
|
||||
pollingInterval: 2000, // SAME: Polling interval
|
||||
handler: (channel, connectionId) => {
|
||||
console.log(`Connection: ${connectionId}`);
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
|
||||
// Get active connections
|
||||
const connections = service.getActiveConnections();
|
||||
|
||||
// Listen for connection events
|
||||
service.on('connection', (connectionId) => {
|
||||
console.log('New connection:', connectionId);
|
||||
});
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `onPoolStatus` callback removed (use `service.on('connection')` instead)
|
||||
- `handle.getStatus()` replaced with `service.getActiveConnections()`
|
||||
- `handle.addOffers()` removed (pool auto-manages offers)
|
||||
- Handler receives `DurableChannel` instead of `RTCDataChannel`
|
||||
|
||||
## Feature Comparison
|
||||
|
||||
| Feature | v0.8.x | v0.9.0 |
|
||||
|---------|--------|--------|
|
||||
| Service exposure | `client.services.exposeService()` | `client.exposeService()` |
|
||||
| Connection | `client.discovery.connect()` | `client.connect()` |
|
||||
| Connection by UUID | `client.discovery.connectByUuid()` | `client.connectByUuid()` |
|
||||
| Channel type | `RTCDataChannel` | `DurableChannel` |
|
||||
| Event handling | `.onmessage`, `.onopen`, etc. | `.on('message')`, `.on('open')`, etc. |
|
||||
| Automatic reconnection | ❌ No | ✅ Yes (configurable) |
|
||||
| Message queuing | ❌ No | ✅ Yes (during disconnections) |
|
||||
| TTL auto-refresh | ❌ No | ✅ Yes (configurable) |
|
||||
| Peer lifecycle | Manual | Automatic |
|
||||
| Connection pooling | ✅ Yes | ✅ Yes (same API) |
|
||||
|
||||
## API Mapping
|
||||
|
||||
### Removed Exports
|
||||
|
||||
These are no longer exported in v0.9.0:
|
||||
|
||||
```typescript
|
||||
// ❌ Removed
|
||||
import {
|
||||
RondevuServices,
|
||||
RondevuDiscovery,
|
||||
RondevuPeer,
|
||||
ServiceHandle,
|
||||
PooledServiceHandle,
|
||||
ConnectResult
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
### New Exports
|
||||
|
||||
These are new in v0.9.0:
|
||||
|
||||
```typescript
|
||||
// ✅ New
|
||||
import {
|
||||
DurableConnection,
|
||||
DurableChannel,
|
||||
DurableService,
|
||||
DurableConnectionState,
|
||||
DurableChannelState,
|
||||
DurableConnectionConfig,
|
||||
DurableChannelConfig,
|
||||
DurableServiceConfig,
|
||||
DurableConnectionEvents,
|
||||
DurableChannelEvents,
|
||||
DurableServiceEvents,
|
||||
ConnectionInfo,
|
||||
ServiceInfo,
|
||||
QueuedMessage
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
### Unchanged Exports
|
||||
|
||||
These work the same in both versions:
|
||||
|
||||
```typescript
|
||||
// ✅ Unchanged
|
||||
import {
|
||||
Rondevu,
|
||||
RondevuAuth,
|
||||
RondevuUsername,
|
||||
Credentials,
|
||||
UsernameClaimResult,
|
||||
UsernameCheckResult
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### New Connection Options
|
||||
|
||||
v0.9.0 adds extensive configuration for automatic reconnection and message queuing:
|
||||
|
||||
```typescript
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
// Reconnection
|
||||
maxReconnectAttempts: 10, // default: 10
|
||||
reconnectBackoffBase: 1000, // default: 1000ms
|
||||
reconnectBackoffMax: 30000, // default: 30000ms (30 seconds)
|
||||
reconnectJitter: 0.2, // default: 0.2 (±20%)
|
||||
connectionTimeout: 30000, // default: 30000ms
|
||||
|
||||
// Message queuing
|
||||
maxQueueSize: 1000, // default: 1000 messages
|
||||
maxMessageAge: 60000, // default: 60000ms (1 minute)
|
||||
|
||||
// WebRTC
|
||||
rtcConfig: {
|
||||
iceServers: [...]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### New Service Options
|
||||
|
||||
Services can now auto-refresh TTL:
|
||||
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
|
||||
// TTL auto-refresh (NEW)
|
||||
ttl: 300000, // default: 300000ms (5 minutes)
|
||||
ttlRefreshMargin: 0.2, // default: 0.2 (refresh at 80% of TTL)
|
||||
|
||||
// All connection options also apply to incoming connections
|
||||
maxReconnectAttempts: 10,
|
||||
maxQueueSize: 1000,
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
- [ ] Replace `client.services.exposeService()` with `client.exposeService()`
|
||||
- [ ] Add `await service.start()` after creating service
|
||||
- [ ] Replace `handle.unpublish()` with `service.stop()`
|
||||
- [ ] Replace `client.discovery.connect()` with `client.connect()`
|
||||
- [ ] Replace `client.discovery.connectByUuid()` with `client.connectByUuid()`
|
||||
- [ ] Create channels with `connection.createChannel()` instead of receiving them directly
|
||||
- [ ] Add `await connection.connect()` to establish connection
|
||||
- [ ] Update handlers from `(channel, peer, connectionId?)` to `(channel, connectionId)`
|
||||
- [ ] Replace `.onmessage` with `.on('message', ...)`
|
||||
- [ ] Replace `.onopen` with `.on('open', ...)`
|
||||
- [ ] Replace `.onclose` with `.on('close', ...)`
|
||||
- [ ] Replace `.onerror` with `.on('error', ...)`
|
||||
- [ ] Add reconnection event handlers (`connection.on('reconnecting', ...)`)
|
||||
- [ ] Review and configure reconnection options if needed
|
||||
- [ ] Review and configure message queue limits if needed
|
||||
- [ ] Update TypeScript imports to use new types
|
||||
- [ ] Test automatic reconnection behavior
|
||||
- [ ] Test message queuing during disconnections
|
||||
|
||||
## Common Migration Patterns
|
||||
|
||||
### Pattern 1: Simple Echo Service
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'echo@1.0.0',
|
||||
handler: (channel) => {
|
||||
channel.onmessage = (e) => {
|
||||
channel.send(`Echo: ${e.data}`);
|
||||
};
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'echo@1.0.0',
|
||||
handler: (channel) => {
|
||||
channel.on('message', (data) => {
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
```
|
||||
|
||||
### Pattern 2: Connection with Error Handling
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
try {
|
||||
const { peer, channel } = await client.discovery.connect('alice', 'chat@1.0.0');
|
||||
|
||||
channel.onopen = () => {
|
||||
channel.send('Hello!');
|
||||
};
|
||||
|
||||
peer.on('failed', (error) => {
|
||||
console.error('Connection failed:', error);
|
||||
// Manual reconnection logic here
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to connect:', error);
|
||||
}
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('open', () => {
|
||||
channel.send('Hello!');
|
||||
});
|
||||
|
||||
connection.on('reconnecting', (attempt, max, delay) => {
|
||||
console.log(`Reconnecting (${attempt}/${max}) in ${delay}ms`);
|
||||
});
|
||||
|
||||
connection.on('failed', (error) => {
|
||||
console.error('Connection failed permanently:', error);
|
||||
});
|
||||
|
||||
try {
|
||||
await connection.connect();
|
||||
} catch (error) {
|
||||
console.error('Initial connection failed:', error);
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 3: Multi-User Chat Server
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
const connections = new Map();
|
||||
|
||||
await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 10,
|
||||
handler: (channel, peer, connectionId) => {
|
||||
connections.set(connectionId, channel);
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
// Broadcast to all
|
||||
for (const [id, ch] of connections) {
|
||||
if (id !== connectionId) {
|
||||
ch.send(e.data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
channel.onclose = () => {
|
||||
connections.delete(connectionId);
|
||||
};
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const channels = new Map();
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 10,
|
||||
handler: (channel, connectionId) => {
|
||||
channels.set(connectionId, channel);
|
||||
|
||||
channel.on('message', (data) => {
|
||||
// Broadcast to all
|
||||
for (const [id, ch] of channels) {
|
||||
if (id !== connectionId) {
|
||||
ch.send(data);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
channel.on('close', () => {
|
||||
channels.delete(connectionId);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
|
||||
// Optional: Track connections
|
||||
service.on('connection', (connectionId) => {
|
||||
console.log(`User ${connectionId} joined`);
|
||||
});
|
||||
|
||||
service.on('disconnection', (connectionId) => {
|
||||
console.log(`User ${connectionId} left`);
|
||||
});
|
||||
```
|
||||
|
||||
## Benefits of Migration
|
||||
|
||||
1. **Reliability**: Automatic reconnection handles network hiccups transparently
|
||||
2. **Simplicity**: No need to manage WebRTC peer lifecycle manually
|
||||
3. **Durability**: Messages sent during disconnections are queued and delivered when connection restores
|
||||
4. **Uptime**: Services automatically refresh TTL before expiration
|
||||
5. **Type Safety**: Better TypeScript types with DurableChannel event emitters
|
||||
6. **Debugging**: Queue size monitoring, connection state tracking, and detailed events
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you encounter issues during migration:
|
||||
1. Check the [README](./README.md) for complete API documentation
|
||||
2. Review the examples for common patterns
|
||||
3. Open an issue on [GitHub](https://github.com/xtr-dev/rondevu-client/issues)
|
||||
27
package-lock.json
generated
27
package-lock.json
generated
@@ -1,25 +1,38 @@
|
||||
{
|
||||
"name": "@xtr-dev/rondevu-client",
|
||||
"version": "0.7.3",
|
||||
"version": "0.9.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@xtr-dev/rondevu-client",
|
||||
"version": "0.7.3",
|
||||
"version": "0.9.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@xtr-dev/rondevu-client": "^0.5.1"
|
||||
"@noble/ed25519": "^3.0.0",
|
||||
"@xtr-dev/rondevu-client": "^0.9.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/ed25519": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ed25519/-/ed25519-3.0.0.tgz",
|
||||
"integrity": "sha512-QyteqMNm0GLqfa5SoYbSC3+Pvykwpn95Zgth4MFVSMKBB75ELl9tX1LAVsN4c3HXOrakHsF2gL4zWDAYCcsnzg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@xtr-dev/rondevu-client": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@xtr-dev/rondevu-client/-/rondevu-client-0.5.1.tgz",
|
||||
"integrity": "sha512-110ejMCizPUPkHwwwNvcdCSZceLaHeFbf1LNkXvbG6pnLBqCf2uoGOOaRkArb7HNNFABFB+HXzm/AVzNdadosw==",
|
||||
"license": "MIT"
|
||||
"version": "0.9.2",
|
||||
"resolved": "https://registry.npmjs.org/@xtr-dev/rondevu-client/-/rondevu-client-0.9.2.tgz",
|
||||
"integrity": "sha512-DVow5AOPU40dqQtlfQK7J2GNX8dz2/4UzltMqublaPZubbkRYgocvp0b76NQu5F6v150IstMV2N49uxAYqogVw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@xtr-dev/rondevu-client",
|
||||
"version": "0.7.3",
|
||||
"description": "TypeScript client for Rondevu topic-based peer discovery and signaling server",
|
||||
"version": "0.9.2",
|
||||
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
@@ -27,6 +27,7 @@
|
||||
"README.md"
|
||||
],
|
||||
"dependencies": {
|
||||
"@xtr-dev/rondevu-client": "^0.5.1"
|
||||
"@noble/ed25519": "^3.0.0",
|
||||
"@xtr-dev/rondevu-client": "^0.9.2"
|
||||
}
|
||||
}
|
||||
|
||||
60
src/auth.ts
60
src/auth.ts
@@ -1,60 +0,0 @@
|
||||
export interface Credentials {
|
||||
peerId: string;
|
||||
secret: string;
|
||||
}
|
||||
|
||||
// Fetch-compatible function type
|
||||
export type FetchFunction = (
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
) => Promise<Response>;
|
||||
|
||||
export class RondevuAuth {
|
||||
private fetchFn: FetchFunction;
|
||||
|
||||
constructor(
|
||||
private baseUrl: string,
|
||||
fetchFn?: FetchFunction
|
||||
) {
|
||||
// Use provided fetch or fall back to global fetch
|
||||
this.fetchFn = fetchFn || ((...args) => {
|
||||
if (typeof globalThis.fetch === 'function') {
|
||||
return globalThis.fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'fetch is not available. Please provide a fetch implementation in the constructor options.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new peer and receive credentials
|
||||
*/
|
||||
async register(): Promise<Credentials> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Registration failed: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return {
|
||||
peerId: data.peerId,
|
||||
secret: data.secret,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Authorization header value
|
||||
*/
|
||||
static createAuthHeader(credentials: Credentials): string {
|
||||
return `Bearer ${credentials.peerId}:${credentials.secret}`;
|
||||
}
|
||||
}
|
||||
83
src/bloom.ts
83
src/bloom.ts
@@ -1,83 +0,0 @@
|
||||
// Declare Buffer for Node.js compatibility
|
||||
declare const Buffer: any;
|
||||
|
||||
/**
|
||||
* Simple bloom filter implementation for peer ID exclusion
|
||||
* Uses multiple hash functions for better distribution
|
||||
*/
|
||||
export class BloomFilter {
|
||||
private bits: Uint8Array;
|
||||
private size: number;
|
||||
private numHashes: number;
|
||||
|
||||
constructor(size: number = 1024, numHashes: number = 3) {
|
||||
this.size = size;
|
||||
this.numHashes = numHashes;
|
||||
this.bits = new Uint8Array(Math.ceil(size / 8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a peer ID to the filter
|
||||
*/
|
||||
add(peerId: string): void {
|
||||
for (let i = 0; i < this.numHashes; i++) {
|
||||
const hash = this.hash(peerId, i);
|
||||
const index = hash % this.size;
|
||||
const byteIndex = Math.floor(index / 8);
|
||||
const bitIndex = index % 8;
|
||||
this.bits[byteIndex] |= 1 << bitIndex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if peer ID might be in the filter
|
||||
*/
|
||||
test(peerId: string): boolean {
|
||||
for (let i = 0; i < this.numHashes; i++) {
|
||||
const hash = this.hash(peerId, i);
|
||||
const index = hash % this.size;
|
||||
const byteIndex = Math.floor(index / 8);
|
||||
const bitIndex = index % 8;
|
||||
if (!(this.bits[byteIndex] & (1 << bitIndex))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get raw bits for transmission
|
||||
*/
|
||||
toBytes(): Uint8Array {
|
||||
return this.bits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert to base64 for URL parameters
|
||||
*/
|
||||
toBase64(): string {
|
||||
// Convert Uint8Array to regular array then to string
|
||||
const binaryString = String.fromCharCode(...Array.from(this.bits));
|
||||
// Use btoa for browser, or Buffer for Node.js
|
||||
if (typeof btoa !== 'undefined') {
|
||||
return btoa(binaryString);
|
||||
} else if (typeof Buffer !== 'undefined') {
|
||||
return Buffer.from(this.bits).toString('base64');
|
||||
} else {
|
||||
// Fallback: manual base64 encoding
|
||||
throw new Error('No base64 encoding available');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple hash function (FNV-1a variant)
|
||||
*/
|
||||
private hash(str: string, seed: number): number {
|
||||
let hash = 2166136261 ^ seed;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash ^= str.charCodeAt(i);
|
||||
hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
}
|
||||
208
src/client.ts
208
src/client.ts
@@ -1,208 +0,0 @@
|
||||
import {
|
||||
RondevuClientOptions,
|
||||
CreateOfferRequest,
|
||||
CreateOfferResponse,
|
||||
AnswerRequest,
|
||||
AnswerResponse,
|
||||
PollRequest,
|
||||
PollOffererResponse,
|
||||
PollAnswererResponse,
|
||||
VersionResponse,
|
||||
HealthResponse,
|
||||
ErrorResponse,
|
||||
Side,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* HTTP API client for Rondevu peer signaling server
|
||||
*/
|
||||
export class RondevuAPI {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
/**
|
||||
* Creates a new Rondevu API client instance
|
||||
* @param options - Client configuration options
|
||||
*/
|
||||
constructor(options: RondevuClientOptions) {
|
||||
this.baseUrl = options.baseUrl.replace(/\/$/, ''); // Remove trailing slash
|
||||
this.fetchImpl = options.fetch || globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes an HTTP request to the Rondevu server
|
||||
*/
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (options.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
const response = await this.fetchImpl(url, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const error = data as ErrorResponse;
|
||||
throw new Error(error.error || `HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets server version information
|
||||
*
|
||||
* @returns Server version
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
* const { version } = await api.getVersion();
|
||||
* console.log('Server version:', version);
|
||||
* ```
|
||||
*/
|
||||
async getVersion(): Promise<VersionResponse> {
|
||||
return this.request<VersionResponse>('/', {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new offer
|
||||
*
|
||||
* @param request - Offer details including peer ID, signaling data, and optional custom code
|
||||
* @returns Unique offer code (UUID or custom code)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
* const { code } = await api.createOffer({
|
||||
* peerId: 'peer-123',
|
||||
* offer: signalingData,
|
||||
* code: 'my-custom-code' // optional
|
||||
* });
|
||||
* console.log('Offer code:', code);
|
||||
* ```
|
||||
*/
|
||||
async createOffer(request: CreateOfferRequest): Promise<CreateOfferResponse> {
|
||||
return this.request<CreateOfferResponse>('/offer', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an answer or candidate to an existing offer
|
||||
*
|
||||
* @param request - Answer details including offer code and signaling data
|
||||
* @returns Success confirmation
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
*
|
||||
* // Send answer
|
||||
* await api.sendAnswer({
|
||||
* code: offerCode,
|
||||
* answer: answerData,
|
||||
* side: 'answerer'
|
||||
* });
|
||||
*
|
||||
* // Send candidate
|
||||
* await api.sendAnswer({
|
||||
* code: offerCode,
|
||||
* candidate: candidateData,
|
||||
* side: 'offerer'
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
async sendAnswer(request: AnswerRequest): Promise<AnswerResponse> {
|
||||
return this.request<AnswerResponse>('/answer', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls for offer data from the other peer
|
||||
*
|
||||
* @param code - Offer code
|
||||
* @param side - Which side is polling ('offerer' or 'answerer')
|
||||
* @returns Offer data including offers, answers, and candidates
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
*
|
||||
* // Offerer polls for answer
|
||||
* const offererData = await api.poll(offerCode, 'offerer');
|
||||
* if (offererData.answer) {
|
||||
* console.log('Received answer:', offererData.answer);
|
||||
* }
|
||||
*
|
||||
* // Answerer polls for offer
|
||||
* const answererData = await api.poll(offerCode, 'answerer');
|
||||
* console.log('Received offer:', answererData.offer);
|
||||
* ```
|
||||
*/
|
||||
async poll(
|
||||
code: string,
|
||||
side: Side
|
||||
): Promise<PollOffererResponse | PollAnswererResponse> {
|
||||
const request: PollRequest = { code, side };
|
||||
return this.request<PollOffererResponse | PollAnswererResponse>('/poll', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks server health and version
|
||||
*
|
||||
* @returns Health status, timestamp, and version
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
* const health = await api.health();
|
||||
* console.log('Server status:', health.status);
|
||||
* console.log('Server version:', health.version);
|
||||
* ```
|
||||
*/
|
||||
async health(): Promise<HealthResponse> {
|
||||
return this.request<HealthResponse>('/health', {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a session by deleting the offer from the server
|
||||
*
|
||||
* @param code - The offer code
|
||||
* @returns Success confirmation
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
||||
* await api.leave('my-offer-code');
|
||||
* ```
|
||||
*/
|
||||
async leave(code: string): Promise<{ success: boolean }> {
|
||||
return this.request<{ success: boolean }>('/leave', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
}
|
||||
}
|
||||
9
src/connection-manager.ts
Normal file
9
src/connection-manager.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* ConnectionManager - Manages WebRTC peer connections
|
||||
*/
|
||||
|
||||
export class ConnectionManager {
|
||||
constructor() {
|
||||
// TODO: Initialize connection manager
|
||||
}
|
||||
}
|
||||
104
src/event-bus.ts
Normal file
104
src/event-bus.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Type-safe EventBus with event name to payload type mapping
|
||||
*/
|
||||
|
||||
type EventHandler<T = any> = (data: T) => void;
|
||||
|
||||
/**
|
||||
* EventBus - Type-safe event emitter with inferred event data types
|
||||
*
|
||||
* @example
|
||||
* interface MyEvents {
|
||||
* 'user:connected': { userId: string; timestamp: number };
|
||||
* 'user:disconnected': { userId: string };
|
||||
* 'message:received': string;
|
||||
* }
|
||||
*
|
||||
* const bus = new EventBus<MyEvents>();
|
||||
*
|
||||
* // TypeScript knows data is { userId: string; timestamp: number }
|
||||
* bus.on('user:connected', (data) => {
|
||||
* console.log(data.userId, data.timestamp);
|
||||
* });
|
||||
*
|
||||
* // TypeScript knows data is string
|
||||
* bus.on('message:received', (data) => {
|
||||
* console.log(data.toUpperCase());
|
||||
* });
|
||||
*/
|
||||
export class EventBus<TEvents extends Record<string, any>> {
|
||||
private handlers: Map<keyof TEvents, Set<EventHandler>>;
|
||||
|
||||
constructor() {
|
||||
this.handlers = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to an event
|
||||
*/
|
||||
on<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
|
||||
if (!this.handlers.has(event)) {
|
||||
this.handlers.set(event, new Set());
|
||||
}
|
||||
this.handlers.get(event)!.add(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to an event once (auto-unsubscribe after first call)
|
||||
*/
|
||||
once<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
|
||||
const wrappedHandler = (data: TEvents[K]) => {
|
||||
handler(data);
|
||||
this.off(event, wrappedHandler);
|
||||
};
|
||||
this.on(event, wrappedHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from an event
|
||||
*/
|
||||
off<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
|
||||
const eventHandlers = this.handlers.get(event);
|
||||
if (eventHandlers) {
|
||||
eventHandlers.delete(handler);
|
||||
if (eventHandlers.size === 0) {
|
||||
this.handlers.delete(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an event with data
|
||||
*/
|
||||
emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void {
|
||||
const eventHandlers = this.handlers.get(event);
|
||||
if (eventHandlers) {
|
||||
eventHandlers.forEach(handler => handler(data));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all handlers for a specific event, or all handlers if no event specified
|
||||
*/
|
||||
clear<K extends keyof TEvents>(event?: K): void {
|
||||
if (event !== undefined) {
|
||||
this.handlers.delete(event);
|
||||
} else {
|
||||
this.handlers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of handlers for an event
|
||||
*/
|
||||
listenerCount<K extends keyof TEvents>(event: K): number {
|
||||
return this.handlers.get(event)?.size ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all event names that have handlers
|
||||
*/
|
||||
eventNames(): Array<keyof TEvents> {
|
||||
return Array.from(this.handlers.keys());
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* Type-safe EventEmitter implementation for browser and Node.js compatibility
|
||||
*
|
||||
* @template EventMap - A type mapping event names to their handler signatures
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* interface MyEvents {
|
||||
* 'data': (value: string) => void;
|
||||
* 'error': (error: Error) => void;
|
||||
* 'ready': () => void;
|
||||
* }
|
||||
*
|
||||
* class MyClass extends EventEmitter<MyEvents> {
|
||||
* doSomething() {
|
||||
* this.emit('data', 'hello'); // Type-safe!
|
||||
* this.emit('error', new Error('oops')); // Type-safe!
|
||||
* this.emit('ready'); // Type-safe!
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* const instance = new MyClass();
|
||||
* instance.on('data', (value) => {
|
||||
* console.log(value.toUpperCase()); // 'value' is typed as string
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class EventEmitter<EventMap extends Record<string, (...args: any[]) => void>> {
|
||||
private events: Map<keyof EventMap, Set<Function>> = new Map();
|
||||
|
||||
/**
|
||||
* Register an event listener
|
||||
*/
|
||||
on<K extends keyof EventMap>(event: K, listener: EventMap[K]): this {
|
||||
if (!this.events.has(event)) {
|
||||
this.events.set(event, new Set());
|
||||
}
|
||||
this.events.get(event)!.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a one-time event listener
|
||||
*/
|
||||
once<K extends keyof EventMap>(event: K, listener: EventMap[K]): this {
|
||||
const onceWrapper = (...args: Parameters<EventMap[K]>) => {
|
||||
this.off(event, onceWrapper as EventMap[K]);
|
||||
listener(...args);
|
||||
};
|
||||
return this.on(event, onceWrapper as EventMap[K]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an event listener
|
||||
*/
|
||||
off<K extends keyof EventMap>(event: K, listener: EventMap[K]): this {
|
||||
const listeners = this.events.get(event);
|
||||
if (listeners) {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) {
|
||||
this.events.delete(event);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an event
|
||||
*/
|
||||
protected emit<K extends keyof EventMap>(
|
||||
event: K,
|
||||
...args: Parameters<EventMap[K]>
|
||||
): boolean {
|
||||
const listeners = this.events.get(event);
|
||||
if (!listeners || listeners.size === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
listeners.forEach(listener => {
|
||||
try {
|
||||
(listener as EventMap[K])(...args);
|
||||
} catch (err) {
|
||||
console.error(`Error in ${String(event)} event listener:`, err);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all listeners for an event (or all events if not specified)
|
||||
*/
|
||||
removeAllListeners<K extends keyof EventMap>(event?: K): this {
|
||||
if (event !== undefined) {
|
||||
this.events.delete(event);
|
||||
} else {
|
||||
this.events.clear();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get listener count for an event
|
||||
*/
|
||||
listenerCount<K extends keyof EventMap>(event: K): number {
|
||||
const listeners = this.events.get(event);
|
||||
return listeners ? listeners.size : 0;
|
||||
}
|
||||
}
|
||||
36
src/index.ts
36
src/index.ts
@@ -1,32 +1,16 @@
|
||||
/**
|
||||
* @xtr-dev/rondevu-client
|
||||
* WebRTC peer signaling and discovery client with topic-based discovery
|
||||
* WebRTC peer signaling client
|
||||
*/
|
||||
|
||||
// Export main client class
|
||||
export { Rondevu } from './rondevu.js';
|
||||
export type { RondevuOptions } from './rondevu.js';
|
||||
export { ConnectionManager } from './connection-manager.js';
|
||||
export { EventBus } from './event-bus.js';
|
||||
|
||||
// Export authentication
|
||||
export { RondevuAuth } from './auth.js';
|
||||
export type { Credentials, FetchFunction } from './auth.js';
|
||||
|
||||
// Export offers API
|
||||
export { RondevuOffers } from './offers.js';
|
||||
// Export types
|
||||
export type {
|
||||
CreateOfferRequest,
|
||||
Offer,
|
||||
IceCandidate,
|
||||
TopicInfo
|
||||
} from './offers.js';
|
||||
|
||||
// Export bloom filter
|
||||
export { BloomFilter } from './bloom.js';
|
||||
|
||||
// Export peer manager
|
||||
export { default as RondevuPeer } from './peer/index.js';
|
||||
export type {
|
||||
PeerOptions,
|
||||
PeerEvents,
|
||||
PeerTimeouts
|
||||
} from './peer/index.js';
|
||||
ConnectionIdentity,
|
||||
ConnectionState,
|
||||
ConnectionInterface,
|
||||
Connection,
|
||||
QueueMessageOptions
|
||||
} from './types.js';
|
||||
|
||||
327
src/offers.ts
327
src/offers.ts
@@ -1,327 +0,0 @@
|
||||
import { Credentials, FetchFunction } from './auth.js';
|
||||
import { RondevuAuth } from './auth.js';
|
||||
|
||||
// Declare Buffer for Node.js compatibility
|
||||
declare const Buffer: any;
|
||||
|
||||
export interface CreateOfferRequest {
|
||||
sdp: string;
|
||||
topics: string[];
|
||||
ttl?: number;
|
||||
}
|
||||
|
||||
export interface Offer {
|
||||
id: string;
|
||||
peerId: string;
|
||||
sdp: string;
|
||||
topics: string[];
|
||||
createdAt?: number;
|
||||
expiresAt: number;
|
||||
lastSeen: number;
|
||||
answererPeerId?: string;
|
||||
answerSdp?: string;
|
||||
answeredAt?: number;
|
||||
}
|
||||
|
||||
export interface IceCandidate {
|
||||
candidate: any; // Full candidate object as plain JSON - don't enforce structure
|
||||
peerId: string;
|
||||
role: 'offerer' | 'answerer';
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface TopicInfo {
|
||||
topic: string;
|
||||
activePeers: number;
|
||||
}
|
||||
|
||||
export class RondevuOffers {
|
||||
private fetchFn: FetchFunction;
|
||||
|
||||
constructor(
|
||||
private baseUrl: string,
|
||||
private credentials: Credentials,
|
||||
fetchFn?: FetchFunction
|
||||
) {
|
||||
// Use provided fetch or fall back to global fetch
|
||||
this.fetchFn = fetchFn || ((...args) => {
|
||||
if (typeof globalThis.fetch === 'function') {
|
||||
return globalThis.fetch(...args);
|
||||
}
|
||||
throw new Error(
|
||||
'fetch is not available. Please provide a fetch implementation in the constructor options.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create one or more offers
|
||||
*/
|
||||
async create(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
body: JSON.stringify({ offers }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to create offers: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.offers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find offers by topic with optional bloom filter
|
||||
*/
|
||||
async findByTopic(
|
||||
topic: string,
|
||||
options?: {
|
||||
bloomFilter?: Uint8Array;
|
||||
limit?: number;
|
||||
}
|
||||
): Promise<Offer[]> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (options?.bloomFilter) {
|
||||
// Convert to base64
|
||||
const binaryString = String.fromCharCode(...Array.from(options.bloomFilter));
|
||||
const base64 = typeof btoa !== 'undefined'
|
||||
? btoa(binaryString)
|
||||
: (typeof Buffer !== 'undefined' ? Buffer.from(options.bloomFilter).toString('base64') : '');
|
||||
params.set('bloom', base64);
|
||||
}
|
||||
|
||||
if (options?.limit) {
|
||||
params.set('limit', options.limit.toString());
|
||||
}
|
||||
|
||||
const url = `${this.baseUrl}/offers/by-topic/${encodeURIComponent(topic)}${
|
||||
params.toString() ? '?' + params.toString() : ''
|
||||
}`;
|
||||
|
||||
const response = await this.fetchFn(url, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to find offers: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.offers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all offers from a specific peer
|
||||
*/
|
||||
async getByPeerId(peerId: string): Promise<{
|
||||
offers: Offer[];
|
||||
topics: string[];
|
||||
}> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/peers/${encodeURIComponent(peerId)}/offers`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to get peer offers: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get topics with active peer counts (paginated)
|
||||
*/
|
||||
async getTopics(options?: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<{
|
||||
topics: TopicInfo[];
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (options?.limit) {
|
||||
params.set('limit', options.limit.toString());
|
||||
}
|
||||
|
||||
if (options?.offset) {
|
||||
params.set('offset', options.offset.toString());
|
||||
}
|
||||
|
||||
const url = `${this.baseUrl}/topics${
|
||||
params.toString() ? '?' + params.toString() : ''
|
||||
}`;
|
||||
|
||||
const response = await this.fetchFn(url, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to get topics: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get own offers
|
||||
*/
|
||||
async getMine(): Promise<Offer[]> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/mine`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to get own offers: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.offers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update offer heartbeat
|
||||
*/
|
||||
async heartbeat(offerId: string): Promise<void> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/heartbeat`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to update heartbeat: ${error.error || response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an offer
|
||||
*/
|
||||
async delete(offerId: string): Promise<void> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to delete offer: ${error.error || response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer an offer
|
||||
*/
|
||||
async answer(offerId: string, sdp: string): Promise<void> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/answer`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
body: JSON.stringify({ sdp }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to answer offer: ${error.error || response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get answers to your offers
|
||||
*/
|
||||
async getAnswers(): Promise<Array<{
|
||||
offerId: string;
|
||||
answererId: string;
|
||||
sdp: string;
|
||||
answeredAt: number;
|
||||
topics: string[];
|
||||
}>> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/answers`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to get answers: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.answers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Post ICE candidates for an offer
|
||||
*/
|
||||
async addIceCandidates(
|
||||
offerId: string,
|
||||
candidates: any[]
|
||||
): Promise<void> {
|
||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/ice-candidates`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
body: JSON.stringify({ candidates }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to add ICE candidates: ${error.error || response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ICE candidates for an offer
|
||||
*/
|
||||
async getIceCandidates(offerId: string, since?: number): Promise<IceCandidate[]> {
|
||||
const params = new URLSearchParams();
|
||||
if (since !== undefined) {
|
||||
params.set('since', since.toString());
|
||||
}
|
||||
|
||||
const url = `${this.baseUrl}/offers/${encodeURIComponent(offerId)}/ice-candidates${
|
||||
params.toString() ? '?' + params.toString() : ''
|
||||
}`;
|
||||
|
||||
const response = await this.fetchFn(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(`Failed to get ICE candidates: ${error.error || response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.candidates;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
import type { PeerOptions } from './types.js';
|
||||
import type RondevuPeer from './index.js';
|
||||
|
||||
/**
|
||||
* Answering an offer and sending to server
|
||||
*/
|
||||
export class AnsweringState extends PeerState {
|
||||
constructor(peer: RondevuPeer) {
|
||||
super(peer);
|
||||
}
|
||||
|
||||
get name() { return 'answering'; }
|
||||
|
||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
||||
try {
|
||||
this.peer.role = 'answerer';
|
||||
this.peer.offerId = offerId;
|
||||
|
||||
// Set remote description
|
||||
await this.peer.pc.setRemoteDescription({
|
||||
type: 'offer',
|
||||
sdp: offerSdp
|
||||
});
|
||||
|
||||
// Create answer
|
||||
const answer = await this.peer.pc.createAnswer();
|
||||
|
||||
// Send answer to server BEFORE setLocalDescription
|
||||
// This registers us as the answerer so ICE candidates will be accepted
|
||||
await this.peer.offersApi.answer(offerId, answer.sdp!);
|
||||
|
||||
// Enable trickle ICE - set up handler before ICE gathering starts
|
||||
this.setupIceCandidateHandler();
|
||||
|
||||
// Set local description - ICE gathering starts here
|
||||
// Server already knows we're the answerer, so candidates will be accepted
|
||||
await this.peer.pc.setLocalDescription(answer);
|
||||
|
||||
// Transition to exchanging ICE
|
||||
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
||||
this.peer.setState(new ExchangingIceState(this.peer, offerId, options));
|
||||
} catch (error) {
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
|
||||
/**
|
||||
* Closed state - connection has been terminated
|
||||
*/
|
||||
export class ClosedState extends PeerState {
|
||||
get name() { return 'closed'; }
|
||||
|
||||
cleanup(): void {
|
||||
this.peer.pc.close();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
|
||||
/**
|
||||
* Connected state - peer connection is established
|
||||
*/
|
||||
export class ConnectedState extends PeerState {
|
||||
get name() { return 'connected'; }
|
||||
|
||||
cleanup(): void {
|
||||
// Keep connection alive, but stop any polling
|
||||
// The peer connection will handle disconnects via onconnectionstatechange
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
import type { PeerOptions } from './types.js';
|
||||
import type RondevuPeer from './index.js';
|
||||
|
||||
/**
|
||||
* Creating offer and sending to server
|
||||
*/
|
||||
export class CreatingOfferState extends PeerState {
|
||||
constructor(peer: RondevuPeer, private options: PeerOptions) {
|
||||
super(peer);
|
||||
}
|
||||
|
||||
get name() { return 'creating-offer'; }
|
||||
|
||||
async createOffer(options: PeerOptions): Promise<string> {
|
||||
try {
|
||||
this.peer.role = 'offerer';
|
||||
|
||||
// Create data channel if requested
|
||||
if (options.createDataChannel !== false) {
|
||||
const channel = this.peer.pc.createDataChannel(
|
||||
options.dataChannelLabel || 'data'
|
||||
);
|
||||
this.peer.emitEvent('datachannel', channel);
|
||||
}
|
||||
|
||||
// Enable trickle ICE - set up handler before ICE gathering starts
|
||||
// Handler will check this.peer.offerId before sending
|
||||
this.setupIceCandidateHandler();
|
||||
|
||||
// Create WebRTC offer
|
||||
const offer = await this.peer.pc.createOffer();
|
||||
await this.peer.pc.setLocalDescription(offer); // ICE gathering starts here
|
||||
|
||||
// Send offer to server immediately (don't wait for ICE)
|
||||
const offers = await this.peer.offersApi.create([{
|
||||
sdp: offer.sdp!,
|
||||
topics: options.topics,
|
||||
ttl: options.ttl || 300000
|
||||
}]);
|
||||
|
||||
const offerId = offers[0].id;
|
||||
this.peer.offerId = offerId; // Now handler can send candidates
|
||||
|
||||
// Transition to waiting for answer
|
||||
const { WaitingForAnswerState } = await import('./waiting-for-answer-state.js');
|
||||
this.peer.setState(new WaitingForAnswerState(this.peer, offerId, options));
|
||||
|
||||
return offerId;
|
||||
} catch (error) {
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
import type { PeerOptions } from './types.js';
|
||||
import type RondevuPeer from './index.js';
|
||||
|
||||
/**
|
||||
* Exchanging ICE candidates and waiting for connection
|
||||
*/
|
||||
export class ExchangingIceState extends PeerState {
|
||||
private pollingInterval?: ReturnType<typeof setInterval>;
|
||||
private timeout?: ReturnType<typeof setTimeout>;
|
||||
private lastIceTimestamp = 0;
|
||||
|
||||
constructor(
|
||||
peer: RondevuPeer,
|
||||
private offerId: string,
|
||||
private options: PeerOptions
|
||||
) {
|
||||
super(peer);
|
||||
this.startPolling();
|
||||
}
|
||||
|
||||
get name() { return 'exchanging-ice'; }
|
||||
|
||||
private startPolling(): void {
|
||||
const connectionTimeout = this.options.timeouts?.iceConnection || 30000;
|
||||
|
||||
this.timeout = setTimeout(async () => {
|
||||
this.cleanup();
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(
|
||||
this.peer,
|
||||
new Error('ICE connection timeout')
|
||||
));
|
||||
}, connectionTimeout);
|
||||
|
||||
this.pollingInterval = setInterval(async () => {
|
||||
try {
|
||||
const candidates = await this.peer.offersApi.getIceCandidates(
|
||||
this.offerId,
|
||||
this.lastIceTimestamp
|
||||
);
|
||||
|
||||
for (const cand of candidates) {
|
||||
if (cand.candidate && cand.candidate.candidate && cand.candidate.candidate !== '') {
|
||||
try {
|
||||
await this.peer.pc.addIceCandidate(new RTCIceCandidate(cand.candidate));
|
||||
this.lastIceTimestamp = cand.createdAt;
|
||||
} catch (err) {
|
||||
console.warn('Failed to add ICE candidate:', err);
|
||||
this.lastIceTimestamp = cand.createdAt;
|
||||
}
|
||||
} else {
|
||||
this.lastIceTimestamp = cand.createdAt;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error polling for ICE candidates:', err);
|
||||
if (err instanceof Error && err.message.includes('not found')) {
|
||||
this.cleanup();
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(
|
||||
this.peer,
|
||||
new Error('Offer expired or not found')
|
||||
));
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
if (this.pollingInterval) clearInterval(this.pollingInterval);
|
||||
if (this.timeout) clearTimeout(this.timeout);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
|
||||
/**
|
||||
* Failed state - connection attempt failed
|
||||
*/
|
||||
export class FailedState extends PeerState {
|
||||
constructor(peer: any, private error: Error) {
|
||||
super(peer);
|
||||
peer.emitEvent('failed', error);
|
||||
}
|
||||
|
||||
get name() { return 'failed'; }
|
||||
|
||||
cleanup(): void {
|
||||
// Connection is failed, clean up resources
|
||||
this.peer.pc.close();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
import type { PeerOptions } from './types.js';
|
||||
|
||||
export class IdleState extends PeerState {
|
||||
get name() { return 'idle'; }
|
||||
|
||||
async createOffer(options: PeerOptions): Promise<string> {
|
||||
const { CreatingOfferState } = await import('./creating-offer-state.js');
|
||||
this.peer.setState(new CreatingOfferState(this.peer, options));
|
||||
return this.peer.state.createOffer(options);
|
||||
}
|
||||
|
||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
||||
const { AnsweringState } = await import('./answering-state.js');
|
||||
this.peer.setState(new AnsweringState(this.peer));
|
||||
return this.peer.state.answer(offerId, offerSdp, options);
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
import { RondevuOffers } from '../offers.js';
|
||||
import { EventEmitter } from '../event-emitter.js';
|
||||
import type { PeerOptions, PeerEvents } from './types.js';
|
||||
import { PeerState } from './state.js';
|
||||
import { IdleState } from './idle-state.js';
|
||||
import { CreatingOfferState } from './creating-offer-state.js';
|
||||
import { WaitingForAnswerState } from './waiting-for-answer-state.js';
|
||||
import { AnsweringState } from './answering-state.js';
|
||||
import { ExchangingIceState } from './exchanging-ice-state.js';
|
||||
import { ConnectedState } from './connected-state.js';
|
||||
import { FailedState } from './failed-state.js';
|
||||
import { ClosedState } from './closed-state.js';
|
||||
|
||||
// Re-export types for external consumers
|
||||
export type { PeerTimeouts, PeerOptions, PeerEvents } from './types.js';
|
||||
|
||||
/**
|
||||
* High-level WebRTC peer connection manager with state-based lifecycle
|
||||
* Handles offer/answer exchange, ICE candidates, timeouts, and error recovery
|
||||
*/
|
||||
export default class RondevuPeer extends EventEmitter<PeerEvents> {
|
||||
pc: RTCPeerConnection;
|
||||
offersApi: RondevuOffers;
|
||||
offerId?: string;
|
||||
role?: 'offerer' | 'answerer';
|
||||
|
||||
private _state: PeerState;
|
||||
|
||||
// Event handler references for cleanup
|
||||
private connectionStateChangeHandler?: () => void;
|
||||
private dataChannelHandler?: (event: RTCDataChannelEvent) => void;
|
||||
private trackHandler?: (event: RTCTrackEvent) => void;
|
||||
private iceCandidateErrorHandler?: (event: Event) => void;
|
||||
|
||||
/**
|
||||
* Current connection state name
|
||||
*/
|
||||
get stateName(): string {
|
||||
return this._state.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current state object (internal use)
|
||||
*/
|
||||
get state(): PeerState {
|
||||
return this._state;
|
||||
}
|
||||
|
||||
/**
|
||||
* RTCPeerConnection state
|
||||
*/
|
||||
get connectionState(): RTCPeerConnectionState {
|
||||
return this.pc.connectionState;
|
||||
}
|
||||
|
||||
constructor(
|
||||
offersApi: RondevuOffers,
|
||||
rtcConfig: RTCConfiguration = {
|
||||
iceServers: [
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
{ urls: 'stun:stun1.l.google.com:19302' }
|
||||
]
|
||||
}
|
||||
) {
|
||||
super();
|
||||
this.offersApi = offersApi;
|
||||
this.pc = new RTCPeerConnection(rtcConfig);
|
||||
this._state = new IdleState(this);
|
||||
|
||||
this.setupPeerConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up peer connection event handlers
|
||||
*/
|
||||
private setupPeerConnection(): void {
|
||||
this.connectionStateChangeHandler = () => {
|
||||
switch (this.pc.connectionState) {
|
||||
case 'connected':
|
||||
this.setState(new ConnectedState(this));
|
||||
this.emitEvent('connected');
|
||||
break;
|
||||
case 'disconnected':
|
||||
this.emitEvent('disconnected');
|
||||
break;
|
||||
case 'failed':
|
||||
this.setState(new FailedState(this, new Error('Connection failed')));
|
||||
break;
|
||||
case 'closed':
|
||||
this.setState(new ClosedState(this));
|
||||
this.emitEvent('disconnected');
|
||||
break;
|
||||
}
|
||||
};
|
||||
this.pc.addEventListener('connectionstatechange', this.connectionStateChangeHandler);
|
||||
|
||||
this.dataChannelHandler = (event: RTCDataChannelEvent) => {
|
||||
this.emitEvent('datachannel', event.channel);
|
||||
};
|
||||
this.pc.addEventListener('datachannel', this.dataChannelHandler);
|
||||
|
||||
this.trackHandler = (event: RTCTrackEvent) => {
|
||||
this.emitEvent('track', event);
|
||||
};
|
||||
this.pc.addEventListener('track', this.trackHandler);
|
||||
|
||||
this.iceCandidateErrorHandler = (event: Event) => {
|
||||
console.error('ICE candidate error:', event);
|
||||
};
|
||||
this.pc.addEventListener('icecandidateerror', this.iceCandidateErrorHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set new state and emit state change event
|
||||
*/
|
||||
setState(newState: PeerState): void {
|
||||
this._state.cleanup();
|
||||
this._state = newState;
|
||||
this.emitEvent('state', newState.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit event (exposed for PeerState classes)
|
||||
* @internal
|
||||
*/
|
||||
emitEvent<K extends keyof PeerEvents>(
|
||||
event: K,
|
||||
...args: Parameters<PeerEvents[K]>
|
||||
): void {
|
||||
this.emit(event, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an offer and advertise on topics
|
||||
*/
|
||||
async createOffer(options: PeerOptions): Promise<string> {
|
||||
return this._state.createOffer(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer an existing offer
|
||||
*/
|
||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
||||
return this._state.answer(offerId, offerSdp, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a media track to the connection
|
||||
*/
|
||||
addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender {
|
||||
return this.pc.addTrack(track, ...streams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection and clean up
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
// Remove RTCPeerConnection event listeners
|
||||
if (this.connectionStateChangeHandler) {
|
||||
this.pc.removeEventListener('connectionstatechange', this.connectionStateChangeHandler);
|
||||
}
|
||||
if (this.dataChannelHandler) {
|
||||
this.pc.removeEventListener('datachannel', this.dataChannelHandler);
|
||||
}
|
||||
if (this.trackHandler) {
|
||||
this.pc.removeEventListener('track', this.trackHandler);
|
||||
}
|
||||
if (this.iceCandidateErrorHandler) {
|
||||
this.pc.removeEventListener('icecandidateerror', this.iceCandidateErrorHandler);
|
||||
}
|
||||
|
||||
await this._state.close();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import type { PeerOptions } from './types.js';
|
||||
import type RondevuPeer from './index.js';
|
||||
|
||||
/**
|
||||
* Base class for peer connection states
|
||||
* Implements the State pattern for managing WebRTC connection lifecycle
|
||||
*/
|
||||
export abstract class PeerState {
|
||||
protected iceCandidateHandler?: (event: RTCPeerConnectionIceEvent) => void;
|
||||
|
||||
constructor(protected peer: RondevuPeer) {}
|
||||
|
||||
abstract get name(): string;
|
||||
|
||||
async createOffer(options: PeerOptions): Promise<string> {
|
||||
throw new Error(`Cannot create offer in ${this.name} state`);
|
||||
}
|
||||
|
||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
||||
throw new Error(`Cannot answer in ${this.name} state`);
|
||||
}
|
||||
|
||||
async handleAnswer(sdp: string): Promise<void> {
|
||||
throw new Error(`Cannot handle answer in ${this.name} state`);
|
||||
}
|
||||
|
||||
async handleIceCandidate(candidate: any): Promise<void> {
|
||||
// ICE candidates can arrive in multiple states, so default is to add them
|
||||
if (this.peer.pc.remoteDescription) {
|
||||
await this.peer.pc.addIceCandidate(new RTCIceCandidate(candidate));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup trickle ICE candidate handler
|
||||
* Sends local ICE candidates to server as they are discovered
|
||||
*/
|
||||
protected setupIceCandidateHandler(): void {
|
||||
this.iceCandidateHandler = async (event: RTCPeerConnectionIceEvent) => {
|
||||
if (event.candidate && this.peer.offerId) {
|
||||
const candidateData = event.candidate.toJSON();
|
||||
if (candidateData.candidate && candidateData.candidate !== '') {
|
||||
try {
|
||||
await this.peer.offersApi.addIceCandidates(this.peer.offerId, [candidateData]);
|
||||
} catch (err) {
|
||||
console.error('Error sending ICE candidate:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
this.peer.pc.addEventListener('icecandidate', this.iceCandidateHandler);
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
// Clean up ICE candidate handler if it exists
|
||||
if (this.iceCandidateHandler) {
|
||||
this.peer.pc.removeEventListener('icecandidate', this.iceCandidateHandler);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.cleanup();
|
||||
const { ClosedState } = await import('./closed-state.js');
|
||||
this.peer.setState(new ClosedState(this.peer));
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
/**
|
||||
* Timeout configurations for different connection phases
|
||||
*/
|
||||
export interface PeerTimeouts {
|
||||
/** Timeout for ICE gathering (default: 10000ms) */
|
||||
iceGathering?: number;
|
||||
/** Timeout for waiting for answer (default: 30000ms) */
|
||||
waitingForAnswer?: number;
|
||||
/** Timeout for creating answer (default: 10000ms) */
|
||||
creatingAnswer?: number;
|
||||
/** Timeout for ICE connection (default: 30000ms) */
|
||||
iceConnection?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for creating a peer connection
|
||||
*/
|
||||
export interface PeerOptions {
|
||||
/** RTCConfiguration for the peer connection */
|
||||
rtcConfig?: RTCConfiguration;
|
||||
/** Topics to advertise this connection under */
|
||||
topics: string[];
|
||||
/** How long the offer should live (milliseconds) */
|
||||
ttl?: number;
|
||||
/** Whether to create a data channel automatically (for offerer) */
|
||||
createDataChannel?: boolean;
|
||||
/** Label for the automatically created data channel */
|
||||
dataChannelLabel?: string;
|
||||
/** Timeout configurations */
|
||||
timeouts?: PeerTimeouts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Events emitted by RondevuPeer
|
||||
*/
|
||||
export interface PeerEvents extends Record<string, (...args: any[]) => void> {
|
||||
'state': (state: string) => void;
|
||||
'connected': () => void;
|
||||
'disconnected': () => void;
|
||||
'failed': (error: Error) => void;
|
||||
'datachannel': (channel: RTCDataChannel) => void;
|
||||
'track': (event: RTCTrackEvent) => void;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import { PeerState } from './state.js';
|
||||
import type { PeerOptions } from './types.js';
|
||||
import type RondevuPeer from './index.js';
|
||||
|
||||
/**
|
||||
* Waiting for answer from another peer
|
||||
*/
|
||||
export class WaitingForAnswerState extends PeerState {
|
||||
private pollingInterval?: ReturnType<typeof setInterval>;
|
||||
private timeout?: ReturnType<typeof setTimeout>;
|
||||
|
||||
constructor(
|
||||
peer: RondevuPeer,
|
||||
private offerId: string,
|
||||
private options: PeerOptions
|
||||
) {
|
||||
super(peer);
|
||||
this.startPolling();
|
||||
}
|
||||
|
||||
get name() { return 'waiting-for-answer'; }
|
||||
|
||||
private startPolling(): void {
|
||||
const answerTimeout = this.options.timeouts?.waitingForAnswer || 30000;
|
||||
|
||||
this.timeout = setTimeout(async () => {
|
||||
this.cleanup();
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(
|
||||
this.peer,
|
||||
new Error('Timeout waiting for answer')
|
||||
));
|
||||
}, answerTimeout);
|
||||
|
||||
this.pollingInterval = setInterval(async () => {
|
||||
try {
|
||||
const answers = await this.peer.offersApi.getAnswers();
|
||||
const myAnswer = answers.find((a: any) => a.offerId === this.offerId);
|
||||
|
||||
if (myAnswer) {
|
||||
this.cleanup();
|
||||
await this.handleAnswer(myAnswer.sdp);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error polling for answers:', err);
|
||||
if (err instanceof Error && err.message.includes('not found')) {
|
||||
this.cleanup();
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(
|
||||
this.peer,
|
||||
new Error('Offer expired or not found')
|
||||
));
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async handleAnswer(sdp: string): Promise<void> {
|
||||
try {
|
||||
await this.peer.pc.setRemoteDescription({
|
||||
type: 'answer',
|
||||
sdp
|
||||
});
|
||||
|
||||
// Transition to exchanging ICE
|
||||
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
||||
this.peer.setState(new ExchangingIceState(this.peer, this.offerId, this.options));
|
||||
} catch (error) {
|
||||
const { FailedState } = await import('./failed-state.js');
|
||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
||||
}
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
if (this.pollingInterval) clearInterval(this.pollingInterval);
|
||||
if (this.timeout) clearTimeout(this.timeout);
|
||||
}
|
||||
}
|
||||
103
src/rondevu.ts
103
src/rondevu.ts
@@ -1,103 +0,0 @@
|
||||
import { RondevuAuth, Credentials, FetchFunction } from './auth.js';
|
||||
import { RondevuOffers } from './offers.js';
|
||||
import RondevuPeer from './peer/index.js';
|
||||
|
||||
export interface RondevuOptions {
|
||||
/**
|
||||
* Base URL of the Rondevu server
|
||||
* @default 'https://api.ronde.vu'
|
||||
*/
|
||||
baseUrl?: string;
|
||||
|
||||
/**
|
||||
* Existing credentials (peerId + secret) to skip registration
|
||||
*/
|
||||
credentials?: Credentials;
|
||||
|
||||
/**
|
||||
* Custom fetch implementation for environments without native fetch
|
||||
* (Node.js < 18, some Workers environments, etc.)
|
||||
*
|
||||
* @example Node.js
|
||||
* ```typescript
|
||||
* import fetch from 'node-fetch';
|
||||
* const client = new Rondevu({ fetch });
|
||||
* ```
|
||||
*/
|
||||
fetch?: FetchFunction;
|
||||
}
|
||||
|
||||
export class Rondevu {
|
||||
readonly auth: RondevuAuth;
|
||||
private _offers?: RondevuOffers;
|
||||
private credentials?: Credentials;
|
||||
private baseUrl: string;
|
||||
private fetchFn?: FetchFunction;
|
||||
|
||||
constructor(options: RondevuOptions = {}) {
|
||||
this.baseUrl = options.baseUrl || 'https://api.ronde.vu';
|
||||
this.fetchFn = options.fetch;
|
||||
|
||||
this.auth = new RondevuAuth(this.baseUrl, this.fetchFn);
|
||||
|
||||
if (options.credentials) {
|
||||
this.credentials = options.credentials;
|
||||
this._offers = new RondevuOffers(this.baseUrl, this.credentials, this.fetchFn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get offers API (requires authentication)
|
||||
*/
|
||||
get offers(): RondevuOffers {
|
||||
if (!this._offers) {
|
||||
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
||||
}
|
||||
return this._offers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register and initialize authenticated client
|
||||
*/
|
||||
async register(): Promise<Credentials> {
|
||||
this.credentials = await this.auth.register();
|
||||
|
||||
// Create offers API instance
|
||||
this._offers = new RondevuOffers(
|
||||
this.baseUrl,
|
||||
this.credentials,
|
||||
this.fetchFn
|
||||
);
|
||||
|
||||
return this.credentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if client is authenticated
|
||||
*/
|
||||
isAuthenticated(): boolean {
|
||||
return !!this.credentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current credentials
|
||||
*/
|
||||
getCredentials(): Credentials | undefined {
|
||||
return this.credentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new WebRTC peer connection (requires authentication)
|
||||
* This is a high-level helper that creates and manages WebRTC connections with state management
|
||||
*
|
||||
* @param rtcConfig Optional RTCConfiguration for the peer connection
|
||||
* @returns RondevuPeer instance
|
||||
*/
|
||||
createPeer(rtcConfig?: RTCConfiguration): RondevuPeer {
|
||||
if (!this._offers) {
|
||||
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
||||
}
|
||||
|
||||
return new RondevuPeer(this._offers, rtcConfig);
|
||||
}
|
||||
}
|
||||
192
src/types.ts
192
src/types.ts
@@ -1,182 +1,24 @@
|
||||
// ============================================================================
|
||||
// Signaling Types
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Session side - identifies which peer in a connection
|
||||
* Core connection types
|
||||
*/
|
||||
export type Side = 'offerer' | 'answerer';
|
||||
|
||||
/**
|
||||
* Request body for POST /offer
|
||||
*/
|
||||
export interface CreateOfferRequest {
|
||||
/** Peer identifier/metadata (max 1024 characters) */
|
||||
peerId: string;
|
||||
/** Signaling data for peer connection */
|
||||
offer: string;
|
||||
/** Optional custom connection code (if not provided, server generates UUID) */
|
||||
code?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from POST /offer
|
||||
*/
|
||||
export interface CreateOfferResponse {
|
||||
/** Unique session identifier (UUID) */
|
||||
code: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request body for POST /answer
|
||||
*/
|
||||
export interface AnswerRequest {
|
||||
/** Session UUID from the offer */
|
||||
code: string;
|
||||
/** Response signaling data (required if candidate not provided) */
|
||||
answer?: string;
|
||||
/** Additional signaling data (required if answer not provided) */
|
||||
candidate?: string;
|
||||
/** Which peer is sending the data */
|
||||
side: Side;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from POST /answer
|
||||
*/
|
||||
export interface AnswerResponse {
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request body for POST /poll
|
||||
*/
|
||||
export interface PollRequest {
|
||||
/** Session UUID */
|
||||
code: string;
|
||||
/** Which side is polling */
|
||||
side: Side;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from POST /poll when side=offerer
|
||||
*/
|
||||
export interface PollOffererResponse {
|
||||
/** Answer from answerer (null if not yet received) */
|
||||
answer: string | null;
|
||||
/** Additional signaling data from answerer */
|
||||
answerCandidates: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from POST /poll when side=answerer
|
||||
*/
|
||||
export interface PollAnswererResponse {
|
||||
/** Offer from offerer */
|
||||
offer: string;
|
||||
/** Additional signaling data from offerer */
|
||||
offerCandidates: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from POST /poll (union type)
|
||||
*/
|
||||
export type PollResponse = PollOffererResponse | PollAnswererResponse;
|
||||
|
||||
/**
|
||||
* Response from GET / - server version information
|
||||
*/
|
||||
export interface VersionResponse {
|
||||
/** Git commit hash or version identifier */
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET /health
|
||||
*/
|
||||
export interface HealthResponse {
|
||||
status: 'ok';
|
||||
timestamp: number;
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response structure
|
||||
*/
|
||||
export interface ErrorResponse {
|
||||
error: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Client configuration options
|
||||
*/
|
||||
export interface RondevuClientOptions {
|
||||
/** Base URL of the Rondevu server (e.g., 'https://example.com') */
|
||||
baseUrl: string;
|
||||
/** Optional fetch implementation (for Node.js environments) */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// WebRTC Types
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* WebRTC polyfill for Node.js and other non-browser platforms
|
||||
*/
|
||||
export interface WebRTCPolyfill {
|
||||
RTCPeerConnection: typeof RTCPeerConnection;
|
||||
RTCSessionDescription: typeof RTCSessionDescription;
|
||||
RTCIceCandidate: typeof RTCIceCandidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for Rondevu WebRTC client
|
||||
*/
|
||||
export interface RondevuOptions {
|
||||
/** Base URL of the Rondevu server (defaults to 'https://api.ronde.vu') */
|
||||
baseUrl?: string;
|
||||
/** Peer identifier (optional, auto-generated if not provided) */
|
||||
peerId?: string;
|
||||
/** Optional fetch implementation (for Node.js environments) */
|
||||
fetch?: typeof fetch;
|
||||
/** WebRTC configuration (ICE servers, etc.) */
|
||||
rtcConfig?: RTCConfiguration;
|
||||
/** Polling interval in milliseconds (default: 1000) */
|
||||
pollingInterval?: number;
|
||||
/** Connection timeout in milliseconds (default: 30000) */
|
||||
connectionTimeout?: number;
|
||||
/** WebRTC polyfill for Node.js (e.g., wrtc or @roamhq/wrtc) */
|
||||
wrtc?: WebRTCPolyfill;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection role - whether this peer is creating or answering
|
||||
*/
|
||||
export type ConnectionRole = 'offerer' | 'answerer';
|
||||
|
||||
/**
|
||||
* Parameters for creating a RondevuConnection
|
||||
*/
|
||||
export interface RondevuConnectionParams {
|
||||
export interface ConnectionIdentity {
|
||||
id: string;
|
||||
topic?: string;
|
||||
role: ConnectionRole;
|
||||
pc: RTCPeerConnection;
|
||||
localPeerId: string;
|
||||
remotePeerId: string;
|
||||
pollingInterval: number;
|
||||
connectionTimeout: number;
|
||||
wrtc?: WebRTCPolyfill;
|
||||
hostUsername: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event map for RondevuConnection events
|
||||
*/
|
||||
export interface RondevuConnectionEvents {
|
||||
connect: () => void;
|
||||
disconnect: () => void;
|
||||
error: (error: Error) => void;
|
||||
datachannel: (channel: RTCDataChannel) => void;
|
||||
stream: (stream: MediaStream) => void;
|
||||
export interface ConnectionState {
|
||||
state: 'connected' | 'disconnected' | 'connecting';
|
||||
lastActive: number;
|
||||
}
|
||||
|
||||
export interface QueueMessageOptions {
|
||||
expiresAt?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionInterface {
|
||||
queueMessage(message: string | ArrayBuffer, options?: QueueMessageOptions): void;
|
||||
sendMessage(message: string | ArrayBuffer): void;
|
||||
}
|
||||
|
||||
export type Connection = ConnectionIdentity & ConnectionState & ConnectionInterface;
|
||||
Reference in New Issue
Block a user