@yrzhao/aves-core 0.1.0 → 0.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.
package/README.md CHANGED
@@ -1,419 +1,184 @@
1
1
  # Aves Core
2
2
 
3
- 一个轻量级的 WebRTC 客户端库,用于实时点对点通信。Aves Core 提供了简单的事件驱动 API,抽象了 WebRTC 的复杂性,让你专注于构建应用。
3
+ 一个轻量级的 WebRTC 客户端库,用于实时点对点通信。提供文件传输、语音通话和消息通信能力,基于全网状拓扑的 DataChannel 直连。
4
4
 
5
5
  ## 特性
6
6
 
7
- - 🚀 简单直观的 WebRTC 连接 API
8
- - 🔄 自动连接管理和重连机制
9
- - 📡 内置 WebSocket 信令客户端
10
- - 🎯 事件驱动的状态管理架构
11
- - 📦 完整的 TypeScript 类型定义支持
12
- - 🔌 基于房间的通信模型
13
- - 💬 DataChannel 消息传输,自动序列化
7
+ - 基于房间的通信模型,全网状 P2P 拓扑
8
+ - 文本消息广播与单播(DataChannel 直传,不经服务器)
9
+ - 文件传输:分块二进制传输,握手协议,进度追踪
10
+ - 实时语音:getUserMedia + RTP transceiver,静音控制
11
+ - 自动断线重连与会话恢复
12
+ - 内置 WebSocket 信令客户端,request/response 关联
13
+ - 事件驱动架构,完整 TypeScript 类型定义
14
+ - 零运行时依赖
14
15
 
15
16
  ## 安装
16
17
 
17
18
  ```bash
18
- npm install aves-core
19
+ npm install @yrzhao/aves-core
19
20
  ```
20
21
 
21
22
  ## 快速开始
22
23
 
23
24
  ```typescript
24
- import { AvesClient } from "aves-core";
25
+ import { AvesClient } from "@yrzhao/aves-core";
25
26
 
26
- // 创建客户端实例
27
27
  const client = new AvesClient({
28
- signalingUrl: "ws://localhost:3000",
28
+ signalingUrl: "ws://localhost:8080",
29
29
  });
30
30
 
31
- // 监听消息
31
+ // 监听事件
32
32
  client.on("message", (peerId, message) => {
33
- console.log(`收到来自 ${peerId} 的消息:`, message);
33
+ console.log(`来自 ${peerId}:`, message);
34
34
  });
35
35
 
36
- // 监听用户加入
37
36
  client.on("userJoined", (participant) => {
38
37
  console.log(`${participant.name} 加入了房间`);
39
38
  });
40
39
 
41
- // 创建房间
40
+ // 创建并加入房间
42
41
  const roomId = await client.createRoom();
43
- console.log("房间已创建:", roomId);
42
+ const participants = await client.joinRoom(roomId, "Alice");
44
43
 
45
- // 加入房间
46
- const participants = await client.joinRoom(roomId, "user-123", "Alice");
47
- console.log("已加入房间,当前参与者:", participants);
48
-
49
- // 向所有对等端发送消息
44
+ // 发送消息
50
45
  client.sendMessage({ text: "大家好!" });
51
46
 
52
- // 向特定对等端发送消息
53
- client.sendMessageToPeer("peer-id", { text: "你好!" });
54
-
55
47
  // 离开房间
56
48
  await client.leaveRoom();
57
49
  ```
58
50
 
59
- ## 配置
60
-
61
- ### AvesClientConfig
62
-
63
- ```typescript
64
- interface AvesClientConfig {
65
- signalingUrl: string; // 信令服务器的 WebSocket URL(必需)
66
- iceServers?: RTCIceServer[]; // STUN/TURN 服务器(可选)
67
- reconnect?: {
68
- // 重连设置(可选)
69
- maxAttempts?: number; // 最大重连次数(默认:5)
70
- delay?: number; // 重连延迟(毫秒,默认:1000)
71
- };
72
- debug?: boolean; // 启用调试日志(默认:false)
73
- }
74
- ```
75
-
76
- ### 默认配置
77
-
78
- 如果未指定,Aves Core 使用以下默认值:
79
-
80
- ```typescript
81
- {
82
- iceServers: [
83
- { urls: 'stun:stun.l.google.com:19302' }
84
- ],
85
- reconnect: {
86
- maxAttempts: 5,
87
- delay: 1000
88
- },
89
- debug: false
90
- }
91
- ```
92
-
93
- ## API 参考
94
-
95
- ### AvesClient
96
-
97
- 管理 WebRTC 连接的主类。
98
-
99
- #### 构造函数
100
-
101
- ```typescript
102
- new AvesClient(config: AvesClientConfig)
103
- ```
104
-
105
- 使用指定配置创建新的 AvesClient 实例。
106
-
107
- #### 方法
108
-
109
- ##### 房间管理
110
-
111
- **`createRoom(): Promise<string>`**
112
-
113
- 创建新房间并返回房间 ID。
114
-
115
- ```typescript
116
- const roomId = await client.createRoom();
117
- ```
118
-
119
- **`joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>`**
120
-
121
- 加入现有房间并返回当前参与者列表。
122
-
123
- ```typescript
124
- const participants = await client.joinRoom("room-123", "user-456", "Bob");
125
- ```
126
-
127
- **`leaveRoom(): Promise<void>`**
128
-
129
- 离开当前房间并关闭所有对等连接。
130
-
131
- ```typescript
132
- await client.leaveRoom();
133
- ```
134
-
135
- ##### 消息传输
136
-
137
- **`sendMessage(message: any): void`**
138
-
139
- 向房间内所有已连接的对等端发送消息。
51
+ ## 文件传输
140
52
 
141
53
  ```typescript
142
- client.sendMessage({ type: "chat", text: "Hello!" });
143
- ```
144
-
145
- **`sendMessageToPeer(peerId: string, message: any): void`**
146
-
147
- 向特定对等端发送消息。
148
-
149
- ```typescript
150
- client.sendMessageToPeer("peer-123", { type: "private", text: "Hi there!" });
151
- ```
152
-
153
- ##### 状态查询
154
-
155
- **`getConnectionState(peerId: string): RTCPeerConnectionState`**
156
-
157
- 返回特定对等端的连接状态。
158
-
159
- ```typescript
160
- const state = client.getConnectionState("peer-123");
161
- // Returns: 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed'
162
- ```
163
-
164
- **`getParticipants(): Participant[]`**
165
-
166
- 返回当前房间内所有参与者的列表。
167
-
168
- ```typescript
169
- const participants = client.getParticipants();
170
- ```
171
-
172
- **`isConnected(): boolean`**
173
-
174
- 返回信令连接是否处于活动状态。
175
-
176
- ```typescript
177
- if (client.isConnected()) {
178
- console.log("已连接到信令服务器");
179
- }
180
- ```
181
-
182
- ##### 生命周期
183
-
184
- **`destroy(): void`**
185
-
186
- 销毁客户端,关闭所有连接并清理资源。
187
-
188
- ```typescript
189
- client.destroy();
190
- ```
191
-
192
- ## 事件
193
-
194
- Aves Core 使用事件驱动架构。使用 `on`、`off` 和 `once` 方法订阅事件。
54
+ import type { FileTransferProgress, FileTransferResult } from "@yrzhao/aves-core";
195
55
 
196
- ### 事件方法
56
+ // 发送文件(广播给所有对等端)
57
+ await client.sendFile(fileBlob, { name: "photo.jpg", size: fileBlob.size });
197
58
 
198
- **`on(event: string, callback: Function): this`**
59
+ // 发送文件给特定对等端
60
+ await client.sendFile(fileBlob, { name: "doc.pdf" }, "peer-123");
199
61
 
200
- 注册事件监听器。
201
-
202
- ```typescript
203
- client.on("message", (peerId, message) => {
204
- console.log("收到消息:", message);
62
+ // 监听传输进度
63
+ client.on("fileTransferProgress", (progress: FileTransferProgress) => {
64
+ console.log(`${progress.fileName}: ${progress.percent}%`);
205
65
  });
206
- ```
207
-
208
- **`off(event: string, callback: Function): this`**
209
-
210
- 移除事件监听器。
211
-
212
- ```typescript
213
- const handler = (peerId, message) => console.log(message);
214
- client.on("message", handler);
215
- client.off("message", handler);
216
- ```
217
-
218
- **`once(event: string, callback: Function): this`**
219
-
220
- 注册一次性事件监听器。
221
66
 
222
- ```typescript
223
- client.once("userJoined", (participant) => {
224
- console.log("第一个用户加入:", participant);
67
+ // 接收文件
68
+ client.on("fileTransferCompleted", (result: FileTransferResult) => {
69
+ // result.file: Blob, result.fileName: string
70
+ const url = URL.createObjectURL(result.file);
71
+ // 用于下载或显示
225
72
  });
226
73
  ```
227
74
 
228
- ### 可用事件
229
-
230
- #### `connectionStateChange`
231
-
232
- 当对等连接状态改变时触发。
233
-
234
- ```typescript
235
- client.on(
236
- "connectionStateChange",
237
- (peerId: string, state: RTCPeerConnectionState) => {
238
- console.log(`与 ${peerId} 的连接状态现在是 ${state}`);
239
- }
240
- );
241
- ```
242
-
243
- #### `dataChannelStateChange`
244
-
245
- 当数据通道状态改变时触发。
75
+ ## 语音通话
246
76
 
247
77
  ```typescript
248
- client.on(
249
- "dataChannelStateChange",
250
- (peerId: string, state: RTCDataChannelState) => {
251
- console.log(`与 ${peerId} 的数据通道状态现在是 ${state}`);
252
- }
253
- );
254
- ```
255
-
256
- #### `signalingStateChange`
78
+ // 开启语音(获取麦克风,发送给所有对等端)
79
+ await client.startVoice();
257
80
 
258
- 当信令连接状态改变时触发。
81
+ // 静音/取消静音
82
+ client.setMuted(true);
259
83
 
260
- ```typescript
261
- client.on(
262
- "signalingStateChange",
263
- (state: "connecting" | "connected" | "disconnected") => {
264
- console.log(`信令状态: ${state}`);
265
- }
266
- );
267
- ```
268
-
269
- #### `message`
270
-
271
- 当从对等端接收到消息时触发。
272
-
273
- ```typescript
274
- client.on("message", (peerId: string, message: any) => {
275
- console.log(`来自 ${peerId} 的消息:`, message);
276
- });
277
- ```
278
-
279
- #### `userJoined`
280
-
281
- 当新用户加入房间时触发。
282
-
283
- ```typescript
284
- client.on("userJoined", (participant: Participant) => {
285
- console.log(`${participant.name} 加入了`);
286
- });
287
- ```
288
-
289
- #### `userLeft`
290
-
291
- 当用户离开房间时触发。
292
-
293
- ```typescript
294
- client.on("userLeft", (userId: string) => {
295
- console.log(`用户 ${userId} 离开了`);
296
- });
297
- ```
84
+ // 获取本地音频状态
85
+ const state = client.getLocalAudioState();
86
+ // { active: boolean, muted: boolean }
298
87
 
299
- #### `error`
300
-
301
- 当发生错误时触发。
302
-
303
- ```typescript
304
- client.on("error", (error: Error) => {
305
- console.error("错误:", error.message);
306
- });
307
- ```
308
-
309
- ## 类型定义
310
-
311
- ### Participant
312
-
313
- ```typescript
314
- interface Participant {
315
- id: string; // 唯一用户 ID
316
- name: string; // 显示名称
88
+ // 获取远端音频流
89
+ const remoteStream = client.getRemoteAudioStream("peer-123");
90
+ if (remoteStream) {
91
+ const audio = new Audio();
92
+ audio.srcObject = remoteStream;
93
+ audio.play();
317
94
  }
318
- ```
319
95
 
320
- ### RTCPeerConnectionState
321
-
322
- ```typescript
323
- type RTCPeerConnectionState =
324
- | "new"
325
- | "connecting"
326
- | "connected"
327
- | "disconnected"
328
- | "failed"
329
- | "closed";
96
+ // 关闭语音
97
+ client.stopVoice();
330
98
  ```
331
99
 
332
- ### RTCDataChannelState
100
+ ## 配置
333
101
 
334
102
  ```typescript
335
- type RTCDataChannelState = "connecting" | "open" | "closing" | "closed";
103
+ interface AvesClientConfig {
104
+ signalingUrl: string; // 信令服务器 WebSocket URL(必需)
105
+ iceServers?: RTCIceServer[]; // STUN/TURN 服务器
106
+ reconnect?: {
107
+ maxAttempts?: number; // 最大重连次数(默认:5)
108
+ delay?: number; // 重连延迟 ms(默认:3000)
109
+ };
110
+ debug?: boolean; // 调试日志(默认:false)
111
+ }
336
112
  ```
337
113
 
338
- ## 高级用法
339
-
340
- ### 自定义 ICE 服务器
341
-
342
- 配置自定义 STUN/TURN 服务器以获得更好的连接性:
114
+ 默认值:
343
115
 
344
116
  ```typescript
345
- const client = new AvesClient({
346
- signalingUrl: "ws://localhost:3000",
347
- iceServers: [
348
- { urls: "stun:stun.l.google.com:19302" },
349
- {
350
- urls: "turn:turn.example.com:3478",
351
- username: "user",
352
- credential: "pass",
353
- },
354
- ],
355
- });
117
+ {
118
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
119
+ reconnect: { maxAttempts: 5, delay: 3000 },
120
+ debug: false
121
+ }
356
122
  ```
357
123
 
358
- ### 自定义重连策略
124
+ ## API 参考
359
125
 
360
- 调整重连行为:
126
+ ### 房间管理
361
127
 
362
- ```typescript
363
- const client = new AvesClient({
364
- signalingUrl: "ws://localhost:3000",
365
- reconnect: {
366
- maxAttempts: 10,
367
- delay: 2000,
368
- },
369
- });
370
- ```
128
+ | 方法 | 返回值 | 说明 |
129
+ |------|--------|------|
130
+ | `createRoom()` | `Promise<string>` | 创建房间,返回 roomId |
131
+ | `joinRoom(roomId, userName)` | `Promise<Participant[]>` | 加入房间 |
132
+ | `joinRoom(roomId, userId, userName)` | `Promise<Participant[]>` | 以指定 userId 加入 |
133
+ | `leaveRoom()` | `Promise<void>` | 离开房间,关闭所有连接 |
134
+ | `destroy()` | `void` | 销毁客户端,清理全部资源 |
371
135
 
372
- ### 调试模式
136
+ ### 消息
373
137
 
374
- 启用调试日志以进行故障排查:
138
+ | 方法 | 说明 |
139
+ |------|------|
140
+ | `sendMessage(message)` | 广播消息给所有对等端 |
141
+ | `sendMessageToPeer(peerId, message)` | 发送消息给特定对等端 |
375
142
 
376
- ```typescript
377
- const client = new AvesClient({
378
- signalingUrl: "ws://localhost:3000",
379
- debug: true,
380
- });
381
- ```
143
+ ### 文件与语音
382
144
 
383
- ## 错误处理
145
+ | 方法 | 说明 |
146
+ |------|------|
147
+ | `sendFile(blob, options, peerId?)` | 发送文件(广播或单播) |
148
+ | `startVoice()` | 开启语音 |
149
+ | `stopVoice()` | 关闭语音 |
150
+ | `setMuted(muted)` | 静音控制 |
151
+ | `getLocalAudioState()` | 获取本地音频状态 |
152
+ | `getRemoteAudioStream(peerId)` | 获取远端音频 MediaStream |
384
153
 
385
- Aves Core 提供全面的错误处理:
154
+ ### 状态查询
386
155
 
387
- ```typescript
388
- client.on("error", (error) => {
389
- if (error.message.includes("DataChannel not ready")) {
390
- console.log("等待连接建立...");
391
- } else if (error.message.includes("Room not found")) {
392
- console.log("房间不存在");
393
- } else {
394
- console.error("意外错误:", error);
395
- }
396
- });
156
+ | 方法 | 说明 |
157
+ |------|------|
158
+ | `getConnectionState(peerId)` | 对等连接状态 |
159
+ | `getParticipants()` | 当前房间参与者列表 |
160
+ | `isConnected()` | 信令连接是否活跃 |
397
161
 
398
- // 处理连接失败
399
- client.on("connectionStateChange", (peerId, state) => {
400
- if (state === "failed") {
401
- console.log(`与 ${peerId} 的连接失败`);
402
- }
403
- });
162
+ ## 事件
404
163
 
405
- // 处理信令断开
406
- client.on("signalingStateChange", (state) => {
407
- if (state === "disconnected") {
408
- console.log("信令连接丢失,正在尝试重连...");
409
- }
410
- });
411
- ```
164
+ | 事件 | 回调参数 | 说明 |
165
+ |------|----------|------|
166
+ | `message` | `(peerId, message)` | 收到对等端消息 |
167
+ | `userJoined` | `(participant)` | 用户加入 |
168
+ | `userLeft` | `(userId)` | 用户离开 |
169
+ | `connectionStateChange` | `(peerId, state)` | 对等连接状态变化 |
170
+ | `dataChannelStateChange` | `(peerId, state)` | 数据通道状态变化 |
171
+ | `signalingStateChange` | `(state)` | 信令连接状态变化 |
172
+ | `remoteAudioTrack` | `(peerId, stream)` | 收到远端音频流 |
173
+ | `localAudioStateChange` | `(state)` | 本地音频状态变化 |
174
+ | `fileTransferStarted` | `(info)` | 文件传输开始 |
175
+ | `fileTransferProgress` | `(progress)` | 文件传输进度 |
176
+ | `fileTransferCompleted` | `(result)` | 文件传输完成 |
177
+ | `fileTransferFailed` | `(error)` | 文件传输失败 |
178
+ | `error` | `(error)` | 错误 |
412
179
 
413
180
  ## 浏览器兼容性
414
181
 
415
- Aves Core 支持所有支持 WebRTC 的现代浏览器:
416
-
417
182
  - Chrome/Edge 56+
418
183
  - Firefox 44+
419
184
  - Safari 11+
@@ -425,4 +190,4 @@ MIT
425
190
 
426
191
  ## 相关包
427
192
 
428
- - [aves-node](https://www.npmjs.com/package/aves-node) - Aves Core 的信令服务器
193
+ - [@yrzhao/aves-node](https://www.npmjs.com/package/@yrzhao/aves-node) - 信令服务器
@@ -1,17 +1,7 @@
1
1
  import { EventEmitter } from "./EventEmitter";
2
- import { AvesClientConfig, Participant } from "../types/types";
2
+ import { AvesClientConfig, FileTransferInfo, FileTransferOptions, LocalAudioState, Participant } from "../types/types";
3
3
  /**
4
- * AvesClient - Main client class for WebRTC communication
5
- *
6
- * This class coordinates WebRTCManager and SignalingClient to provide
7
- * a simple API for WebRTC-based real-time communication.
8
- *
9
- * Features:
10
- * - Room management (create, join, leave)
11
- * - Automatic WebRTC connection establishment
12
- * - Message sending and receiving
13
- * - Connection state monitoring
14
- * - Automatic reconnection
4
+ * AvesClient - Main client class for WebRTC communication.
15
5
  */
16
6
  export declare class AvesClient extends EventEmitter {
17
7
  private config;
@@ -19,66 +9,30 @@ export declare class AvesClient extends EventEmitter {
19
9
  private signalingClient;
20
10
  private currentRoomId;
21
11
  private currentUserId;
12
+ private currentUserName;
22
13
  private participants;
14
+ private preparedPeers;
15
+ private shouldRestoreSession;
23
16
  constructor(config: AvesClientConfig);
24
- /**
25
- * Setup event handlers to coordinate between components
26
- */
27
17
  private setupEventHandlers;
28
- /**
29
- * Initiate a WebRTC connection with a peer (as offerer)
30
- */
18
+ private restoreRoomSession;
19
+ private preparePeerConnection;
31
20
  private initiateConnection;
32
- /**
33
- * Create a new room
34
- * @returns Promise that resolves with the room ID
35
- */
36
21
  createRoom(): Promise<string>;
37
- /**
38
- * Join an existing room
39
- * @param roomId - Room ID to join
40
- * @param userId - User ID
41
- * @param userName - User name
42
- * @returns Promise that resolves with the list of current participants
43
- */
22
+ joinRoom(roomId: string, userName: string): Promise<Participant[]>;
44
23
  joinRoom(roomId: string, userId: string, userName: string): Promise<Participant[]>;
45
- /**
46
- * Leave the current room
47
- * Disconnects from signaling server and closes all WebRTC connections
48
- */
49
24
  leaveRoom(): Promise<void>;
50
- /**
51
- * Send a message to all connected peers
52
- * @param message - Message to send (will be JSON serialized)
53
- * @throws Error if any DataChannel is not ready
54
- */
55
25
  sendMessage(message: any): void;
56
- /**
57
- * Send a message to a specific peer
58
- * @param peerId - Target peer ID
59
- * @param message - Message to send (will be JSON serialized)
60
- * @throws Error if DataChannel is not ready
61
- */
62
26
  sendMessageToPeer(peerId: string, message: any): void;
63
- /**
64
- * Get the connection state for a specific peer
65
- * @param peerId - Peer ID
66
- * @returns Connection state or 'closed' if peer not found
67
- */
27
+ sendFile(blob: Blob, options?: FileTransferOptions): Promise<FileTransferInfo[]>;
28
+ startVoice(): Promise<MediaStream>;
29
+ stopVoice(): void;
30
+ setMuted(muted: boolean): void;
31
+ getLocalAudioState(): LocalAudioState;
32
+ getRemoteAudioStream(peerId: string): MediaStream | null;
68
33
  getConnectionState(peerId: string): RTCPeerConnectionState;
69
- /**
70
- * Get the list of current participants in the room
71
- * @returns Array of participants
72
- */
73
34
  getParticipants(): Participant[];
74
- /**
75
- * Check if connected to the signaling server
76
- * @returns true if connected, false otherwise
77
- */
35
+ getCurrentUserId(): string | null;
78
36
  isConnected(): boolean;
79
- /**
80
- * Destroy the client and clean up all resources
81
- * Closes all connections and removes all event listeners
82
- */
83
37
  destroy(): void;
84
38
  }