@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,84 +1,65 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
- import { AvesClientConfig, Participant } from "../types/types";
2
+ import { AvesError } from "./AvesError";
3
+ import { AvesClientConfig, AvesMessage, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState } from "../types/types";
4
+ export type AvesClientEvents = {
5
+ signalingStateChange: [state: string];
6
+ error: [error: AvesError];
7
+ userJoined: [user: Participant];
8
+ userLeft: [userId: string];
9
+ connectionStateChange: [peerId: string, state: RTCPeerConnectionState];
10
+ dataChannelStateChange: [peerId: string, state: RTCDataChannelState];
11
+ message: [peerId: string, message: AvesMessage];
12
+ remoteAudioTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
13
+ remoteVideoTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
14
+ localAudioStateChange: [state: LocalAudioState];
15
+ localVideoStateChange: [state: LocalVideoState];
16
+ screenShareStateChange: [state: ScreenShareState];
17
+ fileTransferStarted: [peerId: string, info: FileTransferInfo];
18
+ fileTransferProgress: [peerId: string, progress: FileTransferProgress];
19
+ fileTransferCompleted: [peerId: string, result: FileTransferResult];
20
+ fileTransferFailed: [peerId: string, info: FileTransferInfo | null, error: AvesError];
21
+ };
3
22
  /**
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
23
+ * AvesClient - Main client class for WebRTC communication.
15
24
  */
16
- export declare class AvesClient extends EventEmitter {
25
+ export declare class AvesClient extends EventEmitter<AvesClientEvents> {
17
26
  private config;
18
27
  private webrtcManager;
19
28
  private signalingClient;
20
29
  private currentRoomId;
21
30
  private currentUserId;
31
+ private currentUserName;
22
32
  private participants;
33
+ private preparedPeers;
34
+ private shouldRestoreSession;
23
35
  constructor(config: AvesClientConfig);
24
- /**
25
- * Setup event handlers to coordinate between components
26
- */
27
36
  private setupEventHandlers;
28
- /**
29
- * Initiate a WebRTC connection with a peer (as offerer)
30
- */
37
+ private restoreRoomSession;
38
+ private preparePeerConnection;
31
39
  private initiateConnection;
32
- /**
33
- * Create a new room
34
- * @returns Promise that resolves with the room ID
35
- */
36
40
  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
- */
41
+ joinRoom(roomId: string, userName: string): Promise<Participant[]>;
44
42
  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
43
  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
- 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
- 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
- */
44
+ sendMessage(message: AvesMessage): void;
45
+ sendMessageToPeer(peerId: string, message: AvesMessage): void;
46
+ sendFile(blob: Blob, options?: FileTransferOptions): Promise<FileTransferInfo[]>;
47
+ startVoice(): Promise<MediaStream>;
48
+ stopVoice(): void;
49
+ setMuted(muted: boolean): void;
50
+ getLocalAudioState(): LocalAudioState;
51
+ getRemoteAudioStream(peerId: string): MediaStream | null;
52
+ startVideo(constraints?: AvesVideoConstraints): Promise<MediaStream>;
53
+ stopVideo(): void;
54
+ setVideoMuted(muted: boolean): void;
55
+ getLocalVideoState(): LocalVideoState;
56
+ getRemoteVideoStream(peerId: string): MediaStream | null;
57
+ startScreenShare(): Promise<MediaStream>;
58
+ stopScreenShare(): void;
59
+ getScreenShareState(): ScreenShareState;
68
60
  getConnectionState(peerId: string): RTCPeerConnectionState;
69
- /**
70
- * Get the list of current participants in the room
71
- * @returns Array of participants
72
- */
73
61
  getParticipants(): Participant[];
74
- /**
75
- * Check if connected to the signaling server
76
- * @returns true if connected, false otherwise
77
- */
62
+ getCurrentUserId(): string | null;
78
63
  isConnected(): boolean;
79
- /**
80
- * Destroy the client and clean up all resources
81
- * Closes all connections and removes all event listeners
82
- */
83
64
  destroy(): void;
84
65
  }
@@ -2,273 +2,321 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AvesClient = void 0;
4
4
  const EventEmitter_1 = require("./EventEmitter");
5
+ const AvesError_1 = require("./AvesError");
5
6
  const WebRTCManager_1 = require("./WebRTCManager");
6
7
  const SignalingClient_1 = require("./SignalingClient");
8
+ function errorMessage(error) {
9
+ return error instanceof Error ? error.message : String(error);
10
+ }
7
11
  /**
8
- * AvesClient - Main client class for WebRTC communication
9
- *
10
- * This class coordinates WebRTCManager and SignalingClient to provide
11
- * a simple API for WebRTC-based real-time communication.
12
- *
13
- * Features:
14
- * - Room management (create, join, leave)
15
- * - Automatic WebRTC connection establishment
16
- * - Message sending and receiving
17
- * - Connection state monitoring
18
- * - Automatic reconnection
12
+ * AvesClient - Main client class for WebRTC communication.
19
13
  */
20
14
  class AvesClient extends EventEmitter_1.EventEmitter {
21
15
  constructor(config) {
22
16
  super();
23
17
  this.currentRoomId = null;
24
18
  this.currentUserId = null;
19
+ this.currentUserName = null;
25
20
  this.participants = new Map();
26
- // Apply default configuration
21
+ this.preparedPeers = new Set();
22
+ this.shouldRestoreSession = false;
27
23
  const maxAttempts = config.reconnect?.maxAttempts ?? 5;
28
24
  const delay = config.reconnect?.delay ?? 3000;
25
+ const requestTimeoutMs = config.reconnect?.requestTimeoutMs ?? 30000;
29
26
  this.config = {
30
27
  signalingUrl: config.signalingUrl,
31
28
  iceServers: config.iceServers || [
32
29
  { urls: "stun:stun.l.google.com:19302" },
33
30
  ],
31
+ fileChunkSize: config.fileChunkSize ?? 16 * 1024,
34
32
  reconnect: {
35
33
  maxAttempts,
36
34
  delay,
35
+ requestTimeoutMs,
37
36
  },
38
37
  debug: config.debug ?? false,
39
38
  };
40
- // Initialize WebRTC manager
41
- this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers);
42
- // Initialize signaling client
39
+ this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers, this.config.fileChunkSize, config.video);
43
40
  this.signalingClient = new SignalingClient_1.SignalingClient({
44
41
  maxAttempts,
45
42
  delay,
43
+ requestTimeoutMs,
46
44
  });
47
- // Setup event forwarding and coordination
48
45
  this.setupEventHandlers();
49
46
  }
50
- /**
51
- * Setup event handlers to coordinate between components
52
- */
53
47
  setupEventHandlers() {
54
- // Forward signaling state changes
55
48
  this.signalingClient.on("stateChange", (state) => {
56
49
  this.emit("signalingStateChange", state);
50
+ if (state === "disconnected" &&
51
+ this.currentRoomId &&
52
+ this.currentUserId &&
53
+ this.currentUserName) {
54
+ this.shouldRestoreSession = true;
55
+ }
56
+ if (state === "connected" && this.shouldRestoreSession) {
57
+ this.shouldRestoreSession = false;
58
+ void this.restoreRoomSession();
59
+ }
57
60
  });
58
- // Forward errors
59
61
  this.signalingClient.on("error", (error) => {
60
62
  this.emit("error", error);
61
63
  });
62
- // Handle user joined - establish WebRTC connection
63
64
  this.signalingClient.on("userJoined", async (user) => {
64
65
  this.participants.set(user.id, user);
65
66
  this.emit("userJoined", user);
66
- // Initiate WebRTC connection only if our ID is smaller (to avoid both sides initiating)
67
67
  if (this.currentUserId && this.currentUserId < user.id) {
68
68
  await this.initiateConnection(user.id);
69
69
  }
70
70
  });
71
- // Handle user left - cleanup connection
72
71
  this.signalingClient.on("userLeft", (userId) => {
73
72
  this.participants.delete(userId);
73
+ this.preparedPeers.delete(userId);
74
74
  this.webrtcManager.closePeerConnection(userId);
75
75
  this.emit("userLeft", userId);
76
76
  });
77
- // Handle incoming offer - create answer
78
77
  this.signalingClient.on("offer", async (fromId, offer) => {
79
78
  try {
80
- console.log(`[AvesClient] Received offer from ${fromId}`);
81
- const pc = this.webrtcManager.createPeerConnection(fromId);
82
- // Setup ICE candidate forwarding
83
- this.webrtcManager.onIceCandidate(fromId, (candidate) => {
84
- if (this.currentUserId) {
85
- this.signalingClient.sendIceCandidate(fromId, this.currentUserId, candidate);
86
- }
87
- });
88
- // Setup connection state monitoring
89
- this.webrtcManager.onConnectionStateChange(fromId, (state) => {
90
- console.log(`[AvesClient] Connection state with ${fromId}: ${state}`);
91
- this.emit("connectionStateChange", fromId, state);
92
- });
93
- // Setup DataChannel state monitoring
94
- this.webrtcManager.onDataChannelStateChange(fromId, (state) => {
95
- console.log(`[AvesClient] DataChannel state with ${fromId}: ${state}`);
96
- this.emit("dataChannelStateChange", fromId, state);
97
- });
98
- // Create and send answer
79
+ this.preparePeerConnection(fromId);
99
80
  const answer = await this.webrtcManager.createAnswer(fromId, offer);
100
81
  if (this.currentUserId) {
101
- console.log(`[AvesClient] Sending answer to ${fromId} from ${this.currentUserId}`);
102
82
  this.signalingClient.sendAnswer(fromId, this.currentUserId, answer);
103
83
  }
104
84
  }
105
85
  catch (error) {
106
- this.emit("error", new Error(`Failed to handle offer from ${fromId}: ${error}`));
86
+ this.emit("error", new AvesError_1.AvesError({ message: `Failed to handle offer from ${fromId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "signaling", retryable: true, peerId: fromId }));
107
87
  }
108
88
  });
109
- // Handle incoming answer - set remote description
110
89
  this.signalingClient.on("answer", async (fromId, answer) => {
111
90
  try {
112
- console.log(`[AvesClient] Received answer from ${fromId}`);
113
91
  await this.webrtcManager.setRemoteAnswer(fromId, answer);
114
- console.log(`[AvesClient] Successfully set remote answer from ${fromId}`);
115
92
  }
116
93
  catch (error) {
117
- console.error(`[AvesClient] Failed to handle answer from ${fromId}:`, error);
118
- this.emit("error", new Error(`Failed to handle answer from ${fromId}: ${error}`));
94
+ this.emit("error", new AvesError_1.AvesError({ message: `Failed to handle answer from ${fromId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "signaling", retryable: true, peerId: fromId }));
119
95
  }
120
96
  });
121
- // Handle incoming ICE candidate
122
97
  this.signalingClient.on("iceCandidate", async (fromId, candidate) => {
123
98
  try {
124
99
  await this.webrtcManager.addIceCandidate(fromId, candidate);
125
100
  }
126
101
  catch (error) {
127
- this.emit("error", new Error(`Failed to add ICE candidate from ${fromId}: ${error}`));
102
+ this.emit("error", new AvesError_1.AvesError({ message: `Failed to add ICE candidate from ${fromId}: ${errorMessage(error)}`, code: "WEBRTC_ICE_FAILED", stage: "transport", retryable: true, peerId: fromId }));
128
103
  }
129
104
  });
130
- // Forward messages from WebRTC
131
105
  this.webrtcManager.onMessage((peerId, message) => {
132
106
  this.emit("message", peerId, message);
133
107
  });
108
+ this.webrtcManager.onFileTransferStarted((peerId, info) => {
109
+ this.emit("fileTransferStarted", peerId, info);
110
+ });
111
+ this.webrtcManager.onFileTransferProgress((peerId, progress) => {
112
+ this.emit("fileTransferProgress", peerId, progress);
113
+ });
114
+ this.webrtcManager.onFileTransferCompleted((peerId, result) => {
115
+ this.emit("fileTransferCompleted", peerId, result);
116
+ });
117
+ this.webrtcManager.onFileTransferFailed((peerId, info, error) => {
118
+ this.emit("fileTransferFailed", peerId, info, error);
119
+ });
120
+ this.webrtcManager.onRemoteAudioTrack((peerId, stream, track) => {
121
+ this.emit("remoteAudioTrack", peerId, stream, track);
122
+ });
123
+ this.webrtcManager.onLocalAudioStateChange((state) => {
124
+ this.emit("localAudioStateChange", state);
125
+ });
126
+ this.webrtcManager.onRemoteVideoTrack((peerId, stream, track) => {
127
+ this.emit("remoteVideoTrack", peerId, stream, track);
128
+ });
129
+ this.webrtcManager.onLocalVideoStateChange((state) => {
130
+ this.emit("localVideoStateChange", state);
131
+ });
132
+ this.webrtcManager.onScreenShareStateChange((state) => {
133
+ this.emit("screenShareStateChange", state);
134
+ });
135
+ this.webrtcManager.onError((err) => {
136
+ this.emit("error", err);
137
+ });
134
138
  }
135
- /**
136
- * Initiate a WebRTC connection with a peer (as offerer)
137
- */
138
- async initiateConnection(peerId) {
139
+ async restoreRoomSession() {
140
+ if (!this.currentRoomId || !this.currentUserId || !this.currentUserName) {
141
+ return;
142
+ }
139
143
  try {
140
- console.log(`[AvesClient] Initiating connection to ${peerId} from ${this.currentUserId}`);
141
- const pc = this.webrtcManager.createPeerConnection(peerId);
142
- // Setup ICE candidate forwarding
143
- this.webrtcManager.onIceCandidate(peerId, (candidate) => {
144
- if (this.currentUserId) {
145
- this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
144
+ this.webrtcManager.closeAll();
145
+ this.participants.clear();
146
+ this.preparedPeers.clear();
147
+ const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
148
+ this.currentUserId = joinResult.userId;
149
+ const participants = joinResult.participants;
150
+ this.participants.clear();
151
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
152
+ for (const participant of participants) {
153
+ if (participant.id !== this.currentUserId &&
154
+ this.currentUserId < participant.id) {
155
+ await this.initiateConnection(participant.id);
146
156
  }
147
- });
148
- // Setup connection state monitoring
149
- this.webrtcManager.onConnectionStateChange(peerId, (state) => {
150
- console.log(`[AvesClient] Connection state with ${peerId}: ${state}`);
151
- this.emit("connectionStateChange", peerId, state);
152
- });
153
- // Setup DataChannel state monitoring
154
- this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
155
- console.log(`[AvesClient] DataChannel state with ${peerId}: ${state}`);
156
- this.emit("dataChannelStateChange", peerId, state);
157
- });
158
- // Create and send offer
157
+ }
158
+ }
159
+ catch (error) {
160
+ this.currentRoomId = null;
161
+ this.currentUserId = null;
162
+ this.currentUserName = null;
163
+ this.participants.clear();
164
+ this.preparedPeers.clear();
165
+ this.emit("error", new AvesError_1.AvesError({ message: `Failed to restore room session: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "room", retryable: true, roomId: this.currentRoomId ?? undefined }));
166
+ }
167
+ }
168
+ preparePeerConnection(peerId) {
169
+ const pc = this.webrtcManager.createPeerConnection(peerId);
170
+ if (this.preparedPeers.has(peerId)) {
171
+ return pc;
172
+ }
173
+ this.preparedPeers.add(peerId);
174
+ this.webrtcManager.onIceCandidate(peerId, (candidate) => {
175
+ if (this.currentUserId) {
176
+ this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
177
+ }
178
+ });
179
+ this.webrtcManager.onConnectionStateChange(peerId, (state) => {
180
+ if (state === "failed" ||
181
+ state === "disconnected" ||
182
+ state === "closed") {
183
+ this.preparedPeers.delete(peerId);
184
+ }
185
+ this.emit("connectionStateChange", peerId, state);
186
+ });
187
+ this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
188
+ this.emit("dataChannelStateChange", peerId, state);
189
+ });
190
+ return pc;
191
+ }
192
+ async initiateConnection(peerId) {
193
+ try {
194
+ this.preparePeerConnection(peerId);
159
195
  const offer = await this.webrtcManager.createOffer(peerId);
160
196
  if (this.currentUserId) {
161
- console.log(`[AvesClient] Sending offer to ${peerId} from ${this.currentUserId}`);
162
197
  this.signalingClient.sendOffer(peerId, this.currentUserId, offer);
163
198
  }
164
199
  }
165
200
  catch (error) {
166
- this.emit("error", new Error(`Failed to initiate connection with ${peerId}: ${error}`));
201
+ this.emit("error", new AvesError_1.AvesError({ message: `Failed to initiate connection with ${peerId}: ${errorMessage(error)}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: true, peerId }));
167
202
  }
168
203
  }
169
- /**
170
- * Create a new room
171
- * @returns Promise that resolves with the room ID
172
- */
173
204
  async createRoom() {
174
- // Connect to signaling server if not connected
175
- if (!this.isConnected()) {
205
+ if (!this.signalingClient.isConnected()) {
176
206
  await this.signalingClient.connect(this.config.signalingUrl);
177
207
  }
178
208
  const roomId = await this.signalingClient.createRoom();
179
209
  this.currentRoomId = roomId;
180
210
  return roomId;
181
211
  }
182
- /**
183
- * Join an existing room
184
- * @param roomId - Room ID to join
185
- * @param userId - User ID
186
- * @param userName - User name
187
- * @returns Promise that resolves with the list of current participants
188
- */
189
- async joinRoom(roomId, userId, userName) {
190
- // Connect to signaling server if not connected
191
- if (!this.isConnected()) {
212
+ async joinRoom(roomId, userIdOrName, maybeUserName) {
213
+ if (!this.signalingClient.isConnected()) {
192
214
  await this.signalingClient.connect(this.config.signalingUrl);
193
215
  }
194
- this.currentUserId = userId;
216
+ const requestedUserId = maybeUserName ? userIdOrName : null;
217
+ const userName = maybeUserName ?? userIdOrName;
218
+ this.currentUserId = requestedUserId;
195
219
  this.currentRoomId = roomId;
196
- const participants = await this.signalingClient.joinRoom(roomId, userId, userName);
197
- // Store participants
220
+ this.currentUserName = userName;
221
+ const joinResult = requestedUserId
222
+ ? await this.signalingClient.joinRoom(roomId, requestedUserId, userName)
223
+ : await this.signalingClient.joinRoom(roomId, userName);
224
+ const participants = joinResult.participants;
225
+ this.currentUserId = joinResult.userId;
198
226
  this.participants.clear();
199
- participants.forEach((p) => this.participants.set(p.id, p));
200
- // Initiate WebRTC connections with existing participants
201
- // Only initiate if our ID is smaller to avoid both sides initiating
227
+ participants.forEach((participant) => this.participants.set(participant.id, participant));
202
228
  for (const participant of participants) {
203
- if (participant.id !== userId && userId < participant.id) {
229
+ if (this.currentUserId &&
230
+ participant.id !== this.currentUserId &&
231
+ this.currentUserId < participant.id) {
204
232
  await this.initiateConnection(participant.id);
205
233
  }
206
234
  }
207
235
  return participants;
208
236
  }
209
- /**
210
- * Leave the current room
211
- * Disconnects from signaling server and closes all WebRTC connections
212
- */
213
237
  async leaveRoom() {
214
- this.signalingClient.leaveRoom();
238
+ if (this.currentUserId) {
239
+ await this.signalingClient.leaveRoom(this.currentUserId);
240
+ }
215
241
  this.webrtcManager.closeAll();
216
242
  this.participants.clear();
243
+ this.preparedPeers.clear();
217
244
  this.currentRoomId = null;
218
245
  this.currentUserId = null;
219
- this.signalingClient.disconnect();
246
+ this.currentUserName = null;
247
+ this.shouldRestoreSession = false;
220
248
  }
221
- /**
222
- * Send a message to all connected peers
223
- * @param message - Message to send (will be JSON serialized)
224
- * @throws Error if any DataChannel is not ready
225
- */
226
249
  sendMessage(message) {
227
250
  this.webrtcManager.sendMessage(message);
228
251
  }
229
- /**
230
- * Send a message to a specific peer
231
- * @param peerId - Target peer ID
232
- * @param message - Message to send (will be JSON serialized)
233
- * @throws Error if DataChannel is not ready
234
- */
235
252
  sendMessageToPeer(peerId, message) {
236
253
  this.webrtcManager.sendMessageToPeer(peerId, message);
237
254
  }
238
- /**
239
- * Get the connection state for a specific peer
240
- * @param peerId - Peer ID
241
- * @returns Connection state or 'closed' if peer not found
242
- */
255
+ async sendFile(blob, options = {}) {
256
+ return this.webrtcManager.sendFile(blob, options);
257
+ }
258
+ async startVoice() {
259
+ return this.webrtcManager.startVoice();
260
+ }
261
+ stopVoice() {
262
+ this.webrtcManager.stopVoice();
263
+ }
264
+ setMuted(muted) {
265
+ this.webrtcManager.setMuted(muted);
266
+ }
267
+ getLocalAudioState() {
268
+ return this.webrtcManager.getLocalAudioState();
269
+ }
270
+ getRemoteAudioStream(peerId) {
271
+ return this.webrtcManager.getRemoteAudioStream(peerId);
272
+ }
273
+ // --- Video ---
274
+ async startVideo(constraints) {
275
+ return this.webrtcManager.startVideo(constraints);
276
+ }
277
+ stopVideo() {
278
+ this.webrtcManager.stopVideo();
279
+ }
280
+ setVideoMuted(muted) {
281
+ this.webrtcManager.setVideoMuted(muted);
282
+ }
283
+ getLocalVideoState() {
284
+ return this.webrtcManager.getLocalVideoState();
285
+ }
286
+ getRemoteVideoStream(peerId) {
287
+ return this.webrtcManager.getRemoteVideoStream(peerId);
288
+ }
289
+ // --- Screen Share ---
290
+ async startScreenShare() {
291
+ return this.webrtcManager.startScreenShare();
292
+ }
293
+ stopScreenShare() {
294
+ this.webrtcManager.stopScreenShare();
295
+ }
296
+ getScreenShareState() {
297
+ return this.webrtcManager.getScreenShareState();
298
+ }
243
299
  getConnectionState(peerId) {
244
- return this.webrtcManager.isConnected(peerId) ? "connected" : "closed";
300
+ return this.webrtcManager.getConnectionState(peerId);
245
301
  }
246
- /**
247
- * Get the list of current participants in the room
248
- * @returns Array of participants
249
- */
250
302
  getParticipants() {
251
303
  return Array.from(this.participants.values());
252
304
  }
253
- /**
254
- * Check if connected to the signaling server
255
- * @returns true if connected, false otherwise
256
- */
305
+ getCurrentUserId() {
306
+ return this.currentUserId;
307
+ }
257
308
  isConnected() {
258
- // Check if we have an active signaling connection
259
- // This is a simplified check - in production you might want more sophisticated state tracking
260
- return this.currentRoomId !== null;
309
+ return this.signalingClient.isConnected();
261
310
  }
262
- /**
263
- * Destroy the client and clean up all resources
264
- * Closes all connections and removes all event listeners
265
- */
266
311
  destroy() {
267
- this.signalingClient.disconnect();
268
- this.webrtcManager.closeAll();
269
- this.participants.clear();
270
312
  this.currentRoomId = null;
271
313
  this.currentUserId = null;
314
+ this.currentUserName = null;
315
+ this.shouldRestoreSession = false;
316
+ this.participants.clear();
317
+ this.preparedPeers.clear();
318
+ this.signalingClient.disconnect();
319
+ this.webrtcManager.destroy();
272
320
  this.removeAllListeners();
273
321
  }
274
322
  }
@@ -0,0 +1,39 @@
1
+ import type { SignalingErrorCode, SignalingErrorStage } from "../types/types";
2
+ /**
3
+ * All error codes used across the aves ecosystem.
4
+ * Signaling codes come from the shared type; runtime codes extend it.
5
+ */
6
+ export type AvesErrorCode = SignalingErrorCode | "WEBRTC_CONNECTION_FAILED" | "WEBRTC_DATACHANNEL_FAILED" | "WEBRTC_ICE_FAILED" | "MEDIA_CAPTURE_FAILED" | "MEDIA_NOT_AVAILABLE" | "FILE_TRANSFER_FAILED" | "FILE_TRANSFER_TIMEOUT" | "FILE_TRANSFER_REJECTED" | "FILE_CHANNEL_NOT_READY" | "MESSAGE_CHANNEL_NOT_READY" | "MESSAGE_PARSE_FAILED" | "MESSAGE_SEND_FAILED" | "MESSAGE_SERIALIZE_FAILED" | "UNKNOWN_ERROR" | (string & {});
7
+ /**
8
+ * Structured error class used throughout aves-core and aves-node.
9
+ *
10
+ * Every error carries the operation context (peerId, roomId, requestId)
11
+ * so callers can react programmatically instead of string-matching error messages.
12
+ *
13
+ * The `cause` field preserves the original error (e.g. from a WebSocket
14
+ * or getUserMedia failure) for debugging.
15
+ */
16
+ export declare class AvesError extends Error {
17
+ readonly code: AvesErrorCode;
18
+ readonly stage: SignalingErrorStage;
19
+ readonly retryable: boolean;
20
+ readonly peerId?: string;
21
+ readonly roomId?: string;
22
+ readonly requestId?: string;
23
+ readonly cause?: unknown;
24
+ constructor(opts: {
25
+ message: string;
26
+ code: AvesErrorCode;
27
+ stage: SignalingErrorStage;
28
+ retryable: boolean;
29
+ peerId?: string;
30
+ roomId?: string;
31
+ requestId?: string;
32
+ cause?: unknown;
33
+ });
34
+ /**
35
+ * Serialise to a plain object for logging or transmission over the wire.
36
+ * `cause` is deliberately excluded — it may contain non-serialisable objects.
37
+ */
38
+ toJSON(): Record<string, unknown>;
39
+ }