@yrzhao/aves-core 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +131 -75
  2. package/dist/core/AvesClient.d.ts +35 -8
  3. package/dist/core/AvesClient.js +351 -52
  4. package/dist/core/AvesError.d.ts +1 -1
  5. package/dist/core/EventEmitter.d.ts +8 -16
  6. package/dist/core/EventEmitter.js +41 -10
  7. package/dist/core/SignalingClient.d.ts +39 -44
  8. package/dist/core/SignalingClient.js +434 -78
  9. package/dist/core/WebRTCManager.d.ts +68 -99
  10. package/dist/core/WebRTCManager.js +611 -133
  11. package/dist/core/webrtc/channels.d.ts +6 -0
  12. package/dist/core/webrtc/channels.js +15 -0
  13. package/dist/core/webrtc/fileTransfer.d.ts +46 -3
  14. package/dist/core/webrtc/fileTransfer.js +725 -78
  15. package/dist/core/webrtc/mediaTracks.d.ts +38 -5
  16. package/dist/core/webrtc/mediaTracks.js +269 -58
  17. package/dist/esm/core/AvesClient.d.ts +35 -8
  18. package/dist/esm/core/AvesClient.js +351 -52
  19. package/dist/esm/core/AvesError.d.ts +1 -1
  20. package/dist/esm/core/EventEmitter.d.ts +8 -16
  21. package/dist/esm/core/EventEmitter.js +41 -10
  22. package/dist/esm/core/SignalingClient.d.ts +39 -44
  23. package/dist/esm/core/SignalingClient.js +434 -78
  24. package/dist/esm/core/WebRTCManager.d.ts +68 -99
  25. package/dist/esm/core/WebRTCManager.js +612 -134
  26. package/dist/esm/core/webrtc/channels.d.ts +6 -0
  27. package/dist/esm/core/webrtc/channels.js +14 -0
  28. package/dist/esm/core/webrtc/fileTransfer.d.ts +46 -3
  29. package/dist/esm/core/webrtc/fileTransfer.js +722 -77
  30. package/dist/esm/core/webrtc/mediaTracks.d.ts +38 -5
  31. package/dist/esm/core/webrtc/mediaTracks.js +269 -58
  32. package/dist/esm/index.d.ts +2 -1
  33. package/dist/esm/types/types.d.ts +126 -9
  34. package/dist/index.d.ts +2 -1
  35. package/dist/types/types.d.ts +126 -9
  36. package/package.json +22 -6
package/README.md CHANGED
@@ -1,125 +1,181 @@
1
1
  # Aves Core
2
2
 
3
- 轻量级 WebRTC 客户端库,零运行时依赖。支持消息、文件传输、语音、视频、屏幕共享,基于全网状 P2P 拓扑直连。
3
+ Production-grade browser WebRTC client library for peer-to-peer rooms. `@yrzhao/aves-core` connects to an `@yrzhao/aves-node` signaling server, builds a full-mesh WebRTC topology with Perfect Negotiation, ICE candidate buffering, backpressured file transfer with SHA-256 verification, voice/video/screen sharing, RTCStats observability, and resilient reconnection.
4
4
 
5
- 版本:`0.3.0`
5
+ Version: `1.2.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
+ authToken: "optional-jwt-token",
21
+ iceServers: [
22
+ { urls: "stun:stun.l.google.com:19302" },
23
+ {
24
+ urls: "turn:turn.example.com:3478",
25
+ username: "turn-user",
26
+ credential: "turn-password",
27
+ },
28
+ ],
29
+ heartbeatIntervalMs: 25_000,
30
+ iceDisconnectGraceMs: 5_000,
31
+ });
32
+
33
+ client.on("message", (peerId, message) => {
34
+ console.log("message from", peerId, message);
35
+ });
19
36
 
20
- client.on("message", (peerId, message) => console.log(`${peerId}:`, message));
21
- client.on("userJoined", (p) => console.log(`${p.name} 加入了`));
37
+ client.on("error", (error) => {
38
+ console.error(error.code, error.stage, error.message);
39
+ });
22
40
 
23
- const roomId = await client.createRoom();
24
- await client.joinRoom(roomId, "Alice");
41
+ const roomId = await client.createRoom({
42
+ name: "Team Sync",
43
+ maxCapacity: 6,
44
+ password: "room-secret",
45
+ });
25
46
 
26
- client.sendMessage({ text: "大家好!" });
27
- await client.leaveRoom();
47
+ await client.joinRoom(roomId, "Alice", { password: "room-secret" });
48
+
49
+ await client.waitForPeer("peer-user-id", { requireFileChannel: true });
50
+ client.sendMessage({ text: "hello" });
28
51
  ```
29
52
 
30
- ## 核心 API
53
+ ## Key Capabilities
54
+
55
+ - **Perfect Negotiation & Unified Plan**: Polite/impolite glare resolution, dynamic `onnegotiationneeded` renegotiation, and answer-side transceiver binding without orphan m-lines.
56
+ - **ICE Resilience**: Early ICE candidate queue buffering (flushed once `remoteDescription` is applied), transient `disconnected` grace window with automatic ICE restart, and dynamic `updateIceServers()` for ephemeral TURN credential rotation.
57
+ - **Reliable File Transfer**: DataChannel `bufferedAmount` backpressure flow control, configurable `maxReceiveFileSize`, incoming transfer accept/reject hook (`onIncomingTransfer`), byte-count and SHA-256 integrity checks, parallel multi-peer broadcast, and `cancelFileTransfer()`.
58
+ - **Media & Devices**: Voice (with echoCancellation/noiseSuppression constraints), camera video, screen sharing (with optional system audio), live `switchAudioDevice()` / `switchVideoDevice()`, and `remoteTrackEnded` cleanup events.
59
+ - **Observability**: Synchronous `getConnectionSnapshot()` plus async `getPeerStats()` / `getAllPeerStats()` wrapping `RTCPeerConnection.getStats()` (RTT, packet loss, bytes, candidate pair type).
60
+ - **Resilient Signaling**: Exponential backoff with jitter, optional token auth handshake, and optional application heartbeat (`ping` / `pong`).
61
+
62
+ ## Core API
31
63
 
32
- ### 房间管理
64
+ ### Rooms
33
65
 
34
- | 方法 | 返回 | 说明 |
35
- |------|------|------|
36
- | `createRoom()` | `Promise<string>` | 创建房间 |
37
- | `joinRoom(roomId, name)` | `Promise<Participant[]>` | 加入房间 |
38
- | `leaveRoom()` | `Promise<void>` | 离开 |
39
- | `destroy()` | `void` | 销毁客户端 |
66
+ ```ts
67
+ const roomId = await client.createRoom({ name: "Standup", maxCapacity: 5, password: "secret" });
68
+ const existingParticipants = await client.joinRoom(roomId, "Alice", { password: "secret" });
69
+ await client.leaveRoom();
70
+ client.destroy();
71
+ ```
40
72
 
41
- ### 消息
73
+ ### Messages
42
74
 
43
- ```typescript
44
- client.sendMessage({ text: "hi" }); // 广播
45
- client.sendMessageToPeer(peerId, { text: "hi" }); // 单播
75
+ ```ts
76
+ client.sendMessage({ kind: "chat", text: "hello" });
77
+ client.sendMessageToPeer(peerId, { kind: "private", text: "hi" });
46
78
  ```
47
79
 
48
- ### 文件传输
80
+ ### Peer Readiness, Stats & TURN Rotation
81
+
82
+ ```ts
83
+ await client.waitForPeer(peerId, { timeoutMs: 10_000, requireFileChannel: true });
49
84
 
50
- ```typescript
51
- // 发送(广播)
52
- await client.sendFile(fileBlob, { fileName: "photo.jpg" });
85
+ const snapshot = client.getConnectionSnapshot();
86
+ const stats = await client.getPeerStats(peerId);
87
+ client.updateIceServers(freshTurnServers);
88
+ ```
53
89
 
54
- // 发送(单播)
55
- await client.sendFile(fileBlob, { fileName: "doc.pdf", peerId: targetId });
90
+ ### Files
56
91
 
57
- // 监听
58
- client.on("fileTransferProgress", (p, pgr) => {
59
- console.log(`${p}: ${Math.round(pgr.progress * 100)}%`);
92
+ ```ts
93
+ await client.sendFile(file, {
94
+ fileName: file.name,
95
+ mimeType: file.type || "application/octet-stream",
60
96
  });
61
- client.on("fileTransferCompleted", (_, result) => {
62
- const url = URL.createObjectURL(result.blob);
97
+
98
+ client.on("fileTransferProgress", (_peerId, progress) => {
99
+ // progress.progress is already a percentage in the range 0..100
100
+ console.log(`${Math.round(progress.progress)}%`);
63
101
  });
102
+
103
+ client.cancelFileTransfer(peerId);
64
104
  ```
65
105
 
66
- ### 语音
106
+ ### Media
67
107
 
68
- ```typescript
69
- await client.startVoice();
108
+ ```ts
109
+ await client.startVoice({ echoCancellation: true, noiseSuppression: true });
110
+ await client.switchAudioDevice("mic-device-id");
70
111
  client.setMuted(true);
71
112
  client.stopVoice();
72
- ```
73
-
74
- ### 视频
75
113
 
76
- ```typescript
77
114
  await client.startVideo({ width: 1280, height: 720, frameRate: 30 });
115
+ await client.switchVideoDevice("camera-device-id");
78
116
  client.setVideoMuted(true);
79
117
  client.stopVideo();
80
- ```
81
118
 
82
- ### 屏幕共享
83
-
84
- ```typescript
85
- await client.startScreenShare(); // 自动恢复摄像头
119
+ await client.startScreenShare({ audio: true });
86
120
  client.stopScreenShare();
87
121
  ```
88
122
 
89
- ## 配置
123
+ ## Configuration
90
124
 
91
- ```typescript
125
+ ```ts
92
126
  new AvesClient({
93
- signalingUrl: "ws://localhost:8080", // 必需
127
+ signalingUrl: "wss://signal.example.com",
128
+ authToken: "optional-jwt-token",
94
129
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
95
- fileChunkSize: 65536,
96
- reconnect: { maxAttempts: 5, delay: 3000, requestTimeoutMs: 30000 },
130
+ rtcConfiguration: { iceTransportPolicy: "all", bundlePolicy: "max-bundle" },
131
+ heartbeatIntervalMs: 25_000,
132
+ heartbeatTimeoutMs: 10_000,
133
+ iceDisconnectGraceMs: 5_000,
134
+ fileChunkSize: 16 * 1024,
135
+ fileTransfer: {
136
+ maxReceiveFileSize: 100 * 1024 * 1024,
137
+ highWaterMark: 256 * 1024,
138
+ lowWaterMark: 64 * 1024,
139
+ verifyChecksum: true,
140
+ onIncomingTransfer: (_peerId, info) => info.size <= 50 * 1024 * 1024,
141
+ },
142
+ audio: { echoCancellation: true, noiseSuppression: true },
143
+ video: { width: 1280, height: 720, frameRate: 30 },
144
+ reconnect: {
145
+ maxAttempts: 5,
146
+ delay: 3000,
147
+ maxDelay: 30000,
148
+ backoffFactor: 2,
149
+ jitter: true,
150
+ requestTimeoutMs: 30000,
151
+ },
97
152
  debug: false,
98
153
  });
99
154
  ```
100
155
 
101
- ## 事件
102
-
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)` | 错误 |
114
-
115
- ## 浏览器兼容性
116
-
117
- Chrome/Edge 56+、Firefox 44+、Safari 11+、Opera 43+
118
-
119
- ## 发布信息
120
-
121
- - 包大小:~30 KiB gzip
122
- - 全网状拓扑:O(n) 连接数
123
- - 零运行时依赖
156
+ ## Events
157
+
158
+ | Event | Arguments |
159
+ | --- | --- |
160
+ | `signalingStateChange` | `(state)` |
161
+ | `userJoined` | `(participant)` |
162
+ | `userLeft` | `(userId)` |
163
+ | `connectionStateChange` | `(peerId, state)` |
164
+ | `dataChannelStateChange` | `(peerId, state)` |
165
+ | `fileChannelStateChange` | `(peerId, state)` |
166
+ | `message` | `(peerId, message)` |
167
+ | `remoteAudioTrack` / `remoteVideoTrack` | `(peerId, stream, track)` |
168
+ | `remoteTrackEnded` | `(peerId, kind, track)` |
169
+ | `localAudioStateChange` / `localVideoStateChange` | `(state)` |
170
+ | `screenShareStateChange` | `(state)` |
171
+ | `fileTransferStarted` / `fileTransferProgress` / `fileTransferCompleted` / `fileTransferFailed` | transfer lifecycle payloads |
172
+ | `error` | `(AvesError)` |
173
+
174
+ ## Production Notes
175
+
176
+ - Use HTTPS for the web app and WSS for signaling.
177
+ - Configure TURN for restrictive NATs, enterprise networks, and mobile carriers; rotate short-lived credentials with `updateIceServers()`.
178
+ - Full mesh is best suited for small groups (typically 2–6 active video peers).
179
+ - See [API.md](docs/API.md), [FILE_PROTOCOL.md](docs/FILE_PROTOCOL.md), [PRODUCTION.md](docs/PRODUCTION.md), and [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md).
124
180
 
125
181
  MIT
@@ -1,16 +1,20 @@
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 { AvesAudioConstraints, AvesClientConfig, AvesConnectionSnapshot, AvesMessage, AvesPeerSnapshot, AvesPeerStats, AvesVideoConstraints, CreateRoomOptions, FileTransferInfo, FileTransferOptions, FileTransferProgress, FileTransferResult, JoinRoomOptions, LocalAudioState, LocalVideoState, Participant, ScreenShareOptions, ScreenShareState, WaitForPeerOptions } from "../types/types";
4
4
  export type AvesClientEvents = {
5
5
  signalingStateChange: [state: string];
6
+ sessionRestored: [participants: Participant[]];
6
7
  error: [error: AvesError];
7
8
  userJoined: [user: Participant];
8
9
  userLeft: [userId: string];
9
10
  connectionStateChange: [peerId: string, state: RTCPeerConnectionState];
10
11
  dataChannelStateChange: [peerId: string, state: RTCDataChannelState];
12
+ fileChannelStateChange: [peerId: string, state: RTCDataChannelState];
11
13
  message: [peerId: string, message: AvesMessage];
12
14
  remoteAudioTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
13
15
  remoteVideoTrack: [peerId: string, stream: MediaStream, track: MediaStreamTrack];
16
+ remoteTrackEnded: [peerId: string, kind: "audio" | "video", track: MediaStreamTrack];
17
+ remoteTrackMuted: [peerId: string, kind: "audio" | "video", muted: boolean, track: MediaStreamTrack];
14
18
  localAudioStateChange: [state: LocalAudioState];
15
19
  localVideoStateChange: [state: LocalVideoState];
16
20
  screenShareStateChange: [state: ScreenShareState];
@@ -20,7 +24,7 @@ export type AvesClientEvents = {
20
24
  fileTransferFailed: [peerId: string, info: FileTransferInfo | null, error: AvesError];
21
25
  };
22
26
  /**
23
- * AvesClient - Main client class for WebRTC communication.
27
+ * AvesClient - Main browser WebRTC client for P2P rooms.
24
28
  */
25
29
  export declare class AvesClient extends EventEmitter<AvesClientEvents> {
26
30
  private config;
@@ -29,36 +33,59 @@ export declare class AvesClient extends EventEmitter<AvesClientEvents> {
29
33
  private currentRoomId;
30
34
  private currentUserId;
31
35
  private currentUserName;
36
+ private currentRoomPassword;
37
+ private currentReconnectToken;
32
38
  private participants;
33
- private preparedPeers;
39
+ private preparedPeerConnections;
34
40
  private shouldRestoreSession;
35
41
  constructor(config: AvesClientConfig);
42
+ private isPoliteForPeer;
36
43
  private setupEventHandlers;
37
44
  private restoreRoomSession;
38
45
  private preparePeerConnection;
39
46
  private initiateConnection;
40
- createRoom(): Promise<string>;
41
- joinRoom(roomId: string, userName: string): Promise<Participant[]>;
42
- joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
47
+ /**
48
+ * Update authentication token for subsequent signaling connections.
49
+ */
50
+ setAuthToken(token?: string): void;
51
+ /**
52
+ * Update ICE/TURN servers dynamically (e.g. rotating time-limited TURN credentials).
53
+ */
54
+ updateIceServers(iceServers: RTCIceServer[]): void;
55
+ /**
56
+ * Create a new room with optional name, capacity, and password.
57
+ */
58
+ createRoom(options?: CreateRoomOptions): Promise<string>;
59
+ joinRoom(roomId: string, userName: string, options?: JoinRoomOptions): Promise<Participant[]>;
60
+ joinRoom(roomId: string, userId: string, userName: string, password?: string): Promise<Participant[]>;
43
61
  leaveRoom(): Promise<void>;
44
62
  sendMessage(message: AvesMessage): void;
45
63
  sendMessageToPeer(peerId: string, message: AvesMessage): void;
46
64
  sendFile(blob: Blob, options?: FileTransferOptions): Promise<FileTransferInfo[]>;
47
- startVoice(): Promise<MediaStream>;
65
+ cancelFileTransfer(peerId: string, transferId?: string): boolean;
66
+ startVoice(constraints?: AvesAudioConstraints): Promise<MediaStream>;
67
+ switchAudioDevice(deviceId: string): Promise<MediaStream>;
48
68
  stopVoice(): void;
49
69
  setMuted(muted: boolean): void;
50
70
  getLocalAudioState(): LocalAudioState;
51
71
  getRemoteAudioStream(peerId: string): MediaStream | null;
52
72
  startVideo(constraints?: AvesVideoConstraints): Promise<MediaStream>;
73
+ switchVideoDevice(deviceId: string): Promise<MediaStream>;
53
74
  stopVideo(): void;
54
75
  setVideoMuted(muted: boolean): void;
55
76
  getLocalVideoState(): LocalVideoState;
56
77
  getRemoteVideoStream(peerId: string): MediaStream | null;
57
- startScreenShare(): Promise<MediaStream>;
78
+ startScreenShare(options?: ScreenShareOptions): Promise<MediaStream>;
58
79
  stopScreenShare(): void;
59
80
  getScreenShareState(): ScreenShareState;
60
81
  getConnectionState(peerId: string): RTCPeerConnectionState;
82
+ getPeerStats(peerId: string): Promise<AvesPeerStats | null>;
83
+ getAllPeerStats(): Promise<AvesPeerStats[]>;
84
+ restartPeerIce(peerId: string): Promise<void>;
85
+ getConnectionSnapshot(): AvesConnectionSnapshot;
86
+ waitForPeer(peerId: string, options?: WaitForPeerOptions): Promise<AvesPeerSnapshot>;
61
87
  getParticipants(): Participant[];
88
+ private createPeerSnapshot;
62
89
  getCurrentUserId(): string | null;
63
90
  isConnected(): boolean;
64
91
  destroy(): void;