@libp2p/webrtc-peer
Version:
Simple one-to-one WebRTC data channels
60 lines • 2.23 kB
JavaScript
import { EventEmitter } from '@libp2p/interfaces/events';
import errCode from 'err-code';
export class WebRTCHandshake extends EventEmitter {
constructor(options) {
super();
this.log = options.log;
this.peerConnection = options.peerConnection;
this.wrtc = options.wrtc;
this.status = 'idle';
this.peerConnection.addEventListener('negotiationneeded', () => {
this.log('peer connection negotiation needed');
this.handleRenegotiate({ type: 'renegotiate' }).catch(err => {
this.log.error('could not renegotiate %o', err);
});
});
}
async handleSignal(signal) {
this.log('incoming signal "%s"', signal.type);
if (signal.type === 'offer') {
return await this.handleOffer(signal);
}
else if (signal.type === 'answer') {
return await this.handleAnswer(signal);
}
else if (signal.type === 'candidate') {
return await this.handleCandidate(signal);
}
else if (signal.type === 'renegotiate') {
return await this.handleRenegotiate(signal);
}
else if (signal.type === 'goodbye') {
return await this.handleGoodye(signal);
}
else {
// @ts-expect-error all types are handled above
this.log(`Unknown signal type ${signal.type}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
}
}
async handleOffer(signal) { }
async handleAnswer(signal) { }
async handleRenegotiate(signal) { }
async handleGoodye(signal) {
this.peerConnection.close();
}
async handleCandidate(signal) {
const iceCandidate = new this.wrtc.RTCIceCandidate(signal.candidate);
try {
await this.peerConnection.addIceCandidate(iceCandidate);
}
catch (err) {
if (iceCandidate.address == null || iceCandidate.address.endsWith('.local')) {
this.log('ignoring unsupported ICE candidate.');
}
else {
throw errCode(err, 'ERR_ADD_ICE_CANDIDATE');
}
}
}
}
//# sourceMappingURL=handshake.js.map