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