mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 10:53:24 +00:00
Compare commits
9 Commits
5e673ac993
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a3b4dfa15f | |||
| 5c38f8f36c | |||
| 177ee2ec2d | |||
| d06b2166c1 | |||
| cbb0cc3f83 | |||
| fbd3be57d4 | |||
| 54355323d9 | |||
| 945d5a8792 | |||
| 58cd610694 |
9
.prettierrc.json
Normal file
9
.prettierrc.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"useTabs": false,
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"printWidth": 100,
|
||||||
|
"arrowParens": "avoid"
|
||||||
|
}
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
# 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
|
|
||||||
833
README.md
833
README.md
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
||||||
|
|
||||||
🌐 **WebRTC with durable connections and automatic reconnection**
|
🌐 **Simple, high-level WebRTC peer-to-peer connections**
|
||||||
|
|
||||||
TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections that survive network interruptions with automatic reconnection and message queuing.
|
TypeScript/JavaScript client for Rondevu, providing easy-to-use WebRTC connections with automatic signaling, username-based discovery, and built-in reconnection support.
|
||||||
|
|
||||||
**Related repositories:**
|
**Related repositories:**
|
||||||
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
||||||
@@ -15,14 +15,16 @@ TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections t
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Durable Connections**: Automatic reconnection on network drops
|
- **High-Level Wrappers**: ServiceHost and ServiceClient eliminate WebRTC boilerplate
|
||||||
- **Message Queuing**: Messages sent during disconnections are queued and flushed on reconnect
|
- **Username-Based Discovery**: Connect to peers by username, not complex offer/answer exchange
|
||||||
- **Durable Channels**: RTCDataChannel wrappers that survive connection drops
|
- **Semver-Compatible Matching**: Requesting chat@1.0.0 matches any compatible 1.x.x version
|
||||||
- **TTL Auto-Refresh**: Services automatically republish before expiration
|
- **Privacy-First Design**: Services are hidden by default - no enumeration possible
|
||||||
- **Username Claiming**: Cryptographic ownership with Ed25519 signatures
|
- **Automatic Reconnection**: Built-in retry logic with exponential backoff
|
||||||
- **Service Publishing**: Package-style naming (com.example.chat@1.0.0)
|
- **Message Queuing**: Messages sent while disconnected are queued and flushed on reconnect
|
||||||
|
- **Cryptographic Username Claiming**: Secure ownership with Ed25519 signatures
|
||||||
|
- **Service Publishing**: Package-style naming (chat.app@1.0.0) with multiple simultaneous offers
|
||||||
- **TypeScript**: Full type safety and autocomplete
|
- **TypeScript**: Full type safety and autocomplete
|
||||||
- **Configurable**: All timeouts, retry limits, and queue sizes are configurable
|
- **Configurable Polling**: Exponential backoff with jitter to reduce server load
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -32,588 +34,400 @@ npm install @xtr-dev/rondevu-client
|
|||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### Publishing a Service (Alice)
|
### Hosting a Service (Alice)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { RondevuService, ServiceHost } from '@xtr-dev/rondevu-client'
|
||||||
|
|
||||||
// Initialize client and register
|
// Step 1: Create and initialize service
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const service = new RondevuService({
|
||||||
await client.register();
|
apiUrl: 'https://api.ronde.vu',
|
||||||
|
username: 'alice'
|
||||||
|
})
|
||||||
|
|
||||||
// Step 1: Claim username (one-time)
|
await service.initialize() // Generates keypair
|
||||||
const claim = await client.usernames.claimUsername('alice');
|
await service.claimUsername() // Claims username with signature
|
||||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
|
||||||
|
|
||||||
// Step 2: Expose service with handler
|
// Step 2: Create ServiceHost
|
||||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
const host = new ServiceHost({
|
||||||
|
service: 'chat.app@1.0.0',
|
||||||
|
rondevuService: service,
|
||||||
|
maxPeers: 5, // Accept up to 5 connections
|
||||||
|
ttl: 300000 // 5 minutes
|
||||||
|
})
|
||||||
|
|
||||||
const service = await client.exposeService({
|
// Step 3: Listen for incoming connections
|
||||||
username: 'alice',
|
host.events.on('connection', (connection) => {
|
||||||
privateKey: keypair.privateKey,
|
console.log('✅ New connection!')
|
||||||
serviceFqn: 'chat@1.0.0',
|
|
||||||
isPublic: true,
|
|
||||||
poolSize: 10, // Handle 10 concurrent connections
|
|
||||||
handler: (channel, connectionId) => {
|
|
||||||
console.log(`📡 New connection: ${connectionId}`);
|
|
||||||
|
|
||||||
channel.on('message', (data) => {
|
connection.events.on('message', (msg) => {
|
||||||
console.log('📥 Received:', data);
|
console.log('📨 Received:', msg)
|
||||||
channel.send(`Echo: ${data}`);
|
connection.sendMessage('Hello from Alice!')
|
||||||
});
|
})
|
||||||
|
|
||||||
channel.on('close', () => {
|
connection.events.on('state-change', (state) => {
|
||||||
console.log(`👋 Connection ${connectionId} closed`);
|
console.log('Connection state:', state)
|
||||||
});
|
})
|
||||||
}
|
})
|
||||||
});
|
|
||||||
|
|
||||||
// Start the service
|
host.events.on('error', (error) => {
|
||||||
const info = await service.start();
|
console.error('Host error:', error)
|
||||||
console.log(`Service published with UUID: ${info.uuid}`);
|
})
|
||||||
console.log('Waiting for connections...');
|
|
||||||
|
|
||||||
// Later: stop the service
|
// Step 4: Start hosting
|
||||||
await service.stop();
|
await host.start()
|
||||||
|
console.log('Service is now live! Others can connect to @alice')
|
||||||
|
|
||||||
|
// Later: stop hosting
|
||||||
|
host.dispose()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Connecting to a Service (Bob)
|
### Connecting to a Service (Bob)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { RondevuService, ServiceClient } from '@xtr-dev/rondevu-client'
|
||||||
|
|
||||||
// Initialize client and register
|
// Step 1: Create and initialize service
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const service = new RondevuService({
|
||||||
await client.register();
|
apiUrl: 'https://api.ronde.vu',
|
||||||
|
username: 'bob'
|
||||||
|
})
|
||||||
|
|
||||||
// Connect to Alice's service
|
await service.initialize()
|
||||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
await service.claimUsername()
|
||||||
|
|
||||||
|
// Step 2: Create ServiceClient
|
||||||
|
const client = new ServiceClient({
|
||||||
|
username: 'alice', // Connect to Alice
|
||||||
|
serviceFqn: 'chat.app@1.0.0',
|
||||||
|
rondevuService: service,
|
||||||
|
autoReconnect: true,
|
||||||
maxReconnectAttempts: 5
|
maxReconnectAttempts: 5
|
||||||
});
|
})
|
||||||
|
|
||||||
// Create a durable channel
|
// Step 3: Listen for connection events
|
||||||
const channel = connection.createChannel('main');
|
client.events.on('connected', (connection) => {
|
||||||
|
console.log('✅ Connected to Alice!')
|
||||||
|
|
||||||
channel.on('message', (data) => {
|
connection.events.on('message', (msg) => {
|
||||||
console.log('📥 Received:', data);
|
console.log('📨 Received:', msg)
|
||||||
});
|
})
|
||||||
|
|
||||||
channel.on('open', () => {
|
// Send a message
|
||||||
console.log('✅ Channel open');
|
connection.sendMessage('Hello from Bob!')
|
||||||
channel.send('Hello Alice!');
|
})
|
||||||
});
|
|
||||||
|
|
||||||
// Listen for connection events
|
client.events.on('disconnected', () => {
|
||||||
connection.on('connected', () => {
|
console.log('🔌 Disconnected')
|
||||||
console.log('🎉 Connected to Alice');
|
})
|
||||||
});
|
|
||||||
|
|
||||||
connection.on('reconnecting', (attempt, max, delay) => {
|
client.events.on('reconnecting', ({ attempt, maxAttempts }) => {
|
||||||
console.log(`🔄 Reconnecting... (${attempt}/${max}, retry in ${delay}ms)`);
|
console.log(`🔄 Reconnecting (${attempt}/${maxAttempts})...`)
|
||||||
});
|
})
|
||||||
|
|
||||||
connection.on('disconnected', () => {
|
client.events.on('error', (error) => {
|
||||||
console.log('🔌 Disconnected');
|
console.error('❌ Error:', error)
|
||||||
});
|
})
|
||||||
|
|
||||||
connection.on('failed', (error) => {
|
// Step 4: Connect
|
||||||
console.error('❌ Connection failed permanently:', error);
|
await client.connect()
|
||||||
});
|
|
||||||
|
|
||||||
// Establish the connection
|
// Later: disconnect
|
||||||
await connection.connect();
|
client.dispose()
|
||||||
|
|
||||||
// Messages sent during disconnection are automatically queued
|
|
||||||
channel.send('This will be queued if disconnected');
|
|
||||||
|
|
||||||
// Later: close the connection
|
|
||||||
await connection.close();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Core Concepts
|
## Core Concepts
|
||||||
|
|
||||||
### DurableConnection
|
### RondevuService
|
||||||
|
|
||||||
Manages WebRTC peer lifecycle with automatic reconnection:
|
Handles authentication and username management:
|
||||||
- Automatically reconnects when connection drops
|
- Generates Ed25519 keypair for signing
|
||||||
- Exponential backoff with jitter (1s → 2s → 4s → 8s → ... max 30s)
|
- Claims usernames with cryptographic proof
|
||||||
- Configurable max retry attempts (default: 10)
|
- Provides API client for signaling server
|
||||||
- Manages multiple DurableChannel instances
|
|
||||||
|
|
||||||
### DurableChannel
|
### ServiceHost
|
||||||
|
|
||||||
Wraps RTCDataChannel with message queuing:
|
High-level wrapper for hosting a WebRTC service:
|
||||||
- Queues messages during disconnection
|
- Automatically creates and publishes offers
|
||||||
- Flushes queue on reconnection
|
- Handles incoming connections
|
||||||
- Configurable queue size and message age limits
|
- Manages ICE candidate exchange
|
||||||
- RTCDataChannel-compatible API with event emitters
|
- Supports multiple simultaneous peers
|
||||||
|
|
||||||
### DurableService
|
### ServiceClient
|
||||||
|
|
||||||
Server-side service with TTL auto-refresh:
|
High-level wrapper for connecting to services:
|
||||||
- Automatically republishes service before TTL expires
|
- Discovers services by username
|
||||||
- Creates DurableConnection for each incoming peer
|
- Handles offer/answer exchange automatically
|
||||||
- Manages connection pool for multiple simultaneous connections
|
- Built-in auto-reconnection with exponential backoff
|
||||||
|
- Event-driven API
|
||||||
|
|
||||||
|
### RTCDurableConnection
|
||||||
|
|
||||||
|
Low-level connection wrapper (used internally):
|
||||||
|
- Manages WebRTC PeerConnection lifecycle
|
||||||
|
- Handles ICE candidate polling
|
||||||
|
- Provides message queue for reliability
|
||||||
|
- State management and events
|
||||||
|
|
||||||
## API Reference
|
## API Reference
|
||||||
|
|
||||||
### Main Client
|
### RondevuService
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const client = new Rondevu({
|
const service = new RondevuService({
|
||||||
baseUrl: 'https://api.ronde.vu', // optional, default shown
|
apiUrl: string, // Signaling server URL
|
||||||
credentials?: { peerId, secret }, // optional, skip registration
|
username: string, // Your username
|
||||||
fetch?: customFetch, // optional, for Node.js < 18
|
keypair?: Keypair // Optional: reuse existing keypair
|
||||||
RTCPeerConnection?: RTCPeerConnection, // optional, for Node.js
|
})
|
||||||
RTCSessionDescription?: RTCSessionDescription,
|
|
||||||
RTCIceCandidate?: RTCIceCandidate
|
|
||||||
});
|
|
||||||
|
|
||||||
// Register and get credentials
|
// Initialize service (generates keypair if not provided)
|
||||||
const creds = await client.register();
|
await service.initialize(): Promise<void>
|
||||||
// { peerId: '...', secret: '...' }
|
|
||||||
|
|
||||||
// Check if authenticated
|
// Claim username with cryptographic signature
|
||||||
client.isAuthenticated(); // boolean
|
await service.claimUsername(): Promise<void>
|
||||||
|
|
||||||
// Get current credentials
|
// Check if username is claimed
|
||||||
client.getCredentials(); // { peerId, secret } | undefined
|
service.isUsernameClaimed(): boolean
|
||||||
|
|
||||||
|
// Get current username
|
||||||
|
service.getUsername(): string
|
||||||
|
|
||||||
|
// Get keypair
|
||||||
|
service.getKeypair(): Keypair
|
||||||
|
|
||||||
|
// Get API client
|
||||||
|
service.getAPI(): RondevuAPI
|
||||||
```
|
```
|
||||||
|
|
||||||
### Username API
|
### ServiceHost
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Check username availability
|
const host = new ServiceHost({
|
||||||
const check = await client.usernames.checkUsername('alice');
|
service: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||||
// { available: true } or { available: false, expiresAt: number, publicKey: string }
|
rondevuService: RondevuService,
|
||||||
|
maxPeers?: number, // Default: 5
|
||||||
|
ttl?: number, // Default: 300000 (5 minutes)
|
||||||
|
isPublic?: boolean, // Default: true
|
||||||
|
rtcConfiguration?: RTCConfiguration
|
||||||
|
})
|
||||||
|
|
||||||
// Claim username with new keypair
|
// Start hosting
|
||||||
const claim = await client.usernames.claimUsername('alice');
|
await host.start(): Promise<void>
|
||||||
// { username, publicKey, privateKey, claimedAt, expiresAt }
|
|
||||||
|
|
||||||
// Save keypair to localStorage
|
// Stop hosting and cleanup
|
||||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
host.dispose(): void
|
||||||
|
|
||||||
// Load keypair from localStorage
|
// Get all active connections
|
||||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
host.getConnections(): RTCDurableConnection[]
|
||||||
// { publicKey, privateKey } | null
|
|
||||||
|
// Events
|
||||||
|
host.events.on('connection', (conn: RTCDurableConnection) => {})
|
||||||
|
host.events.on('error', (error: Error) => {})
|
||||||
```
|
```
|
||||||
|
|
||||||
**Username Rules:**
|
### ServiceClient
|
||||||
- Format: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
|
|
||||||
- Length: 3-32 characters
|
|
||||||
- Pattern: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
|
|
||||||
- Validity: 365 days from claim/last use
|
|
||||||
- Ownership: Secured by Ed25519 public key
|
|
||||||
|
|
||||||
### Durable Service API
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Expose a durable service
|
const client = new ServiceClient({
|
||||||
const service = await client.exposeService({
|
username: string, // Host username to connect to
|
||||||
username: 'alice',
|
serviceFqn: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||||
privateKey: keypair.privateKey,
|
rondevuService: RondevuService,
|
||||||
serviceFqn: 'chat@1.0.0',
|
autoReconnect?: boolean, // Default: true
|
||||||
|
maxReconnectAttempts?: number, // Default: 5
|
||||||
|
rtcConfiguration?: RTCConfiguration
|
||||||
|
})
|
||||||
|
|
||||||
// Service options
|
// Connect to service
|
||||||
isPublic: true, // optional, default: false
|
await client.connect(): Promise<RTCDurableConnection>
|
||||||
metadata: { version: '1.0' }, // optional
|
|
||||||
ttl: 300000, // optional, default: 5 minutes
|
|
||||||
ttlRefreshMargin: 0.2, // optional, refresh at 80% of TTL
|
|
||||||
|
|
||||||
// Connection pooling
|
// Disconnect and cleanup
|
||||||
poolSize: 10, // optional, default: 1
|
client.dispose(): void
|
||||||
pollingInterval: 2000, // optional, default: 2000ms
|
|
||||||
|
|
||||||
// Connection options (applied to incoming connections)
|
// Get current connection
|
||||||
maxReconnectAttempts: 10, // optional, default: 10
|
client.getConnection(): RTCDurableConnection | null
|
||||||
reconnectBackoffBase: 1000, // optional, default: 1000ms
|
|
||||||
reconnectBackoffMax: 30000, // optional, default: 30000ms
|
|
||||||
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
|
|
||||||
connectionTimeout: 30000, // optional, default: 30000ms
|
|
||||||
|
|
||||||
// Message queuing
|
// Events
|
||||||
maxQueueSize: 1000, // optional, default: 1000
|
client.events.on('connected', (conn: RTCDurableConnection) => {})
|
||||||
maxMessageAge: 60000, // optional, default: 60000ms (1 minute)
|
client.events.on('disconnected', () => {})
|
||||||
|
client.events.on('reconnecting', (info: { attempt: number, maxAttempts: number }) => {})
|
||||||
|
client.events.on('error', (error: Error) => {})
|
||||||
|
```
|
||||||
|
|
||||||
// WebRTC configuration
|
### RTCDurableConnection
|
||||||
rtcConfig: {
|
|
||||||
iceServers: [
|
|
||||||
{ urls: 'stun:stun.l.google.com:19302' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
|
|
||||||
// Connection handler
|
```typescript
|
||||||
handler: (channel, connectionId) => {
|
// Connection state
|
||||||
// Handle incoming connection
|
connection.state: 'connected' | 'connecting' | 'disconnected'
|
||||||
channel.on('message', (data) => {
|
|
||||||
console.log('Received:', data);
|
// Send message (returns true if sent, false if queued)
|
||||||
channel.send(`Echo: ${data}`);
|
await connection.sendMessage(message: string): Promise<boolean>
|
||||||
});
|
|
||||||
|
// Queue message for sending when connected
|
||||||
|
await connection.queueMessage(message: string, options?: QueueMessageOptions): Promise<void>
|
||||||
|
|
||||||
|
// Disconnect
|
||||||
|
connection.disconnect(): void
|
||||||
|
|
||||||
|
// Events
|
||||||
|
connection.events.on('message', (msg: string) => {})
|
||||||
|
connection.events.on('state-change', (state: ConnectionStates) => {})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Polling Configuration
|
||||||
|
|
||||||
|
The signaling uses configurable polling with exponential backoff:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Default polling config
|
||||||
|
{
|
||||||
|
initialInterval: 500, // Start at 500ms
|
||||||
|
maxInterval: 5000, // Max 5 seconds
|
||||||
|
backoffMultiplier: 1.5, // Increase by 1.5x each time
|
||||||
|
maxRetries: 50, // Max 50 attempts
|
||||||
|
jitter: true // Add random 0-100ms to prevent thundering herd
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
// Start the service
|
|
||||||
const info = await service.start();
|
|
||||||
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 }
|
|
||||||
|
|
||||||
// Get active connections
|
|
||||||
const connections = service.getActiveConnections();
|
|
||||||
// ['conn-123', 'conn-456']
|
|
||||||
|
|
||||||
// Get service info
|
|
||||||
const serviceInfo = service.getServiceInfo();
|
|
||||||
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 } | null
|
|
||||||
|
|
||||||
// Stop the service
|
|
||||||
await service.stop();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Service Events:**
|
This is handled automatically - no configuration needed.
|
||||||
```typescript
|
|
||||||
service.on('published', (serviceId, uuid) => {
|
|
||||||
console.log(`Service published: ${uuid}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
service.on('connection', (connectionId) => {
|
### WebRTC Configuration
|
||||||
console.log(`New connection: ${connectionId}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
service.on('disconnection', (connectionId) => {
|
Provide custom STUN/TURN servers:
|
||||||
console.log(`Connection closed: ${connectionId}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
service.on('ttl-refreshed', (expiresAt) => {
|
|
||||||
console.log(`TTL refreshed, expires at: ${new Date(expiresAt)}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
service.on('error', (error, context) => {
|
|
||||||
console.error(`Service error (${context}):`, error);
|
|
||||||
});
|
|
||||||
|
|
||||||
service.on('closed', () => {
|
|
||||||
console.log('Service stopped');
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Durable Connection API
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Connect by username and service FQN
|
const host = new ServiceHost({
|
||||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
service: 'chat.app@1.0.0',
|
||||||
// Connection options
|
rondevuService: service,
|
||||||
maxReconnectAttempts: 10, // optional, default: 10
|
rtcConfiguration: {
|
||||||
reconnectBackoffBase: 1000, // optional, default: 1000ms
|
|
||||||
reconnectBackoffMax: 30000, // optional, default: 30000ms
|
|
||||||
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
|
|
||||||
connectionTimeout: 30000, // optional, default: 30000ms
|
|
||||||
|
|
||||||
// Message queuing
|
|
||||||
maxQueueSize: 1000, // optional, default: 1000
|
|
||||||
maxMessageAge: 60000, // optional, default: 60000ms
|
|
||||||
|
|
||||||
// WebRTC configuration
|
|
||||||
rtcConfig: {
|
|
||||||
iceServers: [
|
iceServers: [
|
||||||
{ urls: 'stun:stun.l.google.com:19302' }
|
{ urls: 'stun:stun.l.google.com:19302' },
|
||||||
|
{
|
||||||
|
urls: 'turn:turn.example.com:3478',
|
||||||
|
username: 'user',
|
||||||
|
credential: 'pass'
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
// Connect by UUID
|
|
||||||
const connection2 = await client.connectByUuid('service-uuid-here', {
|
|
||||||
maxReconnectAttempts: 5
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create channels before connecting
|
|
||||||
const channel = connection.createChannel('main');
|
|
||||||
const fileChannel = connection.createChannel('files', {
|
|
||||||
ordered: false,
|
|
||||||
maxRetransmits: 3
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get existing channel
|
|
||||||
const existingChannel = connection.getChannel('main');
|
|
||||||
|
|
||||||
// Check connection state
|
|
||||||
const state = connection.getState();
|
|
||||||
// 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'failed' | 'closed'
|
|
||||||
|
|
||||||
const isConnected = connection.isConnected();
|
|
||||||
|
|
||||||
// Connect
|
|
||||||
await connection.connect();
|
|
||||||
|
|
||||||
// Close connection
|
|
||||||
await connection.close();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Connection Events:**
|
## Username Rules
|
||||||
```typescript
|
|
||||||
connection.on('state', (newState, previousState) => {
|
|
||||||
console.log(`State: ${previousState} → ${newState}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.on('connected', () => {
|
- **Format**: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
|
||||||
console.log('Connected');
|
- **Length**: 3-32 characters
|
||||||
});
|
- **Pattern**: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
|
||||||
|
- **Validity**: 365 days from claim/last use
|
||||||
connection.on('reconnecting', (attempt, maxAttempts, delay) => {
|
- **Ownership**: Secured by Ed25519 public key signature
|
||||||
console.log(`Reconnecting (${attempt}/${maxAttempts}) in ${delay}ms`);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.on('disconnected', () => {
|
|
||||||
console.log('Disconnected');
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.on('failed', (error, permanent) => {
|
|
||||||
console.error('Connection failed:', error, 'Permanent:', permanent);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.on('closed', () => {
|
|
||||||
console.log('Connection closed');
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Durable Channel API
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const channel = connection.createChannel('chat', {
|
|
||||||
ordered: true, // optional, default: true
|
|
||||||
maxRetransmits: undefined // optional, for unordered channels
|
|
||||||
});
|
|
||||||
|
|
||||||
// Send data (queued if disconnected)
|
|
||||||
channel.send('Hello!');
|
|
||||||
channel.send(new ArrayBuffer(1024));
|
|
||||||
channel.send(new Blob(['data']));
|
|
||||||
|
|
||||||
// Check state
|
|
||||||
const state = channel.readyState;
|
|
||||||
// 'connecting' | 'open' | 'closing' | 'closed'
|
|
||||||
|
|
||||||
// Get buffered amount
|
|
||||||
const buffered = channel.bufferedAmount;
|
|
||||||
|
|
||||||
// Set buffered amount low threshold
|
|
||||||
channel.bufferedAmountLowThreshold = 16 * 1024; // 16KB
|
|
||||||
|
|
||||||
// Get queue size (for debugging)
|
|
||||||
const queueSize = channel.getQueueSize();
|
|
||||||
|
|
||||||
// Close channel
|
|
||||||
channel.close();
|
|
||||||
```
|
|
||||||
|
|
||||||
**Channel Events:**
|
|
||||||
```typescript
|
|
||||||
channel.on('open', () => {
|
|
||||||
console.log('Channel open');
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('message', (data) => {
|
|
||||||
console.log('Received:', data);
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('error', (error) => {
|
|
||||||
console.error('Channel error:', error);
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('close', () => {
|
|
||||||
console.log('Channel closed');
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('bufferedAmountLow', () => {
|
|
||||||
console.log('Buffer drained, safe to send more');
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('queueOverflow', (droppedCount) => {
|
|
||||||
console.warn(`Queue overflow: ${droppedCount} messages dropped`);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration Options
|
|
||||||
|
|
||||||
### Connection Configuration
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
interface DurableConnectionConfig {
|
|
||||||
maxReconnectAttempts?: number; // default: 10
|
|
||||||
reconnectBackoffBase?: number; // default: 1000 (1 second)
|
|
||||||
reconnectBackoffMax?: number; // default: 30000 (30 seconds)
|
|
||||||
reconnectJitter?: number; // default: 0.2 (±20%)
|
|
||||||
connectionTimeout?: number; // default: 30000 (30 seconds)
|
|
||||||
maxQueueSize?: number; // default: 1000 messages
|
|
||||||
maxMessageAge?: number; // default: 60000 (1 minute)
|
|
||||||
rtcConfig?: RTCConfiguration;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Service Configuration
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
interface DurableServiceConfig extends DurableConnectionConfig {
|
|
||||||
username: string;
|
|
||||||
privateKey: string;
|
|
||||||
serviceFqn: string;
|
|
||||||
isPublic?: boolean; // default: false
|
|
||||||
metadata?: Record<string, any>;
|
|
||||||
ttl?: number; // default: 300000 (5 minutes)
|
|
||||||
ttlRefreshMargin?: number; // default: 0.2 (refresh at 80%)
|
|
||||||
poolSize?: number; // default: 1
|
|
||||||
pollingInterval?: number; // default: 2000 (2 seconds)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
### Chat Application
|
### Chat Application
|
||||||
|
|
||||||
```typescript
|
See [demo/demo.js](./demo/demo.js) for a complete working example.
|
||||||
// Server
|
|
||||||
const client = new Rondevu();
|
|
||||||
await client.register();
|
|
||||||
|
|
||||||
const claim = await client.usernames.claimUsername('alice');
|
### Persistent Keypair
|
||||||
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
|
|
||||||
const keypair = client.usernames.loadKeypairFromStorage('alice');
|
|
||||||
|
|
||||||
const service = await client.exposeService({
|
|
||||||
username: 'alice',
|
|
||||||
privateKey: keypair.privateKey,
|
|
||||||
serviceFqn: 'chat@1.0.0',
|
|
||||||
isPublic: true,
|
|
||||||
poolSize: 50, // Handle 50 concurrent users
|
|
||||||
handler: (channel, connectionId) => {
|
|
||||||
console.log(`User ${connectionId} joined`);
|
|
||||||
|
|
||||||
channel.on('message', (data) => {
|
|
||||||
console.log(`[${connectionId}]: ${data}`);
|
|
||||||
// Broadcast to all users (implement your broadcast logic)
|
|
||||||
});
|
|
||||||
|
|
||||||
channel.on('close', () => {
|
|
||||||
console.log(`User ${connectionId} left`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.start();
|
|
||||||
|
|
||||||
// Client
|
|
||||||
const client2 = new Rondevu();
|
|
||||||
await client2.register();
|
|
||||||
|
|
||||||
const connection = await client2.connect('alice', 'chat@1.0.0');
|
|
||||||
const channel = connection.createChannel('chat');
|
|
||||||
|
|
||||||
channel.on('message', (data) => {
|
|
||||||
console.log('Message:', data);
|
|
||||||
});
|
|
||||||
|
|
||||||
await connection.connect();
|
|
||||||
channel.send('Hello everyone!');
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Transfer with Progress
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Server
|
// Save keypair to localStorage
|
||||||
const service = await client.exposeService({
|
const service = new RondevuService({
|
||||||
username: 'alice',
|
apiUrl: 'https://api.ronde.vu',
|
||||||
privateKey: keypair.privateKey,
|
username: 'alice'
|
||||||
serviceFqn: 'files@1.0.0',
|
})
|
||||||
handler: (channel, connectionId) => {
|
|
||||||
channel.on('message', async (data) => {
|
|
||||||
const request = JSON.parse(data);
|
|
||||||
|
|
||||||
if (request.action === 'download') {
|
await service.initialize()
|
||||||
const file = await fs.readFile(request.path);
|
await service.claimUsername()
|
||||||
const chunkSize = 16 * 1024; // 16KB chunks
|
|
||||||
|
|
||||||
for (let i = 0; i < file.byteLength; i += chunkSize) {
|
// Save for later
|
||||||
const chunk = file.slice(i, i + chunkSize);
|
localStorage.setItem('rondevu-keypair', JSON.stringify(service.getKeypair()))
|
||||||
channel.send(chunk);
|
localStorage.setItem('rondevu-username', service.getUsername())
|
||||||
|
|
||||||
// Wait for buffer to drain if needed
|
// Load on next session
|
||||||
while (channel.bufferedAmount > 16 * 1024 * 1024) { // 16MB
|
const savedKeypair = JSON.parse(localStorage.getItem('rondevu-keypair'))
|
||||||
await new Promise(resolve => setTimeout(resolve, 100));
|
const savedUsername = localStorage.getItem('rondevu-username')
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
channel.send(JSON.stringify({ done: true }));
|
const service2 = new RondevuService({
|
||||||
}
|
apiUrl: 'https://api.ronde.vu',
|
||||||
});
|
username: savedUsername,
|
||||||
}
|
keypair: savedKeypair
|
||||||
});
|
})
|
||||||
|
|
||||||
await service.start();
|
await service2.initialize() // Reuses keypair
|
||||||
|
|
||||||
// Client
|
|
||||||
const connection = await client.connect('alice', 'files@1.0.0');
|
|
||||||
const channel = connection.createChannel('files');
|
|
||||||
|
|
||||||
const chunks = [];
|
|
||||||
channel.on('message', (data) => {
|
|
||||||
if (typeof data === 'string') {
|
|
||||||
const msg = JSON.parse(data);
|
|
||||||
if (msg.done) {
|
|
||||||
const blob = new Blob(chunks);
|
|
||||||
console.log('Download complete:', blob.size, 'bytes');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
chunks.push(data);
|
|
||||||
console.log('Progress:', chunks.length * 16 * 1024, 'bytes');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await connection.connect();
|
|
||||||
channel.send(JSON.stringify({ action: 'download', path: '/file.zip' }));
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Platform-Specific Setup
|
### Message Queue Example
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Messages are automatically queued if not connected yet
|
||||||
|
client.events.on('connected', (connection) => {
|
||||||
|
// Send immediately
|
||||||
|
connection.sendMessage('Hello!')
|
||||||
|
})
|
||||||
|
|
||||||
|
// Or queue for later
|
||||||
|
await client.connect()
|
||||||
|
const conn = client.getConnection()
|
||||||
|
await conn.queueMessage('This will be sent when connected', {
|
||||||
|
expiresAt: Date.now() + 60000 // Expire after 1 minute
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration from v0.9.x
|
||||||
|
|
||||||
|
v0.11.0+ introduces high-level wrappers, RESTful API changes, and semver-compatible discovery:
|
||||||
|
|
||||||
|
**API Changes:**
|
||||||
|
- Server endpoints restructured (`/usernames/*` → `/users/*`)
|
||||||
|
- Added `ServiceHost` and `ServiceClient` wrappers
|
||||||
|
- Message queue fully implemented
|
||||||
|
- Configurable polling with exponential backoff
|
||||||
|
- Removed deprecated `cleanup()` methods (use `dispose()`)
|
||||||
|
- **v0.11.0+**: Services use `offers` array instead of single `sdp`
|
||||||
|
- **v0.11.0+**: Semver-compatible service discovery (chat@1.0.0 matches 1.x.x)
|
||||||
|
- **v0.11.0+**: All services are hidden - no listing endpoint
|
||||||
|
- **v0.11.0+**: Services support multiple simultaneous offers for connection pooling
|
||||||
|
|
||||||
|
**Migration Guide:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Before (v0.9.x) - Manual WebRTC setup
|
||||||
|
const signaler = new RondevuSignaler(service, 'chat@1.0.0')
|
||||||
|
const context = new WebRTCContext()
|
||||||
|
const pc = context.createPeerConnection()
|
||||||
|
// ... 50+ lines of boilerplate
|
||||||
|
|
||||||
|
// After (v0.11.0) - ServiceHost wrapper
|
||||||
|
const host = new ServiceHost({
|
||||||
|
service: 'chat@1.0.0',
|
||||||
|
rondevuService: service
|
||||||
|
})
|
||||||
|
await host.start()
|
||||||
|
// Done!
|
||||||
|
```
|
||||||
|
|
||||||
|
## Platform Support
|
||||||
|
|
||||||
### Modern Browsers
|
### Modern Browsers
|
||||||
Works out of the box - no additional setup needed.
|
Works out of the box - no additional setup needed.
|
||||||
|
|
||||||
### Node.js 18+
|
### Node.js 18+
|
||||||
Native fetch is available, but you need WebRTC polyfills:
|
Native fetch is available, but WebRTC requires polyfills:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install wrtc
|
npm install wrtc
|
||||||
```
|
```
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { WebRTCContext } from '@xtr-dev/rondevu-client'
|
||||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc'
|
||||||
|
|
||||||
const client = new Rondevu({
|
// Configure WebRTC context
|
||||||
baseUrl: 'https://api.ronde.vu',
|
const context = new WebRTCContext({
|
||||||
RTCPeerConnection,
|
RTCPeerConnection,
|
||||||
RTCSessionDescription,
|
RTCSessionDescription,
|
||||||
RTCIceCandidate
|
RTCIceCandidate
|
||||||
});
|
} as any)
|
||||||
```
|
|
||||||
|
|
||||||
### Node.js < 18
|
|
||||||
Install both fetch and WebRTC polyfills:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install node-fetch wrtc
|
|
||||||
```
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
|
||||||
import fetch from 'node-fetch';
|
|
||||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
|
||||||
|
|
||||||
const client = new Rondevu({
|
|
||||||
baseUrl: 'https://api.ronde.vu',
|
|
||||||
fetch: fetch as any,
|
|
||||||
RTCPeerConnection,
|
|
||||||
RTCSessionDescription,
|
|
||||||
RTCIceCandidate
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## TypeScript
|
## TypeScript
|
||||||
@@ -622,38 +436,23 @@ All types are exported:
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import type {
|
import type {
|
||||||
// Client types
|
RondevuServiceOptions,
|
||||||
|
ServiceHostOptions,
|
||||||
|
ServiceHostEvents,
|
||||||
|
ServiceClientOptions,
|
||||||
|
ServiceClientEvents,
|
||||||
|
ConnectionInterface,
|
||||||
|
ConnectionEvents,
|
||||||
|
ConnectionStates,
|
||||||
|
Message,
|
||||||
|
QueueMessageOptions,
|
||||||
|
Signaler,
|
||||||
|
PollingConfig,
|
||||||
Credentials,
|
Credentials,
|
||||||
RondevuOptions,
|
Keypair
|
||||||
|
} from '@xtr-dev/rondevu-client'
|
||||||
// Username types
|
|
||||||
UsernameCheckResult,
|
|
||||||
UsernameClaimResult,
|
|
||||||
|
|
||||||
// Durable connection types
|
|
||||||
DurableConnectionState,
|
|
||||||
DurableChannelState,
|
|
||||||
DurableConnectionConfig,
|
|
||||||
DurableChannelConfig,
|
|
||||||
DurableServiceConfig,
|
|
||||||
QueuedMessage,
|
|
||||||
DurableConnectionEvents,
|
|
||||||
DurableChannelEvents,
|
|
||||||
DurableServiceEvents,
|
|
||||||
ConnectionInfo,
|
|
||||||
ServiceInfo
|
|
||||||
} from '@xtr-dev/rondevu-client';
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Migration from v0.8.x
|
|
||||||
|
|
||||||
v0.9.0 is a **breaking change** that replaces the low-level APIs with high-level durable connections. See [MIGRATION.md](./MIGRATION.md) for detailed migration guide.
|
|
||||||
|
|
||||||
**Key Changes:**
|
|
||||||
- ❌ Removed: `client.services.*`, `client.discovery.*`, `client.createPeer()` (low-level APIs)
|
|
||||||
- ✅ Added: `client.exposeService()`, `client.connect()`, `client.connectByUuid()` (durable APIs)
|
|
||||||
- ✅ Changed: Focus on durable connections with automatic reconnection and message queuing
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
|
|||||||
281
USAGE.md
Normal file
281
USAGE.md
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
# Rondevu Client Usage Guide
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install @xtr-dev/rondevu-client
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Register and Create Connection
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { RondevuAPI, RondevuSignaler, WebRTCRondevuConnection } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
const API_URL = 'https://api.ronde.vu';
|
||||||
|
|
||||||
|
// Register to get credentials
|
||||||
|
const api = new RondevuAPI(API_URL);
|
||||||
|
const credentials = await api.register();
|
||||||
|
|
||||||
|
// Create authenticated API client
|
||||||
|
const authenticatedApi = new RondevuAPI(API_URL, credentials);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Create an Offer (Offerer Side)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Create a connection
|
||||||
|
const connection = new WebRTCRondevuConnection(
|
||||||
|
'connection-id',
|
||||||
|
'host-username',
|
||||||
|
'service-name'
|
||||||
|
);
|
||||||
|
|
||||||
|
// Wait for local description
|
||||||
|
await connection.ready;
|
||||||
|
|
||||||
|
// Create offer on server
|
||||||
|
const offers = await authenticatedApi.createOffers([{
|
||||||
|
sdp: connection.connection.localDescription!.sdp!,
|
||||||
|
ttl: 300000 // 5 minutes
|
||||||
|
}]);
|
||||||
|
|
||||||
|
const offerId = offers[0].id;
|
||||||
|
|
||||||
|
// Set up signaler for ICE candidate exchange
|
||||||
|
const signaler = new RondevuSignaler(authenticatedApi, offerId);
|
||||||
|
connection.setSignaler(signaler);
|
||||||
|
|
||||||
|
// Poll for answer
|
||||||
|
const checkAnswer = setInterval(async () => {
|
||||||
|
const answer = await authenticatedApi.getAnswer(offerId);
|
||||||
|
if (answer) {
|
||||||
|
clearInterval(checkAnswer);
|
||||||
|
await connection.connection.setRemoteDescription({
|
||||||
|
type: 'answer',
|
||||||
|
sdp: answer.sdp
|
||||||
|
});
|
||||||
|
console.log('Connection established!');
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Answer an Offer (Answerer Side)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Get the offer
|
||||||
|
const offer = await authenticatedApi.getOffer(offerId);
|
||||||
|
|
||||||
|
// Create connection with remote offer
|
||||||
|
const connection = new WebRTCRondevuConnection(
|
||||||
|
'connection-id',
|
||||||
|
'peer-username',
|
||||||
|
'service-name',
|
||||||
|
{
|
||||||
|
type: 'offer',
|
||||||
|
sdp: offer.sdp
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Wait for local description (answer)
|
||||||
|
await connection.ready;
|
||||||
|
|
||||||
|
// Send answer to server
|
||||||
|
await authenticatedApi.answerOffer(
|
||||||
|
offerId,
|
||||||
|
connection.connection.localDescription!.sdp!
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set up signaler for ICE candidate exchange
|
||||||
|
const signaler = new RondevuSignaler(authenticatedApi, offerId);
|
||||||
|
connection.setSignaler(signaler);
|
||||||
|
|
||||||
|
console.log('Connection established!');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Using Services
|
||||||
|
|
||||||
|
### Publish a Service
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { RondevuAPI } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
const api = new RondevuAPI(API_URL, credentials);
|
||||||
|
|
||||||
|
const service = await api.publishService({
|
||||||
|
username: 'my-username',
|
||||||
|
serviceFqn: 'chat.app@1.0.0',
|
||||||
|
sdp: localDescription.sdp,
|
||||||
|
ttl: 300000,
|
||||||
|
isPublic: true,
|
||||||
|
metadata: { description: 'My chat service' },
|
||||||
|
signature: '...', // Ed25519 signature
|
||||||
|
message: '...' // Signed message
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Service UUID:', service.uuid);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Connect to a Service
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Search for services
|
||||||
|
const services = await api.searchServices('username', 'chat.app@1.0.0');
|
||||||
|
|
||||||
|
if (services.length > 0) {
|
||||||
|
// Get service details with offer
|
||||||
|
const service = await api.getService(services[0].uuid);
|
||||||
|
|
||||||
|
// Create connection with service offer
|
||||||
|
const connection = new WebRTCRondevuConnection(
|
||||||
|
service.serviceId,
|
||||||
|
service.username,
|
||||||
|
service.serviceFqn,
|
||||||
|
{
|
||||||
|
type: 'offer',
|
||||||
|
sdp: service.sdp
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await connection.ready;
|
||||||
|
|
||||||
|
// Answer the service offer
|
||||||
|
await api.answerOffer(
|
||||||
|
service.offerId,
|
||||||
|
connection.connection.localDescription!.sdp!
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set up signaler
|
||||||
|
const signaler = new RondevuSignaler(api, service.offerId);
|
||||||
|
connection.setSignaler(signaler);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Event Handling
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { EventBus } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
// Connection events
|
||||||
|
connection.events.on('state-change', (state) => {
|
||||||
|
console.log('Connection state:', state);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.events.on('message', (message) => {
|
||||||
|
console.log('Received message:', message);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Custom events with EventBus
|
||||||
|
interface MyEvents {
|
||||||
|
'user:connected': { userId: string; timestamp: number };
|
||||||
|
'message:sent': string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const events = new EventBus<MyEvents>();
|
||||||
|
|
||||||
|
events.on('user:connected', (data) => {
|
||||||
|
console.log(`User ${data.userId} connected at ${data.timestamp}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
events.emit('user:connected', {
|
||||||
|
userId: '123',
|
||||||
|
timestamp: Date.now()
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cleanup
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createBin } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
const bin = createBin();
|
||||||
|
|
||||||
|
// Add cleanup functions
|
||||||
|
bin(
|
||||||
|
() => console.log('Cleanup 1'),
|
||||||
|
() => console.log('Cleanup 2')
|
||||||
|
);
|
||||||
|
|
||||||
|
// Clean all
|
||||||
|
bin.clean();
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Reference
|
||||||
|
|
||||||
|
### RondevuAPI
|
||||||
|
|
||||||
|
Complete API client for Rondevu signaling server.
|
||||||
|
|
||||||
|
**Methods:**
|
||||||
|
- `register()` - Register new peer
|
||||||
|
- `createOffers(offers)` - Create offers
|
||||||
|
- `getOffer(offerId)` - Get offer by ID
|
||||||
|
- `answerOffer(offerId, sdp)` - Answer an offer
|
||||||
|
- `getAnswer(offerId)` - Poll for answer
|
||||||
|
- `searchOffers(topic)` - Search by topic
|
||||||
|
- `addIceCandidates(offerId, candidates)` - Add ICE candidates
|
||||||
|
- `getIceCandidates(offerId, since)` - Get ICE candidates (polling)
|
||||||
|
- `publishService(service)` - Publish service
|
||||||
|
- `getService(uuid)` - Get service by UUID
|
||||||
|
- `searchServices(username, serviceFqn)` - Search services
|
||||||
|
- `checkUsername(username)` - Check availability
|
||||||
|
- `claimUsername(username, publicKey, signature, message)` - Claim username
|
||||||
|
|
||||||
|
### RondevuSignaler
|
||||||
|
|
||||||
|
Handles ICE candidate exchange via polling.
|
||||||
|
|
||||||
|
**Constructor:**
|
||||||
|
```typescript
|
||||||
|
new RondevuSignaler(api: RondevuAPI, offerId: string)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Methods:**
|
||||||
|
- `addIceCandidate(candidate)` - Send local candidate
|
||||||
|
- `addListener(callback)` - Poll for remote candidates (returns cleanup function)
|
||||||
|
|
||||||
|
### WebRTCRondevuConnection
|
||||||
|
|
||||||
|
WebRTC connection wrapper with type-safe events.
|
||||||
|
|
||||||
|
**Constructor:**
|
||||||
|
```typescript
|
||||||
|
new WebRTCRondevuConnection(
|
||||||
|
id: string,
|
||||||
|
host: string,
|
||||||
|
service: string,
|
||||||
|
offer?: RTCSessionDescriptionInit
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Properties:**
|
||||||
|
- `id` - Connection ID
|
||||||
|
- `host` - Host username
|
||||||
|
- `service` - Service FQN
|
||||||
|
- `state` - Connection state
|
||||||
|
- `events` - EventBus for state changes and messages
|
||||||
|
- `ready` - Promise that resolves when local description is set
|
||||||
|
|
||||||
|
**Methods:**
|
||||||
|
- `setSignaler(signaler)` - Set signaler for ICE exchange
|
||||||
|
- `queueMessage(message, options)` - Queue message for sending
|
||||||
|
- `sendMessage(message)` - Send message immediately
|
||||||
|
|
||||||
|
### EventBus<TEvents>
|
||||||
|
|
||||||
|
Type-safe event emitter with inferred types.
|
||||||
|
|
||||||
|
**Methods:**
|
||||||
|
- `on(event, handler)` - Subscribe
|
||||||
|
- `once(event, handler)` - Subscribe once
|
||||||
|
- `off(event, handler)` - Unsubscribe
|
||||||
|
- `emit(event, data)` - Emit event
|
||||||
|
- `clear(event?)` - Clear handlers
|
||||||
|
- `listenerCount(event)` - Get listener count
|
||||||
|
- `eventNames()` - Get event names
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
See the demo application at https://github.com/xtr-dev/rondevu-demo for a complete working example.
|
||||||
52
eslint.config.js
Normal file
52
eslint.config.js
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import tsPlugin from '@typescript-eslint/eslint-plugin'
|
||||||
|
import tsParser from '@typescript-eslint/parser'
|
||||||
|
import prettierConfig from 'eslint-config-prettier'
|
||||||
|
import prettierPlugin from 'eslint-plugin-prettier'
|
||||||
|
import unicorn from 'eslint-plugin-unicorn'
|
||||||
|
import globals from 'globals'
|
||||||
|
|
||||||
|
export default [
|
||||||
|
js.configs.recommended,
|
||||||
|
{
|
||||||
|
files: ['**/*.ts', '**/*.tsx', '**/*.js'],
|
||||||
|
languageOptions: {
|
||||||
|
parser: tsParser,
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
...globals.node,
|
||||||
|
RTCPeerConnection: 'readonly',
|
||||||
|
RTCIceCandidate: 'readonly',
|
||||||
|
RTCSessionDescriptionInit: 'readonly',
|
||||||
|
RTCIceCandidateInit: 'readonly',
|
||||||
|
BufferSource: 'readonly',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'@typescript-eslint': tsPlugin,
|
||||||
|
prettier: prettierPlugin,
|
||||||
|
unicorn: unicorn,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...tsPlugin.configs.recommended.rules,
|
||||||
|
...prettierConfig.rules,
|
||||||
|
'prettier/prettier': 'error',
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||||
|
'unicorn/filename-case': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
case: 'kebabCase',
|
||||||
|
ignore: ['^README\\.md$'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ignores: ['dist/**', 'node_modules/**', '*.config.js'],
|
||||||
|
},
|
||||||
|
]
|
||||||
2951
package-lock.json
generated
2951
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
21
package.json
21
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-client",
|
"name": "@xtr-dev/rondevu-client",
|
||||||
"version": "0.9.2",
|
"version": "0.13.0",
|
||||||
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
|
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
@@ -8,6 +8,10 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
"dev": "vite",
|
||||||
|
"lint": "eslint src demo --ext .ts,.tsx,.js",
|
||||||
|
"lint:fix": "eslint src demo --ext .ts,.tsx,.js --fix",
|
||||||
|
"format": "prettier --write \"src/**/*.{ts,tsx,js}\" \"demo/**/*.{ts,tsx,js,html}\"",
|
||||||
"prepublishOnly": "npm run build"
|
"prepublishOnly": "npm run build"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
@@ -20,14 +24,23 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.9.3"
|
"@eslint/js": "^9.39.1",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^8.48.1",
|
||||||
|
"@typescript-eslint/parser": "^8.48.1",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-config-prettier": "^10.1.8",
|
||||||
|
"eslint-plugin-prettier": "^5.5.4",
|
||||||
|
"eslint-plugin-unicorn": "^62.0.0",
|
||||||
|
"globals": "^16.5.0",
|
||||||
|
"prettier": "^3.7.4",
|
||||||
|
"typescript": "^5.9.3",
|
||||||
|
"vite": "^7.2.6"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"README.md"
|
"README.md"
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/ed25519": "^3.0.0",
|
"@noble/ed25519": "^3.0.0"
|
||||||
"@xtr-dev/rondevu-client": "^0.9.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
458
src/api.ts
Normal file
458
src/api.ts
Normal file
@@ -0,0 +1,458 @@
|
|||||||
|
/**
|
||||||
|
* Rondevu API Client - Single class for all API endpoints
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as ed25519 from '@noble/ed25519'
|
||||||
|
|
||||||
|
// Set SHA-512 hash function for ed25519 (required in @noble/ed25519 v3+)
|
||||||
|
ed25519.hashes.sha512Async = async (message: Uint8Array) => {
|
||||||
|
return new Uint8Array(await crypto.subtle.digest('SHA-512', message as BufferSource))
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Credentials {
|
||||||
|
peerId: string
|
||||||
|
secret: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Keypair {
|
||||||
|
publicKey: string
|
||||||
|
privateKey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferRequest {
|
||||||
|
sdp: string
|
||||||
|
topics?: string[]
|
||||||
|
ttl?: number
|
||||||
|
secret?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Offer {
|
||||||
|
id: string
|
||||||
|
peerId: string
|
||||||
|
sdp: string
|
||||||
|
topics: string[]
|
||||||
|
ttl: number
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
answererPeerId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OfferRequest {
|
||||||
|
sdp: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServiceRequest {
|
||||||
|
serviceFqn: string // Must include username: service:version@username
|
||||||
|
offers: OfferRequest[]
|
||||||
|
ttl?: number
|
||||||
|
signature: string
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServiceOffer {
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Service {
|
||||||
|
serviceId: string
|
||||||
|
offers: ServiceOffer[]
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IceCandidate {
|
||||||
|
candidate: RTCIceCandidateInit
|
||||||
|
createdAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper: Convert Uint8Array to base64 string
|
||||||
|
*/
|
||||||
|
function bytesToBase64(bytes: Uint8Array): string {
|
||||||
|
const binString = Array.from(bytes, byte => String.fromCodePoint(byte)).join('')
|
||||||
|
return btoa(binString)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper: Convert base64 string to Uint8Array
|
||||||
|
*/
|
||||||
|
function base64ToBytes(base64: string): Uint8Array {
|
||||||
|
const binString = atob(base64)
|
||||||
|
return Uint8Array.from(binString, char => char.codePointAt(0)!)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RondevuAPI - Complete API client for Rondevu signaling server
|
||||||
|
*/
|
||||||
|
export class RondevuAPI {
|
||||||
|
constructor(
|
||||||
|
private baseUrl: string,
|
||||||
|
private credentials?: Credentials
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set credentials for authentication
|
||||||
|
*/
|
||||||
|
setCredentials(credentials: Credentials): void {
|
||||||
|
this.credentials = credentials
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication header
|
||||||
|
*/
|
||||||
|
private getAuthHeader(): Record<string, string> {
|
||||||
|
if (!this.credentials) {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
Authorization: `Bearer ${this.credentials.peerId}:${this.credentials.secret}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Ed25519 Cryptography Helpers
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate an Ed25519 keypair for username claiming and service publishing
|
||||||
|
*/
|
||||||
|
static async generateKeypair(): Promise<Keypair> {
|
||||||
|
const privateKey = ed25519.utils.randomSecretKey()
|
||||||
|
const publicKey = await ed25519.getPublicKeyAsync(privateKey)
|
||||||
|
|
||||||
|
return {
|
||||||
|
publicKey: bytesToBase64(publicKey),
|
||||||
|
privateKey: bytesToBase64(privateKey),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign a message with an Ed25519 private key
|
||||||
|
*/
|
||||||
|
static async signMessage(message: string, privateKeyBase64: string): Promise<string> {
|
||||||
|
const privateKey = base64ToBytes(privateKeyBase64)
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const messageBytes = encoder.encode(message)
|
||||||
|
|
||||||
|
const signature = await ed25519.signAsync(messageBytes, privateKey)
|
||||||
|
return bytesToBase64(signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a signature
|
||||||
|
*/
|
||||||
|
static async verifySignature(
|
||||||
|
message: string,
|
||||||
|
signatureBase64: string,
|
||||||
|
publicKeyBase64: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
const publicKey = base64ToBytes(publicKeyBase64)
|
||||||
|
const signature = base64ToBytes(signatureBase64)
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const messageBytes = encoder.encode(message)
|
||||||
|
|
||||||
|
return await ed25519.verifyAsync(signature, messageBytes, publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Authentication
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new peer and get credentials
|
||||||
|
*/
|
||||||
|
async register(): Promise<Credentials> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/register`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Registration failed: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Offers
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create one or more offers
|
||||||
|
*/
|
||||||
|
async createOffers(offers: OfferRequest[]): Promise<Offer[]> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/offers`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
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}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get offer by ID
|
||||||
|
*/
|
||||||
|
async getOffer(offerId: string): Promise<Offer> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/offers/${offerId}`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to get offer: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answer a specific offer from a service
|
||||||
|
*/
|
||||||
|
async postOfferAnswer(serviceFqn: string, offerId: string, sdp: string): Promise<{ success: boolean; offerId: string }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/answer`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
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}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get answer for a specific offer (offerer polls this)
|
||||||
|
*/
|
||||||
|
async getOfferAnswer(serviceFqn: string, offerId: string): Promise<{ sdp: string; offerId: string; answererId: string; answeredAt: number } | null> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/answer`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// 404 means not yet answered
|
||||||
|
if (response.status === 404) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to get answer: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search offers by topic
|
||||||
|
*/
|
||||||
|
async searchOffers(topic: string): Promise<Offer[]> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/offers?topic=${encodeURIComponent(topic)}`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to search offers: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// ICE Candidates
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add ICE candidates to a specific offer
|
||||||
|
*/
|
||||||
|
async addOfferIceCandidates(serviceFqn: string, offerId: string, candidates: RTCIceCandidateInit[]): Promise<{ count: number; offerId: string }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/ice-candidates`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
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}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get ICE candidates for a specific offer (with polling support)
|
||||||
|
*/
|
||||||
|
async getOfferIceCandidates(serviceFqn: string, offerId: string, since: number = 0): Promise<{ candidates: IceCandidate[]; offerId: string }> {
|
||||||
|
const url = new URL(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/ice-candidates`)
|
||||||
|
url.searchParams.set('since', since.toString())
|
||||||
|
|
||||||
|
const response = await fetch(url.toString(), { headers: this.getAuthHeader() })
|
||||||
|
|
||||||
|
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 {
|
||||||
|
candidates: data.candidates || [],
|
||||||
|
offerId: data.offerId
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Services
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publish a service
|
||||||
|
* Service FQN must include username: service:version@username
|
||||||
|
*/
|
||||||
|
async publishService(service: ServiceRequest): Promise<Service> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
body: JSON.stringify(service),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to publish service: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get service by FQN (with username) - Direct lookup
|
||||||
|
* Example: chat:1.0.0@alice
|
||||||
|
*/
|
||||||
|
async getService(serviceFqn: string): Promise<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to get service: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover a random available service without knowing the username
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverService(serviceVersion: string): Promise<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceVersion)}`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to discover service: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover multiple available services with pagination
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverServices(serviceVersion: string, limit: number = 10, offset: number = 0): Promise<{ services: Array<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }>; count: number; limit: number; offset: number }> {
|
||||||
|
const url = new URL(`${this.baseUrl}/services/${encodeURIComponent(serviceVersion)}`)
|
||||||
|
url.searchParams.set('limit', limit.toString())
|
||||||
|
url.searchParams.set('offset', offset.toString())
|
||||||
|
|
||||||
|
const response = await fetch(url.toString(), {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to discover services: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Usernames
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if username is available
|
||||||
|
*/
|
||||||
|
async checkUsername(username: string): Promise<{ available: boolean; publicKey?: string; claimedAt?: number; expiresAt?: number }> {
|
||||||
|
const response = await fetch(
|
||||||
|
`${this.baseUrl}/users/${encodeURIComponent(username)}`
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to check username: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claim a username (requires Ed25519 signature)
|
||||||
|
*/
|
||||||
|
async claimUsername(
|
||||||
|
username: string,
|
||||||
|
publicKey: string,
|
||||||
|
signature: string,
|
||||||
|
message: string
|
||||||
|
): Promise<{ success: boolean; username: string }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/users/${encodeURIComponent(username)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
publicKey,
|
||||||
|
signature,
|
||||||
|
message,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to claim username: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
/**
|
|
||||||
* ConnectionManager - Manages WebRTC peer connections
|
|
||||||
*/
|
|
||||||
|
|
||||||
export class ConnectionManager {
|
|
||||||
constructor() {
|
|
||||||
// TODO: Initialize connection manager
|
|
||||||
}
|
|
||||||
}
|
|
||||||
104
src/event-bus.ts
104
src/event-bus.ts
@@ -1,104 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
29
src/index.ts
29
src/index.ts
@@ -3,14 +3,27 @@
|
|||||||
* WebRTC peer signaling client
|
* WebRTC peer signaling client
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export { ConnectionManager } from './connection-manager.js';
|
export { Rondevu } from './rondevu.js'
|
||||||
export { EventBus } from './event-bus.js';
|
export { RondevuAPI } from './api.js'
|
||||||
|
export { RondevuSignaler } from './rondevu-signaler.js'
|
||||||
|
|
||||||
// Export types
|
// Export types
|
||||||
export type {
|
export type {
|
||||||
ConnectionIdentity,
|
Signaler,
|
||||||
ConnectionState,
|
Binnable,
|
||||||
ConnectionInterface,
|
} from './types.js'
|
||||||
Connection,
|
|
||||||
QueueMessageOptions
|
export type {
|
||||||
} from './types.js';
|
Credentials,
|
||||||
|
Keypair,
|
||||||
|
OfferRequest,
|
||||||
|
Offer,
|
||||||
|
ServiceRequest,
|
||||||
|
Service,
|
||||||
|
IceCandidate,
|
||||||
|
} from './api.js'
|
||||||
|
|
||||||
|
export type { RondevuOptions, PublishServiceOptions } from './rondevu.js'
|
||||||
|
|
||||||
|
export type { PollingConfig } from './rondevu-signaler.js'
|
||||||
|
|
||||||
|
|||||||
442
src/rondevu-signaler.ts
Normal file
442
src/rondevu-signaler.ts
Normal file
@@ -0,0 +1,442 @@
|
|||||||
|
import { Signaler, Binnable } from './types.js'
|
||||||
|
import { Rondevu } from './rondevu.js'
|
||||||
|
|
||||||
|
export interface PollingConfig {
|
||||||
|
initialInterval?: number // Default: 500ms
|
||||||
|
maxInterval?: number // Default: 5000ms
|
||||||
|
backoffMultiplier?: number // Default: 1.5
|
||||||
|
maxRetries?: number // Default: 50 (50 seconds max)
|
||||||
|
jitter?: boolean // Default: true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RondevuSignaler - Handles WebRTC signaling via Rondevu service
|
||||||
|
*
|
||||||
|
* Manages offer/answer exchange and ICE candidate polling for establishing
|
||||||
|
* WebRTC connections through the Rondevu signaling server.
|
||||||
|
*
|
||||||
|
* Supports configurable polling with exponential backoff and jitter to reduce
|
||||||
|
* server load and prevent thundering herd issues.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const signaler = new RondevuSignaler(
|
||||||
|
* rondevuService,
|
||||||
|
* 'chat.app@1.0.0',
|
||||||
|
* 'peer-username',
|
||||||
|
* { initialInterval: 500, maxInterval: 5000, jitter: true }
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* // For offerer:
|
||||||
|
* await signaler.setOffer(offer)
|
||||||
|
* signaler.addAnswerListener(answer => {
|
||||||
|
* // Handle remote answer
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* // For answerer:
|
||||||
|
* signaler.addOfferListener(offer => {
|
||||||
|
* // Handle remote offer
|
||||||
|
* })
|
||||||
|
* await signaler.setAnswer(answer)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class RondevuSignaler implements Signaler {
|
||||||
|
private offerId: string | null = null
|
||||||
|
private serviceFqn: string | null = null
|
||||||
|
private offerListeners: Array<(offer: RTCSessionDescriptionInit) => void> = []
|
||||||
|
private answerListeners: Array<(answer: RTCSessionDescriptionInit) => void> = []
|
||||||
|
private iceListeners: Array<(candidate: RTCIceCandidate) => void> = []
|
||||||
|
private answerPollingTimeout: ReturnType<typeof setTimeout> | null = null
|
||||||
|
private icePollingTimeout: ReturnType<typeof setTimeout> | null = null
|
||||||
|
private lastIceTimestamp = 0
|
||||||
|
private isPolling = false
|
||||||
|
private pollingConfig: Required<PollingConfig>
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly rondevu: Rondevu,
|
||||||
|
private readonly service: string,
|
||||||
|
private readonly host?: string,
|
||||||
|
pollingConfig?: PollingConfig
|
||||||
|
) {
|
||||||
|
this.pollingConfig = {
|
||||||
|
initialInterval: pollingConfig?.initialInterval ?? 500,
|
||||||
|
maxInterval: pollingConfig?.maxInterval ?? 5000,
|
||||||
|
backoffMultiplier: pollingConfig?.backoffMultiplier ?? 1.5,
|
||||||
|
maxRetries: pollingConfig?.maxRetries ?? 50,
|
||||||
|
jitter: pollingConfig?.jitter ?? true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publish an offer as a service
|
||||||
|
* Used by the offerer to make their offer available
|
||||||
|
*/
|
||||||
|
async setOffer(offer: RTCSessionDescriptionInit): Promise<void> {
|
||||||
|
if (!offer.sdp) {
|
||||||
|
throw new Error('Offer SDP is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish service with the offer SDP
|
||||||
|
const publishedService = await this.rondevu.publishService({
|
||||||
|
serviceFqn: this.service,
|
||||||
|
offers: [{ sdp: offer.sdp }],
|
||||||
|
ttl: 300000, // 5 minutes
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get the first offer from the published service
|
||||||
|
if (!publishedService.offers || publishedService.offers.length === 0) {
|
||||||
|
throw new Error('No offers returned from service publication')
|
||||||
|
}
|
||||||
|
|
||||||
|
this.offerId = publishedService.offers[0].offerId
|
||||||
|
this.serviceFqn = publishedService.serviceFqn
|
||||||
|
|
||||||
|
// Start polling for answer
|
||||||
|
this.startAnswerPolling()
|
||||||
|
|
||||||
|
// Start polling for ICE candidates
|
||||||
|
this.startIcePolling()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send an answer to the offerer
|
||||||
|
* Used by the answerer to respond to an offer
|
||||||
|
*/
|
||||||
|
async setAnswer(answer: RTCSessionDescriptionInit): Promise<void> {
|
||||||
|
if (!answer.sdp) {
|
||||||
|
throw new Error('Answer SDP is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
throw new Error('No service FQN or offer ID available. Must receive offer first.')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send answer to the service
|
||||||
|
const result = await this.rondevu.getAPI().postOfferAnswer(this.serviceFqn, this.offerId, answer.sdp)
|
||||||
|
this.offerId = result.offerId
|
||||||
|
|
||||||
|
// Start polling for ICE candidates
|
||||||
|
this.startIcePolling()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listen for incoming offers
|
||||||
|
* Used by the answerer to receive offers from the offerer
|
||||||
|
*/
|
||||||
|
addOfferListener(callback: (offer: RTCSessionDescriptionInit) => void): Binnable {
|
||||||
|
this.offerListeners.push(callback)
|
||||||
|
|
||||||
|
// If we have a host, start searching for their service
|
||||||
|
if (this.host && !this.isPolling) {
|
||||||
|
this.searchForOffer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return cleanup function
|
||||||
|
return () => {
|
||||||
|
const index = this.offerListeners.indexOf(callback)
|
||||||
|
if (index > -1) {
|
||||||
|
this.offerListeners.splice(index, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listen for incoming answers
|
||||||
|
* Used by the offerer to receive the answer from the answerer
|
||||||
|
*/
|
||||||
|
addAnswerListener(callback: (answer: RTCSessionDescriptionInit) => void): Binnable {
|
||||||
|
this.answerListeners.push(callback)
|
||||||
|
|
||||||
|
// Return cleanup function
|
||||||
|
return () => {
|
||||||
|
const index = this.answerListeners.indexOf(callback)
|
||||||
|
if (index > -1) {
|
||||||
|
this.answerListeners.splice(index, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send an ICE candidate to the remote peer
|
||||||
|
*/
|
||||||
|
async addIceCandidate(candidate: RTCIceCandidate): Promise<void> {
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
console.warn('Cannot send ICE candidate: no service FQN or offer ID')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidateData = candidate.toJSON()
|
||||||
|
|
||||||
|
// Skip empty candidates
|
||||||
|
if (!candidateData.candidate || candidateData.candidate === '') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.rondevu.getAPI().addOfferIceCandidates(
|
||||||
|
this.serviceFqn,
|
||||||
|
this.offerId,
|
||||||
|
[candidateData]
|
||||||
|
)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to send ICE candidate:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listen for ICE candidates from the remote peer
|
||||||
|
*/
|
||||||
|
addListener(callback: (candidate: RTCIceCandidate) => void): Binnable {
|
||||||
|
this.iceListeners.push(callback)
|
||||||
|
|
||||||
|
// Return cleanup function
|
||||||
|
return () => {
|
||||||
|
const index = this.iceListeners.indexOf(callback)
|
||||||
|
if (index > -1) {
|
||||||
|
this.iceListeners.splice(index, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search for an offer from the host
|
||||||
|
* Used by the answerer to find the offerer's service
|
||||||
|
*/
|
||||||
|
private async searchForOffer(): Promise<void> {
|
||||||
|
if (!this.host) {
|
||||||
|
throw new Error('No host specified for offer search')
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isPolling = true
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get service by FQN (service should include @username)
|
||||||
|
const serviceFqn = `${this.service}@${this.host}`
|
||||||
|
const serviceData = await this.rondevu.getAPI().getService(serviceFqn)
|
||||||
|
|
||||||
|
if (!serviceData) {
|
||||||
|
console.warn(`No service found for ${serviceFqn}`)
|
||||||
|
this.isPolling = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store service details
|
||||||
|
this.offerId = serviceData.offerId
|
||||||
|
this.serviceFqn = serviceData.serviceFqn
|
||||||
|
|
||||||
|
// Notify offer listeners
|
||||||
|
const offer: RTCSessionDescriptionInit = {
|
||||||
|
type: 'offer',
|
||||||
|
sdp: serviceData.sdp,
|
||||||
|
}
|
||||||
|
|
||||||
|
this.offerListeners.forEach(listener => {
|
||||||
|
try {
|
||||||
|
listener(offer)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Offer listener error:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to search for offer:', err)
|
||||||
|
this.isPolling = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start polling for answer (offerer side) with exponential backoff
|
||||||
|
*/
|
||||||
|
private startAnswerPolling(): void {
|
||||||
|
if (this.answerPollingTimeout || !this.serviceFqn || !this.offerId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval = this.pollingConfig.initialInterval
|
||||||
|
let retries = 0
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
this.stopAnswerPolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const answer = await this.rondevu.getAPI().getOfferAnswer(this.serviceFqn, this.offerId)
|
||||||
|
|
||||||
|
if (answer && answer.sdp) {
|
||||||
|
// Store offerId if we didn't have it yet
|
||||||
|
if (!this.offerId) {
|
||||||
|
this.offerId = answer.offerId
|
||||||
|
}
|
||||||
|
|
||||||
|
// Got answer - notify listeners and stop polling
|
||||||
|
const answerDesc: RTCSessionDescriptionInit = {
|
||||||
|
type: 'answer',
|
||||||
|
sdp: answer.sdp,
|
||||||
|
}
|
||||||
|
|
||||||
|
this.answerListeners.forEach(listener => {
|
||||||
|
try {
|
||||||
|
listener(answerDesc)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Answer listener error:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Stop polling once we get the answer
|
||||||
|
this.stopAnswerPolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// No answer yet - exponential backoff
|
||||||
|
retries++
|
||||||
|
if (retries > this.pollingConfig.maxRetries) {
|
||||||
|
console.warn('Max retries reached for answer polling')
|
||||||
|
this.stopAnswerPolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
interval = Math.min(
|
||||||
|
interval * this.pollingConfig.backoffMultiplier,
|
||||||
|
this.pollingConfig.maxInterval
|
||||||
|
)
|
||||||
|
|
||||||
|
// Add jitter to prevent thundering herd
|
||||||
|
const finalInterval = this.pollingConfig.jitter
|
||||||
|
? interval + Math.random() * 100
|
||||||
|
: interval
|
||||||
|
|
||||||
|
this.answerPollingTimeout = setTimeout(poll, finalInterval)
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
// 404 is expected when answer isn't available yet
|
||||||
|
if (err instanceof Error && !err.message?.includes('404')) {
|
||||||
|
console.error('Error polling for answer:', err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retry with backoff
|
||||||
|
const finalInterval = this.pollingConfig.jitter
|
||||||
|
? interval + Math.random() * 100
|
||||||
|
: interval
|
||||||
|
this.answerPollingTimeout = setTimeout(poll, finalInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
poll() // Start immediately
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop polling for answer
|
||||||
|
*/
|
||||||
|
private stopAnswerPolling(): void {
|
||||||
|
if (this.answerPollingTimeout) {
|
||||||
|
clearTimeout(this.answerPollingTimeout)
|
||||||
|
this.answerPollingTimeout = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start polling for ICE candidates with adaptive backoff
|
||||||
|
*/
|
||||||
|
private startIcePolling(): void {
|
||||||
|
if (this.icePollingTimeout || !this.serviceFqn || !this.offerId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval = this.pollingConfig.initialInterval
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
this.stopIcePolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.rondevu
|
||||||
|
.getAPI()
|
||||||
|
.getOfferIceCandidates(this.serviceFqn, this.offerId, this.lastIceTimestamp)
|
||||||
|
|
||||||
|
let foundCandidates = false
|
||||||
|
|
||||||
|
for (const item of result.candidates) {
|
||||||
|
if (item.candidate && item.candidate.candidate && item.candidate.candidate !== '') {
|
||||||
|
foundCandidates = true
|
||||||
|
try {
|
||||||
|
const rtcCandidate = new RTCIceCandidate(item.candidate)
|
||||||
|
|
||||||
|
this.iceListeners.forEach(listener => {
|
||||||
|
try {
|
||||||
|
listener(rtcCandidate)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('ICE listener error:', err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
this.lastIceTimestamp = item.createdAt
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Failed to process ICE candidate:', err)
|
||||||
|
this.lastIceTimestamp = item.createdAt
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.lastIceTimestamp = item.createdAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If candidates found, reset interval to initial value
|
||||||
|
// Otherwise, increase interval with backoff
|
||||||
|
if (foundCandidates) {
|
||||||
|
interval = this.pollingConfig.initialInterval
|
||||||
|
} else {
|
||||||
|
interval = Math.min(
|
||||||
|
interval * this.pollingConfig.backoffMultiplier,
|
||||||
|
this.pollingConfig.maxInterval
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add jitter
|
||||||
|
const finalInterval = this.pollingConfig.jitter
|
||||||
|
? interval + Math.random() * 100
|
||||||
|
: interval
|
||||||
|
|
||||||
|
this.icePollingTimeout = setTimeout(poll, finalInterval)
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
// 404/410 means offer expired, stop polling
|
||||||
|
if (err instanceof Error && (err.message?.includes('404') || err.message?.includes('410'))) {
|
||||||
|
console.warn('Offer not found or expired, stopping ICE polling')
|
||||||
|
this.stopIcePolling()
|
||||||
|
} else if (err instanceof Error && !err.message?.includes('404')) {
|
||||||
|
console.error('Error polling for ICE candidates:', err)
|
||||||
|
// Continue polling despite errors
|
||||||
|
const finalInterval = this.pollingConfig.jitter
|
||||||
|
? interval + Math.random() * 100
|
||||||
|
: interval
|
||||||
|
this.icePollingTimeout = setTimeout(poll, finalInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
poll() // Start immediately
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop polling for ICE candidates
|
||||||
|
*/
|
||||||
|
private stopIcePolling(): void {
|
||||||
|
if (this.icePollingTimeout) {
|
||||||
|
clearTimeout(this.icePollingTimeout)
|
||||||
|
this.icePollingTimeout = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop all polling and cleanup
|
||||||
|
*/
|
||||||
|
dispose(): void {
|
||||||
|
this.stopAnswerPolling()
|
||||||
|
this.stopIcePolling()
|
||||||
|
this.offerListeners = []
|
||||||
|
this.answerListeners = []
|
||||||
|
this.iceListeners = []
|
||||||
|
}
|
||||||
|
}
|
||||||
335
src/rondevu.ts
Normal file
335
src/rondevu.ts
Normal file
@@ -0,0 +1,335 @@
|
|||||||
|
import { RondevuAPI, Credentials, Keypair, Service, ServiceRequest, IceCandidate } from './api.js'
|
||||||
|
|
||||||
|
export interface RondevuOptions {
|
||||||
|
apiUrl: string
|
||||||
|
username: string
|
||||||
|
keypair?: Keypair
|
||||||
|
credentials?: Credentials
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PublishServiceOptions {
|
||||||
|
serviceFqn: string // Must include @username (e.g., "chat:1.0.0@alice")
|
||||||
|
offers: Array<{ sdp: string }>
|
||||||
|
ttl?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rondevu - Complete WebRTC signaling client
|
||||||
|
*
|
||||||
|
* Provides a unified API for:
|
||||||
|
* - Username claiming with Ed25519 signatures
|
||||||
|
* - Service publishing with automatic signature generation
|
||||||
|
* - Service discovery (direct, random, paginated)
|
||||||
|
* - WebRTC signaling (offer/answer exchange, ICE relay)
|
||||||
|
* - Keypair management
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Initialize (generates keypair automatically)
|
||||||
|
* const rondevu = new Rondevu({
|
||||||
|
* apiUrl: 'https://signal.example.com',
|
||||||
|
* username: 'alice',
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* await rondevu.initialize()
|
||||||
|
*
|
||||||
|
* // Claim username (one time)
|
||||||
|
* await rondevu.claimUsername()
|
||||||
|
*
|
||||||
|
* // Publish a service
|
||||||
|
* const publishedService = await rondevu.publishService({
|
||||||
|
* serviceFqn: 'chat:1.0.0@alice',
|
||||||
|
* offers: [{ sdp: offerSdp }],
|
||||||
|
* ttl: 300000,
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* // Discover a service
|
||||||
|
* const service = await rondevu.getService('chat:1.0.0@bob')
|
||||||
|
*
|
||||||
|
* // Post answer
|
||||||
|
* await rondevu.postOfferAnswer(service.serviceFqn, service.offerId, answerSdp)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class Rondevu {
|
||||||
|
private readonly api: RondevuAPI
|
||||||
|
private readonly username: string
|
||||||
|
private keypair: Keypair | null = null
|
||||||
|
private usernameClaimed = false
|
||||||
|
|
||||||
|
constructor(options: RondevuOptions) {
|
||||||
|
this.username = options.username
|
||||||
|
this.keypair = options.keypair || null
|
||||||
|
this.api = new RondevuAPI(options.apiUrl, options.credentials)
|
||||||
|
|
||||||
|
console.log('[Rondevu] Constructor called:', {
|
||||||
|
username: this.username,
|
||||||
|
hasKeypair: !!this.keypair,
|
||||||
|
publicKey: this.keypair?.publicKey
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Initialization
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the service - generates keypair if not provided
|
||||||
|
* Call this before using other methods
|
||||||
|
*/
|
||||||
|
async initialize(): Promise<void> {
|
||||||
|
console.log('[Rondevu] Initialize called, hasKeypair:', !!this.keypair)
|
||||||
|
|
||||||
|
if (!this.keypair) {
|
||||||
|
console.log('[Rondevu] Generating new keypair...')
|
||||||
|
this.keypair = await RondevuAPI.generateKeypair()
|
||||||
|
console.log('[Rondevu] Generated keypair, publicKey:', this.keypair.publicKey)
|
||||||
|
} else {
|
||||||
|
console.log('[Rondevu] Using existing keypair, publicKey:', this.keypair.publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register with API if no credentials provided
|
||||||
|
if (!this.api['credentials']) {
|
||||||
|
const credentials = await this.api.register()
|
||||||
|
this.api.setCredentials(credentials)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Username Management
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claim the username with Ed25519 signature
|
||||||
|
* Should be called once before publishing services
|
||||||
|
*/
|
||||||
|
async claimUsername(): Promise<void> {
|
||||||
|
if (!this.keypair) {
|
||||||
|
throw new Error('Not initialized. Call initialize() first.')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if username is already claimed
|
||||||
|
const check = await this.api.checkUsername(this.username)
|
||||||
|
if (!check.available) {
|
||||||
|
// Verify it's claimed by us
|
||||||
|
if (check.publicKey === this.keypair.publicKey) {
|
||||||
|
this.usernameClaimed = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
throw new Error(`Username "${this.username}" is already claimed by another user`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate signature for username claim
|
||||||
|
const message = `claim:${this.username}:${Date.now()}`
|
||||||
|
const signature = await RondevuAPI.signMessage(message, this.keypair.privateKey)
|
||||||
|
|
||||||
|
// Claim the username
|
||||||
|
await this.api.claimUsername(this.username, this.keypair.publicKey, signature, message)
|
||||||
|
this.usernameClaimed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if username has been claimed (checks with server)
|
||||||
|
*/
|
||||||
|
async isUsernameClaimed(): Promise<boolean> {
|
||||||
|
if (!this.keypair) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const check = await this.api.checkUsername(this.username)
|
||||||
|
|
||||||
|
// Debug logging
|
||||||
|
console.log('[Rondevu] Username check:', {
|
||||||
|
username: this.username,
|
||||||
|
available: check.available,
|
||||||
|
serverPublicKey: check.publicKey,
|
||||||
|
localPublicKey: this.keypair.publicKey,
|
||||||
|
match: check.publicKey === this.keypair.publicKey
|
||||||
|
})
|
||||||
|
|
||||||
|
// Username is claimed if it's not available and owned by our public key
|
||||||
|
const claimed = !check.available && check.publicKey === this.keypair.publicKey
|
||||||
|
|
||||||
|
// Update internal flag to match server state
|
||||||
|
this.usernameClaimed = claimed
|
||||||
|
|
||||||
|
return claimed
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to check username claim status:', err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Service Publishing
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publish a service with automatic signature generation
|
||||||
|
*/
|
||||||
|
async publishService(options: PublishServiceOptions): Promise<Service> {
|
||||||
|
if (!this.keypair) {
|
||||||
|
throw new Error('Not initialized. Call initialize() first.')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.usernameClaimed) {
|
||||||
|
throw new Error(
|
||||||
|
'Username not claimed. Call claimUsername() first or the server will reject the service.'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { serviceFqn, offers, ttl } = options
|
||||||
|
|
||||||
|
// Generate signature for service publication
|
||||||
|
const message = `publish:${this.username}:${serviceFqn}:${Date.now()}`
|
||||||
|
const signature = await RondevuAPI.signMessage(message, this.keypair.privateKey)
|
||||||
|
|
||||||
|
// Create service request
|
||||||
|
const serviceRequest: ServiceRequest = {
|
||||||
|
serviceFqn, // Must include @username
|
||||||
|
offers,
|
||||||
|
signature,
|
||||||
|
message,
|
||||||
|
ttl,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish to server
|
||||||
|
return await this.api.publishService(serviceRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Service Discovery
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get service by FQN (with username) - Direct lookup
|
||||||
|
* Example: chat:1.0.0@alice
|
||||||
|
*/
|
||||||
|
async getService(serviceFqn: string): Promise<{
|
||||||
|
serviceId: string
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}> {
|
||||||
|
return await this.api.getService(serviceFqn)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover a random available service without knowing the username
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverService(serviceVersion: string): Promise<{
|
||||||
|
serviceId: string
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}> {
|
||||||
|
return await this.api.discoverService(serviceVersion)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover multiple available services with pagination
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverServices(serviceVersion: string, limit: number = 10, offset: number = 0): Promise<{
|
||||||
|
services: Array<{
|
||||||
|
serviceId: string
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}>
|
||||||
|
count: number
|
||||||
|
limit: number
|
||||||
|
offset: number
|
||||||
|
}> {
|
||||||
|
return await this.api.discoverServices(serviceVersion, limit, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// WebRTC Signaling
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post answer SDP to specific offer
|
||||||
|
*/
|
||||||
|
async postOfferAnswer(serviceFqn: string, offerId: string, sdp: string): Promise<{
|
||||||
|
success: boolean
|
||||||
|
offerId: string
|
||||||
|
}> {
|
||||||
|
return await this.api.postOfferAnswer(serviceFqn, offerId, sdp)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get answer SDP (offerer polls this)
|
||||||
|
*/
|
||||||
|
async getOfferAnswer(serviceFqn: string, offerId: string): Promise<{
|
||||||
|
sdp: string
|
||||||
|
offerId: string
|
||||||
|
answererId: string
|
||||||
|
answeredAt: number
|
||||||
|
} | null> {
|
||||||
|
return await this.api.getOfferAnswer(serviceFqn, offerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add ICE candidates to specific offer
|
||||||
|
*/
|
||||||
|
async addOfferIceCandidates(serviceFqn: string, offerId: string, candidates: RTCIceCandidateInit[]): Promise<{
|
||||||
|
count: number
|
||||||
|
offerId: string
|
||||||
|
}> {
|
||||||
|
return await this.api.addOfferIceCandidates(serviceFqn, offerId, candidates)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get ICE candidates for specific offer (with polling support)
|
||||||
|
*/
|
||||||
|
async getOfferIceCandidates(serviceFqn: string, offerId: string, since: number = 0): Promise<{
|
||||||
|
candidates: IceCandidate[]
|
||||||
|
offerId: string
|
||||||
|
}> {
|
||||||
|
return await this.api.getOfferIceCandidates(serviceFqn, offerId, since)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Utility Methods
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current keypair (for backup/storage)
|
||||||
|
*/
|
||||||
|
getKeypair(): Keypair | null {
|
||||||
|
return this.keypair
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the username
|
||||||
|
*/
|
||||||
|
getUsername(): string {
|
||||||
|
return this.username
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the public key
|
||||||
|
*/
|
||||||
|
getPublicKey(): string | null {
|
||||||
|
return this.keypair?.publicKey || null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Access to underlying API for advanced operations
|
||||||
|
* @deprecated Use direct methods on Rondevu instance instead
|
||||||
|
*/
|
||||||
|
getAPI(): RondevuAPI {
|
||||||
|
return this.api
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/types.ts
34
src/types.ts
@@ -1,24 +1,20 @@
|
|||||||
/**
|
/**
|
||||||
* Core connection types
|
* Core signaling types
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface ConnectionIdentity {
|
/**
|
||||||
id: string;
|
* Cleanup function returned by listener methods
|
||||||
hostUsername: string;
|
*/
|
||||||
}
|
export type Binnable = () => void
|
||||||
|
|
||||||
export interface ConnectionState {
|
/**
|
||||||
state: 'connected' | 'disconnected' | 'connecting';
|
* Signaler interface for WebRTC offer/answer/ICE exchange
|
||||||
lastActive: number;
|
*/
|
||||||
|
export interface Signaler {
|
||||||
|
addIceCandidate(candidate: RTCIceCandidate): Promise<void>
|
||||||
|
addListener(callback: (candidate: RTCIceCandidate) => void): Binnable
|
||||||
|
addOfferListener(callback: (offer: RTCSessionDescriptionInit) => void): Binnable
|
||||||
|
addAnswerListener(callback: (answer: RTCSessionDescriptionInit) => void): Binnable
|
||||||
|
setOffer(offer: RTCSessionDescriptionInit): Promise<void>
|
||||||
|
setAnswer(answer: RTCSessionDescriptionInit): Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
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