@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
@@ -3,10 +3,31 @@ import { AvesError } from "./AvesError.js";
3
3
  function errorMessage(error) {
4
4
  return error instanceof Error ? error.message : String(error);
5
5
  }
6
+ function unrefTimer(timer) {
7
+ const maybeNodeTimer = timer;
8
+ maybeNodeTimer.unref?.();
9
+ }
6
10
  const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
11
+ const DEFAULT_MAX_RECONNECT_DELAY_MS = 30000;
12
+ const DEFAULT_BACKOFF_FACTOR = 2;
13
+ const DEFAULT_HEARTBEAT_TIMEOUT_MS = 10000;
14
+ const DEFAULT_MIN_STABLE_DURATION_MS = 10000;
15
+ const MIN_HEARTBEAT_INTERVAL_MS = 1000;
16
+ function isPlaintextRemoteWs(url) {
17
+ if (!url.startsWith("ws://")) {
18
+ return false;
19
+ }
20
+ try {
21
+ const host = new URL(url).hostname;
22
+ return host !== "localhost" && host !== "127.0.0.1" && host !== "::1";
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
7
28
  /**
8
- * SignalingClient manages WebSocket connection and signaling message exchange
9
- * Extends EventEmitter to provide event-driven communication
29
+ * SignalingClient manages WebSocket connection, optional token auth handshake,
30
+ * heartbeat liveness, exponential backoff reconnection, and signaling messages.
10
31
  */
11
32
  export class SignalingClient extends EventEmitter {
12
33
  constructor(reconnectConfig) {
@@ -14,8 +35,12 @@ export class SignalingClient extends EventEmitter {
14
35
  this.ws = null;
15
36
  this.reconnectAttempts = 0;
16
37
  this.reconnectTimer = null;
38
+ this.stableResetTimer = null;
39
+ this.heartbeatTimer = null;
40
+ this.heartbeatTimeoutTimer = null;
17
41
  this.url = "";
18
42
  this.shouldReconnect = true;
43
+ this.authenticated = false;
19
44
  this.pendingRequests = new Map();
20
45
  this.requestCounter = 0;
21
46
  this.reconnectConfig = reconnectConfig;
@@ -25,73 +50,337 @@ export class SignalingClient extends EventEmitter {
25
50
  : DEFAULT_REQUEST_TIMEOUT_MS;
26
51
  }
27
52
  /**
28
- * Connect to the signaling server
29
- * @param url - WebSocket server URL
30
- * @returns Promise that resolves when connected
53
+ * Update auth token used for subsequent connections/reconnects.
54
+ */
55
+ setAuthToken(token) {
56
+ this.reconnectConfig = {
57
+ ...this.reconnectConfig,
58
+ authToken: token,
59
+ };
60
+ }
61
+ /**
62
+ * Connect to the signaling server.
63
+ * Cleans up any stale socket or pending reconnect timer before opening a new one.
31
64
  */
32
65
  connect(url) {
33
66
  this.url = url;
34
67
  this.shouldReconnect = true;
68
+ this.authenticated = !this.reconnectConfig.authToken;
69
+ this.clearReconnectTimer();
70
+ this.clearStableResetTimer();
71
+ this.stopHeartbeat();
72
+ this.cleanupSocket(true);
73
+ if (this.reconnectConfig.authToken && isPlaintextRemoteWs(url)) {
74
+ console.warn("[Aves] authToken is configured over an unencrypted ws:// connection. Use wss:// in production.");
75
+ }
35
76
  return new Promise((resolve, reject) => {
36
- try {
37
- this.ws = new WebSocket(url);
38
- this.ws.onopen = () => {
39
- this.reconnectAttempts = 0;
40
- this.emit("stateChange", "connected");
77
+ let settled = false;
78
+ const rejectOnce = (err) => {
79
+ if (!settled) {
80
+ settled = true;
81
+ reject(err);
82
+ }
83
+ };
84
+ const resolveOnce = () => {
85
+ if (!settled) {
86
+ settled = true;
41
87
  resolve();
88
+ }
89
+ };
90
+ try {
91
+ const ws = new WebSocket(url);
92
+ this.ws = ws;
93
+ ws.onopen = () => {
94
+ if (this.ws !== ws) {
95
+ return;
96
+ }
97
+ const finalizeConnect = () => {
98
+ if (this.ws !== ws) {
99
+ return;
100
+ }
101
+ this.authenticated = true;
102
+ // Delay resetting reconnectAttempts until the connection stays healthy
103
+ // so immediate server-side kicks (1008/1013) preserve exponential backoff.
104
+ this.scheduleStableReconnectReset(ws);
105
+ this.startHeartbeat();
106
+ this.emit("stateChange", "connected");
107
+ resolveOnce();
108
+ };
109
+ if (this.reconnectConfig.authToken) {
110
+ this.authenticated = false;
111
+ this.authenticate(this.reconnectConfig.authToken)
112
+ .then(() => {
113
+ finalizeConnect();
114
+ })
115
+ .catch((authError) => {
116
+ const avesError = authError instanceof AvesError
117
+ ? authError
118
+ : new AvesError({
119
+ message: `Signaling authentication failed: ${errorMessage(authError)}`,
120
+ code: "UNAUTHORIZED",
121
+ stage: "auth",
122
+ retryable: false,
123
+ cause: authError,
124
+ });
125
+ const isFatalAuthError = !avesError.retryable || avesError.code === "UNAUTHORIZED";
126
+ if (isFatalAuthError) {
127
+ this.shouldReconnect = false;
128
+ }
129
+ this.authenticated = false;
130
+ this.cleanupSocket(true);
131
+ this.emit("stateChange", "disconnected");
132
+ rejectOnce(avesError);
133
+ if (!isFatalAuthError) {
134
+ this.handleDisconnect();
135
+ }
136
+ });
137
+ return;
138
+ }
139
+ finalizeConnect();
42
140
  };
43
- this.ws.onclose = () => {
141
+ ws.onclose = (event) => {
142
+ if (this.ws !== ws) {
143
+ return;
144
+ }
145
+ const closeCode = typeof event?.code === "number" ? event.code : undefined;
146
+ this.authenticated = false;
147
+ this.clearStableResetTimer();
148
+ this.stopHeartbeat();
44
149
  this.emit("stateChange", "disconnected");
150
+ // Policy violation (e.g. auth rejected / rate-limit kick) stops blind retries.
151
+ if (closeCode === 1008) {
152
+ this.shouldReconnect = false;
153
+ const policyError = new AvesError({
154
+ message: event?.reason || "Signaling connection rejected by server policy (1008)",
155
+ code: "UNAUTHORIZED",
156
+ stage: "transport",
157
+ retryable: false,
158
+ });
159
+ rejectOnce(policyError);
160
+ this.emit("error", policyError);
161
+ this.handleDisconnect();
162
+ return;
163
+ }
164
+ rejectOnce(new AvesError({
165
+ message: "WebSocket closed before connection completed",
166
+ code: "SIGNALING_CONNECTION_FAILED",
167
+ stage: "transport",
168
+ retryable: true,
169
+ }));
45
170
  this.handleDisconnect();
46
171
  };
47
- this.ws.onerror = (error) => {
48
- this.emit("error", new AvesError({ message: "WebSocket error", code: "SERVER_ERROR", stage: "transport", retryable: true }));
49
- reject(new AvesError({ message: "WebSocket connection failed", code: "SERVER_ERROR", stage: "transport", retryable: true }));
172
+ ws.onerror = (error) => {
173
+ if (this.ws !== ws) {
174
+ return;
175
+ }
176
+ const avesError = new AvesError({
177
+ message: "WebSocket error",
178
+ code: "SIGNALING_CONNECTION_FAILED",
179
+ stage: "transport",
180
+ retryable: true,
181
+ cause: error,
182
+ });
183
+ this.emit("error", avesError);
184
+ rejectOnce(new AvesError({
185
+ message: "WebSocket connection failed",
186
+ code: "SIGNALING_CONNECTION_FAILED",
187
+ stage: "transport",
188
+ retryable: true,
189
+ cause: error,
190
+ }));
50
191
  };
51
- this.ws.onmessage = (event) => {
192
+ ws.onmessage = (event) => {
193
+ if (this.ws !== ws) {
194
+ return;
195
+ }
52
196
  this.handleMessage(event.data);
53
197
  };
54
198
  this.emit("stateChange", "connecting");
55
199
  }
56
200
  catch (error) {
57
- reject(new AvesError({ message: `WebSocket construction failed: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "transport", retryable: true }));
201
+ rejectOnce(new AvesError({
202
+ message: `WebSocket construction failed: ${errorMessage(error)}`,
203
+ code: "SIGNALING_CONNECTION_FAILED",
204
+ stage: "transport",
205
+ retryable: true,
206
+ cause: error,
207
+ }));
58
208
  }
59
209
  });
60
210
  }
61
211
  /**
62
- * Disconnect from the signaling server
212
+ * Disconnect from the signaling server.
63
213
  */
64
214
  disconnect() {
65
215
  this.shouldReconnect = false;
66
- if (this.reconnectTimer !== null) {
67
- clearTimeout(this.reconnectTimer);
68
- this.reconnectTimer = null;
69
- }
70
- const ws = this.ws;
71
- this.ws = null;
72
- if (ws) {
73
- ws.onclose = null;
74
- ws.close();
75
- }
216
+ this.authenticated = false;
217
+ this.clearReconnectTimer();
218
+ this.clearStableResetTimer();
219
+ this.stopHeartbeat();
220
+ this.cleanupSocket(true);
76
221
  this.rejectPendingRequests(new AvesError({
77
222
  message: "Signaling connection closed",
78
- code: "SERVER_ERROR",
223
+ code: "SIGNALING_DISCONNECTED",
79
224
  stage: "transport",
80
225
  retryable: true,
81
226
  }));
82
227
  this.emit("stateChange", "disconnected");
83
228
  }
84
229
  isConnected() {
85
- return this.ws?.readyState === WebSocket.OPEN;
230
+ if (this.ws?.readyState !== WebSocket.OPEN) {
231
+ return false;
232
+ }
233
+ if (this.reconnectConfig.authToken && !this.authenticated) {
234
+ return false;
235
+ }
236
+ return true;
237
+ }
238
+ scheduleStableReconnectReset(ws) {
239
+ this.clearStableResetTimer();
240
+ const stableMs = this.reconnectConfig.minStableDurationMs !== undefined &&
241
+ this.reconnectConfig.minStableDurationMs >= 0
242
+ ? this.reconnectConfig.minStableDurationMs
243
+ : DEFAULT_MIN_STABLE_DURATION_MS;
244
+ if (stableMs === 0) {
245
+ this.reconnectAttempts = 0;
246
+ return;
247
+ }
248
+ this.stableResetTimer = setTimeout(() => {
249
+ this.stableResetTimer = null;
250
+ if (this.ws === ws && this.isConnected()) {
251
+ this.reconnectAttempts = 0;
252
+ }
253
+ }, stableMs);
254
+ unrefTimer(this.stableResetTimer);
255
+ }
256
+ clearStableResetTimer() {
257
+ if (this.stableResetTimer !== null) {
258
+ clearTimeout(this.stableResetTimer);
259
+ this.stableResetTimer = null;
260
+ }
261
+ }
262
+ /**
263
+ * Calculate reconnect delay with exponential backoff and optional jitter.
264
+ */
265
+ computeReconnectDelay(attempt) {
266
+ const baseDelay = Math.max(0, this.reconnectConfig.delay);
267
+ const factor = this.reconnectConfig.backoffFactor && this.reconnectConfig.backoffFactor >= 1
268
+ ? this.reconnectConfig.backoffFactor
269
+ : DEFAULT_BACKOFF_FACTOR;
270
+ const maxDelay = this.reconnectConfig.maxDelay && this.reconnectConfig.maxDelay >= baseDelay
271
+ ? this.reconnectConfig.maxDelay
272
+ : Math.max(baseDelay, DEFAULT_MAX_RECONNECT_DELAY_MS);
273
+ const exponentialDelay = Math.min(maxDelay, baseDelay * Math.pow(factor, Math.max(0, attempt - 1)));
274
+ if (this.reconnectConfig.jitter === false) {
275
+ return Math.round(exponentialDelay);
276
+ }
277
+ // Apply ±20% jitter to avoid synchronized reconnect storms.
278
+ const jitterMultiplier = 0.8 + Math.random() * 0.4;
279
+ return Math.round(exponentialDelay * jitterMultiplier);
280
+ }
281
+ authenticate(token) {
282
+ const requestId = this.createRequestId("auth");
283
+ return new Promise((resolve, reject) => {
284
+ this.trackPendingRequest(requestId, "auth", resolve, reject);
285
+ try {
286
+ this.send({ type: "auth", token, requestId });
287
+ }
288
+ catch (error) {
289
+ this.deletePendingRequest(requestId);
290
+ reject(error);
291
+ }
292
+ });
293
+ }
294
+ cleanupSocket(closeSocket) {
295
+ const ws = this.ws;
296
+ this.ws = null;
297
+ if (!ws) {
298
+ return;
299
+ }
300
+ ws.onopen = null;
301
+ ws.onclose = null;
302
+ ws.onerror = null;
303
+ ws.onmessage = null;
304
+ if (closeSocket) {
305
+ try {
306
+ ws.close();
307
+ }
308
+ catch {
309
+ // Ignore close errors on already-closed sockets.
310
+ }
311
+ }
312
+ }
313
+ clearReconnectTimer() {
314
+ if (this.reconnectTimer !== null) {
315
+ clearTimeout(this.reconnectTimer);
316
+ this.reconnectTimer = null;
317
+ }
318
+ }
319
+ startHeartbeat() {
320
+ this.stopHeartbeat();
321
+ const rawIntervalMs = this.reconnectConfig.heartbeatIntervalMs ?? 0;
322
+ if (rawIntervalMs <= 0) {
323
+ return;
324
+ }
325
+ const intervalMs = Math.max(MIN_HEARTBEAT_INTERVAL_MS, rawIntervalMs);
326
+ const timeoutMs = this.reconnectConfig.heartbeatTimeoutMs &&
327
+ this.reconnectConfig.heartbeatTimeoutMs > 0
328
+ ? this.reconnectConfig.heartbeatTimeoutMs
329
+ : DEFAULT_HEARTBEAT_TIMEOUT_MS;
330
+ this.heartbeatTimer = setInterval(() => {
331
+ if (!this.isConnected()) {
332
+ return;
333
+ }
334
+ if (this.heartbeatTimeoutTimer !== null) {
335
+ return;
336
+ }
337
+ try {
338
+ this.send({ type: "ping", timestamp: Date.now() });
339
+ }
340
+ catch {
341
+ return;
342
+ }
343
+ this.heartbeatTimeoutTimer = setTimeout(() => {
344
+ this.heartbeatTimeoutTimer = null;
345
+ if (!this.ws) {
346
+ return;
347
+ }
348
+ const staleWs = this.ws;
349
+ this.stopHeartbeat();
350
+ this.emit("stateChange", "disconnected");
351
+ this.cleanupSocket(true);
352
+ // Trigger reconnect cycle as if socket dropped.
353
+ void staleWs;
354
+ this.handleDisconnect();
355
+ }, timeoutMs);
356
+ unrefTimer(this.heartbeatTimeoutTimer);
357
+ }, intervalMs);
358
+ unrefTimer(this.heartbeatTimer);
359
+ }
360
+ stopHeartbeat() {
361
+ if (this.heartbeatTimer !== null) {
362
+ clearInterval(this.heartbeatTimer);
363
+ this.heartbeatTimer = null;
364
+ }
365
+ if (this.heartbeatTimeoutTimer !== null) {
366
+ clearTimeout(this.heartbeatTimeoutTimer);
367
+ this.heartbeatTimeoutTimer = null;
368
+ }
369
+ }
370
+ handlePong() {
371
+ if (this.heartbeatTimeoutTimer !== null) {
372
+ clearTimeout(this.heartbeatTimeoutTimer);
373
+ this.heartbeatTimeoutTimer = null;
374
+ }
86
375
  }
87
376
  /**
88
- * Handle WebSocket disconnection and attempt reconnection
377
+ * Handle WebSocket disconnection and attempt reconnection.
89
378
  */
90
379
  handleDisconnect() {
91
380
  this.ws = null;
92
381
  this.rejectPendingRequests(new AvesError({
93
382
  message: "Signaling connection closed",
94
- code: "SERVER_ERROR",
383
+ code: "SIGNALING_DISCONNECTED",
95
384
  stage: "transport",
96
385
  retryable: true,
97
386
  }));
@@ -100,41 +389,69 @@ export class SignalingClient extends EventEmitter {
100
389
  }
101
390
  if (this.reconnectAttempts < this.reconnectConfig.maxAttempts) {
102
391
  this.reconnectAttempts++;
392
+ const delayMs = this.computeReconnectDelay(this.reconnectAttempts);
103
393
  this.reconnectTimer = setTimeout(() => {
394
+ this.reconnectTimer = null;
104
395
  this.connect(this.url).catch((error) => {
105
396
  this.emit("error", new AvesError({
106
397
  message: `Reconnection attempt ${this.reconnectAttempts} failed: ${errorMessage(error)}`,
107
- code: "SERVER_ERROR",
398
+ code: "SIGNALING_CONNECTION_FAILED",
108
399
  stage: "transport",
109
400
  retryable: true,
401
+ cause: error,
110
402
  }));
111
403
  });
112
- }, this.reconnectConfig.delay);
404
+ }, delayMs);
405
+ unrefTimer(this.reconnectTimer);
113
406
  }
114
407
  else {
115
408
  this.emit("error", new AvesError({
116
409
  message: `Max reconnection attempts (${this.reconnectConfig.maxAttempts}) reached`,
117
- code: "SERVER_ERROR",
410
+ code: "SIGNALING_CONNECTION_FAILED",
118
411
  stage: "transport",
119
412
  retryable: false,
120
413
  }));
121
414
  }
122
415
  }
123
416
  /**
124
- * Handle incoming WebSocket messages
125
- * @param data - Raw message data
417
+ * Handle incoming WebSocket messages.
126
418
  */
127
419
  handleMessage(data) {
128
420
  try {
129
421
  const message = JSON.parse(data);
130
422
  switch (message.type) {
423
+ case "auth-ok":
424
+ this.resolvePendingRequest(message.requestId, "auth", {
425
+ userId: message.userId,
426
+ userName: message.userName,
427
+ });
428
+ break;
429
+ case "pong":
430
+ this.reconnectAttempts = 0;
431
+ this.handlePong();
432
+ break;
433
+ case "ping":
434
+ if (this.isConnected()) {
435
+ try {
436
+ this.send({ type: "pong", timestamp: message.timestamp ?? Date.now() });
437
+ }
438
+ catch {
439
+ // Ignore pong failures on closing socket.
440
+ }
441
+ }
442
+ break;
131
443
  case "room-created":
444
+ this.reconnectAttempts = 0;
132
445
  this.resolvePendingRequest(message.requestId, "create-room", message.roomId);
133
446
  break;
134
447
  case "room-joined":
448
+ this.reconnectAttempts = 0;
135
449
  this.resolvePendingRequest(message.requestId, "join-room", {
136
450
  participants: message.participants,
137
451
  userId: message.userId,
452
+ ...(message.reconnectToken !== undefined
453
+ ? { reconnectToken: message.reconnectToken }
454
+ : {}),
138
455
  });
139
456
  break;
140
457
  case "room-left":
@@ -163,30 +480,41 @@ export class SignalingClient extends EventEmitter {
163
480
  break;
164
481
  }
165
482
  }
166
- catch (error) {
167
- this.emit("error", new AvesError({ message: "Failed to parse signaling message", code: "INVALID_MESSAGE_FORMAT", stage: "protocol", retryable: false }));
483
+ catch {
484
+ this.emit("error", new AvesError({
485
+ message: "Failed to parse signaling message",
486
+ code: "INVALID_MESSAGE_FORMAT",
487
+ stage: "protocol",
488
+ retryable: false,
489
+ }));
168
490
  }
169
491
  }
170
492
  /**
171
- * Send a message to the signaling server
172
- * @param message - Signaling message to send
493
+ * Send a message to the signaling server.
173
494
  */
174
495
  send(message) {
175
496
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
176
- throw new AvesError({ message: "WebSocket is not connected", code: "SERVER_ERROR", stage: "transport", retryable: true });
497
+ throw new AvesError({
498
+ message: "WebSocket is not connected",
499
+ code: "SIGNALING_DISCONNECTED",
500
+ stage: "transport",
501
+ retryable: true,
502
+ });
177
503
  }
178
504
  this.ws.send(JSON.stringify(message));
179
505
  }
180
506
  /**
181
- * Create a new room
182
- * @returns Promise that resolves with the room ID
507
+ * Create a new room with optional name, maxCapacity, and password.
183
508
  */
184
- createRoom() {
509
+ createRoom(options) {
185
510
  const requestId = this.createRequestId("create-room");
186
511
  return new Promise((resolve, reject) => {
187
512
  this.trackPendingRequest(requestId, "create-room", resolve, reject);
188
513
  try {
189
- this.send({ type: "create-room", requestId });
514
+ const message = options
515
+ ? { type: "create-room", options, requestId }
516
+ : { type: "create-room", requestId };
517
+ this.send(message);
190
518
  }
191
519
  catch (error) {
192
520
  this.deletePendingRequest(requestId);
@@ -194,14 +522,40 @@ export class SignalingClient extends EventEmitter {
194
522
  }
195
523
  });
196
524
  }
197
- joinRoom(roomId, userIdOrName, maybeUserName) {
525
+ joinRoom(roomId, userIdOrName, maybeUserNameOrOptions, maybePassword) {
198
526
  const requestId = this.createRequestId("join-room");
199
- const userId = maybeUserName ? userIdOrName : undefined;
200
- const userName = maybeUserName ?? userIdOrName;
527
+ let userId;
528
+ let userName;
529
+ let password;
530
+ let reconnectToken;
531
+ if (typeof maybeUserNameOrOptions === "string") {
532
+ userId = userIdOrName;
533
+ userName = maybeUserNameOrOptions;
534
+ password = maybePassword;
535
+ }
536
+ else if (maybeUserNameOrOptions &&
537
+ typeof maybeUserNameOrOptions === "object") {
538
+ userName = userIdOrName;
539
+ userId = maybeUserNameOrOptions.userId;
540
+ password = maybeUserNameOrOptions.password;
541
+ reconnectToken = maybeUserNameOrOptions.reconnectToken;
542
+ }
543
+ else {
544
+ userName = userIdOrName;
545
+ }
201
546
  return new Promise((resolve, reject) => {
202
547
  this.trackPendingRequest(requestId, "join-room", resolve, reject);
203
548
  try {
204
- this.send({ type: "join-room", roomId, userId, userName, requestId });
549
+ const payload = {
550
+ type: "join-room",
551
+ roomId,
552
+ userId,
553
+ userName,
554
+ ...(password !== undefined ? { password } : {}),
555
+ ...(reconnectToken !== undefined ? { reconnectToken } : {}),
556
+ requestId,
557
+ };
558
+ this.send(payload);
205
559
  }
206
560
  catch (error) {
207
561
  this.deletePendingRequest(requestId);
@@ -210,7 +564,7 @@ export class SignalingClient extends EventEmitter {
210
564
  });
211
565
  }
212
566
  /**
213
- * Leave the current room
567
+ * Leave the current room.
214
568
  */
215
569
  leaveRoom(userId) {
216
570
  const requestId = this.createRequestId("leave-room");
@@ -226,56 +580,64 @@ export class SignalingClient extends EventEmitter {
226
580
  });
227
581
  }
228
582
  /**
229
- * Send an offer to a peer
230
- * @param targetId - Target peer ID
231
- * @param fromId - Sender ID
232
- * @param offer - RTC session description (offer)
583
+ * Send an offer to a peer.
233
584
  */
234
585
  sendOffer(targetId, fromId, offer) {
235
586
  try {
236
587
  this.send({ type: "offer", targetId, fromId, offer });
237
588
  }
238
589
  catch (error) {
239
- this.emit("error", new AvesError({ message: `Failed to send offer to ${targetId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "transport", retryable: true, peerId: targetId }));
590
+ this.emit("error", new AvesError({
591
+ message: `Failed to send offer to ${targetId}: ${errorMessage(error)}`,
592
+ code: "SIGNALING_DISCONNECTED",
593
+ stage: "transport",
594
+ retryable: true,
595
+ peerId: targetId,
596
+ cause: error,
597
+ }));
240
598
  }
241
599
  }
242
600
  /**
243
- * Send an answer to a peer
244
- * @param targetId - Target peer ID
245
- * @param fromId - Sender ID
246
- * @param answer - RTC session description (answer)
601
+ * Send an answer to a peer.
247
602
  */
248
603
  sendAnswer(targetId, fromId, answer) {
249
604
  try {
250
605
  this.send({ type: "answer", targetId, fromId, answer });
251
606
  }
252
607
  catch (error) {
253
- this.emit("error", new AvesError({ message: `Failed to send answer to ${targetId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "transport", retryable: true, peerId: targetId }));
608
+ this.emit("error", new AvesError({
609
+ message: `Failed to send answer to ${targetId}: ${errorMessage(error)}`,
610
+ code: "SIGNALING_DISCONNECTED",
611
+ stage: "transport",
612
+ retryable: true,
613
+ peerId: targetId,
614
+ cause: error,
615
+ }));
254
616
  }
255
617
  }
256
618
  /**
257
- * Send an ICE candidate to a peer
258
- * @param targetId - Target peer ID
259
- * @param fromId - Sender ID
260
- * @param candidate - ICE candidate
619
+ * Send an ICE candidate to a peer.
261
620
  */
262
621
  sendIceCandidate(targetId, fromId, candidate) {
263
622
  try {
264
623
  this.send({ type: "ice-candidate", targetId, fromId, candidate });
265
624
  }
266
625
  catch (error) {
267
- this.emit("error", new AvesError({ message: `Failed to send ICE candidate to ${targetId}: ${errorMessage(error)}`, code: "WEBRTC_ICE_FAILED", stage: "transport", retryable: true, peerId: targetId }));
626
+ this.emit("error", new AvesError({
627
+ message: `Failed to send ICE candidate to ${targetId}: ${errorMessage(error)}`,
628
+ code: "WEBRTC_ICE_FAILED",
629
+ stage: "transport",
630
+ retryable: true,
631
+ peerId: targetId,
632
+ cause: error,
633
+ }));
268
634
  }
269
635
  }
270
636
  /**
271
637
  * Resolve a pending request by its requestId.
272
- * If the server response omitted the requestId, we reject all pending
273
- * requests of that type rather than guessing which one to resolve.
274
638
  */
275
639
  resolvePendingRequest(requestId, requestType, value) {
276
640
  if (!requestId) {
277
- // Server response missing requestId — can't match to a specific request.
278
- // Reject all pending requests of this type so they don't hang forever.
279
641
  this.rejectPendingRequestsByType(requestType, new AvesError({
280
642
  message: `Server responded to ${requestType} without requestId`,
281
643
  code: "SERVER_ERROR",
@@ -318,9 +680,10 @@ export class SignalingClient extends EventEmitter {
318
680
  request.reject(error);
319
681
  this.emit("error", error);
320
682
  }, this.requestTimeoutMs);
683
+ unrefTimer(timeoutId);
321
684
  this.pendingRequests.set(requestId, {
322
685
  type,
323
- resolve,
686
+ resolve: resolve,
324
687
  reject,
325
688
  timeoutId,
326
689
  });
@@ -333,20 +696,13 @@ export class SignalingClient extends EventEmitter {
333
696
  clearTimeout(request.timeoutId);
334
697
  this.pendingRequests.delete(requestId);
335
698
  }
336
- /**
337
- * Reject all pending requests
338
- * @param error - Error to reject with
339
- */
340
699
  rejectPendingRequests(error) {
341
- for (const [key, request] of this.pendingRequests) {
700
+ for (const [, request] of this.pendingRequests) {
342
701
  clearTimeout(request.timeoutId);
343
702
  request.reject(error);
344
703
  }
345
704
  this.pendingRequests.clear();
346
705
  }
347
- /**
348
- * Reject all pending requests of a specific type.
349
- */
350
706
  rejectPendingRequestsByType(requestType, error) {
351
707
  for (const [requestId, request] of this.pendingRequests) {
352
708
  if (request.type === requestType) {