@yrzhao/aves-core 0.1.0 → 0.2.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.
@@ -1,17 +1,7 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
- import { AvesClientConfig, Participant } from "../types/types";
2
+ import { AvesClientConfig, FileTransferInfo, FileTransferOptions, LocalAudioState, Participant } from "../types/types";
3
3
  /**
4
- * AvesClient - Main client class for WebRTC communication
5
- *
6
- * This class coordinates WebRTCManager and SignalingClient to provide
7
- * a simple API for WebRTC-based real-time communication.
8
- *
9
- * Features:
10
- * - Room management (create, join, leave)
11
- * - Automatic WebRTC connection establishment
12
- * - Message sending and receiving
13
- * - Connection state monitoring
14
- * - Automatic reconnection
4
+ * AvesClient - Main client class for WebRTC communication.
15
5
  */
16
6
  export declare class AvesClient extends EventEmitter {
17
7
  private config;
@@ -19,66 +9,30 @@ export declare class AvesClient extends EventEmitter {
19
9
  private signalingClient;
20
10
  private currentRoomId;
21
11
  private currentUserId;
12
+ private currentUserName;
22
13
  private participants;
14
+ private preparedPeers;
15
+ private shouldRestoreSession;
23
16
  constructor(config: AvesClientConfig);
24
- /**
25
- * Setup event handlers to coordinate between components
26
- */
27
17
  private setupEventHandlers;
28
- /**
29
- * Initiate a WebRTC connection with a peer (as offerer)
30
- */
18
+ private restoreRoomSession;
19
+ private preparePeerConnection;
31
20
  private initiateConnection;
32
- /**
33
- * Create a new room
34
- * @returns Promise that resolves with the room ID
35
- */
36
21
  createRoom(): Promise<string>;
37
- /**
38
- * Join an existing room
39
- * @param roomId - Room ID to join
40
- * @param userId - User ID
41
- * @param userName - User name
42
- * @returns Promise that resolves with the list of current participants
43
- */
22
+ joinRoom(roomId: string, userName: string): Promise<Participant[]>;
44
23
  joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
45
- /**
46
- * Leave the current room
47
- * Disconnects from signaling server and closes all WebRTC connections
48
- */
49
24
  leaveRoom(): Promise<void>;
50
- /**
51
- * Send a message to all connected peers
52
- * @param message - Message to send (will be JSON serialized)
53
- * @throws Error if any DataChannel is not ready
54
- */
55
25
  sendMessage(message: any): void;
56
- /**
57
- * Send a message to a specific peer
58
- * @param peerId - Target peer ID
59
- * @param message - Message to send (will be JSON serialized)
60
- * @throws Error if DataChannel is not ready
61
- */
62
26
  sendMessageToPeer(peerId: string, message: any): void;
63
- /**
64
- * Get the connection state for a specific peer
65
- * @param peerId - Peer ID
66
- * @returns Connection state or 'closed' if peer not found
67
- */
27
+ sendFile(blob: Blob, options?: FileTransferOptions): Promise<FileTransferInfo[]>;
28
+ startVoice(): Promise<MediaStream>;
29
+ stopVoice(): void;
30
+ setMuted(muted: boolean): void;
31
+ getLocalAudioState(): LocalAudioState;
32
+ getRemoteAudioStream(peerId: string): MediaStream | null;
68
33
  getConnectionState(peerId: string): RTCPeerConnectionState;
69
- /**
70
- * Get the list of current participants in the room
71
- * @returns Array of participants
72
- */
73
34
  getParticipants(): Participant[];
74
- /**
75
- * Check if connected to the signaling server
76
- * @returns true if connected, false otherwise
77
- */
35
+ getCurrentUserId(): string | null;
78
36
  isConnected(): boolean;
79
- /**
80
- * Destroy the client and clean up all resources
81
- * Closes all connections and removes all event listeners
82
- */
83
37
  destroy(): void;
84
38
  }
@@ -2,25 +2,17 @@ import { EventEmitter } from "./EventEmitter";
2
2
  import { WebRTCManager } from "./WebRTCManager";
3
3
  import { SignalingClient } from "./SignalingClient";
4
4
  /**
5
- * AvesClient - Main client class for WebRTC communication
6
- *
7
- * This class coordinates WebRTCManager and SignalingClient to provide
8
- * a simple API for WebRTC-based real-time communication.
9
- *
10
- * Features:
11
- * - Room management (create, join, leave)
12
- * - Automatic WebRTC connection establishment
13
- * - Message sending and receiving
14
- * - Connection state monitoring
15
- * - Automatic reconnection
5
+ * AvesClient - Main client class for WebRTC communication.
16
6
  */
17
7
  export class AvesClient extends EventEmitter {
18
8
  constructor(config) {
19
9
  super();
20
10
  this.currentRoomId = null;
21
11
  this.currentUserId = null;
12
+ this.currentUserName = null;
22
13
  this.participants = new Map();
23
- // Apply default configuration
14
+ this.preparedPeers = new Set();
15
+ this.shouldRestoreSession = false;
24
16
  const maxAttempts = config.reconnect?.maxAttempts ?? 5;
25
17
  const delay = config.reconnect?.delay ?? 3000;
26
18
  this.config = {
@@ -28,74 +20,55 @@ export class AvesClient extends EventEmitter {
28
20
  iceServers: config.iceServers || [
29
21
  { urls: "stun:stun.l.google.com:19302" },
30
22
  ],
23
+ fileChunkSize: config.fileChunkSize ?? 16 * 1024,
31
24
  reconnect: {
32
25
  maxAttempts,
33
26
  delay,
34
27
  },
35
28
  debug: config.debug ?? false,
36
29
  };
37
- // Initialize WebRTC manager
38
- this.webrtcManager = new WebRTCManager(this.config.iceServers);
39
- // Initialize signaling client
30
+ this.webrtcManager = new WebRTCManager(this.config.iceServers, this.config.fileChunkSize);
40
31
  this.signalingClient = new SignalingClient({
41
32
  maxAttempts,
42
33
  delay,
43
34
  });
44
- // Setup event forwarding and coordination
45
35
  this.setupEventHandlers();
46
36
  }
47
- /**
48
- * Setup event handlers to coordinate between components
49
- */
50
37
  setupEventHandlers() {
51
- // Forward signaling state changes
52
38
  this.signalingClient.on("stateChange", (state) => {
53
39
  this.emit("signalingStateChange", state);
40
+ if (state === "disconnected" &&
41
+ this.currentRoomId &&
42
+ this.currentUserId &&
43
+ this.currentUserName) {
44
+ this.shouldRestoreSession = true;
45
+ }
46
+ if (state === "connected" && this.shouldRestoreSession) {
47
+ this.shouldRestoreSession = false;
48
+ void this.restoreRoomSession();
49
+ }
54
50
  });
55
- // Forward errors
56
51
  this.signalingClient.on("error", (error) => {
57
52
  this.emit("error", error);
58
53
  });
59
- // Handle user joined - establish WebRTC connection
60
54
  this.signalingClient.on("userJoined", async (user) => {
61
55
  this.participants.set(user.id, user);
62
56
  this.emit("userJoined", user);
63
- // Initiate WebRTC connection only if our ID is smaller (to avoid both sides initiating)
64
57
  if (this.currentUserId && this.currentUserId < user.id) {
65
58
  await this.initiateConnection(user.id);
66
59
  }
67
60
  });
68
- // Handle user left - cleanup connection
69
61
  this.signalingClient.on("userLeft", (userId) => {
70
62
  this.participants.delete(userId);
63
+ this.preparedPeers.delete(userId);
71
64
  this.webrtcManager.closePeerConnection(userId);
72
65
  this.emit("userLeft", userId);
73
66
  });
74
- // Handle incoming offer - create answer
75
67
  this.signalingClient.on("offer", async (fromId, offer) => {
76
68
  try {
77
- console.log(`[AvesClient] Received offer from ${fromId}`);
78
- const pc = this.webrtcManager.createPeerConnection(fromId);
79
- // Setup ICE candidate forwarding
80
- this.webrtcManager.onIceCandidate(fromId, (candidate) => {
81
- if (this.currentUserId) {
82
- this.signalingClient.sendIceCandidate(fromId, this.currentUserId, candidate);
83
- }
84
- });
85
- // Setup connection state monitoring
86
- this.webrtcManager.onConnectionStateChange(fromId, (state) => {
87
- console.log(`[AvesClient] Connection state with ${fromId}: ${state}`);
88
- this.emit("connectionStateChange", fromId, state);
89
- });
90
- // Setup DataChannel state monitoring
91
- this.webrtcManager.onDataChannelStateChange(fromId, (state) => {
92
- console.log(`[AvesClient] DataChannel state with ${fromId}: ${state}`);
93
- this.emit("dataChannelStateChange", fromId, state);
94
- });
95
- // Create and send answer
69
+ this.preparePeerConnection(fromId);
96
70
  const answer = await this.webrtcManager.createAnswer(fromId, offer);
97
71
  if (this.currentUserId) {
98
- console.log(`[AvesClient] Sending answer to ${fromId} from ${this.currentUserId}`);
99
72
  this.signalingClient.sendAnswer(fromId, this.currentUserId, answer);
100
73
  }
101
74
  }
@@ -103,19 +76,14 @@ export class AvesClient extends EventEmitter {
103
76
  this.emit("error", new Error(`Failed to handle offer from ${fromId}: ${error}`));
104
77
  }
105
78
  });
106
- // Handle incoming answer - set remote description
107
79
  this.signalingClient.on("answer", async (fromId, answer) => {
108
80
  try {
109
- console.log(`[AvesClient] Received answer from ${fromId}`);
110
81
  await this.webrtcManager.setRemoteAnswer(fromId, answer);
111
- console.log(`[AvesClient] Successfully set remote answer from ${fromId}`);
112
82
  }
113
83
  catch (error) {
114
- console.error(`[AvesClient] Failed to handle answer from ${fromId}:`, error);
115
84
  this.emit("error", new Error(`Failed to handle answer from ${fromId}: ${error}`));
116
85
  }
117
86
  });
118
- // Handle incoming ICE candidate
119
87
  this.signalingClient.on("iceCandidate", async (fromId, candidate) => {
120
88
  try {
121
89
  await this.webrtcManager.addIceCandidate(fromId, candidate);
@@ -124,38 +92,86 @@ export class AvesClient extends EventEmitter {
124
92
  this.emit("error", new Error(`Failed to add ICE candidate from ${fromId}: ${error}`));
125
93
  }
126
94
  });
127
- // Forward messages from WebRTC
128
95
  this.webrtcManager.onMessage((peerId, message) => {
129
96
  this.emit("message", peerId, message);
130
97
  });
98
+ this.webrtcManager.onFileTransferStarted((peerId, info) => {
99
+ this.emit("fileTransferStarted", peerId, info);
100
+ });
101
+ this.webrtcManager.onFileTransferProgress((peerId, progress) => {
102
+ this.emit("fileTransferProgress", peerId, progress);
103
+ });
104
+ this.webrtcManager.onFileTransferCompleted((peerId, result) => {
105
+ this.emit("fileTransferCompleted", peerId, result);
106
+ });
107
+ this.webrtcManager.onFileTransferFailed((peerId, info, error) => {
108
+ this.emit("fileTransferFailed", peerId, info, error);
109
+ });
110
+ this.webrtcManager.onRemoteAudioTrack((peerId, stream, track) => {
111
+ this.emit("remoteAudioTrack", peerId, stream, track);
112
+ });
113
+ this.webrtcManager.onLocalAudioStateChange((state) => {
114
+ this.emit("localAudioStateChange", state);
115
+ });
131
116
  }
132
- /**
133
- * Initiate a WebRTC connection with a peer (as offerer)
134
- */
135
- async initiateConnection(peerId) {
117
+ async restoreRoomSession() {
118
+ if (!this.currentRoomId || !this.currentUserId || !this.currentUserName) {
119
+ return;
120
+ }
136
121
  try {
137
- console.log(`[AvesClient] Initiating connection to ${peerId} from ${this.currentUserId}`);
138
- const pc = this.webrtcManager.createPeerConnection(peerId);
139
- // Setup ICE candidate forwarding
140
- this.webrtcManager.onIceCandidate(peerId, (candidate) => {
141
- if (this.currentUserId) {
142
- this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
122
+ this.webrtcManager.closeAll();
123
+ this.participants.clear();
124
+ this.preparedPeers.clear();
125
+ const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
126
+ this.currentUserId = joinResult.userId;
127
+ const participants = joinResult.participants;
128
+ this.participants.clear();
129
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
130
+ for (const participant of participants) {
131
+ if (participant.id !== this.currentUserId &&
132
+ this.currentUserId < participant.id) {
133
+ await this.initiateConnection(participant.id);
143
134
  }
144
- });
145
- // Setup connection state monitoring
146
- this.webrtcManager.onConnectionStateChange(peerId, (state) => {
147
- console.log(`[AvesClient] Connection state with ${peerId}: ${state}`);
148
- this.emit("connectionStateChange", peerId, state);
149
- });
150
- // Setup DataChannel state monitoring
151
- this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
152
- console.log(`[AvesClient] DataChannel state with ${peerId}: ${state}`);
153
- this.emit("dataChannelStateChange", peerId, state);
154
- });
155
- // Create and send offer
135
+ }
136
+ }
137
+ catch (error) {
138
+ this.currentRoomId = null;
139
+ this.currentUserId = null;
140
+ this.currentUserName = null;
141
+ this.participants.clear();
142
+ this.preparedPeers.clear();
143
+ this.emit("error", new Error(`Failed to restore room session: ${error}`));
144
+ }
145
+ }
146
+ preparePeerConnection(peerId) {
147
+ const pc = this.webrtcManager.createPeerConnection(peerId);
148
+ if (this.preparedPeers.has(peerId)) {
149
+ return pc;
150
+ }
151
+ this.preparedPeers.add(peerId);
152
+ this.webrtcManager.onIceCandidate(peerId, (candidate) => {
153
+ if (this.currentUserId) {
154
+ this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
155
+ }
156
+ });
157
+ this.webrtcManager.onConnectionStateChange(peerId, (state) => {
158
+ if (state === "failed" ||
159
+ state === "disconnected" ||
160
+ state === "closed") {
161
+ this.preparedPeers.delete(peerId);
162
+ }
163
+ this.emit("connectionStateChange", peerId, state);
164
+ });
165
+ this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
166
+ this.emit("dataChannelStateChange", peerId, state);
167
+ });
168
+ return pc;
169
+ }
170
+ async initiateConnection(peerId) {
171
+ try {
172
+ this.preparePeerConnection(peerId);
156
173
  const offer = await this.webrtcManager.createOffer(peerId);
157
174
  if (this.currentUserId) {
158
- console.log(`[AvesClient] Sending offer to ${peerId} from ${this.currentUserId}`);
159
175
  this.signalingClient.sendOffer(peerId, this.currentUserId, offer);
160
176
  }
161
177
  }
@@ -163,109 +179,96 @@ export class AvesClient extends EventEmitter {
163
179
  this.emit("error", new Error(`Failed to initiate connection with ${peerId}: ${error}`));
164
180
  }
165
181
  }
166
- /**
167
- * Create a new room
168
- * @returns Promise that resolves with the room ID
169
- */
170
182
  async createRoom() {
171
- // Connect to signaling server if not connected
172
- if (!this.isConnected()) {
183
+ if (!this.signalingClient.isConnected()) {
173
184
  await this.signalingClient.connect(this.config.signalingUrl);
174
185
  }
175
186
  const roomId = await this.signalingClient.createRoom();
176
187
  this.currentRoomId = roomId;
177
188
  return roomId;
178
189
  }
179
- /**
180
- * Join an existing room
181
- * @param roomId - Room ID to join
182
- * @param userId - User ID
183
- * @param userName - User name
184
- * @returns Promise that resolves with the list of current participants
185
- */
186
- async joinRoom(roomId, userId, userName) {
187
- // Connect to signaling server if not connected
188
- if (!this.isConnected()) {
190
+ async joinRoom(roomId, userIdOrName, maybeUserName) {
191
+ if (!this.signalingClient.isConnected()) {
189
192
  await this.signalingClient.connect(this.config.signalingUrl);
190
193
  }
191
- this.currentUserId = userId;
194
+ const requestedUserId = maybeUserName ? userIdOrName : null;
195
+ const userName = maybeUserName ?? userIdOrName;
196
+ this.currentUserId = requestedUserId;
192
197
  this.currentRoomId = roomId;
193
- const participants = await this.signalingClient.joinRoom(roomId, userId, userName);
194
- // Store participants
198
+ this.currentUserName = userName;
199
+ const joinResult = requestedUserId
200
+ ? await this.signalingClient.joinRoom(roomId, requestedUserId, userName)
201
+ : await this.signalingClient.joinRoom(roomId, userName);
202
+ const participants = joinResult.participants;
203
+ this.currentUserId = joinResult.userId;
195
204
  this.participants.clear();
196
- participants.forEach((p) => this.participants.set(p.id, p));
197
- // Initiate WebRTC connections with existing participants
198
- // Only initiate if our ID is smaller to avoid both sides initiating
205
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
199
206
  for (const participant of participants) {
200
- if (participant.id !== userId && userId < participant.id) {
207
+ if (this.currentUserId &&
208
+ participant.id !== this.currentUserId &&
209
+ this.currentUserId < participant.id) {
201
210
  await this.initiateConnection(participant.id);
202
211
  }
203
212
  }
204
213
  return participants;
205
214
  }
206
- /**
207
- * Leave the current room
208
- * Disconnects from signaling server and closes all WebRTC connections
209
- */
210
215
  async leaveRoom() {
211
- this.signalingClient.leaveRoom();
216
+ if (this.currentUserId) {
217
+ await this.signalingClient.leaveRoom(this.currentUserId);
218
+ }
212
219
  this.webrtcManager.closeAll();
213
220
  this.participants.clear();
221
+ this.preparedPeers.clear();
214
222
  this.currentRoomId = null;
215
223
  this.currentUserId = null;
216
- this.signalingClient.disconnect();
224
+ this.currentUserName = null;
225
+ this.shouldRestoreSession = false;
217
226
  }
218
- /**
219
- * Send a message to all connected peers
220
- * @param message - Message to send (will be JSON serialized)
221
- * @throws Error if any DataChannel is not ready
222
- */
223
227
  sendMessage(message) {
224
228
  this.webrtcManager.sendMessage(message);
225
229
  }
226
- /**
227
- * Send a message to a specific peer
228
- * @param peerId - Target peer ID
229
- * @param message - Message to send (will be JSON serialized)
230
- * @throws Error if DataChannel is not ready
231
- */
232
230
  sendMessageToPeer(peerId, message) {
233
231
  this.webrtcManager.sendMessageToPeer(peerId, message);
234
232
  }
235
- /**
236
- * Get the connection state for a specific peer
237
- * @param peerId - Peer ID
238
- * @returns Connection state or 'closed' if peer not found
239
- */
233
+ async sendFile(blob, options = {}) {
234
+ return this.webrtcManager.sendFile(blob, options);
235
+ }
236
+ async startVoice() {
237
+ return this.webrtcManager.startVoice();
238
+ }
239
+ stopVoice() {
240
+ this.webrtcManager.stopVoice();
241
+ }
242
+ setMuted(muted) {
243
+ this.webrtcManager.setMuted(muted);
244
+ }
245
+ getLocalAudioState() {
246
+ return this.webrtcManager.getLocalAudioState();
247
+ }
248
+ getRemoteAudioStream(peerId) {
249
+ return this.webrtcManager.getRemoteAudioStream(peerId);
250
+ }
240
251
  getConnectionState(peerId) {
241
252
  return this.webrtcManager.isConnected(peerId) ? "connected" : "closed";
242
253
  }
243
- /**
244
- * Get the list of current participants in the room
245
- * @returns Array of participants
246
- */
247
254
  getParticipants() {
248
255
  return Array.from(this.participants.values());
249
256
  }
250
- /**
251
- * Check if connected to the signaling server
252
- * @returns true if connected, false otherwise
253
- */
257
+ getCurrentUserId() {
258
+ return this.currentUserId;
259
+ }
254
260
  isConnected() {
255
- // Check if we have an active signaling connection
256
- // This is a simplified check - in production you might want more sophisticated state tracking
257
- return this.currentRoomId !== null;
261
+ return this.signalingClient.isConnected();
258
262
  }
259
- /**
260
- * Destroy the client and clean up all resources
261
- * Closes all connections and removes all event listeners
262
- */
263
263
  destroy() {
264
- this.signalingClient.disconnect();
265
- this.webrtcManager.closeAll();
266
- this.participants.clear();
267
264
  this.currentRoomId = null;
268
265
  this.currentUserId = null;
266
+ this.currentUserName = null;
267
+ this.shouldRestoreSession = false;
268
+ this.participants.clear();
269
+ this.preparedPeers.clear();
270
+ this.signalingClient.disconnect();
271
+ this.webrtcManager.destroy();
269
272
  this.removeAllListeners();
270
273
  }
271
274
  }
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
- import { Participant, ReconnectConfig } from "../types/types";
2
+ import { JoinRoomResult, ReconnectConfig } from "../types/types";
3
3
  /**
4
4
  * SignalingClient manages WebSocket connection and signaling message exchange
5
5
  * Extends EventEmitter to provide event-driven communication
@@ -12,6 +12,7 @@ export declare class SignalingClient extends EventEmitter {
12
12
  private url;
13
13
  private shouldReconnect;
14
14
  private pendingRequests;
15
+ private requestCounter;
15
16
  constructor(reconnectConfig: ReconnectConfig);
16
17
  /**
17
18
  * Connect to the signaling server
@@ -23,6 +24,7 @@ export declare class SignalingClient extends EventEmitter {
23
24
  * Disconnect from the signaling server
24
25
  */
25
26
  disconnect(): void;
27
+ isConnected(): boolean;
26
28
  /**
27
29
  * Handle WebSocket disconnection and attempt reconnection
28
30
  */
@@ -49,11 +51,12 @@ export declare class SignalingClient extends EventEmitter {
49
51
  * @param userName - User name
50
52
  * @returns Promise that resolves with the list of participants
51
53
  */
52
- joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
54
+ joinRoom(roomId: string, userName: string): Promise<JoinRoomResult>;
55
+ joinRoom(roomId: string, userId: string, userName: string): Promise<JoinRoomResult>;
53
56
  /**
54
57
  * Leave the current room
55
58
  */
56
- leaveRoom(): void;
59
+ leaveRoom(userId: string): Promise<void>;
57
60
  /**
58
61
  * Send an offer to a peer
59
62
  * @param targetId - Target peer ID
@@ -81,9 +84,13 @@ export declare class SignalingClient extends EventEmitter {
81
84
  * @param value - Value to resolve with
82
85
  */
83
86
  private resolvePendingRequest;
87
+ private handleErrorMessage;
84
88
  /**
85
89
  * Reject all pending requests
86
90
  * @param error - Error to reject with
87
91
  */
88
92
  private rejectPendingRequests;
93
+ private createRequestId;
94
+ private findPendingRequestByType;
95
+ private deletePendingRequestByReference;
89
96
  }