A shim to insulate apps from WebRTC spec changes and browser prefix differences
Overall
score
98%
WebRTC Adapter provides a comprehensive set of utility functions for logging control, browser detection, event handling, and WebRTC statistics processing.
Functions for controlling adapter.js logging output and deprecation warnings.
/**
* Enable or disable adapter.js logging
* @param bool - true to disable logging, false to enable
* @returns Success message or Error object for invalid input
*/
function disableLog(bool: boolean): string | Error;
/**
* Enable or disable deprecation warnings
* @param bool - true to disable warnings, false to enable
* @returns Success message for valid input, Error object for invalid input
*/
function disableWarnings(bool: boolean): string | Error;
/**
* Internal logging function used by adapter
* Only outputs when logging is enabled and console is available
*/
function log(...args: any[]): void;
/**
* Display deprecation warning for old API usage
* Only shows warning when deprecation warnings are enabled
* @param oldMethod - Name of the deprecated method
* @param newMethod - Name of the recommended replacement method
*/
function deprecated(oldMethod: string, newMethod: string): void;Usage Examples:
import adapter from 'webrtc-adapter';
// Disable all adapter logging
const result = adapter.disableLog(true);
console.log(result); // "adapter.js logging disabled"
// Enable logging back
adapter.disableLog(false); // "adapter.js logging enabled"
// Disable deprecation warnings
adapter.disableWarnings(true); // "adapter.js deprecation warnings disabled"
// Invalid input handling
const error = adapter.disableLog("invalid");
console.log(error); // Error: Argument type: string. Please use a boolean.Core browser detection and version extraction functions.
/**
* Comprehensive browser detection from window object
* @param window - Browser window object to analyze
* @returns Browser details with type, version, and capabilities
*/
function detectBrowser(window: Window): IBrowserDetails;
/**
* Extract version number from user agent string using regex
* @param uastring - User agent string to parse
* @param expr - Regular expression pattern for extraction
* @param pos - Position in regex match array containing version
* @returns Parsed version number or null if not found
*/
function extractVersion(uastring: string, expr: string, pos: number): number | null;
interface IBrowserDetails {
browser: string;
version: number | null;
supportsUnifiedPlan?: boolean;
}Usage Examples:
import { detectBrowser, extractVersion } from 'webrtc-adapter/src/js/utils.js';
// Detect current browser
const browserInfo = detectBrowser(window);
console.log(`Running on ${browserInfo.browser} version ${browserInfo.version}`);
// Extract specific version information
const chromeVersion = extractVersion(
navigator.userAgent,
/Chrome\/(\d+)\./,
1
);
// Custom version extraction
const appVersion = extractVersion(
'MyWebRTCApp/2.1.0',
/MyWebRTCApp\/(\d+\.\d+\.\d+)/,
1
);Functions for wrapping and managing RTCPeerConnection events.
/**
* Wrap RTCPeerConnection events with custom handling logic
* @param window - Browser window object
* @param eventNameToWrap - Name of the event to wrap (e.g., 'icecandidate')
* @param wrapper - Function to modify or filter events
*/
function wrapPeerConnectionEvent(
window: Window,
eventNameToWrap: string,
wrapper: (event: Event) => Event | false
): void;Usage Examples:
import { wrapPeerConnectionEvent } from 'webrtc-adapter/src/js/utils.js';
// Wrap icecandidate events to add custom logging
wrapPeerConnectionEvent(window, 'icecandidate', (event) => {
if (event.candidate) {
console.log('ICE candidate generated:', event.candidate.candidate);
}
return event; // Return event to continue normal processing
});
// Filter out specific types of ICE candidates
wrapPeerConnectionEvent(window, 'icecandidate', (event) => {
if (event.candidate && event.candidate.candidate.includes('typ relay')) {
console.log('Blocking relay candidate');
return false; // Block this event
}
return event;
});Functions for processing and cleaning nested objects and data structures.
/**
* Remove empty objects and undefined values from nested objects
* Enhanced version of Lodash's compact function for object cleanup
* @param data - Data object to clean
* @returns Cleaned object with empty values removed
*/
function compactObject(data: any): any;Usage Examples:
import { compactObject } from 'webrtc-adapter/src/js/utils.js';
// Clean configuration object
const dirtyConfig = {
servers: {
stun: 'stun:stun.l.google.com:19302',
turn: undefined,
backup: {}
},
options: {
audio: true,
video: undefined,
advanced: {
echoCancellation: true,
noiseSuppression: undefined
}
}
};
const cleanConfig = compactObject(dirtyConfig);
// Result: { servers: { stun: 'stun...' }, options: { audio: true, advanced: { echoCancellation: true } } }Specialized functions for processing WebRTC statistics and navigating the stats graph.
/**
* Recursively walk through WebRTC statistics graph
* Follows ID references to build complete stat relationships
* @param stats - WebRTC stats Map object
* @param base - Starting stats object
* @param resultSet - Map to store visited stats objects
*/
function walkStats(stats: Map<any, any>, base: any, resultSet: Map<any, any>): void;
/**
* Filter WebRTC statistics for a specific media track
* Extracts track-specific stats for detailed analysis
* @param result - Complete WebRTC stats Map
* @param track - MediaStreamTrack to filter for (null for all tracks)
* @param outbound - true for outbound stats, false for inbound stats
* @returns Filtered Map containing only relevant statistics
*/
function filterStats(
result: Map<any, any>,
track: MediaStreamTrack | null,
outbound: boolean
): Map<any, any>;Usage Examples:
import { walkStats, filterStats } from 'webrtc-adapter/src/js/utils.js';
// Process complete WebRTC statistics
async function analyzeConnectionStats(pc) {
const stats = await pc.getStats();
// Find outbound video stats for specific track
const videoTrack = localStream.getVideoTracks()[0];
const videoStats = filterStats(stats, videoTrack, true);
videoStats.forEach((report) => {
if (report.type === 'outbound-rtp') {
console.log('Video bytes sent:', report.bytesSent);
console.log('Video packets sent:', report.packetsSent);
}
});
}
// Build complete statistics graph
function buildStatsGraph(stats) {
const completeStats = new Map();
// Walk from each top-level stat to build relationships
stats.forEach((stat) => {
if (stat.type === 'peer-connection') {
walkStats(stats, stat, completeStats);
}
});
return completeStats;
}// Track-specific statistics analysis
async function getTrackStatistics(pc, track, isOutbound = true) {
const allStats = await pc.getStats();
const trackStats = filterStats(allStats, track, isOutbound);
const analysis = {
bandwidth: 0,
packets: 0,
quality: 'unknown'
};
trackStats.forEach((report) => {
const rtpType = isOutbound ? 'outbound-rtp' : 'inbound-rtp';
if (report.type === rtpType) {
analysis.bandwidth = report.bytesSent || report.bytesReceived || 0;
analysis.packets = report.packetsSent || report.packetsReceived || 0;
// Calculate quality metrics
if (report.packetsLost !== undefined) {
const lossRate = report.packetsLost / (analysis.packets + report.packetsLost);
analysis.quality = lossRate < 0.02 ? 'good' : lossRate < 0.05 ? 'fair' : 'poor';
}
}
});
return analysis;
}All utility functions include appropriate error handling:
Install with Tessl CLI
npx tessl i tessl/npm-webrtc-adapterdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10