@yrzhao/aves-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +157 -343
  2. package/dist/core/AvesClient.d.ts +45 -64
  3. package/dist/core/AvesClient.js +190 -142
  4. package/dist/core/AvesError.d.ts +39 -0
  5. package/dist/core/AvesError.js +42 -0
  6. package/dist/core/EventEmitter.d.ts +26 -24
  7. package/dist/core/EventEmitter.js +12 -23
  8. package/dist/core/SignalingClient.d.ts +30 -7
  9. package/dist/core/SignalingClient.js +177 -41
  10. package/dist/core/WebRTCManager.d.ts +152 -39
  11. package/dist/core/WebRTCManager.js +409 -196
  12. package/dist/core/webrtc/channels.d.ts +10 -0
  13. package/dist/core/webrtc/channels.js +25 -0
  14. package/dist/core/webrtc/fileTransfer.d.ts +84 -0
  15. package/dist/core/webrtc/fileTransfer.js +399 -0
  16. package/dist/core/webrtc/mediaTracks.d.ts +53 -0
  17. package/dist/core/webrtc/mediaTracks.js +385 -0
  18. package/dist/core/webrtc/messages.d.ts +4 -0
  19. package/dist/core/webrtc/messages.js +53 -0
  20. package/dist/esm/core/AvesClient.d.ts +45 -64
  21. package/dist/esm/core/AvesClient.js +193 -145
  22. package/dist/esm/core/AvesError.d.ts +39 -0
  23. package/dist/esm/core/AvesError.js +38 -0
  24. package/dist/esm/core/EventEmitter.d.ts +26 -24
  25. package/dist/esm/core/EventEmitter.js +12 -23
  26. package/dist/esm/core/SignalingClient.d.ts +30 -7
  27. package/dist/esm/core/SignalingClient.js +178 -42
  28. package/dist/esm/core/WebRTCManager.d.ts +152 -39
  29. package/dist/esm/core/WebRTCManager.js +409 -196
  30. package/dist/esm/core/webrtc/channels.d.ts +10 -0
  31. package/dist/esm/core/webrtc/channels.js +19 -0
  32. package/dist/esm/core/webrtc/fileTransfer.d.ts +84 -0
  33. package/dist/esm/core/webrtc/fileTransfer.js +393 -0
  34. package/dist/esm/core/webrtc/mediaTracks.d.ts +53 -0
  35. package/dist/esm/core/webrtc/mediaTracks.js +381 -0
  36. package/dist/esm/core/webrtc/messages.d.ts +4 -0
  37. package/dist/esm/core/webrtc/messages.js +48 -0
  38. package/dist/esm/index.d.ts +4 -1
  39. package/dist/esm/index.js +5 -4
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/types/types.d.ts +84 -4
  42. package/dist/index.cjs +3 -1
  43. package/dist/index.d.ts +4 -1
  44. package/dist/index.js +3 -1
  45. package/dist/types/types.d.ts +84 -4
  46. package/package.json +4 -3
@@ -1,304 +1,517 @@
1
+ import { AvesError } from "./AvesError.js";
2
+ import { FILE_CHANNEL_LABEL, MESSAGE_CHANNEL_LABEL, getChannelKind, isPeerChannels, normalizePeerChannels, } from "./webrtc/channels.js";
3
+ import { DEFAULT_FILE_CHUNK_SIZE, FileTransferManager, isFileControlMessage, } from "./webrtc/fileTransfer.js";
4
+ import { MediaTrackManager } from "./webrtc/mediaTracks.js";
5
+ import { errorMessage, serializeUserMessage } from "./webrtc/messages.js";
1
6
  /**
2
- * WebRTCManager - Manages WebRTC PeerConnections and DataChannels
3
- *
4
- * This class handles the low-level WebRTC connection management including:
5
- * - Creating and managing RTCPeerConnection instances
6
- * - Creating and managing RTCDataChannel instances
7
- * - Handling ICE candidate exchange
8
- * - Serializing and deserializing messages
9
- * - Managing connection lifecycle and cleanup
7
+ * WebRTCManager - Manages WebRTC PeerConnections, DataChannels, and media tracks
10
8
  */
11
9
  export class WebRTCManager {
12
- constructor(iceServers) {
10
+ constructor(iceServers, fileChunkSize = DEFAULT_FILE_CHUNK_SIZE, videoConstraints = {}) {
13
11
  this.peerConnections = new Map();
14
12
  this.dataChannels = new Map();
15
13
  this.iceServers = iceServers;
14
+ this.fileTransfers = new FileTransferManager({
15
+ fileChunkSize,
16
+ getActivePeers: () => this.getActivePeers(),
17
+ isFileChannelReady: (peerId) => this.isFileChannelReady(peerId),
18
+ getMessageChannel: (peerId) => this.getMessageChannel(peerId),
19
+ getFileChannel: (peerId) => this.getFileChannel(peerId),
20
+ });
16
21
  this.messageCallbacks = new Set();
17
22
  this.connectionStateCallbacks = new Map();
18
23
  this.dataChannelStateCallbacks = new Map();
19
24
  this.iceCandidateCallbacks = new Map();
25
+ this.outgoingTransfers = this.fileTransfers.outgoingTransfers;
26
+ this.incomingTransfers = this.fileTransfers.incomingTransfers;
27
+ this.readyResolvers = this.fileTransfers.readyResolvers;
28
+ this.completionResolvers = this.fileTransfers.completionResolvers;
29
+ this.fileTransferStartedCallbacks =
30
+ this.fileTransfers.fileTransferStartedCallbacks;
31
+ this.fileTransferProgressCallbacks =
32
+ this.fileTransfers.fileTransferProgressCallbacks;
33
+ this.fileTransferCompletedCallbacks =
34
+ this.fileTransfers.fileTransferCompletedCallbacks;
35
+ this.fileTransferFailedCallbacks =
36
+ this.fileTransfers.fileTransferFailedCallbacks;
37
+ this.mediaTracks = new MediaTrackManager(this.peerConnections, () => this.getActivePeers(), videoConstraints);
38
+ this.videoSenders = this.mediaTracks.videoSenders;
39
+ this.remoteAudioTrackCallbacks = this.mediaTracks.remoteAudioTrackCallbacks;
40
+ this.localAudioStateCallbacks = this.mediaTracks.localAudioStateCallbacks;
41
+ this.remoteVideoTrackCallbacks = this.mediaTracks.remoteVideoTrackCallbacks;
42
+ this.localVideoStateCallbacks = this.mediaTracks.localVideoStateCallbacks;
43
+ this.screenShareStateCallbacks = this.mediaTracks.screenShareStateCallbacks;
44
+ this.errorCallbacks = new Set();
20
45
  }
21
46
  /**
22
- * Create a new PeerConnection for the specified peer
23
- * If a connection already exists, returns the existing connection
47
+ * Create a new PeerConnection for the specified peer.
48
+ * If a connection already exists, returns the existing connection.
24
49
  */
25
50
  createPeerConnection(peerId) {
26
- if (this.peerConnections.has(peerId)) {
27
- console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
28
- return this.peerConnections.get(peerId);
51
+ const existing = this.peerConnections.get(peerId);
52
+ if (existing) {
53
+ return existing;
29
54
  }
30
- console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
31
55
  const pc = new RTCPeerConnection({
32
56
  iceServers: this.iceServers,
33
57
  });
34
58
  this.peerConnections.set(peerId, pc);
35
- // Monitor connection state changes
36
- pc.onconnectionstatechange = () => {
37
- console.log(`[WebRTCManager] Connection state for ${peerId}: ${pc.connectionState}`);
38
- const callbacks = this.connectionStateCallbacks.get(peerId);
39
- if (callbacks) {
40
- callbacks.forEach((callback) => callback(pc.connectionState));
41
- }
42
- // Auto-cleanup on failed/closed/disconnected states
43
- if (pc.connectionState === "failed" ||
44
- pc.connectionState === "closed" ||
45
- pc.connectionState === "disconnected") {
46
- this.closePeerConnection(peerId);
47
- }
48
- };
59
+ this.dataChannels.set(peerId, {});
60
+ this.setupPeerConnection(peerId, pc);
49
61
  return pc;
50
62
  }
51
63
  /**
52
- * Create an offer for the specified peer
53
- * This also creates the DataChannel (offer side creates the channel)
64
+ * Create an offer for the specified peer.
65
+ * The offer side creates both the message and file channels.
54
66
  */
55
67
  async createOffer(peerId) {
56
- const pc = this.peerConnections.get(peerId);
57
- if (!pc) {
58
- throw new Error(`No peer connection found for ${peerId}`);
59
- }
60
- console.log(`[WebRTCManager] Creating offer for ${peerId}, current state: ${pc.signalingState}`);
61
- // Create DataChannel (offer side creates it)
62
- const dataChannel = pc.createDataChannel("data");
63
- this.setupDataChannel(peerId, dataChannel);
68
+ const pc = this.getPeerConnection(peerId);
69
+ this.ensureDataChannel(peerId, pc, MESSAGE_CHANNEL_LABEL);
70
+ this.ensureDataChannel(peerId, pc, FILE_CHANNEL_LABEL);
64
71
  const offer = await pc.createOffer();
65
72
  await pc.setLocalDescription(offer);
66
- console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
67
73
  return offer;
68
74
  }
69
75
  /**
70
- * Create an answer for the specified peer
71
- * Sets up the remote offer and creates an answer
76
+ * Create an answer for the specified peer.
77
+ * The answer side receives data channels from the remote offer.
72
78
  */
73
79
  async createAnswer(peerId, offer) {
74
- const pc = this.peerConnections.get(peerId);
75
- if (!pc) {
76
- throw new Error(`No peer connection found for ${peerId}`);
77
- }
78
- // Listen for DataChannel (answer side receives it)
80
+ const pc = this.getPeerConnection(peerId);
79
81
  pc.ondatachannel = (event) => {
80
82
  this.setupDataChannel(peerId, event.channel);
81
83
  };
82
- console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
83
84
  await pc.setRemoteDescription(new RTCSessionDescription(offer));
84
- console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
85
85
  const answer = await pc.createAnswer();
86
86
  await pc.setLocalDescription(answer);
87
- console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
88
87
  return answer;
89
88
  }
90
89
  /**
91
- * Set the remote answer for the specified peer
90
+ * Set the remote answer for the specified peer.
92
91
  */
93
92
  async setRemoteAnswer(peerId, answer) {
94
- const pc = this.peerConnections.get(peerId);
95
- if (!pc) {
96
- throw new Error(`No peer connection found for ${peerId}`);
97
- }
98
- console.log(`[WebRTCManager] Setting remote answer for ${peerId}, current state: ${pc.signalingState}`);
99
- // Check if we're in the correct state to set remote answer
100
- if (pc.signalingState !== "have-local-offer") {
101
- throw new Error(`Cannot set remote answer for ${peerId}: wrong state ${pc.signalingState}, expected have-local-offer`);
102
- }
93
+ const pc = this.getPeerConnection(peerId);
103
94
  await pc.setRemoteDescription(new RTCSessionDescription(answer));
104
- console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
105
95
  }
106
96
  /**
107
- * Add an ICE candidate for the specified peer
97
+ * Add an ICE candidate for the specified peer.
108
98
  */
109
99
  async addIceCandidate(peerId, candidate) {
110
- const pc = this.peerConnections.get(peerId);
111
- if (!pc) {
112
- throw new Error(`No peer connection found for ${peerId}`);
113
- }
114
- try {
115
- await pc.addIceCandidate(new RTCIceCandidate(candidate));
116
- }
117
- catch (error) {
118
- console.error(`Error adding ICE candidate for ${peerId}:`, error);
119
- throw error;
120
- }
100
+ const pc = this.getPeerConnection(peerId);
101
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
121
102
  }
122
103
  /**
123
- * Register a callback for ICE candidates from the specified peer
104
+ * Send a JSON message to all connected peers.
105
+ * Peers with unavailable channels are skipped gracefully;
106
+ * the message is delivered to every ready peer.
124
107
  */
125
- onIceCandidate(peerId, callback) {
126
- const pc = this.peerConnections.get(peerId);
127
- if (!pc) {
128
- throw new Error(`No peer connection found for ${peerId}`);
129
- }
130
- if (!this.iceCandidateCallbacks.has(peerId)) {
131
- this.iceCandidateCallbacks.set(peerId, new Set());
132
- }
133
- this.iceCandidateCallbacks.get(peerId).add(callback);
134
- pc.onicecandidate = (event) => {
135
- if (event.candidate) {
136
- const callbacks = this.iceCandidateCallbacks.get(peerId);
137
- if (callbacks) {
138
- callbacks.forEach((cb) => cb(event.candidate.toJSON()));
139
- }
108
+ sendMessage(message) {
109
+ const payload = serializeUserMessage(message);
110
+ this.dataChannels.forEach((storedChannels, peerId) => {
111
+ const channels = normalizePeerChannels(storedChannels);
112
+ if (!channels.message || channels.message.readyState !== "open") {
113
+ return;
140
114
  }
141
- };
115
+ try {
116
+ channels.message.send(payload);
117
+ }
118
+ catch (error) {
119
+ this.emitError(new AvesError({ message: `Failed to send message to ${peerId}: ${errorMessage(error)}`, code: "MESSAGE_SEND_FAILED", stage: "transport", retryable: true, peerId }));
120
+ }
121
+ });
142
122
  }
143
123
  /**
144
- * Register a callback for connection state changes
124
+ * Send a JSON message to a specific peer.
145
125
  */
146
- onConnectionStateChange(peerId, callback) {
147
- if (!this.connectionStateCallbacks.has(peerId)) {
148
- this.connectionStateCallbacks.set(peerId, new Set());
126
+ sendMessageToPeer(peerId, message) {
127
+ const dataChannel = this.getMessageChannel(peerId);
128
+ if (dataChannel.readyState !== "open") {
129
+ throw new AvesError({ message: `DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`, code: "MESSAGE_CHANNEL_NOT_READY", stage: "transport", retryable: true, peerId });
149
130
  }
150
- this.connectionStateCallbacks.get(peerId).add(callback);
131
+ dataChannel.send(serializeUserMessage(message));
151
132
  }
152
133
  /**
153
- * Register a callback for DataChannel state changes
134
+ * Send a file to one peer or broadcast to every connected peer.
154
135
  */
155
- onDataChannelStateChange(peerId, callback) {
156
- if (!this.dataChannelStateCallbacks.has(peerId)) {
157
- this.dataChannelStateCallbacks.set(peerId, new Set());
158
- }
159
- this.dataChannelStateCallbacks.get(peerId).add(callback);
136
+ async sendFile(blob, options = {}) {
137
+ return this.fileTransfers.sendFile(blob, options);
160
138
  }
161
139
  /**
162
- * Register a callback for incoming messages
140
+ * Start capturing local audio and bind it to current peer connections.
163
141
  */
164
- onMessage(callback) {
165
- this.messageCallbacks.add(callback);
142
+ async startVoice() {
143
+ return this.mediaTracks.startVoice();
166
144
  }
167
145
  /**
168
- * Setup DataChannel event handlers
146
+ * Stop local audio capture and detach it from active peers.
169
147
  */
170
- setupDataChannel(peerId, dataChannel) {
171
- this.dataChannels.set(peerId, dataChannel);
172
- dataChannel.onopen = () => {
173
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
174
- if (callbacks) {
175
- callbacks.forEach((callback) => callback(dataChannel.readyState));
176
- }
177
- };
178
- dataChannel.onclose = () => {
179
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
180
- if (callbacks) {
181
- callbacks.forEach((callback) => callback(dataChannel.readyState));
182
- }
183
- this.dataChannels.delete(peerId);
184
- };
185
- dataChannel.onerror = (error) => {
186
- console.error(`DataChannel error with ${peerId}:`, error);
187
- };
188
- dataChannel.onmessage = (event) => {
189
- try {
190
- // Deserialize JSON message
191
- const message = JSON.parse(event.data);
192
- this.messageCallbacks.forEach((callback) => callback(peerId, message));
193
- }
194
- catch (error) {
195
- // Log error but don't interrupt connection
196
- console.error(`Failed to parse message from ${peerId}:`, error);
197
- }
198
- };
148
+ stopVoice() {
149
+ this.mediaTracks.stopVoice();
199
150
  }
200
151
  /**
201
- * Send a message to all connected peers
202
- * Throws error if any DataChannel is not ready
152
+ * Toggle local mute state.
203
153
  */
204
- sendMessage(message) {
205
- const errors = [];
206
- this.dataChannels.forEach((dataChannel, peerId) => {
207
- if (dataChannel.readyState === "open") {
208
- try {
209
- // Serialize message to JSON
210
- const serialized = JSON.stringify(message);
211
- dataChannel.send(serialized);
212
- }
213
- catch (error) {
214
- console.error(`Failed to send message to ${peerId}:`, error);
215
- errors.push(peerId);
216
- }
217
- }
218
- else {
219
- errors.push(peerId);
220
- }
221
- });
222
- if (errors.length > 0) {
223
- throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
224
- }
154
+ setMuted(muted) {
155
+ this.mediaTracks.setMuted(muted);
225
156
  }
226
157
  /**
227
- * Send a message to a specific peer
228
- * Throws error if DataChannel is not ready
158
+ * Read current local audio state.
229
159
  */
230
- sendMessageToPeer(peerId, message) {
231
- const dataChannel = this.dataChannels.get(peerId);
232
- if (!dataChannel) {
233
- throw new Error(`No DataChannel found for ${peerId}`);
234
- }
235
- if (dataChannel.readyState !== "open") {
236
- throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
160
+ getLocalAudioState() {
161
+ return this.mediaTracks.getLocalAudioState();
162
+ }
163
+ /**
164
+ * Read current remote audio stream for a peer.
165
+ */
166
+ getRemoteAudioStream(peerId) {
167
+ return this.mediaTracks.getRemoteAudioStream(peerId);
168
+ }
169
+ // ========== Video Methods ==========
170
+ /**
171
+ * Start capturing local camera video and bind it to current peer connections.
172
+ * Idempotent: returns the existing stream if already active.
173
+ */
174
+ async startVideo(constraints) {
175
+ return this.mediaTracks.startVideo(constraints);
176
+ }
177
+ /**
178
+ * Stop local camera capture and detach it from active peers.
179
+ */
180
+ stopVideo() {
181
+ this.mediaTracks.stopVideo();
182
+ }
183
+ /**
184
+ * Toggle local video mute state (camera on/off).
185
+ */
186
+ setVideoMuted(muted) {
187
+ this.mediaTracks.setVideoMuted(muted);
188
+ }
189
+ /**
190
+ * Read current local video state.
191
+ */
192
+ getLocalVideoState() {
193
+ return this.mediaTracks.getLocalVideoState();
194
+ }
195
+ /**
196
+ * Read current remote video stream for a peer.
197
+ */
198
+ getRemoteVideoStream(peerId) {
199
+ return this.mediaTracks.getRemoteVideoStream(peerId);
200
+ }
201
+ // ========== Screen Share Methods ==========
202
+ /**
203
+ * Start screen sharing. Replaces the camera video track with the display track
204
+ * on all active peer connections. The camera track is saved and restored when
205
+ * screen sharing stops.
206
+ */
207
+ async startScreenShare() {
208
+ return this.mediaTracks.startScreenShare();
209
+ }
210
+ /**
211
+ * Stop screen sharing and restore the camera video track (if it was active).
212
+ */
213
+ stopScreenShare() {
214
+ this.mediaTracks.stopScreenShare();
215
+ }
216
+ /**
217
+ * Read current screen share state.
218
+ */
219
+ getScreenShareState() {
220
+ return this.mediaTracks.getScreenShareState();
221
+ }
222
+ // ========== Video / Screen Share Callback Registration ==========
223
+ /**
224
+ * Register a callback for remote video tracks.
225
+ */
226
+ onRemoteVideoTrack(callback) {
227
+ this.mediaTracks.onRemoteVideoTrack(callback);
228
+ }
229
+ /**
230
+ * Register a callback for local video state changes.
231
+ */
232
+ onLocalVideoStateChange(callback) {
233
+ this.mediaTracks.onLocalVideoStateChange(callback);
234
+ }
235
+ /**
236
+ * Register a callback for screen share state changes.
237
+ */
238
+ onScreenShareStateChange(callback) {
239
+ this.mediaTracks.onScreenShareStateChange(callback);
240
+ }
241
+ // ========== Error Callback Registration ==========
242
+ /**
243
+ * Register a callback for WebRTCManager-level errors
244
+ * (e.g. DataChannel failures, message parse errors).
245
+ */
246
+ onError(callback) {
247
+ this.errorCallbacks.add(callback);
248
+ }
249
+ // ========== Emit Helpers ==========
250
+ emitError(error) {
251
+ this.errorCallbacks.forEach((callback) => callback(error));
252
+ }
253
+ /**
254
+ * Register a callback for ICE candidates from the specified peer.
255
+ */
256
+ onIceCandidate(peerId, callback) {
257
+ // Ensure the peer connection exists
258
+ this.getPeerConnection(peerId);
259
+ let callbacks = this.iceCandidateCallbacks.get(peerId);
260
+ if (!callbacks) {
261
+ callbacks = new Set();
262
+ this.iceCandidateCallbacks.set(peerId, callbacks);
237
263
  }
238
- try {
239
- // Serialize message to JSON
240
- const serialized = JSON.stringify(message);
241
- dataChannel.send(serialized);
264
+ callbacks.add(callback);
265
+ }
266
+ /**
267
+ * Register a callback for connection state changes.
268
+ */
269
+ onConnectionStateChange(peerId, callback) {
270
+ let callbacks = this.connectionStateCallbacks.get(peerId);
271
+ if (!callbacks) {
272
+ callbacks = new Set();
273
+ this.connectionStateCallbacks.set(peerId, callbacks);
242
274
  }
243
- catch (error) {
244
- console.error(`Failed to send message to ${peerId}:`, error);
245
- throw error;
275
+ callbacks.add(callback);
276
+ }
277
+ /**
278
+ * Register a callback for main DataChannel state changes.
279
+ */
280
+ onDataChannelStateChange(peerId, callback) {
281
+ let callbacks = this.dataChannelStateCallbacks.get(peerId);
282
+ if (!callbacks) {
283
+ callbacks = new Set();
284
+ this.dataChannelStateCallbacks.set(peerId, callbacks);
246
285
  }
286
+ callbacks.add(callback);
247
287
  }
248
288
  /**
249
- * Close the connection with a specific peer
289
+ * Register a callback for incoming user messages.
290
+ */
291
+ onMessage(callback) {
292
+ this.messageCallbacks.add(callback);
293
+ }
294
+ onFileTransferStarted(callback) {
295
+ this.fileTransfers.onStarted(callback);
296
+ }
297
+ onFileTransferProgress(callback) {
298
+ this.fileTransfers.onProgress(callback);
299
+ }
300
+ onFileTransferCompleted(callback) {
301
+ this.fileTransfers.onCompleted(callback);
302
+ }
303
+ onFileTransferFailed(callback) {
304
+ this.fileTransfers.onFailed(callback);
305
+ }
306
+ onRemoteAudioTrack(callback) {
307
+ this.mediaTracks.onRemoteAudioTrack(callback);
308
+ }
309
+ onLocalAudioStateChange(callback) {
310
+ this.mediaTracks.onLocalAudioStateChange(callback);
311
+ }
312
+ /**
313
+ * Close the connection with a specific peer.
250
314
  */
251
315
  closePeerConnection(peerId) {
252
- const dataChannel = this.dataChannels.get(peerId);
253
- if (dataChannel) {
254
- dataChannel.close();
255
- this.dataChannels.delete(peerId);
256
- }
316
+ this.failActiveTransfers(peerId, new AvesError({ message: `Peer connection closed for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId }));
317
+ const channels = normalizePeerChannels(this.dataChannels.get(peerId));
318
+ channels?.message?.close();
319
+ channels?.file?.close();
320
+ this.dataChannels.delete(peerId);
257
321
  const pc = this.peerConnections.get(peerId);
258
322
  if (pc) {
259
323
  pc.close();
260
324
  this.peerConnections.delete(peerId);
261
325
  }
262
- // Clean up callbacks
326
+ this.clearReadyResolver(peerId);
327
+ this.clearCompletionResolver(peerId);
328
+ this.outgoingTransfers.delete(peerId);
329
+ this.incomingTransfers.delete(peerId);
330
+ this.mediaTracks.closePeer(peerId);
263
331
  this.connectionStateCallbacks.delete(peerId);
264
332
  this.dataChannelStateCallbacks.delete(peerId);
265
333
  this.iceCandidateCallbacks.delete(peerId);
266
334
  }
267
335
  /**
268
- * Close all connections and clean up resources
336
+ * Close all connections and clean up resources.
269
337
  */
270
338
  closeAll() {
271
- this.dataChannels.forEach((dataChannel) => {
272
- dataChannel.close();
339
+ this.getActivePeers().forEach((peerId) => {
340
+ this.closePeerConnection(peerId);
273
341
  });
274
- this.dataChannels.clear();
275
- this.peerConnections.forEach((pc) => {
276
- pc.close();
277
- });
278
- this.peerConnections.clear();
342
+ this.stopVoice();
343
+ this.stopVideo();
344
+ this.stopScreenShare();
345
+ }
346
+ destroy() {
347
+ this.closeAll();
279
348
  this.messageCallbacks.clear();
280
- this.connectionStateCallbacks.clear();
281
- this.dataChannelStateCallbacks.clear();
282
- this.iceCandidateCallbacks.clear();
349
+ this.fileTransfers.clearCallbacks();
350
+ this.mediaTracks.clearCallbacks();
351
+ this.errorCallbacks.clear();
283
352
  }
284
353
  /**
285
- * Get all active peer IDs
354
+ * Get all active peer IDs.
286
355
  */
287
356
  getActivePeers() {
288
357
  return Array.from(this.peerConnections.keys());
289
358
  }
290
359
  /**
291
- * Check if connected to a specific peer
360
+ * Check if connected to a specific peer.
292
361
  */
293
362
  isConnected(peerId) {
294
363
  const pc = this.peerConnections.get(peerId);
295
364
  return pc?.connectionState === "connected";
296
365
  }
297
366
  /**
298
- * Check if DataChannel is ready for a specific peer
367
+ * Get the actual RTCPeerConnectionState for a peer.
368
+ */
369
+ getConnectionState(peerId) {
370
+ const pc = this.peerConnections.get(peerId);
371
+ return pc?.connectionState ?? "closed";
372
+ }
373
+ /**
374
+ * Check if the main DataChannel is ready for a specific peer.
299
375
  */
300
376
  isDataChannelReady(peerId) {
301
- const dataChannel = this.dataChannels.get(peerId);
302
- return dataChannel?.readyState === "open";
377
+ return (normalizePeerChannels(this.dataChannels.get(peerId)).message
378
+ ?.readyState === "open");
379
+ }
380
+ /**
381
+ * Check if the file channel is ready for a specific peer.
382
+ */
383
+ isFileChannelReady(peerId) {
384
+ return (normalizePeerChannels(this.dataChannels.get(peerId)).file
385
+ ?.readyState === "open");
386
+ }
387
+ setupPeerConnection(peerId, pc) {
388
+ pc.onconnectionstatechange = () => {
389
+ const callbacks = this.connectionStateCallbacks.get(peerId);
390
+ callbacks?.forEach((callback) => callback(pc.connectionState));
391
+ if (pc.connectionState === "failed" ||
392
+ pc.connectionState === "closed" ||
393
+ pc.connectionState === "disconnected") {
394
+ this.closePeerConnection(peerId);
395
+ }
396
+ };
397
+ pc.onicecandidate = (event) => {
398
+ if (!event.candidate) {
399
+ return;
400
+ }
401
+ const callbacks = this.iceCandidateCallbacks.get(peerId);
402
+ callbacks?.forEach((cb) => cb(event.candidate.toJSON()));
403
+ };
404
+ this.mediaTracks.bindPeerConnection(peerId, pc);
405
+ }
406
+ ensureDataChannel(peerId, pc, label) {
407
+ const channels = this.dataChannels.get(peerId) ?? {};
408
+ const kind = getChannelKind(label);
409
+ const existing = channels[kind];
410
+ if (existing) {
411
+ return existing;
412
+ }
413
+ const channel = pc.createDataChannel(label);
414
+ this.setupDataChannel(peerId, channel);
415
+ return channel;
416
+ }
417
+ setupDataChannel(peerId, dataChannel) {
418
+ const kind = getChannelKind(dataChannel.label);
419
+ const channels = normalizePeerChannels(this.dataChannels.get(peerId));
420
+ channels[kind] = dataChannel;
421
+ this.dataChannels.set(peerId, channels);
422
+ if (kind === "file") {
423
+ dataChannel.binaryType = "arraybuffer";
424
+ }
425
+ dataChannel.onopen = () => {
426
+ if (kind !== "message") {
427
+ return;
428
+ }
429
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
430
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
431
+ };
432
+ dataChannel.onclose = () => {
433
+ if (kind === "message") {
434
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
435
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
436
+ }
437
+ const storedChannels = this.dataChannels.get(peerId);
438
+ if (storedChannels && isPeerChannels(storedChannels) && storedChannels[kind] === dataChannel) {
439
+ delete storedChannels[kind];
440
+ if (!storedChannels.message && !storedChannels.file) {
441
+ this.dataChannels.delete(peerId);
442
+ }
443
+ }
444
+ if (kind === "message" || kind === "file") {
445
+ this.failActiveTransfers(peerId, new AvesError({ message: `${kind} channel closed during file transfer`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
446
+ }
447
+ };
448
+ dataChannel.onerror = (error) => {
449
+ this.emitError(new AvesError({ message: `DataChannel error with ${peerId}: ${errorMessage(error)}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
450
+ const transfer = kind === "file"
451
+ ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
452
+ : null;
453
+ if (transfer) {
454
+ this.emitFileTransferFailed(peerId, transfer, new AvesError({ message: `DataChannel error on ${kind} channel`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
455
+ }
456
+ };
457
+ dataChannel.onmessage = (event) => {
458
+ if (kind === "file") {
459
+ this.handleFileChunk(peerId, event.data);
460
+ return;
461
+ }
462
+ this.handleMessageChannelMessage(peerId, event.data);
463
+ };
464
+ }
465
+ handleMessageChannelMessage(peerId, rawData) {
466
+ try {
467
+ const message = JSON.parse(rawData);
468
+ if (isFileControlMessage(message)) {
469
+ this.handleFileControlMessage(peerId, message);
470
+ return;
471
+ }
472
+ this.messageCallbacks.forEach((callback) => callback(peerId, message));
473
+ }
474
+ catch (error) {
475
+ this.emitError(new AvesError({ message: `Failed to parse message from ${peerId}: ${errorMessage(error)}`, code: "MESSAGE_PARSE_FAILED", stage: "transport", retryable: false, peerId }));
476
+ }
477
+ }
478
+ handleFileControlMessage(peerId, message) {
479
+ this.fileTransfers.handleControlMessage(peerId, message);
480
+ }
481
+ handleFileChunk(peerId, data) {
482
+ this.fileTransfers.handleChunk(peerId, data);
483
+ }
484
+ emitFileTransferFailed(peerId, info, error) {
485
+ this.fileTransfers.reportFailure(peerId, info, error);
486
+ }
487
+ clearReadyResolver(peerId) {
488
+ this.fileTransfers.clearReadyResolver(peerId);
489
+ }
490
+ clearCompletionResolver(peerId) {
491
+ this.fileTransfers.clearCompletionResolver(peerId);
492
+ }
493
+ getPeerConnection(peerId) {
494
+ const pc = this.peerConnections.get(peerId);
495
+ if (!pc) {
496
+ throw new AvesError({ message: `No peer connection found for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId });
497
+ }
498
+ return pc;
499
+ }
500
+ getMessageChannel(peerId) {
501
+ const channel = normalizePeerChannels(this.dataChannels.get(peerId)).message;
502
+ if (!channel) {
503
+ throw new AvesError({ message: `No DataChannel found for ${peerId}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: false, peerId });
504
+ }
505
+ return channel;
506
+ }
507
+ getFileChannel(peerId) {
508
+ const channel = normalizePeerChannels(this.dataChannels.get(peerId)).file;
509
+ if (!channel) {
510
+ throw new AvesError({ message: `No file channel found for ${peerId}`, code: "FILE_CHANNEL_NOT_READY", stage: "transport", retryable: false, peerId });
511
+ }
512
+ return channel;
513
+ }
514
+ failActiveTransfers(peerId, error) {
515
+ this.fileTransfers.failActiveTransfers(peerId, error);
303
516
  }
304
517
  }