UNPKG

@webrtc2/types

Version:

WebRTC2 Types - Comprehensive TypeScript definitions for WebRTC cross-platform development including React Native, Web, and Electron type definitions

444 lines (370 loc) 9.65 kB
# @webrtc2/types - WebRTC TypeScript Definitions [![npm version](https://img.shields.io/npm/v/@webrtc2/types.svg)](https://www.npmjs.com/package/@webrtc2/types) [![TypeScript](https://img.shields.io/badge/TypeScript-Definitions-blue.svg)](https://typescriptlang.org/) [![WebRTC](https://img.shields.io/badge/WebRTC-Types-green.svg)](https://webrtc.org/) **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 ```bash npm install @webrtc2/types ``` ## 🎯 Type Definitions ### Core WebRTC Types ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript // 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 ```typescript 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](../client) - React hooks using these types - [@webrtc2/peer](../peer) - Peer connection with type safety - [@webrtc2/utils](../utils) - Utility functions with types - [@webrtc2/config](../config) - Configuration management ## 🤝 Contributing We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details. ## 📄 License MIT License - see [LICENSE](../../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