Package Exports
- @webrtc2/types
Readme
@webrtc2/types - WebRTC TypeScript Definitions
Comprehensive TypeScript definitions for WebRTC cross-platform development - Complete type safety for React Native, Web, and Electron WebRTC applications.
🎯 WebRTC TypeScript Made Simple
@webrtc2/types provides complete TypeScript definitions for:
- 🔗 RTCPeerConnection Types: Full WebRTC API coverage
- 🎥 Media Stream Types: Video, audio, and screen sharing
- 🧊 ICE & Signaling Types: Connection establishment
- 📱 Cross-Platform Types: React Native, Web, Electron
- ⚡ Event Types: Type-safe event handling
- 🏠 Room & Participant Types: Multi-user communication
📦 Installation
npm install @webrtc2/types🎯 Type Definitions
Core WebRTC Types
import {
RTCConnectionConfig,
ConnectionState,
WebRTCError,
ICEConnectionState
} from '@webrtc2/types';
// WebRTC configuration with type safety
const config: RTCConnectionConfig = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:your-turn-server.com:3478',
username: 'user',
credential: 'password'
}
],
iceCandidatePoolSize: 10,
bundlePolicy: 'max-bundle'
};
// Connection state management
const handleStateChange = (state: ConnectionState) => {
switch (state) {
case 'connecting':
console.log('Establishing connection...');
break;
case 'connected':
console.log('Connected successfully!');
break;
case 'disconnected':
console.log('Connection lost');
break;
case 'failed':
console.error('Connection failed');
break;
}
};Media Stream Types
import {
MediaStreamConstraints,
MediaDeviceInfo,
VideoConstraints,
AudioConstraints
} from '@webrtc2/types';
// Type-safe media constraints
const videoConstraints: VideoConstraints = {
width: { ideal: 1280, max: 1920 },
height: { ideal: 720, max: 1080 },
frameRate: { ideal: 30, max: 60 },
facingMode: 'user'
};
const audioConstraints: AudioConstraints = {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
sampleRate: 48000
};
const mediaConstraints: MediaStreamConstraints = {
video: videoConstraints,
audio: audioConstraints
};
// Device enumeration with types
const handleDevices = (devices: MediaDeviceInfo[]) => {
const cameras = devices.filter(d => d.kind === 'videoinput');
const microphones = devices.filter(d => d.kind === 'audioinput');
const speakers = devices.filter(d => d.kind === 'audiooutput');
};Signaling Types
import {
SignalingMessage,
OfferMessage,
AnswerMessage,
ICECandidateMessage,
SignalingEvent
} from '@webrtc2/types';
// Type-safe signaling messages
const handleSignalingMessage = (message: SignalingMessage) => {
switch (message.type) {
case 'offer':
const offer = message as OfferMessage;
console.log('Received offer from:', offer.from);
break;
case 'answer':
const answer = message as AnswerMessage;
console.log('Received answer from:', answer.from);
break;
case 'ice-candidate':
const candidate = message as ICECandidateMessage;
console.log('Received ICE candidate:', candidate.candidate);
break;
}
};
// Event handling with types
const signaling = {
on: <T extends SignalingEvent>(
event: T,
handler: (data: SignalingEventData[T]) => void
) => {
// Type-safe event handling
}
};Room & Participant Types
import {
Room,
Participant,
RoomSettings,
ParticipantRole,
RoomEvent
} from '@webrtc2/types';
// Room configuration
const roomSettings: RoomSettings = {
maxParticipants: 50,
enableVideo: true,
enableAudio: true,
enableScreenShare: true,
enableChat: true,
recordSession: false
};
// Participant management
const participant: Participant = {
id: 'user-123',
name: 'John Doe',
role: 'participant',
isVideoEnabled: true,
isAudioEnabled: true,
isScreenSharing: false,
joinedAt: new Date(),
lastSeen: new Date()
};
// Room state
const room: Room = {
id: 'room-456',
name: 'Team Meeting',
settings: roomSettings,
participants: [participant],
createdAt: new Date(),
isActive: true
};
// Type-safe room events
const handleRoomEvent = (event: RoomEvent) => {
switch (event.type) {
case 'participant-joined':
console.log('User joined:', event.participant.name);
break;
case 'participant-left':
console.log('User left:', event.participant.name);
break;
case 'media-state-changed':
console.log('Media state changed:', event.mediaState);
break;
}
};🌐 Cross-Platform Types
React Native Types
import {
ReactNativeMediaStream,
ReactNativeRTCView,
ReactNativeMediaConstraints
} from '@webrtc2/types';
// React Native specific constraints
const rnConstraints: ReactNativeMediaConstraints = {
video: {
width: 640,
height: 480,
frameRate: 30,
facingMode: 'user'
},
audio: true
};
// RTCView component props
interface RTCViewProps extends ReactNativeRTCView {
streamURL: string;
mirror?: boolean;
objectFit?: 'contain' | 'cover';
}Electron Types
import {
ElectronWebRTCConfig,
ElectronMediaAccess,
DesktopCapturerSource
} from '@webrtc2/types';
// Electron-specific configuration
const electronConfig: ElectronWebRTCConfig = {
webSecurity: false,
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
};
// Desktop screen capture
const screenSources: DesktopCapturerSource[] = [
{
id: 'screen:0',
name: 'Entire Screen',
thumbnail: Buffer.from('...'),
display_id: '0'
}
];Web Browser Types
import {
WebRTCBrowserSupport,
BrowserCapabilities,
WebRTCAdapter
} from '@webrtc2/types';
// Browser compatibility
const browserSupport: WebRTCBrowserSupport = {
webrtc: true,
getUserMedia: true,
getDisplayMedia: true,
dataChannels: true,
rtcStats: true
};
// Feature detection
const capabilities: BrowserCapabilities = {
video: {
codecs: ['VP8', 'VP9', 'H264'],
maxResolution: { width: 1920, height: 1080 },
maxFrameRate: 60
},
audio: {
codecs: ['OPUS', 'G722', 'PCMU'],
echoCancellation: true,
noiseSuppression: true
}
};🔧 Utility Types
Generic WebRTC Types
import {
WebRTCEvent,
WebRTCEventHandler,
WebRTCPromise,
WebRTCCallback
} from '@webrtc2/types';
// Event handling utilities
type EventMap = {
'connected': void;
'disconnected': void;
'stream': MediaStream;
'error': WebRTCError;
};
class WebRTCEventEmitter {
on<K extends keyof EventMap>(
event: K,
handler: WebRTCEventHandler<EventMap[K]>
): void;
emit<K extends keyof EventMap>(
event: K,
data: EventMap[K]
): void;
}
// Promise-based API types
type ConnectResult = WebRTCPromise<{
peerId: string;
connectionState: ConnectionState;
}>;
type MediaResult = WebRTCPromise<{
stream: MediaStream;
devices: MediaDeviceInfo[];
}>;Configuration Types
import {
WebRTCConfig,
STUNConfig,
TURNConfig,
SignalingConfig
} from '@webrtc2/types';
// Complete configuration interface
interface AppWebRTCConfig extends WebRTCConfig {
stun: STUNConfig;
turn: TURNConfig;
signaling: SignalingConfig;
}
const config: AppWebRTCConfig = {
stun: {
urls: ['stun:stun.l.google.com:19302']
},
turn: {
urls: 'turn:your-server.com:3478',
username: 'user',
credential: 'pass'
},
signaling: {
url: 'wss://signaling.example.com',
reconnectInterval: 5000,
maxReconnectAttempts: 10
}
};📚 Type Exports
// Core WebRTC types
export * from './webrtc';
export * from './peer-connection';
export * from './media-stream';
export * from './ice';
// Platform-specific types
export * from './react-native';
export * from './electron';
export * from './web';
// Application types
export * from './room';
export * from './participant';
export * from './signaling';
// Utility types
export * from './events';
export * from './config';
export * from './errors';🔍 Type Checking Examples
import { WebRTCConnection } from '@webrtc2/types';
// Type-safe WebRTC usage
const connection: WebRTCConnection = {
async connect(peerId: string) {
// TypeScript ensures correct parameter types
return Promise.resolve();
},
on(event, handler) {
// Event names and handler signatures are type-checked
},
addStream(stream) {
// MediaStream type is enforced
}
};📚 Related Packages
- @webrtc2/client - React hooks using these types
- @webrtc2/peer - Peer connection with type safety
- @webrtc2/utils - Utility functions with types
- @webrtc2/config - Configuration management
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT License - see LICENSE for details.
Keywords: WebRTC TypeScript, WebRTC types, RTCPeerConnection types, WebRTC definitions, TypeScript WebRTC, React Native WebRTC types, Electron WebRTC types, WebRTC interfaces, type safety WebRTC