@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.
- package/LICENSE +21 -0
- package/README.md +428 -0
- package/dist/core/AvesClient.d.ts +84 -0
- package/dist/core/AvesClient.js +275 -0
- package/dist/core/EventEmitter.d.ts +40 -0
- package/dist/core/EventEmitter.js +82 -0
- package/dist/core/SignalingClient.d.ts +89 -0
- package/dist/core/SignalingClient.js +231 -0
- package/dist/core/WebRTCManager.d.ts +93 -0
- package/dist/core/WebRTCManager.js +308 -0
- package/dist/esm/core/AvesClient.d.ts +84 -0
- package/dist/esm/core/AvesClient.js +271 -0
- package/dist/esm/core/EventEmitter.d.ts +40 -0
- package/dist/esm/core/EventEmitter.js +78 -0
- package/dist/esm/core/SignalingClient.d.ts +89 -0
- package/dist/esm/core/SignalingClient.js +227 -0
- package/dist/esm/core/WebRTCManager.d.ts +93 -0
- package/dist/esm/core/WebRTCManager.js +304 -0
- package/dist/esm/index.d.ts +10 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/types/types.d.ts +55 -0
- package/dist/esm/types/types.js +2 -0
- package/dist/index.cjs +18 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +18 -0
- package/dist/types/types.d.ts +55 -0
- package/dist/types/types.js +3 -0
- package/package.json +44 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { EventEmitter } from "./EventEmitter";
|
|
2
|
+
/**
|
|
3
|
+
* SignalingClient manages WebSocket connection and signaling message exchange
|
|
4
|
+
* Extends EventEmitter to provide event-driven communication
|
|
5
|
+
*/
|
|
6
|
+
export class SignalingClient extends EventEmitter {
|
|
7
|
+
constructor(reconnectConfig) {
|
|
8
|
+
super();
|
|
9
|
+
this.ws = null;
|
|
10
|
+
this.reconnectAttempts = 0;
|
|
11
|
+
this.reconnectTimer = null;
|
|
12
|
+
this.url = "";
|
|
13
|
+
this.shouldReconnect = true;
|
|
14
|
+
this.pendingRequests = new Map();
|
|
15
|
+
this.reconnectConfig = reconnectConfig;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Connect to the signaling server
|
|
19
|
+
* @param url - WebSocket server URL
|
|
20
|
+
* @returns Promise that resolves when connected
|
|
21
|
+
*/
|
|
22
|
+
connect(url) {
|
|
23
|
+
this.url = url;
|
|
24
|
+
this.shouldReconnect = true;
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
try {
|
|
27
|
+
this.ws = new WebSocket(url);
|
|
28
|
+
this.ws.onopen = () => {
|
|
29
|
+
this.reconnectAttempts = 0;
|
|
30
|
+
this.emit("stateChange", "connected");
|
|
31
|
+
resolve();
|
|
32
|
+
};
|
|
33
|
+
this.ws.onclose = () => {
|
|
34
|
+
this.emit("stateChange", "disconnected");
|
|
35
|
+
this.handleDisconnect();
|
|
36
|
+
};
|
|
37
|
+
this.ws.onerror = (error) => {
|
|
38
|
+
this.emit("error", new Error("WebSocket error"));
|
|
39
|
+
reject(new Error("WebSocket connection failed"));
|
|
40
|
+
};
|
|
41
|
+
this.ws.onmessage = (event) => {
|
|
42
|
+
this.handleMessage(event.data);
|
|
43
|
+
};
|
|
44
|
+
this.emit("stateChange", "connecting");
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
reject(error);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Disconnect from the signaling server
|
|
53
|
+
*/
|
|
54
|
+
disconnect() {
|
|
55
|
+
this.shouldReconnect = false;
|
|
56
|
+
if (this.reconnectTimer !== null) {
|
|
57
|
+
clearTimeout(this.reconnectTimer);
|
|
58
|
+
this.reconnectTimer = null;
|
|
59
|
+
}
|
|
60
|
+
if (this.ws) {
|
|
61
|
+
this.ws.close();
|
|
62
|
+
this.ws = null;
|
|
63
|
+
}
|
|
64
|
+
this.emit("stateChange", "disconnected");
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Handle WebSocket disconnection and attempt reconnection
|
|
68
|
+
*/
|
|
69
|
+
handleDisconnect() {
|
|
70
|
+
this.ws = null;
|
|
71
|
+
if (!this.shouldReconnect) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (this.reconnectAttempts < this.reconnectConfig.maxAttempts) {
|
|
75
|
+
this.reconnectAttempts++;
|
|
76
|
+
this.reconnectTimer = setTimeout(() => {
|
|
77
|
+
this.connect(this.url).catch((error) => {
|
|
78
|
+
// Connection failed, will retry on next attempt
|
|
79
|
+
});
|
|
80
|
+
}, this.reconnectConfig.delay);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
this.emit("error", new Error(`Max reconnection attempts (${this.reconnectConfig.maxAttempts}) reached`));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Handle incoming WebSocket messages
|
|
88
|
+
* @param data - Raw message data
|
|
89
|
+
*/
|
|
90
|
+
handleMessage(data) {
|
|
91
|
+
try {
|
|
92
|
+
const message = JSON.parse(data);
|
|
93
|
+
switch (message.type) {
|
|
94
|
+
case "room-created":
|
|
95
|
+
this.resolvePendingRequest("create-room", message.roomId);
|
|
96
|
+
break;
|
|
97
|
+
case "room-joined":
|
|
98
|
+
this.resolvePendingRequest("join-room", message.participants);
|
|
99
|
+
break;
|
|
100
|
+
case "user-joined":
|
|
101
|
+
this.emit("userJoined", message.user);
|
|
102
|
+
break;
|
|
103
|
+
case "user-left":
|
|
104
|
+
this.emit("userLeft", message.userId);
|
|
105
|
+
break;
|
|
106
|
+
case "offer":
|
|
107
|
+
this.emit("offer", message.fromId, message.offer);
|
|
108
|
+
break;
|
|
109
|
+
case "answer":
|
|
110
|
+
this.emit("answer", message.fromId, message.answer);
|
|
111
|
+
break;
|
|
112
|
+
case "ice-candidate":
|
|
113
|
+
this.emit("iceCandidate", message.fromId, message.candidate);
|
|
114
|
+
break;
|
|
115
|
+
case "error":
|
|
116
|
+
this.rejectPendingRequests(new Error(message.message));
|
|
117
|
+
this.emit("error", new Error(message.message));
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
this.emit("error", new Error("Failed to parse signaling message"));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Send a message to the signaling server
|
|
127
|
+
* @param message - Signaling message to send
|
|
128
|
+
*/
|
|
129
|
+
send(message) {
|
|
130
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
131
|
+
throw new Error("WebSocket is not connected");
|
|
132
|
+
}
|
|
133
|
+
this.ws.send(JSON.stringify(message));
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Create a new room
|
|
137
|
+
* @returns Promise that resolves with the room ID
|
|
138
|
+
*/
|
|
139
|
+
createRoom() {
|
|
140
|
+
return new Promise((resolve, reject) => {
|
|
141
|
+
this.pendingRequests.set("create-room", { resolve, reject });
|
|
142
|
+
try {
|
|
143
|
+
this.send({ type: "create-room" });
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
this.pendingRequests.delete("create-room");
|
|
147
|
+
reject(error);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Join an existing room
|
|
153
|
+
* @param roomId - Room ID to join
|
|
154
|
+
* @param userId - User ID
|
|
155
|
+
* @param userName - User name
|
|
156
|
+
* @returns Promise that resolves with the list of participants
|
|
157
|
+
*/
|
|
158
|
+
joinRoom(roomId, userId, userName) {
|
|
159
|
+
return new Promise((resolve, reject) => {
|
|
160
|
+
this.pendingRequests.set("join-room", { resolve, reject });
|
|
161
|
+
try {
|
|
162
|
+
this.send({ type: "join-room", roomId, userId, userName });
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
this.pendingRequests.delete("join-room");
|
|
166
|
+
reject(error);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Leave the current room
|
|
172
|
+
*/
|
|
173
|
+
leaveRoom() {
|
|
174
|
+
// In the current design, leaving is handled by disconnecting
|
|
175
|
+
// or the server will handle it when the connection closes
|
|
176
|
+
// This method is here for API completeness
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Send an offer to a peer
|
|
180
|
+
* @param targetId - Target peer ID
|
|
181
|
+
* @param fromId - Sender ID
|
|
182
|
+
* @param offer - RTC session description (offer)
|
|
183
|
+
*/
|
|
184
|
+
sendOffer(targetId, fromId, offer) {
|
|
185
|
+
this.send({ type: "offer", targetId, fromId, offer });
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Send an answer to a peer
|
|
189
|
+
* @param targetId - Target peer ID
|
|
190
|
+
* @param fromId - Sender ID
|
|
191
|
+
* @param answer - RTC session description (answer)
|
|
192
|
+
*/
|
|
193
|
+
sendAnswer(targetId, fromId, answer) {
|
|
194
|
+
this.send({ type: "answer", targetId, fromId, answer });
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Send an ICE candidate to a peer
|
|
198
|
+
* @param targetId - Target peer ID
|
|
199
|
+
* @param fromId - Sender ID
|
|
200
|
+
* @param candidate - ICE candidate
|
|
201
|
+
*/
|
|
202
|
+
sendIceCandidate(targetId, fromId, candidate) {
|
|
203
|
+
this.send({ type: "ice-candidate", targetId, fromId, candidate });
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Resolve a pending request
|
|
207
|
+
* @param requestType - Type of request to resolve
|
|
208
|
+
* @param value - Value to resolve with
|
|
209
|
+
*/
|
|
210
|
+
resolvePendingRequest(requestType, value) {
|
|
211
|
+
const request = this.pendingRequests.get(requestType);
|
|
212
|
+
if (request) {
|
|
213
|
+
request.resolve(value);
|
|
214
|
+
this.pendingRequests.delete(requestType);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Reject all pending requests
|
|
219
|
+
* @param error - Error to reject with
|
|
220
|
+
*/
|
|
221
|
+
rejectPendingRequests(error) {
|
|
222
|
+
for (const [key, request] of this.pendingRequests) {
|
|
223
|
+
request.reject(error);
|
|
224
|
+
}
|
|
225
|
+
this.pendingRequests.clear();
|
|
226
|
+
}
|
|
227
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
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
|
|
10
|
+
*/
|
|
11
|
+
export declare class WebRTCManager {
|
|
12
|
+
private peerConnections;
|
|
13
|
+
private dataChannels;
|
|
14
|
+
private iceServers;
|
|
15
|
+
private messageCallbacks;
|
|
16
|
+
private connectionStateCallbacks;
|
|
17
|
+
private dataChannelStateCallbacks;
|
|
18
|
+
private iceCandidateCallbacks;
|
|
19
|
+
constructor(iceServers: RTCIceServer[]);
|
|
20
|
+
/**
|
|
21
|
+
* Create a new PeerConnection for the specified peer
|
|
22
|
+
* If a connection already exists, returns the existing connection
|
|
23
|
+
*/
|
|
24
|
+
createPeerConnection(peerId: string): RTCPeerConnection;
|
|
25
|
+
/**
|
|
26
|
+
* Create an offer for the specified peer
|
|
27
|
+
* This also creates the DataChannel (offer side creates the channel)
|
|
28
|
+
*/
|
|
29
|
+
createOffer(peerId: string): Promise<RTCSessionDescriptionInit>;
|
|
30
|
+
/**
|
|
31
|
+
* Create an answer for the specified peer
|
|
32
|
+
* Sets up the remote offer and creates an answer
|
|
33
|
+
*/
|
|
34
|
+
createAnswer(peerId: string, offer: RTCSessionDescriptionInit): Promise<RTCSessionDescriptionInit>;
|
|
35
|
+
/**
|
|
36
|
+
* Set the remote answer for the specified peer
|
|
37
|
+
*/
|
|
38
|
+
setRemoteAnswer(peerId: string, answer: RTCSessionDescriptionInit): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Add an ICE candidate for the specified peer
|
|
41
|
+
*/
|
|
42
|
+
addIceCandidate(peerId: string, candidate: RTCIceCandidateInit): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Register a callback for ICE candidates from the specified peer
|
|
45
|
+
*/
|
|
46
|
+
onIceCandidate(peerId: string, callback: (candidate: RTCIceCandidateInit) => void): void;
|
|
47
|
+
/**
|
|
48
|
+
* Register a callback for connection state changes
|
|
49
|
+
*/
|
|
50
|
+
onConnectionStateChange(peerId: string, callback: (state: RTCPeerConnectionState) => void): void;
|
|
51
|
+
/**
|
|
52
|
+
* Register a callback for DataChannel state changes
|
|
53
|
+
*/
|
|
54
|
+
onDataChannelStateChange(peerId: string, callback: (state: RTCDataChannelState) => void): void;
|
|
55
|
+
/**
|
|
56
|
+
* Register a callback for incoming messages
|
|
57
|
+
*/
|
|
58
|
+
onMessage(callback: (peerId: string, message: any) => void): void;
|
|
59
|
+
/**
|
|
60
|
+
* Setup DataChannel event handlers
|
|
61
|
+
*/
|
|
62
|
+
private setupDataChannel;
|
|
63
|
+
/**
|
|
64
|
+
* Send a message to all connected peers
|
|
65
|
+
* Throws error if any DataChannel is not ready
|
|
66
|
+
*/
|
|
67
|
+
sendMessage(message: any): void;
|
|
68
|
+
/**
|
|
69
|
+
* Send a message to a specific peer
|
|
70
|
+
* Throws error if DataChannel is not ready
|
|
71
|
+
*/
|
|
72
|
+
sendMessageToPeer(peerId: string, message: any): void;
|
|
73
|
+
/**
|
|
74
|
+
* Close the connection with a specific peer
|
|
75
|
+
*/
|
|
76
|
+
closePeerConnection(peerId: string): void;
|
|
77
|
+
/**
|
|
78
|
+
* Close all connections and clean up resources
|
|
79
|
+
*/
|
|
80
|
+
closeAll(): void;
|
|
81
|
+
/**
|
|
82
|
+
* Get all active peer IDs
|
|
83
|
+
*/
|
|
84
|
+
getActivePeers(): string[];
|
|
85
|
+
/**
|
|
86
|
+
* Check if connected to a specific peer
|
|
87
|
+
*/
|
|
88
|
+
isConnected(peerId: string): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Check if DataChannel is ready for a specific peer
|
|
91
|
+
*/
|
|
92
|
+
isDataChannelReady(peerId: string): boolean;
|
|
93
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
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
|
|
10
|
+
*/
|
|
11
|
+
export class WebRTCManager {
|
|
12
|
+
constructor(iceServers) {
|
|
13
|
+
this.peerConnections = new Map();
|
|
14
|
+
this.dataChannels = new Map();
|
|
15
|
+
this.iceServers = iceServers;
|
|
16
|
+
this.messageCallbacks = new Set();
|
|
17
|
+
this.connectionStateCallbacks = new Map();
|
|
18
|
+
this.dataChannelStateCallbacks = new Map();
|
|
19
|
+
this.iceCandidateCallbacks = new Map();
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Create a new PeerConnection for the specified peer
|
|
23
|
+
* If a connection already exists, returns the existing connection
|
|
24
|
+
*/
|
|
25
|
+
createPeerConnection(peerId) {
|
|
26
|
+
if (this.peerConnections.has(peerId)) {
|
|
27
|
+
console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
|
|
28
|
+
return this.peerConnections.get(peerId);
|
|
29
|
+
}
|
|
30
|
+
console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
|
|
31
|
+
const pc = new RTCPeerConnection({
|
|
32
|
+
iceServers: this.iceServers,
|
|
33
|
+
});
|
|
34
|
+
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
|
+
};
|
|
49
|
+
return pc;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create an offer for the specified peer
|
|
53
|
+
* This also creates the DataChannel (offer side creates the channel)
|
|
54
|
+
*/
|
|
55
|
+
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);
|
|
64
|
+
const offer = await pc.createOffer();
|
|
65
|
+
await pc.setLocalDescription(offer);
|
|
66
|
+
console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
|
|
67
|
+
return offer;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Create an answer for the specified peer
|
|
71
|
+
* Sets up the remote offer and creates an answer
|
|
72
|
+
*/
|
|
73
|
+
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)
|
|
79
|
+
pc.ondatachannel = (event) => {
|
|
80
|
+
this.setupDataChannel(peerId, event.channel);
|
|
81
|
+
};
|
|
82
|
+
console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
|
|
83
|
+
await pc.setRemoteDescription(new RTCSessionDescription(offer));
|
|
84
|
+
console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
|
|
85
|
+
const answer = await pc.createAnswer();
|
|
86
|
+
await pc.setLocalDescription(answer);
|
|
87
|
+
console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
|
|
88
|
+
return answer;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Set the remote answer for the specified peer
|
|
92
|
+
*/
|
|
93
|
+
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
|
+
}
|
|
103
|
+
await pc.setRemoteDescription(new RTCSessionDescription(answer));
|
|
104
|
+
console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Add an ICE candidate for the specified peer
|
|
108
|
+
*/
|
|
109
|
+
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
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Register a callback for ICE candidates from the specified peer
|
|
124
|
+
*/
|
|
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
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Register a callback for connection state changes
|
|
145
|
+
*/
|
|
146
|
+
onConnectionStateChange(peerId, callback) {
|
|
147
|
+
if (!this.connectionStateCallbacks.has(peerId)) {
|
|
148
|
+
this.connectionStateCallbacks.set(peerId, new Set());
|
|
149
|
+
}
|
|
150
|
+
this.connectionStateCallbacks.get(peerId).add(callback);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Register a callback for DataChannel state changes
|
|
154
|
+
*/
|
|
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);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Register a callback for incoming messages
|
|
163
|
+
*/
|
|
164
|
+
onMessage(callback) {
|
|
165
|
+
this.messageCallbacks.add(callback);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Setup DataChannel event handlers
|
|
169
|
+
*/
|
|
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
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Send a message to all connected peers
|
|
202
|
+
* Throws error if any DataChannel is not ready
|
|
203
|
+
*/
|
|
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
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Send a message to a specific peer
|
|
228
|
+
* Throws error if DataChannel is not ready
|
|
229
|
+
*/
|
|
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}`);
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
// Serialize message to JSON
|
|
240
|
+
const serialized = JSON.stringify(message);
|
|
241
|
+
dataChannel.send(serialized);
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
console.error(`Failed to send message to ${peerId}:`, error);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Close the connection with a specific peer
|
|
250
|
+
*/
|
|
251
|
+
closePeerConnection(peerId) {
|
|
252
|
+
const dataChannel = this.dataChannels.get(peerId);
|
|
253
|
+
if (dataChannel) {
|
|
254
|
+
dataChannel.close();
|
|
255
|
+
this.dataChannels.delete(peerId);
|
|
256
|
+
}
|
|
257
|
+
const pc = this.peerConnections.get(peerId);
|
|
258
|
+
if (pc) {
|
|
259
|
+
pc.close();
|
|
260
|
+
this.peerConnections.delete(peerId);
|
|
261
|
+
}
|
|
262
|
+
// Clean up callbacks
|
|
263
|
+
this.connectionStateCallbacks.delete(peerId);
|
|
264
|
+
this.dataChannelStateCallbacks.delete(peerId);
|
|
265
|
+
this.iceCandidateCallbacks.delete(peerId);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Close all connections and clean up resources
|
|
269
|
+
*/
|
|
270
|
+
closeAll() {
|
|
271
|
+
this.dataChannels.forEach((dataChannel) => {
|
|
272
|
+
dataChannel.close();
|
|
273
|
+
});
|
|
274
|
+
this.dataChannels.clear();
|
|
275
|
+
this.peerConnections.forEach((pc) => {
|
|
276
|
+
pc.close();
|
|
277
|
+
});
|
|
278
|
+
this.peerConnections.clear();
|
|
279
|
+
this.messageCallbacks.clear();
|
|
280
|
+
this.connectionStateCallbacks.clear();
|
|
281
|
+
this.dataChannelStateCallbacks.clear();
|
|
282
|
+
this.iceCandidateCallbacks.clear();
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Get all active peer IDs
|
|
286
|
+
*/
|
|
287
|
+
getActivePeers() {
|
|
288
|
+
return Array.from(this.peerConnections.keys());
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Check if connected to a specific peer
|
|
292
|
+
*/
|
|
293
|
+
isConnected(peerId) {
|
|
294
|
+
const pc = this.peerConnections.get(peerId);
|
|
295
|
+
return pc?.connectionState === "connected";
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Check if DataChannel is ready for a specific peer
|
|
299
|
+
*/
|
|
300
|
+
isDataChannelReady(peerId) {
|
|
301
|
+
const dataChannel = this.dataChannels.get(peerId);
|
|
302
|
+
return dataChannel?.readyState === "open";
|
|
303
|
+
}
|
|
304
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aves-core - WebRTC client library
|
|
3
|
+
*
|
|
4
|
+
* Main exports for the aves-core package
|
|
5
|
+
*/
|
|
6
|
+
export { AvesClient } from "./core/AvesClient";
|
|
7
|
+
export { EventEmitter } from "./core/EventEmitter";
|
|
8
|
+
export { WebRTCManager } from "./core/WebRTCManager";
|
|
9
|
+
export { SignalingClient } from "./core/SignalingClient";
|
|
10
|
+
export type { Participant, AvesClientConfig, SignalingMessage, ReconnectConfig, } from "./types/types";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aves-core - WebRTC client library
|
|
3
|
+
*
|
|
4
|
+
* Main exports for the aves-core package
|
|
5
|
+
*/
|
|
6
|
+
// Main client class
|
|
7
|
+
export { AvesClient } from "./core/AvesClient";
|
|
8
|
+
// Core components (for advanced usage)
|
|
9
|
+
export { EventEmitter } from "./core/EventEmitter";
|
|
10
|
+
export { WebRTCManager } from "./core/WebRTCManager";
|
|
11
|
+
export { SignalingClient } from "./core/SignalingClient";
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export interface Participant {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
export interface AvesClientConfig {
|
|
6
|
+
signalingUrl: string;
|
|
7
|
+
iceServers?: RTCIceServer[];
|
|
8
|
+
reconnect?: {
|
|
9
|
+
maxAttempts?: number;
|
|
10
|
+
delay?: number;
|
|
11
|
+
};
|
|
12
|
+
debug?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export type SignalingMessage = {
|
|
15
|
+
type: "create-room";
|
|
16
|
+
} | {
|
|
17
|
+
type: "room-created";
|
|
18
|
+
roomId: string;
|
|
19
|
+
} | {
|
|
20
|
+
type: "join-room";
|
|
21
|
+
roomId: string;
|
|
22
|
+
userId: string;
|
|
23
|
+
userName: string;
|
|
24
|
+
} | {
|
|
25
|
+
type: "room-joined";
|
|
26
|
+
participants: Participant[];
|
|
27
|
+
} | {
|
|
28
|
+
type: "user-joined";
|
|
29
|
+
user: Participant;
|
|
30
|
+
} | {
|
|
31
|
+
type: "user-left";
|
|
32
|
+
userId: string;
|
|
33
|
+
} | {
|
|
34
|
+
type: "offer";
|
|
35
|
+
fromId: string;
|
|
36
|
+
targetId: string;
|
|
37
|
+
offer: RTCSessionDescriptionInit;
|
|
38
|
+
} | {
|
|
39
|
+
type: "answer";
|
|
40
|
+
fromId: string;
|
|
41
|
+
targetId: string;
|
|
42
|
+
answer: RTCSessionDescriptionInit;
|
|
43
|
+
} | {
|
|
44
|
+
type: "ice-candidate";
|
|
45
|
+
fromId: string;
|
|
46
|
+
targetId: string;
|
|
47
|
+
candidate: RTCIceCandidateInit;
|
|
48
|
+
} | {
|
|
49
|
+
type: "error";
|
|
50
|
+
message: string;
|
|
51
|
+
};
|
|
52
|
+
export interface ReconnectConfig {
|
|
53
|
+
maxAttempts: number;
|
|
54
|
+
delay: number;
|
|
55
|
+
}
|