or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

connection.mddata.mdindex.mdinfo.mdmedia.md

connection.mddocs/

0

# Connection Management

1

2

Core WebRTC peer connection functionality providing automatic negotiation, signaling handling, and connection lifecycle management.

3

4

## Capabilities

5

6

### Peer Constructor

7

8

Creates a new WebRTC peer connection with configurable options.

9

10

```javascript { .api }

11

/**

12

* Create a new WebRTC peer connection

13

* @param opts - Configuration options for the peer

14

*/

15

class Peer extends Duplex {

16

constructor(opts?: PeerOptions);

17

}

18

19

interface PeerOptions {

20

/** Set to true if this is the initiating peer */

21

initiator?: boolean;

22

/** Custom WebRTC data channel configuration */

23

channelConfig?: RTCDataChannelInit;

24

/** Custom WebRTC data channel name */

25

channelName?: string;

26

/** Custom WebRTC configuration (ICE servers, etc.) */

27

config?: RTCConfiguration;

28

/** Custom offer options for createOffer */

29

offerOptions?: RTCOfferOptions;

30

/** Custom answer options for createAnswer */

31

answerOptions?: RTCAnswerOptions;

32

/** Function to transform generated SDP signaling data */

33

sdpTransform?: (sdp: string) => string;

34

/** MediaStream for video/voice (deprecated, use streams) */

35

stream?: MediaStream;

36

/** Array of MediaStreams for video/voice */

37

streams?: MediaStream[];

38

/** Enable trickle ICE candidates (default: true) */

39

trickle?: boolean;

40

/** Allow half trickle ICE (default: false) */

41

allowHalfTrickle?: boolean;

42

/** Timeout for ICE completion in milliseconds (default: 5000) */

43

iceCompleteTimeout?: number;

44

/** Custom WebRTC implementation (required in Node.js) */

45

wrtc?: WebRTCImplementation;

46

/** Create stream in Object Mode (default: false) */

47

objectMode?: boolean;

48

/** Allow half-open duplex streams (default: false) */

49

allowHalfOpen?: boolean;

50

}

51

52

interface WebRTCImplementation {

53

RTCPeerConnection: typeof RTCPeerConnection;

54

RTCSessionDescription: typeof RTCSessionDescription;

55

RTCIceCandidate: typeof RTCIceCandidate;

56

}

57

```

58

59

**Usage Examples:**

60

61

```javascript

62

const Peer = require('simple-peer');

63

64

// Basic peer (browser)

65

const peer = new Peer({ initiator: true });

66

67

// Node.js peer with wrtc

68

const wrtc = require('wrtc');

69

const peer = new Peer({

70

initiator: true,

71

wrtc: wrtc

72

});

73

74

// Peer with custom configuration

75

const peer = new Peer({

76

initiator: false,

77

config: {

78

iceServers: [

79

{ urls: 'stun:stun.l.google.com:19302' },

80

{ urls: 'turn:turnserver.com', username: 'user', credential: 'pass' }

81

]

82

},

83

trickle: false,

84

iceCompleteTimeout: 10000

85

});

86

```

87

88

### Signal Processing

89

90

Process signaling data from the remote peer to establish and maintain the connection.

91

92

```javascript { .api }

93

/**

94

* Process signaling data from remote peer

95

* @param data - Signaling data (offer/answer/ice candidate)

96

* @throws {Error} ERR_DESTROYED - if peer is destroyed

97

* @throws {Error} ERR_SIGNALING - if signaling data is invalid

98

*/

99

peer.signal(data: SignalData | string): void;

100

101

interface SignalData {

102

/** Type of signaling message */

103

type?: 'offer' | 'answer' | 'renegotiate' | 'transceiverRequest' | 'candidate';

104

/** SDP data for offers/answers */

105

sdp?: string;

106

/** ICE candidate data */

107

candidate?: RTCIceCandidateInit;

108

/** Renegotiation request flag */

109

renegotiate?: boolean;

110

/** Transceiver request data */

111

transceiverRequest?: {

112

kind: string;

113

init?: RTCRtpTransceiverInit;

114

};

115

}

116

```

117

118

**Usage Examples:**

119

120

```javascript

121

// Handle signaling between peers

122

peer1.on('signal', data => {

123

// Send to peer2 via signaling server (websocket, etc.)

124

signalingServer.send(JSON.stringify(data));

125

});

126

127

signalingServer.on('message', data => {

128

const signalData = JSON.parse(data);

129

peer1.signal(signalData);

130

});

131

132

// Direct signaling (same process, for testing)

133

peer1.on('signal', data => peer2.signal(data));

134

peer2.on('signal', data => peer1.signal(data));

135

```

136

137

### Connection Lifecycle

138

139

Manage the peer connection lifecycle including negotiation and cleanup.

140

141

```javascript { .api }

142

/**

143

* Initiate renegotiation of the peer connection

144

*/

145

peer.negotiate(): void;

146

147

/**

148

* Destroy and cleanup the peer connection

149

* @param err - Optional error to emit

150

*/

151

peer.destroy(err?: Error): void;

152

```

153

154

**Usage Examples:**

155

156

```javascript

157

// Manual renegotiation

158

peer.negotiate();

159

160

// Graceful cleanup

161

peer.on('close', () => {

162

console.log('Peer connection closed');

163

});

164

165

peer.destroy();

166

167

// Cleanup with error

168

peer.destroy(new Error('Connection timeout'));

169

```

170

171

### Connection Events

172

173

Events emitted during the connection lifecycle.

174

175

```javascript { .api }

176

// Connection established and ready

177

peer.on('connect', () => void);

178

179

// Signaling data ready to send

180

peer.on('signal', (data: SignalData) => void);

181

182

// Connection closed

183

peer.on('close', () => void);

184

185

// Fatal error occurred

186

peer.on('error', (err: Error) => void);

187

188

// ICE connection state changed

189

peer.on('iceStateChange', (iceConnectionState: string, iceGatheringState: string) => void);

190

191

// Negotiation completed

192

peer.on('negotiated', () => void);

193

194

// Signaling state changed

195

peer.on('signalingStateChange', (signalingState: string) => void);

196

197

// ICE timeout reached

198

peer.on('iceTimeout', () => void);

199

```

200

201

**Usage Examples:**

202

203

```javascript

204

const peer = new Peer({ initiator: true });

205

206

peer.on('signal', data => {

207

console.log('Send this to remote peer:', JSON.stringify(data));

208

});

209

210

peer.on('connect', () => {

211

console.log('Peer connected successfully');

212

peer.send('Hello!');

213

});

214

215

peer.on('iceStateChange', (iceConnectionState, iceGatheringState) => {

216

console.log('ICE state:', iceConnectionState, iceGatheringState);

217

});

218

219

peer.on('error', err => {

220

console.error('Peer error:', err.message, err.code);

221

peer.destroy();

222

});

223

224

peer.on('close', () => {

225

console.log('Peer connection closed');

226

});

227

```

228

229

## Error Handling

230

231

Simple Peer emits errors with specific error codes for different failure scenarios:

232

233

```javascript { .api }

234

interface PeerError extends Error {

235

code: string;

236

}

237

```

238

239

**Common Error Codes:**

240

241

- `ERR_WEBRTC_SUPPORT` - No WebRTC support detected

242

- `ERR_PC_CONSTRUCTOR` - RTCPeerConnection constructor failed

243

- `ERR_DESTROYED` - Operation on destroyed peer

244

- `ERR_CREATE_OFFER` - Failed to create offer

245

- `ERR_CREATE_ANSWER` - Failed to create answer

246

- `ERR_SET_LOCAL_DESCRIPTION` - Failed to set local description

247

- `ERR_SET_REMOTE_DESCRIPTION` - Failed to set remote description

248

- `ERR_ADD_ICE_CANDIDATE` - Failed to add ICE candidate

249

- `ERR_ICE_CONNECTION_FAILURE` - ICE connection failed

250

- `ERR_CONNECTION_FAILURE` - General connection failure

251

- `ERR_SIGNALING` - Invalid signaling data

252

- `ERR_DATA_CHANNEL` - Data channel operation failed

253

- `ERR_ADD_TRANSCEIVER` - Failed to add transceiver

254

- `ERR_SENDER_REMOVED` - Track sender was removed

255

- `ERR_SENDER_ALREADY_ADDED` - Track already added to connection

256

- `ERR_TRACK_NOT_ADDED` - Cannot remove track that was never added

257

- `ERR_REMOVE_TRACK` - Failed to remove track

258

- `ERR_UNSUPPORTED_REPLACETRACK` - replaceTrack not supported

259

260

**Usage Examples:**

261

262

```javascript

263

peer.on('error', err => {

264

switch (err.code) {

265

case 'ERR_WEBRTC_SUPPORT':

266

console.error('WebRTC not supported in this browser');

267

break;

268

case 'ERR_ICE_CONNECTION_FAILURE':

269

console.error('ICE connection failed - check network/firewall');

270

break;

271

case 'ERR_SIGNALING':

272

console.error('Invalid signaling data received');

273

break;

274

default:

275

console.error('Peer error:', err.message);

276

}

277

});

278

```