@yrzhao/aves-core 1.0.0 → 1.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/README.md CHANGED
@@ -1,125 +1,166 @@
1
1
  # Aves Core
2
2
 
3
- 轻量级 WebRTC 客户端库,零运行时依赖。支持消息、文件传输、语音、视频、屏幕共享,基于全网状 P2P 拓扑直连。
3
+ Browser WebRTC client library for peer-to-peer rooms. `@yrzhao/aves-core` connects to an `aves-node` signaling server, builds a full-mesh WebRTC topology, and provides typed APIs for messages, file transfer, voice, video, screen sharing, reconnect restore, and diagnostics.
4
4
 
5
- 版本:`0.3.0`
5
+ Version: `1.1.0`
6
6
 
7
- ## 安装
7
+ ## Install
8
8
 
9
9
  ```bash
10
10
  npm install @yrzhao/aves-core
11
11
  ```
12
12
 
13
- ## 快速开始
13
+ ## Quick Start
14
14
 
15
- ```typescript
15
+ ```ts
16
16
  import { AvesClient } from "@yrzhao/aves-core";
17
17
 
18
- const client = new AvesClient({ signalingUrl: "ws://localhost:8080" });
18
+ const client = new AvesClient({
19
+ signalingUrl: "wss://signal.example.com",
20
+ iceServers: [
21
+ { urls: "stun:stun.l.google.com:19302" },
22
+ {
23
+ urls: "turn:turn.example.com:3478",
24
+ username: "turn-user",
25
+ credential: "turn-password",
26
+ },
27
+ ],
28
+ });
19
29
 
20
- client.on("message", (peerId, message) => console.log(`${peerId}:`, message));
21
- client.on("userJoined", (p) => console.log(`${p.name} 加入了`));
30
+ client.on("message", (peerId, message) => {
31
+ console.log("message from", peerId, message);
32
+ });
33
+
34
+ client.on("error", (error) => {
35
+ console.error(error.code, error.stage, error.message);
36
+ });
22
37
 
23
38
  const roomId = await client.createRoom();
24
39
  await client.joinRoom(roomId, "Alice");
25
40
 
26
- client.sendMessage({ text: "大家好!" });
27
- await client.leaveRoom();
41
+ await client.waitForPeer("peer-user-id");
42
+ client.sendMessage({ text: "hello" });
28
43
  ```
29
44
 
30
- ## 核心 API
45
+ ## What It Does
31
46
 
32
- ### 房间管理
47
+ - Creates and joins signaling rooms through `aves-node`.
48
+ - Builds direct WebRTC peer connections between every participant in a room.
49
+ - Sends JSON messages over a data channel.
50
+ - Sends files over a dedicated file data channel.
51
+ - Captures and forwards microphone, camera, and screen-share tracks.
52
+ - Restores room membership after transient signaling disconnects.
53
+ - Emits typed events for application state and errors.
54
+ - Exposes connection snapshots for diagnostics panels and smoke tests.
33
55
 
34
- | 方法 | 返回 | 说明 |
35
- |------|------|------|
36
- | `createRoom()` | `Promise<string>` | 创建房间 |
37
- | `joinRoom(roomId, name)` | `Promise<Participant[]>` | 加入房间 |
38
- | `leaveRoom()` | `Promise<void>` | 离开 |
39
- | `destroy()` | `void` | 销毁客户端 |
56
+ ## What It Does Not Do
57
+
58
+ - It does not host a signaling server. Use `@yrzhao/aves-node`.
59
+ - It does not relay media or data traffic. Peers communicate directly.
60
+ - It does not replace TURN. Production networks still need TURN fallback.
61
+ - It does not encrypt beyond WebRTC/WebSocket transport guarantees. Use HTTPS/WSS.
62
+ - It is not an SFU. Full-mesh rooms are best for small groups.
63
+
64
+ ## Core API
65
+
66
+ ### Rooms
67
+
68
+ ```ts
69
+ const roomId = await client.createRoom();
70
+ const existingParticipants = await client.joinRoom(roomId, "Alice");
71
+ await client.leaveRoom();
72
+ client.destroy();
73
+ ```
40
74
 
41
- ### 消息
75
+ ### Messages
42
76
 
43
- ```typescript
44
- client.sendMessage({ text: "hi" }); // 广播
45
- client.sendMessageToPeer(peerId, { text: "hi" }); // 单播
77
+ ```ts
78
+ client.sendMessage({ kind: "chat", text: "hello" });
79
+ client.sendMessageToPeer(peerId, { kind: "private", text: "hi" });
46
80
  ```
47
81
 
48
- ### 文件传输
82
+ ### Peer Readiness And Diagnostics
49
83
 
50
- ```typescript
51
- // 发送(广播)
52
- await client.sendFile(fileBlob, { fileName: "photo.jpg" });
84
+ ```ts
85
+ await client.waitForPeer(peerId, { timeoutMs: 10000 });
53
86
 
54
- // 发送(单播)
55
- await client.sendFile(fileBlob, { fileName: "doc.pdf", peerId: targetId });
87
+ const snapshot = client.getConnectionSnapshot();
88
+ console.log(snapshot.signalingConnected, snapshot.peers);
89
+ ```
56
90
 
57
- // 监听
58
- client.on("fileTransferProgress", (p, pgr) => {
59
- console.log(`${p}: ${Math.round(pgr.progress * 100)}%`);
91
+ ### Files
92
+
93
+ ```ts
94
+ await client.sendFile(file, {
95
+ fileName: file.name,
96
+ mimeType: file.type || "application/octet-stream",
60
97
  });
61
- client.on("fileTransferCompleted", (_, result) => {
62
- const url = URL.createObjectURL(result.blob);
98
+
99
+ client.on("fileTransferProgress", (_peerId, progress) => {
100
+ console.log(Math.round(progress.progress * 100));
63
101
  });
64
102
  ```
65
103
 
66
- ### 语音
104
+ ### Media
67
105
 
68
- ```typescript
106
+ ```ts
69
107
  await client.startVoice();
70
108
  client.setMuted(true);
71
109
  client.stopVoice();
72
- ```
73
-
74
- ### 视频
75
110
 
76
- ```typescript
77
111
  await client.startVideo({ width: 1280, height: 720, frameRate: 30 });
78
112
  client.setVideoMuted(true);
79
113
  client.stopVideo();
80
- ```
81
114
 
82
- ### 屏幕共享
83
-
84
- ```typescript
85
- await client.startScreenShare(); // 自动恢复摄像头
115
+ await client.startScreenShare();
86
116
  client.stopScreenShare();
87
117
  ```
88
118
 
89
- ## 配置
119
+ ## Configuration
90
120
 
91
- ```typescript
121
+ ```ts
92
122
  new AvesClient({
93
- signalingUrl: "ws://localhost:8080", // 必需
123
+ signalingUrl: "wss://signal.example.com",
94
124
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
95
- fileChunkSize: 65536,
96
- reconnect: { maxAttempts: 5, delay: 3000, requestTimeoutMs: 30000 },
125
+ fileChunkSize: 16 * 1024,
126
+ video: { width: 1280, height: 720, frameRate: 30 },
127
+ reconnect: {
128
+ maxAttempts: 5,
129
+ delay: 3000,
130
+ requestTimeoutMs: 30000,
131
+ },
97
132
  debug: false,
98
133
  });
99
134
  ```
100
135
 
101
- ## 事件
136
+ ## Events
137
+
138
+ | Event | Arguments |
139
+ | --- | --- |
140
+ | `signalingStateChange` | `(state)` |
141
+ | `userJoined` | `(participant)` |
142
+ | `userLeft` | `(userId)` |
143
+ | `connectionStateChange` | `(peerId, state)` |
144
+ | `dataChannelStateChange` | `(peerId, state)` |
145
+ | `message` | `(peerId, message)` |
146
+ | `remoteAudioTrack` / `remoteVideoTrack` | `(peerId, stream, track)` |
147
+ | `localAudioStateChange` / `localVideoStateChange` | `(state)` |
148
+ | `screenShareStateChange` | `(state)` |
149
+ | `fileTransferStarted` / `fileTransferProgress` / `fileTransferCompleted` / `fileTransferFailed` | transfer lifecycle payloads |
150
+ | `error` | `(AvesError)` |
102
151
 
103
- | 事件 | 参数 | 说明 |
104
- |------|------|------|
105
- | `message` | `(peerId, message)` | 收到消息 |
106
- | `userJoined` / `userLeft` | `(user)` / `(userId)` | 用户进出 |
107
- | `connectionStateChange` | `(peerId, state)` | 连接状态 |
108
- | `localAudioStateChange` | `(state)` | 本地音频状态 |
109
- | `localVideoStateChange` | `(state)` | 本地视频状态 |
110
- | `screenShareStateChange` | `(state)` | 屏幕共享状态 |
111
- | `fileTransferStarted/Progress/Completed/Failed` | — | 文件传输各阶段 |
112
- | `remoteAudioTrack` / `remoteVideoTrack` | `(peerId, stream, track)` | 收到远端媒体 |
113
- | `error` | `(error)` | 错误 |
152
+ ## Production Notes
114
153
 
115
- ## 浏览器兼容性
154
+ - Use HTTPS for the web app and WSS for signaling.
155
+ - Configure TURN for restrictive NATs, enterprise networks, and mobile carriers.
156
+ - Keep rooms small. Full mesh requires each peer to maintain one connection to every other peer.
157
+ - Prefer small to medium files over data channels. Very large files need application-level resume/retry UX.
158
+ - Test Safari and mobile browsers separately if they are target platforms.
116
159
 
117
- Chrome/Edge 56+、Firefox 44+、Safari 11+、Opera 43+
160
+ See [PRODUCTION.md](docs/PRODUCTION.md) and [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
118
161
 
119
- ## 发布信息
162
+ ## Browser Support
120
163
 
121
- - 包大小:~30 KiB gzip
122
- - 全网状拓扑:O(n) 连接数
123
- - 零运行时依赖
164
+ Modern Chromium, Firefox, and Safari versions with WebRTC, DataChannel, `getUserMedia`, and `getDisplayMedia` support. Screen sharing and media permissions vary by browser and platform.
124
165
 
125
166
  MIT
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
2
  import { AvesError } from "./AvesError";
3
- import { AvesClientConfig, AvesMessage, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState } from "../types/types";
3
+ import { AvesClientConfig, AvesConnectionSnapshot, AvesMessage, AvesPeerSnapshot, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState, WaitForPeerOptions } from "../types/types";
4
4
  export type AvesClientEvents = {
5
5
  signalingStateChange: [state: string];
6
6
  error: [error: AvesError];
@@ -58,7 +58,10 @@ export declare class AvesClient extends EventEmitter<AvesClientEvents> {
58
58
  stopScreenShare(): void;
59
59
  getScreenShareState(): ScreenShareState;
60
60
  getConnectionState(peerId: string): RTCPeerConnectionState;
61
+ getConnectionSnapshot(): AvesConnectionSnapshot;
62
+ waitForPeer(peerId: string, options?: WaitForPeerOptions): Promise<AvesPeerSnapshot>;
61
63
  getParticipants(): Participant[];
64
+ private createPeerSnapshot;
62
65
  getCurrentUserId(): string | null;
63
66
  isConnected(): boolean;
64
67
  destroy(): void;
@@ -141,7 +141,7 @@ class AvesClient extends EventEmitter_1.EventEmitter {
141
141
  return;
142
142
  }
143
143
  try {
144
- this.webrtcManager.closeAll();
144
+ this.webrtcManager.closeAllPeerConnections();
145
145
  this.participants.clear();
146
146
  this.preparedPeers.clear();
147
147
  const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
@@ -299,9 +299,109 @@ class AvesClient extends EventEmitter_1.EventEmitter {
299
299
  getConnectionState(peerId) {
300
300
  return this.webrtcManager.getConnectionState(peerId);
301
301
  }
302
+ getConnectionSnapshot() {
303
+ const participants = this.getParticipants();
304
+ const participantById = new Map(participants.map((participant) => [participant.id, participant]));
305
+ const peerIds = new Set([
306
+ ...this.webrtcManager.getActivePeers(),
307
+ ...participants.map((participant) => participant.id),
308
+ ]);
309
+ if (this.currentUserId) {
310
+ peerIds.delete(this.currentUserId);
311
+ }
312
+ const peers = Array.from(peerIds).map((peerId) => this.createPeerSnapshot(peerId, participantById.get(peerId)));
313
+ return {
314
+ roomId: this.currentRoomId,
315
+ currentUserId: this.currentUserId,
316
+ signalingConnected: this.signalingClient.isConnected(),
317
+ participantCount: participants.length,
318
+ participants,
319
+ peers,
320
+ };
321
+ }
322
+ waitForPeer(peerId, options = {}) {
323
+ const timeoutMs = options.timeoutMs ?? 30000;
324
+ const getSnapshot = () => this.createPeerSnapshot(peerId, this.participants.get(peerId));
325
+ const isReady = () => {
326
+ const messageReady = this.webrtcManager.isDataChannelReady(peerId);
327
+ const fileReady = !options.requireFileChannel ||
328
+ this.webrtcManager.isFileChannelReady(peerId);
329
+ return messageReady && fileReady;
330
+ };
331
+ if (isReady()) {
332
+ return Promise.resolve(getSnapshot());
333
+ }
334
+ return new Promise((resolve, reject) => {
335
+ let timeoutId = null;
336
+ const cleanup = () => {
337
+ this.off("dataChannelStateChange", handleDataChannelStateChange);
338
+ this.off("connectionStateChange", handleConnectionStateChange);
339
+ if (timeoutId) {
340
+ clearTimeout(timeoutId);
341
+ timeoutId = null;
342
+ }
343
+ };
344
+ const resolveIfReady = () => {
345
+ if (!isReady()) {
346
+ return;
347
+ }
348
+ cleanup();
349
+ resolve(getSnapshot());
350
+ };
351
+ const handleDataChannelStateChange = (changedPeerId) => {
352
+ if (changedPeerId === peerId) {
353
+ resolveIfReady();
354
+ }
355
+ };
356
+ const handleConnectionStateChange = (changedPeerId, state) => {
357
+ if (changedPeerId !== peerId) {
358
+ return;
359
+ }
360
+ if (state === "failed" || state === "closed") {
361
+ cleanup();
362
+ reject(new AvesError_1.AvesError({
363
+ message: `Peer ${peerId} connection ${state}`,
364
+ code: "WEBRTC_CONNECTION_FAILED",
365
+ stage: "transport",
366
+ retryable: state === "failed",
367
+ peerId,
368
+ }));
369
+ return;
370
+ }
371
+ resolveIfReady();
372
+ };
373
+ this.on("dataChannelStateChange", handleDataChannelStateChange);
374
+ this.on("connectionStateChange", handleConnectionStateChange);
375
+ timeoutId = setTimeout(() => {
376
+ cleanup();
377
+ reject(new AvesError_1.AvesError({
378
+ message: `Timed out waiting for peer ${peerId}`,
379
+ code: "WEBRTC_CONNECTION_FAILED",
380
+ stage: "transport",
381
+ retryable: true,
382
+ peerId,
383
+ }));
384
+ }, timeoutMs);
385
+ resolveIfReady();
386
+ });
387
+ }
302
388
  getParticipants() {
303
389
  return Array.from(this.participants.values());
304
390
  }
391
+ createPeerSnapshot(peerId, participant) {
392
+ const messageChannelReady = this.webrtcManager.isDataChannelReady(peerId);
393
+ const fileChannelReady = this.webrtcManager.isFileChannelReady(peerId);
394
+ return {
395
+ peerId,
396
+ participant,
397
+ connectionState: this.webrtcManager.getConnectionState(peerId),
398
+ dataChannelState: messageChannelReady
399
+ ? "open"
400
+ : this.webrtcManager.getDataChannelState(peerId),
401
+ messageChannelReady,
402
+ fileChannelReady,
403
+ };
404
+ }
305
405
  getCurrentUserId() {
306
406
  return this.currentUserId;
307
407
  }
@@ -165,6 +165,11 @@ export declare class WebRTCManager {
165
165
  * Close the connection with a specific peer.
166
166
  */
167
167
  closePeerConnection(peerId: string): void;
168
+ /**
169
+ * Close all peer connections while preserving local media capture.
170
+ * Used during signaling reconnect restore so camera/mic intent survives.
171
+ */
172
+ closeAllPeerConnections(): void;
168
173
  /**
169
174
  * Close all connections and clean up resources.
170
175
  */
@@ -182,6 +187,10 @@ export declare class WebRTCManager {
182
187
  * Get the actual RTCPeerConnectionState for a peer.
183
188
  */
184
189
  getConnectionState(peerId: string): RTCPeerConnectionState;
190
+ /**
191
+ * Get the primary message DataChannel state for a peer.
192
+ */
193
+ getDataChannelState(peerId: string): RTCDataChannelState | "closed";
185
194
  /**
186
195
  * Check if the main DataChannel is ready for a specific peer.
187
196
  */
@@ -193,6 +202,7 @@ export declare class WebRTCManager {
193
202
  private setupPeerConnection;
194
203
  private ensureDataChannel;
195
204
  private setupDataChannel;
205
+ private isCurrentDataChannel;
196
206
  private handleMessageChannelMessage;
197
207
  private handleFileControlMessage;
198
208
  private handleFileChunk;
@@ -336,12 +336,19 @@ class WebRTCManager {
336
336
  this.iceCandidateCallbacks.delete(peerId);
337
337
  }
338
338
  /**
339
- * Close all connections and clean up resources.
339
+ * Close all peer connections while preserving local media capture.
340
+ * Used during signaling reconnect restore so camera/mic intent survives.
340
341
  */
341
- closeAll() {
342
+ closeAllPeerConnections() {
342
343
  this.getActivePeers().forEach((peerId) => {
343
344
  this.closePeerConnection(peerId);
344
345
  });
346
+ }
347
+ /**
348
+ * Close all connections and clean up resources.
349
+ */
350
+ closeAll() {
351
+ this.closeAllPeerConnections();
345
352
  this.stopVoice();
346
353
  this.stopVideo();
347
354
  this.stopScreenShare();
@@ -373,6 +380,13 @@ class WebRTCManager {
373
380
  const pc = this.peerConnections.get(peerId);
374
381
  return pc?.connectionState ?? "closed";
375
382
  }
383
+ /**
384
+ * Get the primary message DataChannel state for a peer.
385
+ */
386
+ getDataChannelState(peerId) {
387
+ return ((0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId)).message
388
+ ?.readyState ?? "closed");
389
+ }
376
390
  /**
377
391
  * Check if the main DataChannel is ready for a specific peer.
378
392
  */
@@ -449,6 +463,9 @@ class WebRTCManager {
449
463
  }
450
464
  };
451
465
  dataChannel.onerror = (error) => {
466
+ if (!this.isCurrentDataChannel(peerId, kind, dataChannel)) {
467
+ return;
468
+ }
452
469
  this.emitError(new AvesError_1.AvesError({ message: `DataChannel error with ${peerId}: ${(0, messages_1.errorMessage)(error)}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
453
470
  const transfer = kind === "file"
454
471
  ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
@@ -465,6 +482,13 @@ class WebRTCManager {
465
482
  this.handleMessageChannelMessage(peerId, event.data);
466
483
  };
467
484
  }
485
+ isCurrentDataChannel(peerId, kind, dataChannel) {
486
+ if (!this.peerConnections.has(peerId)) {
487
+ return false;
488
+ }
489
+ const channels = (0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId));
490
+ return channels[kind] === dataChannel;
491
+ }
468
492
  handleMessageChannelMessage(peerId, rawData) {
469
493
  try {
470
494
  const message = JSON.parse(rawData);
@@ -47,6 +47,8 @@ export declare class MediaTrackManager {
47
47
  private createTransceiverSender;
48
48
  private syncLocalAudioTrack;
49
49
  private syncLocalVideoTrack;
50
+ private getOutgoingVideoTrack;
51
+ private getOutgoingVideoStream;
50
52
  private emitLocalAudioState;
51
53
  private emitLocalVideoState;
52
54
  private emitScreenShareState;
@@ -52,6 +52,7 @@ class MediaTrackManager {
52
52
  this.audioSenders.set(peerId, this.createTransceiverSender(pc, "audio"));
53
53
  this.videoSenders.set(peerId, this.createTransceiverSender(pc, "video"));
54
54
  void this.syncLocalAudioTrack(peerId);
55
+ void this.syncLocalVideoTrack(peerId);
55
56
  }
56
57
  async startVoice() {
57
58
  if (this.localAudioStream && this.localAudioTrack) {
@@ -351,24 +352,41 @@ class MediaTrackManager {
351
352
  if (!pc) {
352
353
  return;
353
354
  }
355
+ const outgoingTrack = this.getOutgoingVideoTrack();
354
356
  let sender = this.videoSenders.get(peerId) ?? null;
355
357
  if (sender && typeof sender.replaceTrack === "function") {
356
- await sender.replaceTrack(this.localVideoTrack);
358
+ await sender.replaceTrack(outgoingTrack);
357
359
  return;
358
360
  }
359
361
  const addTrackCapable = pc;
360
- if (this.localVideoTrack &&
362
+ if (outgoingTrack &&
361
363
  typeof addTrackCapable.addTrack === "function") {
362
- const stream = this.localVideoStream ??
364
+ const stream = this.getOutgoingVideoStream() ??
363
365
  (typeof MediaStream !== "undefined"
364
- ? new MediaStream([this.localVideoTrack])
366
+ ? new MediaStream([outgoingTrack])
365
367
  : undefined);
366
368
  sender = stream
367
- ? addTrackCapable.addTrack(this.localVideoTrack, stream)
368
- : addTrackCapable.addTrack(this.localVideoTrack);
369
+ ? addTrackCapable.addTrack(outgoingTrack, stream)
370
+ : addTrackCapable.addTrack(outgoingTrack);
369
371
  this.videoSenders.set(peerId, sender);
370
372
  }
371
373
  }
374
+ getOutgoingVideoTrack() {
375
+ if (this.screenShareActive &&
376
+ this.screenShareTrack &&
377
+ this.screenShareTrack.readyState === "live") {
378
+ return this.screenShareTrack;
379
+ }
380
+ return this.localVideoTrack;
381
+ }
382
+ getOutgoingVideoStream() {
383
+ if (this.screenShareActive &&
384
+ this.screenShareStream &&
385
+ this.screenShareTrack?.readyState === "live") {
386
+ return this.screenShareStream;
387
+ }
388
+ return this.localVideoStream;
389
+ }
372
390
  emitLocalAudioState() {
373
391
  const state = this.getLocalAudioState();
374
392
  this.localAudioStateCallbacks.forEach((callback) => callback(state));
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
2
  import { AvesError } from "./AvesError";
3
- import { AvesClientConfig, AvesMessage, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState } from "../types/types";
3
+ import { AvesClientConfig, AvesConnectionSnapshot, AvesMessage, AvesPeerSnapshot, AvesVideoConstraints, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, Participant, ScreenShareState, WaitForPeerOptions } from "../types/types";
4
4
  export type AvesClientEvents = {
5
5
  signalingStateChange: [state: string];
6
6
  error: [error: AvesError];
@@ -58,7 +58,10 @@ export declare class AvesClient extends EventEmitter<AvesClientEvents> {
58
58
  stopScreenShare(): void;
59
59
  getScreenShareState(): ScreenShareState;
60
60
  getConnectionState(peerId: string): RTCPeerConnectionState;
61
+ getConnectionSnapshot(): AvesConnectionSnapshot;
62
+ waitForPeer(peerId: string, options?: WaitForPeerOptions): Promise<AvesPeerSnapshot>;
61
63
  getParticipants(): Participant[];
64
+ private createPeerSnapshot;
62
65
  getCurrentUserId(): string | null;
63
66
  isConnected(): boolean;
64
67
  destroy(): void;
@@ -138,7 +138,7 @@ export class AvesClient extends EventEmitter {
138
138
  return;
139
139
  }
140
140
  try {
141
- this.webrtcManager.closeAll();
141
+ this.webrtcManager.closeAllPeerConnections();
142
142
  this.participants.clear();
143
143
  this.preparedPeers.clear();
144
144
  const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
@@ -296,9 +296,109 @@ export class AvesClient extends EventEmitter {
296
296
  getConnectionState(peerId) {
297
297
  return this.webrtcManager.getConnectionState(peerId);
298
298
  }
299
+ getConnectionSnapshot() {
300
+ const participants = this.getParticipants();
301
+ const participantById = new Map(participants.map((participant) => [participant.id, participant]));
302
+ const peerIds = new Set([
303
+ ...this.webrtcManager.getActivePeers(),
304
+ ...participants.map((participant) => participant.id),
305
+ ]);
306
+ if (this.currentUserId) {
307
+ peerIds.delete(this.currentUserId);
308
+ }
309
+ const peers = Array.from(peerIds).map((peerId) => this.createPeerSnapshot(peerId, participantById.get(peerId)));
310
+ return {
311
+ roomId: this.currentRoomId,
312
+ currentUserId: this.currentUserId,
313
+ signalingConnected: this.signalingClient.isConnected(),
314
+ participantCount: participants.length,
315
+ participants,
316
+ peers,
317
+ };
318
+ }
319
+ waitForPeer(peerId, options = {}) {
320
+ const timeoutMs = options.timeoutMs ?? 30000;
321
+ const getSnapshot = () => this.createPeerSnapshot(peerId, this.participants.get(peerId));
322
+ const isReady = () => {
323
+ const messageReady = this.webrtcManager.isDataChannelReady(peerId);
324
+ const fileReady = !options.requireFileChannel ||
325
+ this.webrtcManager.isFileChannelReady(peerId);
326
+ return messageReady && fileReady;
327
+ };
328
+ if (isReady()) {
329
+ return Promise.resolve(getSnapshot());
330
+ }
331
+ return new Promise((resolve, reject) => {
332
+ let timeoutId = null;
333
+ const cleanup = () => {
334
+ this.off("dataChannelStateChange", handleDataChannelStateChange);
335
+ this.off("connectionStateChange", handleConnectionStateChange);
336
+ if (timeoutId) {
337
+ clearTimeout(timeoutId);
338
+ timeoutId = null;
339
+ }
340
+ };
341
+ const resolveIfReady = () => {
342
+ if (!isReady()) {
343
+ return;
344
+ }
345
+ cleanup();
346
+ resolve(getSnapshot());
347
+ };
348
+ const handleDataChannelStateChange = (changedPeerId) => {
349
+ if (changedPeerId === peerId) {
350
+ resolveIfReady();
351
+ }
352
+ };
353
+ const handleConnectionStateChange = (changedPeerId, state) => {
354
+ if (changedPeerId !== peerId) {
355
+ return;
356
+ }
357
+ if (state === "failed" || state === "closed") {
358
+ cleanup();
359
+ reject(new AvesError({
360
+ message: `Peer ${peerId} connection ${state}`,
361
+ code: "WEBRTC_CONNECTION_FAILED",
362
+ stage: "transport",
363
+ retryable: state === "failed",
364
+ peerId,
365
+ }));
366
+ return;
367
+ }
368
+ resolveIfReady();
369
+ };
370
+ this.on("dataChannelStateChange", handleDataChannelStateChange);
371
+ this.on("connectionStateChange", handleConnectionStateChange);
372
+ timeoutId = setTimeout(() => {
373
+ cleanup();
374
+ reject(new AvesError({
375
+ message: `Timed out waiting for peer ${peerId}`,
376
+ code: "WEBRTC_CONNECTION_FAILED",
377
+ stage: "transport",
378
+ retryable: true,
379
+ peerId,
380
+ }));
381
+ }, timeoutMs);
382
+ resolveIfReady();
383
+ });
384
+ }
299
385
  getParticipants() {
300
386
  return Array.from(this.participants.values());
301
387
  }
388
+ createPeerSnapshot(peerId, participant) {
389
+ const messageChannelReady = this.webrtcManager.isDataChannelReady(peerId);
390
+ const fileChannelReady = this.webrtcManager.isFileChannelReady(peerId);
391
+ return {
392
+ peerId,
393
+ participant,
394
+ connectionState: this.webrtcManager.getConnectionState(peerId),
395
+ dataChannelState: messageChannelReady
396
+ ? "open"
397
+ : this.webrtcManager.getDataChannelState(peerId),
398
+ messageChannelReady,
399
+ fileChannelReady,
400
+ };
401
+ }
302
402
  getCurrentUserId() {
303
403
  return this.currentUserId;
304
404
  }
@@ -165,6 +165,11 @@ export declare class WebRTCManager {
165
165
  * Close the connection with a specific peer.
166
166
  */
167
167
  closePeerConnection(peerId: string): void;
168
+ /**
169
+ * Close all peer connections while preserving local media capture.
170
+ * Used during signaling reconnect restore so camera/mic intent survives.
171
+ */
172
+ closeAllPeerConnections(): void;
168
173
  /**
169
174
  * Close all connections and clean up resources.
170
175
  */
@@ -182,6 +187,10 @@ export declare class WebRTCManager {
182
187
  * Get the actual RTCPeerConnectionState for a peer.
183
188
  */
184
189
  getConnectionState(peerId: string): RTCPeerConnectionState;
190
+ /**
191
+ * Get the primary message DataChannel state for a peer.
192
+ */
193
+ getDataChannelState(peerId: string): RTCDataChannelState | "closed";
185
194
  /**
186
195
  * Check if the main DataChannel is ready for a specific peer.
187
196
  */
@@ -193,6 +202,7 @@ export declare class WebRTCManager {
193
202
  private setupPeerConnection;
194
203
  private ensureDataChannel;
195
204
  private setupDataChannel;
205
+ private isCurrentDataChannel;
196
206
  private handleMessageChannelMessage;
197
207
  private handleFileControlMessage;
198
208
  private handleFileChunk;
@@ -333,12 +333,19 @@ export class WebRTCManager {
333
333
  this.iceCandidateCallbacks.delete(peerId);
334
334
  }
335
335
  /**
336
- * Close all connections and clean up resources.
336
+ * Close all peer connections while preserving local media capture.
337
+ * Used during signaling reconnect restore so camera/mic intent survives.
337
338
  */
338
- closeAll() {
339
+ closeAllPeerConnections() {
339
340
  this.getActivePeers().forEach((peerId) => {
340
341
  this.closePeerConnection(peerId);
341
342
  });
343
+ }
344
+ /**
345
+ * Close all connections and clean up resources.
346
+ */
347
+ closeAll() {
348
+ this.closeAllPeerConnections();
342
349
  this.stopVoice();
343
350
  this.stopVideo();
344
351
  this.stopScreenShare();
@@ -370,6 +377,13 @@ export class WebRTCManager {
370
377
  const pc = this.peerConnections.get(peerId);
371
378
  return pc?.connectionState ?? "closed";
372
379
  }
380
+ /**
381
+ * Get the primary message DataChannel state for a peer.
382
+ */
383
+ getDataChannelState(peerId) {
384
+ return (normalizePeerChannels(this.dataChannels.get(peerId)).message
385
+ ?.readyState ?? "closed");
386
+ }
373
387
  /**
374
388
  * Check if the main DataChannel is ready for a specific peer.
375
389
  */
@@ -446,6 +460,9 @@ export class WebRTCManager {
446
460
  }
447
461
  };
448
462
  dataChannel.onerror = (error) => {
463
+ if (!this.isCurrentDataChannel(peerId, kind, dataChannel)) {
464
+ return;
465
+ }
449
466
  this.emitError(new AvesError({ message: `DataChannel error with ${peerId}: ${errorMessage(error)}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
450
467
  const transfer = kind === "file"
451
468
  ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
@@ -462,6 +479,13 @@ export class WebRTCManager {
462
479
  this.handleMessageChannelMessage(peerId, event.data);
463
480
  };
464
481
  }
482
+ isCurrentDataChannel(peerId, kind, dataChannel) {
483
+ if (!this.peerConnections.has(peerId)) {
484
+ return false;
485
+ }
486
+ const channels = normalizePeerChannels(this.dataChannels.get(peerId));
487
+ return channels[kind] === dataChannel;
488
+ }
465
489
  handleMessageChannelMessage(peerId, rawData) {
466
490
  try {
467
491
  const message = JSON.parse(rawData);
@@ -47,6 +47,8 @@ export declare class MediaTrackManager {
47
47
  private createTransceiverSender;
48
48
  private syncLocalAudioTrack;
49
49
  private syncLocalVideoTrack;
50
+ private getOutgoingVideoTrack;
51
+ private getOutgoingVideoStream;
50
52
  private emitLocalAudioState;
51
53
  private emitLocalVideoState;
52
54
  private emitScreenShareState;
@@ -49,6 +49,7 @@ export class MediaTrackManager {
49
49
  this.audioSenders.set(peerId, this.createTransceiverSender(pc, "audio"));
50
50
  this.videoSenders.set(peerId, this.createTransceiverSender(pc, "video"));
51
51
  void this.syncLocalAudioTrack(peerId);
52
+ void this.syncLocalVideoTrack(peerId);
52
53
  }
53
54
  async startVoice() {
54
55
  if (this.localAudioStream && this.localAudioTrack) {
@@ -348,24 +349,41 @@ export class MediaTrackManager {
348
349
  if (!pc) {
349
350
  return;
350
351
  }
352
+ const outgoingTrack = this.getOutgoingVideoTrack();
351
353
  let sender = this.videoSenders.get(peerId) ?? null;
352
354
  if (sender && typeof sender.replaceTrack === "function") {
353
- await sender.replaceTrack(this.localVideoTrack);
355
+ await sender.replaceTrack(outgoingTrack);
354
356
  return;
355
357
  }
356
358
  const addTrackCapable = pc;
357
- if (this.localVideoTrack &&
359
+ if (outgoingTrack &&
358
360
  typeof addTrackCapable.addTrack === "function") {
359
- const stream = this.localVideoStream ??
361
+ const stream = this.getOutgoingVideoStream() ??
360
362
  (typeof MediaStream !== "undefined"
361
- ? new MediaStream([this.localVideoTrack])
363
+ ? new MediaStream([outgoingTrack])
362
364
  : undefined);
363
365
  sender = stream
364
- ? addTrackCapable.addTrack(this.localVideoTrack, stream)
365
- : addTrackCapable.addTrack(this.localVideoTrack);
366
+ ? addTrackCapable.addTrack(outgoingTrack, stream)
367
+ : addTrackCapable.addTrack(outgoingTrack);
366
368
  this.videoSenders.set(peerId, sender);
367
369
  }
368
370
  }
371
+ getOutgoingVideoTrack() {
372
+ if (this.screenShareActive &&
373
+ this.screenShareTrack &&
374
+ this.screenShareTrack.readyState === "live") {
375
+ return this.screenShareTrack;
376
+ }
377
+ return this.localVideoTrack;
378
+ }
379
+ getOutgoingVideoStream() {
380
+ if (this.screenShareActive &&
381
+ this.screenShareStream &&
382
+ this.screenShareTrack?.readyState === "live") {
383
+ return this.screenShareStream;
384
+ }
385
+ return this.localVideoStream;
386
+ }
369
387
  emitLocalAudioState() {
370
388
  const state = this.getLocalAudioState();
371
389
  this.localAudioStateCallbacks.forEach((callback) => callback(state));
@@ -10,4 +10,4 @@ export type { AvesErrorCode } from "./core/AvesError";
10
10
  export { EventEmitter } from "./core/EventEmitter";
11
11
  export { WebRTCManager } from "./core/WebRTCManager";
12
12
  export { SignalingClient } from "./core/SignalingClient";
13
- export type { Participant, AvesMessage, AvesClientConfig, AvesVideoConstraints, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, } from "./types/types";
13
+ export type { Participant, AvesMessage, AvesClientConfig, AvesConnectionSnapshot, AvesPeerSnapshot, AvesVideoConstraints, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, WaitForPeerOptions, } from "./types/types";
@@ -33,6 +33,26 @@ export interface AvesClientConfig {
33
33
  };
34
34
  debug?: boolean;
35
35
  }
36
+ export interface AvesPeerSnapshot {
37
+ peerId: string;
38
+ participant?: Participant;
39
+ connectionState: RTCPeerConnectionState;
40
+ dataChannelState: RTCDataChannelState | "closed";
41
+ messageChannelReady: boolean;
42
+ fileChannelReady: boolean;
43
+ }
44
+ export interface AvesConnectionSnapshot {
45
+ roomId: string | null;
46
+ currentUserId: string | null;
47
+ signalingConnected: boolean;
48
+ participantCount: number;
49
+ participants: Participant[];
50
+ peers: AvesPeerSnapshot[];
51
+ }
52
+ export interface WaitForPeerOptions {
53
+ timeoutMs?: number;
54
+ requireFileChannel?: boolean;
55
+ }
36
56
  export interface FileTransferOptions {
37
57
  peerId?: string;
38
58
  fileName?: string;
package/dist/index.d.ts CHANGED
@@ -10,4 +10,4 @@ export type { AvesErrorCode } from "./core/AvesError";
10
10
  export { EventEmitter } from "./core/EventEmitter";
11
11
  export { WebRTCManager } from "./core/WebRTCManager";
12
12
  export { SignalingClient } from "./core/SignalingClient";
13
- export type { Participant, AvesMessage, AvesClientConfig, AvesVideoConstraints, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, } from "./types/types";
13
+ export type { Participant, AvesMessage, AvesClientConfig, AvesConnectionSnapshot, AvesPeerSnapshot, AvesVideoConstraints, FileTransferOptions, FileTransferInfo, FileTransferProgress, FileTransferResult, LocalAudioState, LocalVideoState, ScreenShareState, ScreenShareSource, JsonObject, JsonPrimitive, JsonValue, SignalingMessage, SignalingErrorCode, SignalingErrorStage, SignalingErrorPayload, JoinRoomResult, ReconnectConfig, WaitForPeerOptions, } from "./types/types";
@@ -33,6 +33,26 @@ export interface AvesClientConfig {
33
33
  };
34
34
  debug?: boolean;
35
35
  }
36
+ export interface AvesPeerSnapshot {
37
+ peerId: string;
38
+ participant?: Participant;
39
+ connectionState: RTCPeerConnectionState;
40
+ dataChannelState: RTCDataChannelState | "closed";
41
+ messageChannelReady: boolean;
42
+ fileChannelReady: boolean;
43
+ }
44
+ export interface AvesConnectionSnapshot {
45
+ roomId: string | null;
46
+ currentUserId: string | null;
47
+ signalingConnected: boolean;
48
+ participantCount: number;
49
+ participants: Participant[];
50
+ peers: AvesPeerSnapshot[];
51
+ }
52
+ export interface WaitForPeerOptions {
53
+ timeoutMs?: number;
54
+ requireFileChannel?: boolean;
55
+ }
36
56
  export interface FileTransferOptions {
37
57
  peerId?: string;
38
58
  fileName?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yrzhao/aves-core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "WebRTC client library for real-time communication",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.js",
@@ -25,7 +25,6 @@
25
25
  "test:watch": "jest --watch",
26
26
  "test:coverage": "jest --coverage"
27
27
  },
28
- "peerDependencies": {},
29
28
  "devDependencies": {
30
29
  "@types/jest": "^29.5.0",
31
30
  "@types/node": "^20.0.0",
@@ -40,6 +39,21 @@
40
39
  "communication",
41
40
  "peer-to-peer"
42
41
  ],
43
- "author": "",
44
- "license": "MIT"
42
+ "author": "Yrzhao",
43
+ "license": "MIT",
44
+ "sideEffects": false,
45
+ "engines": {
46
+ "node": ">=18"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/yrzhao/aves.git"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/yrzhao/aves/issues"
57
+ },
58
+ "homepage": "https://github.com/yrzhao/aves#readme"
45
59
  }