xavia-webrtc-sdk
v1.0.0
Published
Complete backend SDK for Xavia Calling Service - REST API client and Socket.IO client for Node.js applications
Maintainers
Readme
Xavia Calling Backend SDK
Complete backend SDK for Xavia Calling Service integration. This SDK provides both REST API client and Socket.IO client for full WebRTC functionality in Node.js applications.
🚀 Features
- ✅ REST API Client - Complete HTTP API integration
- ✅ Socket.IO Client - Real-time WebRTC signaling
- ✅ TypeScript Support - Full type definitions
- ✅ Call Management - Create, join, leave calls
- ✅ User Management - Online users, invitations
- ✅ WebRTC Signaling - Offer/Answer/ICE handling
- ✅ Server Helpers - Configuration utilities
- ✅ Error Handling - Comprehensive error management
- ✅ Event System - Flexible event handlers
📦 Installation
npm install @xavia-calling/backend-sdk🔧 Quick Start
REST API Client
import { WebRTCClient } from '@xavia-calling/backend-sdk';
const client = new WebRTCClient({
baseURL: 'http://localhost:4009'
});
// Create a call
const call = await client.createCall({
callType: 'video',
isGroup: false,
maxParticipants: 2
});
console.log('Call created:', call.callId);
// Join the call
const participant = await client.joinCall(call.callId, {
userName: 'John Doe',
userId: 'user123'
});
console.log('Joined as:', participant.participantId);Socket.IO Client
import { WebRTCSocketClient } from '@xavia-calling/backend-sdk';
const socketClient = new WebRTCSocketClient({
serverUrl: 'http://localhost:4009',
userId: 'user123',
userName: 'John Doe'
});
// Set up event handlers
socketClient.setEventHandlers({
onIncomingCall: (data) => {
console.log(`Incoming ${data.callType} call from ${data.callerName}`);
// Accept the call
socketClient.acceptCall(data.callId, data.callerId);
},
onCallAccepted: (data) => {
console.log(`Call accepted by ${data.acceptedByName}`);
},
onUserOnline: (users) => {
console.log(`${users.length} users online`);
},
onSignal: (data) => {
console.log('WebRTC signal received:', data.type);
// Handle WebRTC signaling (offer, answer, ICE candidates)
}
});
// Connect to the service
await socketClient.connect();📚 API Reference
WebRTCClient (REST API)
Constructor
new WebRTCClient(config: WebRTCClientConfig)Config Options:
baseURL(string) - WebRTC service URLtimeout?(number) - Request timeout in ms (default: 10000)apiKey?(string) - API key for authenticationheaders?(object) - Additional headers
Methods
createCall(options?)
Create a new call.
const call = await client.createCall({
callType: 'video', // 'audio' | 'video' | 'screen'
isGroup: false, // boolean
maxParticipants: 10 // number
});getCall(callId)
Get call information.
const callInfo = await client.getCall('call-123');
console.log('Participants:', callInfo.participantCount);joinCall(callId, options)
Join a call.
const participant = await client.joinCall('call-123', {
userName: 'John Doe',
userId: 'user456' // optional
});leaveCall(callId, participantId)
Leave a call.
await client.leaveCall('call-123', 'participant-456');getParticipants(callId)
Get all participants in a call.
const participants = await client.getParticipants('call-123');
participants.participants.forEach(p => {
console.log(`- ${p.name} (joined: ${p.joinedAt})`);
});getHealth()
Check server health.
const health = await client.getHealth();
console.log('Server status:', health.status);
console.log('Active calls:', health.activeCalls);getTurnConfig()
Get TURN server configuration.
const turnConfig = await client.getTurnConfig();
console.log('ICE servers:', turnConfig.iceServers);testConnection()
Test connection to the service.
const isConnected = await client.testConnection();
if (isConnected) {
console.log('✅ Connected to WebRTC service');
}WebRTCSocketClient (Socket.IO)
Constructor
new WebRTCSocketClient(config: WebRTCSocketConfig)Config Options:
serverUrl(string) - WebRTC service URLuserId(string) - User IDuserName(string) - User nameautoConnect?(boolean) - Auto-connect on creation (default: true)reconnection?(boolean) - Enable reconnection (default: true)reconnectionAttempts?(number) - Max reconnection attempts (default: 5)reconnectionDelay?(number) - Reconnection delay in ms (default: 1000)timeout?(number) - Connection timeout in ms (default: 20000)
Methods
connect()
Connect to the WebRTC service.
await socketClient.connect();
console.log('Connected to WebRTC service');disconnect()
Disconnect from the service.
socketClient.disconnect();setEventHandlers(handlers)
Set event handlers.
socketClient.setEventHandlers({
onIncomingCall: (data) => {
console.log(`Incoming call from ${data.callerName}`);
},
onCallAccepted: (data) => {
console.log(`Call accepted by ${data.acceptedByName}`);
},
onCallRejected: (data) => {
console.log(`Call rejected by ${data.rejectedByName}`);
},
onUserOnline: (users) => {
console.log(`${users.length} users online`);
},
onSignal: (data) => {
// Handle WebRTC signaling
console.log('Signal received:', data.type);
},
onError: (error) => {
console.error('Socket error:', error.message);
}
});joinCall(callId, participantId, userName?)
Join a call room for real-time communication.
await socketClient.joinCall('call-123', 'participant-456');sendSignal(callId, signal, type, targetId?)
Send WebRTC signaling data.
// Send offer to specific participant
socketClient.sendSignal('call-123', offerData, 'offer', 'participant-456');
// Broadcast ICE candidate to all participants
socketClient.sendSignal('call-123', iceCandidate, 'ice-candidate');sendCallInvitation(targetUserId, callId, callType, callerName?)
Send call invitation to another user.
const result = await socketClient.sendCallInvitation(
'user456',
'call-123',
'video'
);
if (result.success) {
console.log('Invitation sent successfully');
}acceptCall(callId, callerId)
Accept an incoming call.
socketClient.acceptCall('call-123', 'caller-456');rejectCall(callId, callerId)
Reject an incoming call.
socketClient.rejectCall('call-123', 'caller-456');leaveCall(callId?, reason?)
Leave a call.
socketClient.leaveCall('call-123', 'user ended call');WebRTCServerHelper
Utility class for server configuration.
import { WebRTCServerHelper } from '@xavia-calling/backend-sdk';
const helper = new WebRTCServerHelper({
port: 4009,
turnUrls: ['turn:your-server.com:3478'],
turnUsername: 'username',
turnCredential: 'password'
});
// Get environment variables
const envVars = helper.getEnvConfig();
// Get ICE server configuration
const iceConfig = helper.getIceServers();
// Validate configuration
const validation = helper.validateConfig();
if (!validation.isValid) {
console.error('Configuration errors:', validation.errors);
}
// Generate .env file
const envContent = helper.generateEnvFile();
require('fs').writeFileSync('.env', envContent);🎯 Complete Example
Here's a complete example showing both REST API and Socket.IO usage:
import { WebRTCClient, WebRTCSocketClient } from '@xavia-calling/backend-sdk';
class XaviaCallingService {
private client: WebRTCClient;
private socketClient: WebRTCSocketClient;
private currentCall: string | null = null;
constructor(serverUrl: string, userId: string, userName: string) {
// Initialize REST client
this.client = new WebRTCClient({
baseURL: serverUrl
});
// Initialize Socket client
this.socketClient = new WebRTCSocketClient({
serverUrl,
userId,
userName
});
this.setupEventHandlers();
}
private setupEventHandlers() {
this.socketClient.setEventHandlers({
onIncomingCall: async (data) => {
console.log(`📞 Incoming ${data.callType} call from ${data.callerName}`);
// Auto-accept for demo (you'd show UI here)
this.socketClient.acceptCall(data.callId, data.callerId);
this.currentCall = data.callId;
},
onCallAccepted: async (data) => {
console.log(`✅ Call accepted by ${data.acceptedByName}`);
// Join the call room
const participant = await this.client.joinCall(data.callId, {
userName: 'Current User'
});
await this.socketClient.joinCall(
data.callId,
participant.participantId
);
},
onSignal: (data) => {
console.log(`📡 WebRTC signal: ${data.type} from ${data.fromId}`);
// Handle WebRTC signaling here
// This is where you'd process offers, answers, and ICE candidates
},
onUserOnline: (users) => {
console.log(`👥 ${users.length} users online:`,
users.map(u => u.userName).join(', '));
},
onError: (error) => {
console.error('❌ Socket error:', error.message);
}
});
}
async connect() {
await this.socketClient.connect();
console.log('🔌 Connected to Xavia Calling service');
}
async createCall(callType: 'audio' | 'video' = 'video') {
const call = await this.client.createCall({
callType,
isGroup: false
});
this.currentCall = call.callId;
console.log(`📞 Call created: ${call.callId}`);
return call;
}
async inviteUser(targetUserId: string, callType: 'audio' | 'video' = 'video') {
if (!this.currentCall) {
const call = await this.createCall(callType);
this.currentCall = call.callId;
}
const result = await this.socketClient.sendCallInvitation(
targetUserId,
this.currentCall,
callType
);
if (result.success) {
console.log(`📤 Invitation sent to ${targetUserId}`);
} else {
console.error(`❌ Failed to send invitation: ${result.error}`);
}
return result;
}
async endCall() {
if (this.currentCall) {
this.socketClient.leaveCall(this.currentCall, 'call ended');
this.currentCall = null;
console.log('📞 Call ended');
}
}
disconnect() {
this.socketClient.disconnect();
console.log('🔌 Disconnected from Xavia Calling service');
}
}
// Usage
async function main() {
const xaviaCalling = new XaviaCallingService(
'http://localhost:4009',
'user123',
'John Doe'
);
await xaviaCalling.connect();
// Create a call and invite another user
await xaviaCalling.inviteUser('user456', 'video');
// End call after 30 seconds (for demo)
setTimeout(() => {
xaviaCalling.endCall();
xaviaCalling.disconnect();
}, 30000);
}
main().catch(console.error);🔧 Configuration
Environment Variables
The SDK works with these environment variables:
# Server Configuration
PORT=4009
HOST=0.0.0.0
NODE_ENV=production
# TURN Server Configuration
TURN_URLS=turn:your-server.com:3478
TURN_USERNAME=username
TURN_CREDENTIAL=password
# Redis Configuration (for clustering)
USE_REDIS=false
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=optionalServer Helper
Use WebRTCServerHelper to generate configuration:
import { WebRTCServerHelper } from '@xavia-calling/backend-sdk';
// Get recommended config for your scale
const config = WebRTCServerHelper.getRecommendedConfig('medium');
const helper = new WebRTCServerHelper(config);
// Generate .env file
const envContent = helper.generateEnvFile();
console.log(envContent);🚨 Error Handling
The SDK provides comprehensive error handling:
try {
const call = await client.createCall();
} catch (error) {
if (error.message.includes('Network error')) {
console.error('Connection failed - check server URL');
} else if (error.message.includes('HTTP 404')) {
console.error('API endpoint not found');
} else {
console.error('Unexpected error:', error.message);
}
}
// Socket errors
socketClient.setEventHandlers({
onError: (error) => {
console.error('Socket error:', error.message);
// Handle reconnection, show user message, etc.
}
});📝 TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
WebRTCClient,
WebRTCSocketClient,
CallType,
CreateCallResponse,
CallEventHandlers
} from '@xavia-calling/backend-sdk';
// All types are available for import
const handlers: CallEventHandlers = {
onIncomingCall: (data) => {
// data is fully typed
console.log(data.callType); // 'audio' | 'video' | 'screen'
}
};🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
MIT
👨💻 Author
Zohaib Rana - Xavia Calling
🏢 Company
Xavia Calling - Advanced WebRTC Communication Solutions
For more examples and advanced usage, check the /examples directory in the main repository.
