@yrzhao/aves-core 0.1.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.
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AvesClient = void 0;
4
+ const EventEmitter_1 = require("./EventEmitter");
5
+ const WebRTCManager_1 = require("./WebRTCManager");
6
+ const SignalingClient_1 = require("./SignalingClient");
7
+ /**
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
19
+ */
20
+ class AvesClient extends EventEmitter_1.EventEmitter {
21
+ constructor(config) {
22
+ super();
23
+ this.currentRoomId = null;
24
+ this.currentUserId = null;
25
+ this.participants = new Map();
26
+ // Apply default configuration
27
+ const maxAttempts = config.reconnect?.maxAttempts ?? 5;
28
+ const delay = config.reconnect?.delay ?? 3000;
29
+ this.config = {
30
+ signalingUrl: config.signalingUrl,
31
+ iceServers: config.iceServers || [
32
+ { urls: "stun:stun.l.google.com:19302" },
33
+ ],
34
+ reconnect: {
35
+ maxAttempts,
36
+ delay,
37
+ },
38
+ debug: config.debug ?? false,
39
+ };
40
+ // Initialize WebRTC manager
41
+ this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers);
42
+ // Initialize signaling client
43
+ this.signalingClient = new SignalingClient_1.SignalingClient({
44
+ maxAttempts,
45
+ delay,
46
+ });
47
+ // Setup event forwarding and coordination
48
+ this.setupEventHandlers();
49
+ }
50
+ /**
51
+ * Setup event handlers to coordinate between components
52
+ */
53
+ setupEventHandlers() {
54
+ // Forward signaling state changes
55
+ this.signalingClient.on("stateChange", (state) => {
56
+ this.emit("signalingStateChange", state);
57
+ });
58
+ // Forward errors
59
+ this.signalingClient.on("error", (error) => {
60
+ this.emit("error", error);
61
+ });
62
+ // Handle user joined - establish WebRTC connection
63
+ this.signalingClient.on("userJoined", async (user) => {
64
+ this.participants.set(user.id, user);
65
+ this.emit("userJoined", user);
66
+ // Initiate WebRTC connection only if our ID is smaller (to avoid both sides initiating)
67
+ if (this.currentUserId && this.currentUserId < user.id) {
68
+ await this.initiateConnection(user.id);
69
+ }
70
+ });
71
+ // Handle user left - cleanup connection
72
+ this.signalingClient.on("userLeft", (userId) => {
73
+ this.participants.delete(userId);
74
+ this.webrtcManager.closePeerConnection(userId);
75
+ this.emit("userLeft", userId);
76
+ });
77
+ // Handle incoming offer - create answer
78
+ this.signalingClient.on("offer", async (fromId, offer) => {
79
+ 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
99
+ const answer = await this.webrtcManager.createAnswer(fromId, offer);
100
+ if (this.currentUserId) {
101
+ console.log(`[AvesClient] Sending answer to ${fromId} from ${this.currentUserId}`);
102
+ this.signalingClient.sendAnswer(fromId, this.currentUserId, answer);
103
+ }
104
+ }
105
+ catch (error) {
106
+ this.emit("error", new Error(`Failed to handle offer from ${fromId}: ${error}`));
107
+ }
108
+ });
109
+ // Handle incoming answer - set remote description
110
+ this.signalingClient.on("answer", async (fromId, answer) => {
111
+ try {
112
+ console.log(`[AvesClient] Received answer from ${fromId}`);
113
+ await this.webrtcManager.setRemoteAnswer(fromId, answer);
114
+ console.log(`[AvesClient] Successfully set remote answer from ${fromId}`);
115
+ }
116
+ 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}`));
119
+ }
120
+ });
121
+ // Handle incoming ICE candidate
122
+ this.signalingClient.on("iceCandidate", async (fromId, candidate) => {
123
+ try {
124
+ await this.webrtcManager.addIceCandidate(fromId, candidate);
125
+ }
126
+ catch (error) {
127
+ this.emit("error", new Error(`Failed to add ICE candidate from ${fromId}: ${error}`));
128
+ }
129
+ });
130
+ // Forward messages from WebRTC
131
+ this.webrtcManager.onMessage((peerId, message) => {
132
+ this.emit("message", peerId, message);
133
+ });
134
+ }
135
+ /**
136
+ * Initiate a WebRTC connection with a peer (as offerer)
137
+ */
138
+ async initiateConnection(peerId) {
139
+ 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);
146
+ }
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
159
+ const offer = await this.webrtcManager.createOffer(peerId);
160
+ if (this.currentUserId) {
161
+ console.log(`[AvesClient] Sending offer to ${peerId} from ${this.currentUserId}`);
162
+ this.signalingClient.sendOffer(peerId, this.currentUserId, offer);
163
+ }
164
+ }
165
+ catch (error) {
166
+ this.emit("error", new Error(`Failed to initiate connection with ${peerId}: ${error}`));
167
+ }
168
+ }
169
+ /**
170
+ * Create a new room
171
+ * @returns Promise that resolves with the room ID
172
+ */
173
+ async createRoom() {
174
+ // Connect to signaling server if not connected
175
+ if (!this.isConnected()) {
176
+ await this.signalingClient.connect(this.config.signalingUrl);
177
+ }
178
+ const roomId = await this.signalingClient.createRoom();
179
+ this.currentRoomId = roomId;
180
+ return roomId;
181
+ }
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()) {
192
+ await this.signalingClient.connect(this.config.signalingUrl);
193
+ }
194
+ this.currentUserId = userId;
195
+ this.currentRoomId = roomId;
196
+ const participants = await this.signalingClient.joinRoom(roomId, userId, userName);
197
+ // Store participants
198
+ 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
202
+ for (const participant of participants) {
203
+ if (participant.id !== userId && userId < participant.id) {
204
+ await this.initiateConnection(participant.id);
205
+ }
206
+ }
207
+ return participants;
208
+ }
209
+ /**
210
+ * Leave the current room
211
+ * Disconnects from signaling server and closes all WebRTC connections
212
+ */
213
+ async leaveRoom() {
214
+ this.signalingClient.leaveRoom();
215
+ this.webrtcManager.closeAll();
216
+ this.participants.clear();
217
+ this.currentRoomId = null;
218
+ this.currentUserId = null;
219
+ this.signalingClient.disconnect();
220
+ }
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
+ sendMessage(message) {
227
+ this.webrtcManager.sendMessage(message);
228
+ }
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
+ sendMessageToPeer(peerId, message) {
236
+ this.webrtcManager.sendMessageToPeer(peerId, message);
237
+ }
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
+ */
243
+ getConnectionState(peerId) {
244
+ return this.webrtcManager.isConnected(peerId) ? "connected" : "closed";
245
+ }
246
+ /**
247
+ * Get the list of current participants in the room
248
+ * @returns Array of participants
249
+ */
250
+ getParticipants() {
251
+ return Array.from(this.participants.values());
252
+ }
253
+ /**
254
+ * Check if connected to the signaling server
255
+ * @returns true if connected, false otherwise
256
+ */
257
+ 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;
261
+ }
262
+ /**
263
+ * Destroy the client and clean up all resources
264
+ * Closes all connections and removes all event listeners
265
+ */
266
+ destroy() {
267
+ this.signalingClient.disconnect();
268
+ this.webrtcManager.closeAll();
269
+ this.participants.clear();
270
+ this.currentRoomId = null;
271
+ this.currentUserId = null;
272
+ this.removeAllListeners();
273
+ }
274
+ }
275
+ exports.AvesClient = AvesClient;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * EventEmitter base class
3
+ * Provides event handling functionality for aves-core components
4
+ */
5
+ export declare class EventEmitter {
6
+ private events;
7
+ constructor();
8
+ /**
9
+ * Register an event listener
10
+ * @param event - Event name
11
+ * @param callback - Callback function to be invoked when event is emitted
12
+ * @returns this for chaining
13
+ */
14
+ on(event: string, callback: Function): this;
15
+ /**
16
+ * Remove an event listener
17
+ * @param event - Event name
18
+ * @param callback - Callback function to remove
19
+ * @returns this for chaining
20
+ */
21
+ off(event: string, callback: Function): this;
22
+ /**
23
+ * Register a one-time event listener
24
+ * @param event - Event name
25
+ * @param callback - Callback function to be invoked once when event is emitted
26
+ * @returns this for chaining
27
+ */
28
+ once(event: string, callback: Function): this;
29
+ /**
30
+ * Emit an event with arguments
31
+ * @param event - Event name
32
+ * @param args - Arguments to pass to listeners
33
+ */
34
+ emit(event: string, ...args: any[]): void;
35
+ /**
36
+ * Remove all listeners for a specific event or all events
37
+ * @param event - Optional event name. If not provided, removes all listeners for all events
38
+ */
39
+ removeAllListeners(event?: string): void;
40
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventEmitter = void 0;
4
+ /**
5
+ * EventEmitter base class
6
+ * Provides event handling functionality for aves-core components
7
+ */
8
+ class EventEmitter {
9
+ constructor() {
10
+ this.events = new Map();
11
+ }
12
+ /**
13
+ * Register an event listener
14
+ * @param event - Event name
15
+ * @param callback - Callback function to be invoked when event is emitted
16
+ * @returns this for chaining
17
+ */
18
+ on(event, callback) {
19
+ if (!this.events.has(event)) {
20
+ this.events.set(event, new Set());
21
+ }
22
+ this.events.get(event).add(callback);
23
+ return this;
24
+ }
25
+ /**
26
+ * Remove an event listener
27
+ * @param event - Event name
28
+ * @param callback - Callback function to remove
29
+ * @returns this for chaining
30
+ */
31
+ off(event, callback) {
32
+ const callbacks = this.events.get(event);
33
+ if (callbacks) {
34
+ callbacks.delete(callback);
35
+ if (callbacks.size === 0) {
36
+ this.events.delete(event);
37
+ }
38
+ }
39
+ return this;
40
+ }
41
+ /**
42
+ * Register a one-time event listener
43
+ * @param event - Event name
44
+ * @param callback - Callback function to be invoked once when event is emitted
45
+ * @returns this for chaining
46
+ */
47
+ once(event, callback) {
48
+ const onceWrapper = (...args) => {
49
+ this.off(event, onceWrapper);
50
+ callback(...args);
51
+ };
52
+ return this.on(event, onceWrapper);
53
+ }
54
+ /**
55
+ * Emit an event with arguments
56
+ * @param event - Event name
57
+ * @param args - Arguments to pass to listeners
58
+ */
59
+ emit(event, ...args) {
60
+ const callbacks = this.events.get(event);
61
+ if (callbacks) {
62
+ // Create array from Set to preserve order and avoid modification during iteration
63
+ const callbackArray = Array.from(callbacks);
64
+ for (const callback of callbackArray) {
65
+ callback(...args);
66
+ }
67
+ }
68
+ }
69
+ /**
70
+ * Remove all listeners for a specific event or all events
71
+ * @param event - Optional event name. If not provided, removes all listeners for all events
72
+ */
73
+ removeAllListeners(event) {
74
+ if (event) {
75
+ this.events.delete(event);
76
+ }
77
+ else {
78
+ this.events.clear();
79
+ }
80
+ }
81
+ }
82
+ exports.EventEmitter = EventEmitter;
@@ -0,0 +1,89 @@
1
+ import { EventEmitter } from "./EventEmitter";
2
+ import { Participant, ReconnectConfig } from "../types/types";
3
+ /**
4
+ * SignalingClient manages WebSocket connection and signaling message exchange
5
+ * Extends EventEmitter to provide event-driven communication
6
+ */
7
+ export declare class SignalingClient extends EventEmitter {
8
+ private ws;
9
+ private reconnectConfig;
10
+ private reconnectAttempts;
11
+ private reconnectTimer;
12
+ private url;
13
+ private shouldReconnect;
14
+ private pendingRequests;
15
+ constructor(reconnectConfig: ReconnectConfig);
16
+ /**
17
+ * Connect to the signaling server
18
+ * @param url - WebSocket server URL
19
+ * @returns Promise that resolves when connected
20
+ */
21
+ connect(url: string): Promise<void>;
22
+ /**
23
+ * Disconnect from the signaling server
24
+ */
25
+ disconnect(): void;
26
+ /**
27
+ * Handle WebSocket disconnection and attempt reconnection
28
+ */
29
+ private handleDisconnect;
30
+ /**
31
+ * Handle incoming WebSocket messages
32
+ * @param data - Raw message data
33
+ */
34
+ private handleMessage;
35
+ /**
36
+ * Send a message to the signaling server
37
+ * @param message - Signaling message to send
38
+ */
39
+ private send;
40
+ /**
41
+ * Create a new room
42
+ * @returns Promise that resolves with the room ID
43
+ */
44
+ createRoom(): Promise<string>;
45
+ /**
46
+ * Join an existing room
47
+ * @param roomId - Room ID to join
48
+ * @param userId - User ID
49
+ * @param userName - User name
50
+ * @returns Promise that resolves with the list of participants
51
+ */
52
+ joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
53
+ /**
54
+ * Leave the current room
55
+ */
56
+ leaveRoom(): void;
57
+ /**
58
+ * Send an offer to a peer
59
+ * @param targetId - Target peer ID
60
+ * @param fromId - Sender ID
61
+ * @param offer - RTC session description (offer)
62
+ */
63
+ sendOffer(targetId: string, fromId: string, offer: RTCSessionDescriptionInit): void;
64
+ /**
65
+ * Send an answer to a peer
66
+ * @param targetId - Target peer ID
67
+ * @param fromId - Sender ID
68
+ * @param answer - RTC session description (answer)
69
+ */
70
+ sendAnswer(targetId: string, fromId: string, answer: RTCSessionDescriptionInit): void;
71
+ /**
72
+ * Send an ICE candidate to a peer
73
+ * @param targetId - Target peer ID
74
+ * @param fromId - Sender ID
75
+ * @param candidate - ICE candidate
76
+ */
77
+ sendIceCandidate(targetId: string, fromId: string, candidate: RTCIceCandidateInit): void;
78
+ /**
79
+ * Resolve a pending request
80
+ * @param requestType - Type of request to resolve
81
+ * @param value - Value to resolve with
82
+ */
83
+ private resolvePendingRequest;
84
+ /**
85
+ * Reject all pending requests
86
+ * @param error - Error to reject with
87
+ */
88
+ private rejectPendingRequests;
89
+ }