@tangle-network/sandbox 0.64.1 → 0.64.2

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.
@@ -33,7 +33,7 @@ function calculateConnectionQuality(metrics, isConnected) {
33
33
  return "good";
34
34
  }
35
35
  //#endregion
36
- //#region ../../../packages/sdk/dist/types-B0EH3UTU.js
36
+ //#region ../../../packages/sdk/dist/types-BpG4d3NG.js
37
37
  function invokeClientCallback(name, callback, onError) {
38
38
  try {
39
39
  callback();
@@ -44,7 +44,74 @@ function invokeClientCallback(name, callback, onError) {
44
44
  } catch {}
45
45
  }
46
46
  }
47
+ /** Browser-safe session gateway contracts for both SDK clients. */
48
+ const INITIAL_METRICS = createConnectionMetrics();
49
+ /** Connection quality metrics derived from ping latency and missed pongs. */
50
+ var ConnectionMetricsTracker = class {
51
+ metrics;
52
+ latencyHistory = [];
53
+ constructor(initialMetrics, latencyHistorySize, isConnected, onChange) {
54
+ this.initialMetrics = initialMetrics;
55
+ this.latencyHistorySize = latencyHistorySize;
56
+ this.isConnected = isConnected;
57
+ this.onChange = onChange;
58
+ this.metrics = { ...initialMetrics };
59
+ }
60
+ get quality() {
61
+ return this.metrics.quality;
62
+ }
63
+ snapshot() {
64
+ return { ...this.metrics };
65
+ }
66
+ reset() {
67
+ this.latencyHistory = [];
68
+ this.metrics = { ...this.initialMetrics };
69
+ this.onChange(this.metrics);
70
+ }
71
+ recordMissedPongs(missedPongCount) {
72
+ this.metrics = {
73
+ ...this.metrics,
74
+ missedPongCount
75
+ };
76
+ this.refreshQuality();
77
+ }
78
+ recordLatency(latency, pongTime, missedPongCount) {
79
+ this.latencyHistory.push(latency);
80
+ if (this.latencyHistory.length > this.latencyHistorySize) this.latencyHistory.shift();
81
+ const avgLatency = this.latencyHistory.length > 0 ? this.latencyHistory.reduce((a, b) => a + b, 0) / this.latencyHistory.length : null;
82
+ this.metrics = {
83
+ ...this.metrics,
84
+ lastPingLatencyMs: latency,
85
+ avgPingLatencyMs: avgLatency,
86
+ missedPongCount,
87
+ lastPongAt: pongTime
88
+ };
89
+ this.refreshQuality();
90
+ }
91
+ trackReconnection() {
92
+ const now = Date.now();
93
+ this.metrics = {
94
+ ...this.metrics,
95
+ reconnectCount: this.metrics.reconnectCount + 1,
96
+ lastReconnectAt: now
97
+ };
98
+ this.latencyHistory = [];
99
+ this.refreshQuality();
100
+ }
101
+ refreshQuality() {
102
+ const quality = calculateConnectionQuality(this.metrics, this.isConnected());
103
+ if (this.metrics.quality !== quality) {
104
+ this.metrics = {
105
+ ...this.metrics,
106
+ quality
107
+ };
108
+ this.onChange(this.metrics);
109
+ }
110
+ }
111
+ };
47
112
  var ConnectionWaiters = class {
113
+ /** True once the current socket has reported `connection.established`. */
114
+ established = false;
48
115
  waiters = /* @__PURE__ */ new Set();
49
116
  establishmentTimeout = null;
50
117
  constructor(timeoutMs) {
@@ -73,6 +140,15 @@ var ConnectionWaiters = class {
73
140
  });
74
141
  });
75
142
  }
143
+ /** Wait for the socket to be established, or fail with `closedMessage`. */
144
+ async awaitEstablished(getState, closedMessage) {
145
+ const ready = () => this.established && getState() === "connected";
146
+ if (!ready()) {
147
+ if (getState() === "disconnected") throw new Error("Client is not connected");
148
+ await this.wait();
149
+ }
150
+ if (!ready()) throw new Error(closedMessage);
151
+ }
76
152
  resolveAll() {
77
153
  this.clear();
78
154
  for (const waiter of this.waiters) waiter.resolve();
@@ -84,8 +160,211 @@ var ConnectionWaiters = class {
84
160
  this.waiters.clear();
85
161
  }
86
162
  };
87
- /** Browser-safe session gateway contracts for both SDK clients. */
88
- const INITIAL_METRICS = createConnectionMetrics();
163
+ const PONG_TIMEOUT_CLOSE_CODE = 4e3;
164
+ const PONG_TIMEOUT_CLOSE_REASON = "Pong timeout - connection unresponsive";
165
+ /** Sends pings on an interval and closes a socket that stops answering. */
166
+ var Heartbeat = class {
167
+ lastPingAt = null;
168
+ lastPongAt = null;
169
+ lastPingSentAt = null;
170
+ missedPongCount = 0;
171
+ pingInterval = null;
172
+ pongTimeout = null;
173
+ constructor(policy, metrics, socket, send) {
174
+ this.policy = policy;
175
+ this.metrics = metrics;
176
+ this.socket = socket;
177
+ this.send = send;
178
+ }
179
+ start() {
180
+ this.stopInterval();
181
+ this.pingInterval = setInterval(() => {
182
+ this.sendPing();
183
+ }, this.policy.pingIntervalMs);
184
+ }
185
+ stop() {
186
+ this.stopInterval();
187
+ this.clearPongTimeout();
188
+ }
189
+ resetMissedPongs() {
190
+ this.missedPongCount = 0;
191
+ }
192
+ handlePong(timestamp) {
193
+ const now = Date.now();
194
+ this.lastPongAt = timestamp;
195
+ this.missedPongCount = 0;
196
+ this.clearPongTimeout();
197
+ if (this.lastPingSentAt) this.metrics.recordLatency(now - this.lastPingSentAt, now, this.missedPongCount);
198
+ }
199
+ stopInterval() {
200
+ if (this.pingInterval) {
201
+ clearInterval(this.pingInterval);
202
+ this.pingInterval = null;
203
+ }
204
+ }
205
+ clearPongTimeout() {
206
+ if (this.pongTimeout) {
207
+ clearTimeout(this.pongTimeout);
208
+ this.pongTimeout = null;
209
+ }
210
+ }
211
+ /** Count a missed pong. Returns true when the socket was closed for it. */
212
+ recordMissedPong() {
213
+ this.missedPongCount++;
214
+ this.metrics.recordMissedPongs(this.missedPongCount);
215
+ if (this.missedPongCount >= this.policy.maxMissedPongs) {
216
+ this.socket()?.close(PONG_TIMEOUT_CLOSE_CODE, PONG_TIMEOUT_CLOSE_REASON);
217
+ return true;
218
+ }
219
+ return false;
220
+ }
221
+ sendPing() {
222
+ if (this.socket()?.readyState !== WebSocket.OPEN) return;
223
+ const timeSinceLastPong = this.lastPongAt ? Date.now() - this.lastPongAt : 0;
224
+ if (this.lastPongAt && timeSinceLastPong > this.policy.pongTimeoutMs && this.recordMissedPong()) return;
225
+ this.lastPingAt = Date.now();
226
+ this.lastPingSentAt = Date.now();
227
+ this.send({ type: "ping" });
228
+ this.pongTimeout = setTimeout(() => {
229
+ this.recordMissedPong();
230
+ }, this.policy.pongTimeoutMs);
231
+ }
232
+ };
233
+ /**
234
+ * Parse a wire frame into a server message. Reports a frame with no message
235
+ * type through `onError` and returns null; throws on invalid JSON.
236
+ */
237
+ function parseServerFrame(data, handlers) {
238
+ const raw = JSON.parse(data);
239
+ if (typeof raw.type !== "string") {
240
+ invokeClientCallback("onError", () => handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
241
+ return null;
242
+ }
243
+ if (raw.data && typeof raw.data === "object") {
244
+ const d = raw.data;
245
+ if (raw.type === "error") {
246
+ if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
247
+ if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
248
+ }
249
+ }
250
+ return raw;
251
+ }
252
+ /** Dispatch a message to client state, then to the catch-all `onMessage`. */
253
+ function deliverServerMessage(message, targets) {
254
+ const { handlers } = targets;
255
+ invokeClientCallback("message dispatch", () => dispatchServerMessage(message, targets), handlers.onError);
256
+ invokeClientCallback("onMessage", () => handlers.onMessage?.(message), handlers.onError);
257
+ }
258
+ /** Apply one validated server message to client state and its handlers. */
259
+ function dispatchServerMessage(message, targets) {
260
+ const { handlers, replay } = targets;
261
+ if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") replay.clear();
262
+ if (targets.requests.settle(message)) return;
263
+ switch (message.type) {
264
+ case "connection.established":
265
+ targets.onConnectionEstablished(message.data.sessionId);
266
+ break;
267
+ case "runtime.connected":
268
+ handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
269
+ break;
270
+ case "runtime.disconnected":
271
+ handlers.onRuntimeDisconnected?.(message.data.sandboxId, message.data.error);
272
+ break;
273
+ case "runtime.unavailable":
274
+ handlers.onRuntimeUnavailable?.(message.data);
275
+ break;
276
+ case "runtime.not_found":
277
+ handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
278
+ break;
279
+ case "runtime.ready":
280
+ handlers.onRuntimeReady?.(message.data);
281
+ break;
282
+ case "port.opened":
283
+ handlers.onPortOpened?.(message.data.port, message.data.protocol, message.data.processName);
284
+ break;
285
+ case "port.closed":
286
+ handlers.onPortClosed?.(message.data.port);
287
+ break;
288
+ case "agent.event":
289
+ targets.onAgentEvent(message.data);
290
+ handlers.onAgentEvent?.(message.channel, message.data, message.seq);
291
+ break;
292
+ case "replay.start":
293
+ replay.start(message.total);
294
+ handlers.onReplayStart?.(message.total);
295
+ break;
296
+ case "replay.progress": {
297
+ const total = replay.advance(message.received);
298
+ handlers.onReplayProgress?.(message.received, total);
299
+ break;
300
+ }
301
+ case "replay.complete":
302
+ replay.complete();
303
+ handlers.onReplayComplete?.(message.total);
304
+ break;
305
+ case "replay.truncated":
306
+ handlers.onReplayTruncated?.(message.data);
307
+ break;
308
+ case "stream.gap":
309
+ handlers.onStreamGap?.(message.data);
310
+ break;
311
+ case "stream.dead":
312
+ handlers.onStreamDead?.(message.data);
313
+ break;
314
+ case "error":
315
+ handlers.onError?.(message.message, message.code);
316
+ break;
317
+ case "token.expiring":
318
+ invokeClientCallback("onTokenExpiring", () => handlers.onTokenExpiring?.(message.data.secondsRemaining), handlers.onError);
319
+ targets.tokenRefresher.refresh();
320
+ break;
321
+ case "token.expired":
322
+ handlers.onTokenExpired?.();
323
+ break;
324
+ case "backpressure.warning":
325
+ handlers.onBackpressureWarning?.(message.data.droppedCount, message.data.since, message.data.totalDropped);
326
+ break;
327
+ }
328
+ }
329
+ const REQUEST_TIMEOUT_MS = 1e4;
330
+ /** Correlates request messages with the server replies that carry their id. */
331
+ var PendingRequests = class {
332
+ callbacks = /* @__PURE__ */ new Map();
333
+ idCounter = 0;
334
+ /** Assign a correlation id, send via `send`, and await the reply. */
335
+ request(send) {
336
+ return new Promise((resolve, reject) => {
337
+ const id = `msg_${++this.idCounter}`;
338
+ this.callbacks.set(id, {
339
+ resolve,
340
+ reject
341
+ });
342
+ setTimeout(() => {
343
+ if (this.callbacks.has(id)) {
344
+ this.callbacks.delete(id);
345
+ reject(/* @__PURE__ */ new Error("Request timeout"));
346
+ }
347
+ }, REQUEST_TIMEOUT_MS);
348
+ send(id);
349
+ });
350
+ }
351
+ /** Settle the request a reply answers. Returns false when none is waiting. */
352
+ settle(message) {
353
+ if (!("id" in message && message.id)) return false;
354
+ const callback = this.callbacks.get(message.id);
355
+ if (!callback) return false;
356
+ this.callbacks.delete(message.id);
357
+ if (message.type === "error") callback.reject(new Error(message.message));
358
+ else callback.resolve("data" in message ? message.data : void 0);
359
+ return true;
360
+ }
361
+ rejectAll(reason) {
362
+ for (const [id, callback] of this.callbacks) {
363
+ callback.reject(new Error(reason));
364
+ this.callbacks.delete(id);
365
+ }
366
+ }
367
+ };
89
368
  const DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG = {
90
369
  transport: "websocket",
91
370
  channels: [],
@@ -126,6 +405,191 @@ function acceptedSubscriptionChannels(acknowledgement) {
126
405
  }
127
406
  return acknowledgement.channels;
128
407
  }
408
+ /** Fill every option the caller left unset with its documented default. */
409
+ function resolveClientConfig(config) {
410
+ const defaults = DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG;
411
+ return {
412
+ url: config.url,
413
+ sessionId: config.sessionId,
414
+ token: config.token,
415
+ transport: config.transport ?? defaults.transport,
416
+ channels: config.channels ?? defaults.channels,
417
+ autoReconnect: config.autoReconnect ?? defaults.autoReconnect,
418
+ maxReconnectAttempts: config.maxReconnectAttempts ?? defaults.maxReconnectAttempts,
419
+ initialReconnectDelayMs: config.initialReconnectDelayMs ?? defaults.initialReconnectDelayMs,
420
+ maxReconnectDelayMs: config.maxReconnectDelayMs ?? defaults.maxReconnectDelayMs,
421
+ pingIntervalMs: config.pingIntervalMs ?? defaults.pingIntervalMs,
422
+ pongTimeoutMs: config.pongTimeoutMs ?? defaults.pongTimeoutMs,
423
+ maxMissedPongs: config.maxMissedPongs ?? defaults.maxMissedPongs,
424
+ enableDeduplication: config.enableDeduplication ?? defaults.enableDeduplication,
425
+ maxDeduplicationSize: config.maxDeduplicationSize ?? defaults.maxDeduplicationSize,
426
+ enableReplayPersistence: config.enableReplayPersistence ?? defaults.enableReplayPersistence,
427
+ replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? defaults.replayStorageKeyPrefix,
428
+ latencyHistorySize: config.latencyHistorySize ?? defaults.latencyHistorySize,
429
+ connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? defaults.connectionEstablishmentTimeoutMs
430
+ };
431
+ }
432
+ /** Decides whether to reconnect and schedules attempts with jittered backoff. */
433
+ var ReconnectScheduler = class {
434
+ hasConnectedBefore = false;
435
+ attempts = 0;
436
+ timer = null;
437
+ constructor(policy) {
438
+ this.policy = policy;
439
+ }
440
+ canRetry() {
441
+ return this.policy.autoReconnect && this.attempts < this.policy.maxReconnectAttempts;
442
+ }
443
+ schedule(reconnect) {
444
+ if (this.timer) return;
445
+ this.attempts++;
446
+ const delay = Math.min(this.policy.initialReconnectDelayMs * 2 ** (this.attempts - 1), this.policy.maxReconnectDelayMs);
447
+ const jitter = delay * .3 * (Math.random() * 2 - 1);
448
+ this.timer = setTimeout(() => {
449
+ this.timer = null;
450
+ reconnect();
451
+ }, delay + jitter);
452
+ }
453
+ cancel() {
454
+ if (this.timer) {
455
+ clearTimeout(this.timer);
456
+ this.timer = null;
457
+ }
458
+ }
459
+ };
460
+ /**
461
+ * Replay position of one gateway session: the last delivered event, the
462
+ * execution and session being followed, replay progress, and the set of event
463
+ * IDs already delivered. Position changes are persisted through the store.
464
+ */
465
+ var ReplayCursor = class {
466
+ lastEventId = null;
467
+ duplicatesSkipped = 0;
468
+ executionId = null;
469
+ sessionId = null;
470
+ isReplaying = false;
471
+ progress = {
472
+ total: 0,
473
+ received: 0
474
+ };
475
+ processedEventIds = /* @__PURE__ */ new Set();
476
+ constructor(store, dedup) {
477
+ this.store = store;
478
+ this.dedup = dedup;
479
+ const state = this.store.load();
480
+ this.lastEventId = state.lastEventId;
481
+ this.executionId = state.executionId;
482
+ this.sessionId = state.sessionId;
483
+ }
484
+ setContext(sessionId, executionId) {
485
+ this.sessionId = sessionId;
486
+ if (executionId) this.executionId = executionId;
487
+ this.save();
488
+ }
489
+ clear() {
490
+ this.lastEventId = null;
491
+ this.executionId = null;
492
+ this.sessionId = null;
493
+ this.isReplaying = false;
494
+ this.progress = {
495
+ total: 0,
496
+ received: 0
497
+ };
498
+ this.processedEventIds.clear();
499
+ this.duplicatesSkipped = 0;
500
+ this.store.clear();
501
+ }
502
+ state() {
503
+ return {
504
+ isReplaying: this.isReplaying,
505
+ progress: { ...this.progress }
506
+ };
507
+ }
508
+ /** Follow the execution and session named by an agent event payload. */
509
+ trackExecution(raw) {
510
+ if (typeof raw !== "object" || raw === null) return;
511
+ const eventData = raw;
512
+ if (eventData.executionId) {
513
+ this.executionId = eventData.executionId;
514
+ this.save();
515
+ }
516
+ if (eventData.type === "execution.started" && eventData.sessionId) {
517
+ this.sessionId = eventData.sessionId;
518
+ this.save();
519
+ }
520
+ }
521
+ /**
522
+ * Record a delivered event ID as the new cursor. Returns false when
523
+ * deduplication is on and the event was already delivered.
524
+ */
525
+ accept(eventId) {
526
+ if (this.dedup.enabled) {
527
+ if (this.processedEventIds.has(eventId)) {
528
+ this.duplicatesSkipped++;
529
+ return false;
530
+ }
531
+ this.processedEventIds.add(eventId);
532
+ if (this.processedEventIds.size > this.dedup.maxSize) {
533
+ const entriesToRemove = Math.floor(this.dedup.maxSize * .1);
534
+ let removed = 0;
535
+ for (const oldId of this.processedEventIds) {
536
+ if (removed >= entriesToRemove) break;
537
+ this.processedEventIds.delete(oldId);
538
+ removed++;
539
+ }
540
+ }
541
+ }
542
+ this.lastEventId = eventId;
543
+ this.save();
544
+ return true;
545
+ }
546
+ /**
547
+ * The subscribe frame sent after a connection is established, asking the
548
+ * server to resume from this cursor when there is one. Null when there is
549
+ * nothing to subscribe to.
550
+ */
551
+ subscribeMessage(channels) {
552
+ const replayOptions = {};
553
+ if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
554
+ if (this.executionId) replayOptions.executionId = this.executionId;
555
+ if (this.sessionId) replayOptions.sessionId = this.sessionId;
556
+ const hasReplayCursor = this.lastEventId !== null;
557
+ if (channels.length === 0 && !hasReplayCursor) return null;
558
+ if (hasReplayCursor) {
559
+ this.isReplaying = true;
560
+ this.progress = {
561
+ total: 0,
562
+ received: 0
563
+ };
564
+ }
565
+ return {
566
+ type: "subscribe",
567
+ channels,
568
+ ...hasReplayCursor ? { replayOptions } : {}
569
+ };
570
+ }
571
+ start(total) {
572
+ this.isReplaying = true;
573
+ this.progress = {
574
+ total,
575
+ received: 0
576
+ };
577
+ }
578
+ advance(received) {
579
+ this.progress.received = received;
580
+ return this.progress.total;
581
+ }
582
+ complete() {
583
+ this.isReplaying = false;
584
+ }
585
+ save() {
586
+ this.store.save({
587
+ lastEventId: this.lastEventId,
588
+ executionId: this.executionId,
589
+ sessionId: this.sessionId
590
+ });
591
+ }
592
+ };
129
593
  const STORAGE_KEYS = {
130
594
  lastEventId: "last_event_id",
131
595
  executionId: "execution_id",
@@ -239,79 +703,53 @@ const CONNECTION_ERROR_REASON = "WebSocket connection error";
239
703
  var SessionGatewayClientCore = class {
240
704
  ws = null;
241
705
  #config;
242
- handlers;
243
- replayStateStore;
244
- tokenRefresher;
245
706
  #currentToken;
707
+ handlers;
246
708
  state = "disconnected";
247
- connectedAt = null;
248
- hasConnectedBefore = false;
249
- connectionEstablishedForSocket = false;
250
- lastPingAt = null;
251
- lastPongAt = null;
252
- lastPingSentAt = null;
253
- missedPongCount = 0;
254
- reconnectAttempts = 0;
255
- messagesReceived = 0;
256
- messagesSent = 0;
257
- eventsReceived = 0;
258
- duplicatesSkipped = 0;
259
- reconnectTimer = null;
260
- pingInterval = null;
261
- pongTimeout = null;
262
- pendingCallbacks = /* @__PURE__ */ new Map();
263
- connectionWaiters;
264
- messageIdCounter = 0;
265
- processedEventIds = /* @__PURE__ */ new Set();
266
- pingLatencyHistory = [];
267
- connectionMetrics;
268
- lastEventId = null;
269
- currentExecutionId = null;
270
- currentSessionId = null;
271
- isReplaying = false;
272
- replayProgress = {
273
- total: 0,
274
- received: 0
709
+ counters = {
710
+ connectedAt: null,
711
+ messagesReceived: 0,
712
+ messagesSent: 0,
713
+ eventsReceived: 0
275
714
  };
715
+ connectionWaiters;
716
+ reconnects;
717
+ heartbeat;
718
+ metrics;
719
+ replayCursor;
720
+ inbound;
276
721
  constructor(config, initialMetrics = INITIAL_METRICS) {
277
- this.initialMetrics = initialMetrics;
278
- this.connectionMetrics = { ...initialMetrics };
279
722
  if (!config.token.trim()) throw new Error("Session gateway token must not be empty");
280
723
  const replayStorage = resolveReplayStorage(config.replayStorage);
281
- const defaults = DEFAULT_SESSION_GATEWAY_CLIENT_CONFIG;
282
- this.#config = {
283
- url: config.url,
284
- sessionId: config.sessionId,
285
- token: config.token,
286
- transport: config.transport ?? defaults.transport,
287
- channels: config.channels ?? defaults.channels,
288
- autoReconnect: config.autoReconnect ?? defaults.autoReconnect,
289
- maxReconnectAttempts: config.maxReconnectAttempts ?? defaults.maxReconnectAttempts,
290
- initialReconnectDelayMs: config.initialReconnectDelayMs ?? defaults.initialReconnectDelayMs,
291
- maxReconnectDelayMs: config.maxReconnectDelayMs ?? defaults.maxReconnectDelayMs,
292
- pingIntervalMs: config.pingIntervalMs ?? defaults.pingIntervalMs,
293
- pongTimeoutMs: config.pongTimeoutMs ?? defaults.pongTimeoutMs,
294
- maxMissedPongs: config.maxMissedPongs ?? defaults.maxMissedPongs,
295
- enableDeduplication: config.enableDeduplication ?? defaults.enableDeduplication,
296
- maxDeduplicationSize: config.maxDeduplicationSize ?? defaults.maxDeduplicationSize,
297
- enableReplayPersistence: config.enableReplayPersistence ?? defaults.enableReplayPersistence,
298
- replayStorageKeyPrefix: config.replayStorageKeyPrefix ?? defaults.replayStorageKeyPrefix,
299
- latencyHistorySize: config.latencyHistorySize ?? defaults.latencyHistorySize,
300
- connectionEstablishmentTimeoutMs: config.connectionEstablishmentTimeoutMs ?? defaults.connectionEstablishmentTimeoutMs
301
- };
724
+ this.#config = resolveClientConfig(config);
302
725
  this.handlers = config.handlers ?? {};
303
726
  this.connectionWaiters = new ConnectionWaiters(this.#config.connectionEstablishmentTimeoutMs);
304
- this.replayStateStore = new ReplayStateStore(this.#config.enableReplayPersistence, replayStorage, this.#config.replayStorageKeyPrefix, this.#config.url, this.#config.sessionId);
305
- this.tokenRefresher = new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError);
727
+ this.reconnects = new ReconnectScheduler(this.#config);
728
+ this.metrics = new ConnectionMetricsTracker(initialMetrics, this.#config.latencyHistorySize, () => this.state === "connected", (metrics) => invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(metrics), this.handlers.onError));
729
+ this.heartbeat = new Heartbeat(this.#config, this.metrics, () => this.ws, (message) => this.send(message));
730
+ this.replayCursor = new ReplayCursor(new ReplayStateStore(this.#config.enableReplayPersistence, replayStorage, this.#config.replayStorageKeyPrefix, this.#config.url, this.#config.sessionId), {
731
+ enabled: this.#config.enableDeduplication,
732
+ maxSize: this.#config.maxDeduplicationSize
733
+ });
734
+ this.inbound = {
735
+ handlers: this.handlers,
736
+ replay: this.replayCursor,
737
+ requests: new PendingRequests(),
738
+ tokenRefresher: new TokenRefresher(config.onTokenRefresh, (token) => this.updateToken(token), this.handlers.onError),
739
+ onConnectionEstablished: (sessionId) => this.handleConnectionEstablished(sessionId),
740
+ onAgentEvent: (data) => {
741
+ this.counters.eventsReceived++;
742
+ this.replayCursor.trackExecution(data);
743
+ }
744
+ };
306
745
  this.#currentToken = config.token;
307
- if (this.#config.enableReplayPersistence) this.loadReplayState();
308
746
  }
309
747
  /**
310
748
  * Connect to the session gateway.
311
749
  */
312
750
  connect() {
313
751
  if (this.state === "connected" || this.state === "connecting" || this.state === "reconnecting") return;
314
- const nextState = this.hasConnectedBefore ? "reconnecting" : "connecting";
752
+ const nextState = this.reconnects.hasConnectedBefore ? "reconnecting" : "connecting";
315
753
  this.setState(nextState);
316
754
  if (this.getState() !== nextState) return;
317
755
  this.connectWebSocket();
@@ -319,19 +757,31 @@ var SessionGatewayClientCore = class {
319
757
  connectWebSocket() {
320
758
  const url = new URL(this.#config.url);
321
759
  url.searchParams.set("token", this.#currentToken);
322
- this.connectionEstablishedForSocket = false;
760
+ this.connectionWaiters.established = false;
323
761
  const socket = new WebSocket(url.toString());
324
762
  this.ws = socket;
763
+ const closeBeforeEstablishment = (code, reason) => {
764
+ if (this.ws !== socket || this.connectionWaiters.established) return;
765
+ try {
766
+ socket.close(code, reason);
767
+ } finally {
768
+ this.handleClose(socket, code, reason);
769
+ }
770
+ };
325
771
  socket.onopen = () => {
326
- if (this.ws === socket) this.handleOpen();
772
+ if (this.ws === socket) this.heartbeat.resetMissedPongs();
327
773
  };
328
774
  socket.onclose = (event) => this.handleClose(socket, event.code, event.reason);
329
- socket.onerror = () => this.handleError(socket);
775
+ socket.onerror = () => {
776
+ if (this.ws !== socket) return;
777
+ this.connectionWaiters.clear();
778
+ closeBeforeEstablishment(CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
779
+ };
330
780
  socket.onmessage = (event) => {
331
781
  if (this.ws === socket) this.handleMessage(event.data);
332
782
  };
333
783
  this.connectionWaiters.start((error) => {
334
- this.closeBeforeEstablishment(socket, CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
784
+ closeBeforeEstablishment(CONNECTION_ESTABLISHMENT_TIMEOUT_CODE, error.message);
335
785
  });
336
786
  }
337
787
  /**
@@ -339,8 +789,10 @@ var SessionGatewayClientCore = class {
339
789
  */
340
790
  disconnect() {
341
791
  this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Client disconnected"));
342
- this.cleanup();
343
- this.connectionEstablishedForSocket = false;
792
+ this.heartbeat.stop();
793
+ this.reconnects.cancel();
794
+ this.inbound.requests.rejectAll("Connection closed");
795
+ this.connectionWaiters.established = false;
344
796
  const socket = this.ws;
345
797
  this.ws = null;
346
798
  if (socket) socket.close(1e3, "Client disconnect");
@@ -376,8 +828,7 @@ var SessionGatewayClientCore = class {
376
828
  this.send(message);
377
829
  }
378
830
  async replayAfterConnection(message) {
379
- if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
380
- if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before replay could be requested");
831
+ await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before replay could be requested");
381
832
  this.send(message);
382
833
  }
383
834
  /**
@@ -398,34 +849,19 @@ var SessionGatewayClientCore = class {
398
849
  * Set the current session/execution context for event tracking.
399
850
  */
400
851
  setSessionContext(sessionId, executionId) {
401
- this.currentSessionId = sessionId;
402
- if (executionId) this.currentExecutionId = executionId;
403
- this.saveReplayState();
852
+ this.replayCursor.setContext(sessionId, executionId);
404
853
  }
405
854
  /**
406
855
  * Clear replay state (call when session ends).
407
856
  */
408
857
  clearReplayState() {
409
- this.lastEventId = null;
410
- this.currentExecutionId = null;
411
- this.currentSessionId = null;
412
- this.isReplaying = false;
413
- this.replayProgress = {
414
- total: 0,
415
- received: 0
416
- };
417
- this.processedEventIds.clear();
418
- this.duplicatesSkipped = 0;
419
- this.replayStateStore.clear();
858
+ this.replayCursor.clear();
420
859
  }
421
860
  /**
422
861
  * Get current replay state for UI indicators.
423
862
  */
424
863
  getReplayState() {
425
- return {
426
- isReplaying: this.isReplaying,
427
- progress: { ...this.replayProgress }
428
- };
864
+ return this.replayCursor.state();
429
865
  }
430
866
  /**
431
867
  * Get connection statistics.
@@ -433,15 +869,15 @@ var SessionGatewayClientCore = class {
433
869
  getStats() {
434
870
  return {
435
871
  state: this.state,
436
- connectedAt: this.connectedAt,
437
- lastPingAt: this.lastPingAt,
438
- lastPongAt: this.lastPongAt,
439
- reconnectAttempts: this.reconnectAttempts,
440
- messagesReceived: this.messagesReceived,
441
- messagesSent: this.messagesSent,
442
- eventsReceived: this.eventsReceived,
443
- duplicatesSkipped: this.duplicatesSkipped,
444
- metrics: { ...this.connectionMetrics },
872
+ connectedAt: this.counters.connectedAt,
873
+ lastPingAt: this.heartbeat.lastPingAt,
874
+ lastPongAt: this.heartbeat.lastPongAt,
875
+ reconnectAttempts: this.reconnects.attempts,
876
+ messagesReceived: this.counters.messagesReceived,
877
+ messagesSent: this.counters.messagesSent,
878
+ eventsReceived: this.counters.eventsReceived,
879
+ duplicatesSkipped: this.replayCursor.duplicatesSkipped,
880
+ metrics: this.metrics.snapshot(),
445
881
  replay: this.getReplayState()
446
882
  };
447
883
  }
@@ -452,15 +888,13 @@ var SessionGatewayClientCore = class {
452
888
  return this.state === "connected";
453
889
  }
454
890
  getConnectionQuality() {
455
- return this.connectionMetrics.quality;
891
+ return this.metrics.quality;
456
892
  }
457
893
  getConnectionMetrics() {
458
- return { ...this.connectionMetrics };
894
+ return this.metrics.snapshot();
459
895
  }
460
896
  resetMetrics() {
461
- this.pingLatencyHistory = [];
462
- this.connectionMetrics = { ...this.initialMetrics };
463
- invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
897
+ this.metrics.reset();
464
898
  }
465
899
  /**
466
900
  * Update the auth token and reconnect with the new token.
@@ -479,29 +913,27 @@ var SessionGatewayClientCore = class {
479
913
  setState(state) {
480
914
  if (this.state !== state) {
481
915
  this.state = state;
482
- this.updateConnectionQuality();
916
+ this.metrics.refreshQuality();
483
917
  invokeClientCallback("onStateChange", () => this.handlers.onStateChange?.(state), this.handlers.onError);
484
918
  }
485
919
  }
486
- handleOpen() {
487
- this.missedPongCount = 0;
488
- }
489
920
  handleConnectionEstablished(sessionId) {
490
- if (this.connectionEstablishedForSocket) return;
921
+ if (this.connectionWaiters.established) return;
491
922
  this.connectionWaiters.clear();
492
- const isReconnect = this.hasConnectedBefore;
493
- this.connectionEstablishedForSocket = true;
494
- this.hasConnectedBefore = true;
495
- this.connectedAt = Date.now();
496
- this.reconnectAttempts = 0;
497
- this.startPingInterval();
498
- this.restoreSubscriptions();
923
+ const isReconnect = this.reconnects.hasConnectedBefore;
924
+ this.connectionWaiters.established = true;
925
+ this.reconnects.hasConnectedBefore = true;
926
+ this.counters.connectedAt = Date.now();
927
+ this.reconnects.attempts = 0;
928
+ this.heartbeat.start();
929
+ const subscribe = this.replayCursor.subscribeMessage(this.#config.channels);
930
+ if (subscribe) this.send(subscribe);
499
931
  this.setState("connected");
500
- if (!this.connectionEstablishedForSocket || !this.isConnected()) return;
932
+ if (!this.connectionWaiters.established || !this.isConnected()) return;
501
933
  this.connectionWaiters.resolveAll();
502
934
  invokeClientCallback("onConnect", () => this.handlers.onConnect?.(sessionId), this.handlers.onError);
503
- if (isReconnect && this.connectionEstablishedForSocket && this.isConnected()) {
504
- this.trackReconnection();
935
+ if (isReconnect && this.connectionWaiters.established && this.isConnected()) {
936
+ this.metrics.trackReconnection();
505
937
  invokeClientCallback("onReconnect", () => this.handlers.onReconnect?.(), this.handlers.onError);
506
938
  }
507
939
  }
@@ -509,349 +941,47 @@ var SessionGatewayClientCore = class {
509
941
  if (this.ws !== socket) return;
510
942
  this.connectionWaiters.clear();
511
943
  this.ws = null;
512
- this.connectionEstablishedForSocket = false;
513
- this.cleanup();
514
- if (this.#config.autoReconnect && this.reconnectAttempts < this.#config.maxReconnectAttempts) {
944
+ this.connectionWaiters.established = false;
945
+ this.heartbeat.stop();
946
+ this.reconnects.cancel();
947
+ this.inbound.requests.rejectAll("Connection closed");
948
+ if (this.reconnects.canRetry()) {
515
949
  this.setState("reconnecting");
516
- if (this.state === "reconnecting") this.scheduleReconnect();
950
+ if (this.state === "reconnecting") this.reconnects.schedule(() => {
951
+ if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
952
+ });
517
953
  } else {
518
954
  this.connectionWaiters.rejectAll(/* @__PURE__ */ new Error("Connection closed"));
519
955
  this.setState("disconnected");
520
956
  }
521
957
  invokeClientCallback("onDisconnect", () => this.handlers.onDisconnect?.(code, reason), this.handlers.onError);
522
958
  }
523
- handleError(socket) {
524
- if (this.ws !== socket) return;
525
- this.connectionWaiters.clear();
526
- this.closeBeforeEstablishment(socket, CONNECTION_ERROR_CODE, CONNECTION_ERROR_REASON);
527
- }
528
- closeBeforeEstablishment(socket, code, reason) {
529
- if (this.ws !== socket || this.connectionEstablishedForSocket) return;
530
- try {
531
- socket.close(code, reason);
532
- } finally {
533
- this.handleClose(socket, code, reason);
534
- }
535
- }
536
959
  handleMessage(data) {
537
- this.messagesReceived++;
960
+ this.counters.messagesReceived++;
538
961
  try {
539
- const raw = JSON.parse(data);
540
- if (typeof raw.type !== "string") {
541
- invokeClientCallback("onError", () => this.handlers.onError?.("Session gateway frame is missing a message type", "INVALID_MESSAGE"), void 0);
542
- return;
543
- }
544
- if (raw.data && typeof raw.data === "object") {
545
- const d = raw.data;
546
- if (raw.type === "error") {
547
- if (raw.message === void 0 && typeof d.message === "string") raw.message = d.message;
548
- if (raw.code === void 0 && typeof d.code === "string") raw.code = d.code;
549
- }
550
- }
551
- const message = raw;
962
+ const message = parseServerFrame(data, this.handlers);
963
+ if (!message) return;
552
964
  if (CONTROL_MESSAGE_TYPES.has(message.type)) {
553
- if (message.type === "pong") this.handlePong(message.timestamp);
554
- this.deliverMessage(message);
965
+ if (message.type === "pong") this.heartbeat.handlePong(message.timestamp);
966
+ deliverServerMessage(message, this.inbound);
555
967
  return;
556
968
  }
557
- if ("id" in message && message.id) {
558
- const eventId = message.id;
559
- if (this.#config.enableDeduplication) {
560
- if (this.processedEventIds.has(eventId)) {
561
- this.duplicatesSkipped++;
562
- return;
563
- }
564
- this.processedEventIds.add(eventId);
565
- if (this.processedEventIds.size > this.#config.maxDeduplicationSize) {
566
- const entriesToRemove = Math.floor(this.#config.maxDeduplicationSize * .1);
567
- let removed = 0;
568
- for (const oldId of this.processedEventIds) {
569
- if (removed >= entriesToRemove) break;
570
- this.processedEventIds.delete(oldId);
571
- removed++;
572
- }
573
- }
574
- }
575
- this.lastEventId = eventId;
576
- this.saveReplayState();
577
- }
578
- this.deliverMessage(message);
969
+ if ("id" in message && message.id && !this.replayCursor.accept(message.id)) return;
970
+ deliverServerMessage(message, this.inbound);
579
971
  } catch {}
580
972
  }
581
- handlePong(timestamp) {
582
- const now = Date.now();
583
- this.lastPongAt = timestamp;
584
- this.missedPongCount = 0;
585
- this.clearPongTimeout();
586
- if (this.lastPingSentAt) {
587
- const latency = now - this.lastPingSentAt;
588
- this.pingLatencyHistory.push(latency);
589
- if (this.pingLatencyHistory.length > this.#config.latencyHistorySize) this.pingLatencyHistory.shift();
590
- this.updateConnectionMetrics(latency, now);
591
- }
592
- }
593
- dispatchMessage(message) {
594
- if (message.type === "error" && message.code === "REPLAY_CURSOR_UNAVAILABLE") this.clearReplayState();
595
- if ("id" in message && message.id) {
596
- const callback = this.pendingCallbacks.get(message.id);
597
- if (callback) {
598
- this.pendingCallbacks.delete(message.id);
599
- if (message.type === "error") callback.reject(new Error(message.message));
600
- else callback.resolve("data" in message ? message.data : void 0);
601
- return;
602
- }
603
- }
604
- switch (message.type) {
605
- case "connection.established":
606
- this.handleConnectionEstablished(message.data.sessionId);
607
- break;
608
- case "runtime.connected":
609
- this.handlers.onRuntimeConnected?.(message.data.sandboxId, message.data.baseUrl);
610
- break;
611
- case "runtime.disconnected":
612
- this.handlers.onRuntimeDisconnected?.(message.data.sandboxId, message.data.error);
613
- break;
614
- case "runtime.unavailable":
615
- this.handlers.onRuntimeUnavailable?.(message.data);
616
- break;
617
- case "runtime.not_found":
618
- this.handlers.onRuntimeNotFound?.(message.data.sessionId, message.data.containerId, message.data.reason);
619
- break;
620
- case "runtime.ready":
621
- this.handlers.onRuntimeReady?.(message.data);
622
- break;
623
- case "port.opened":
624
- this.handlers.onPortOpened?.(message.data.port, message.data.protocol, message.data.processName);
625
- break;
626
- case "port.closed":
627
- this.handlers.onPortClosed?.(message.data.port);
628
- break;
629
- case "agent.event":
630
- this.eventsReceived++;
631
- this.trackExecutionContext(message.data);
632
- this.handlers.onAgentEvent?.(message.channel, message.data, message.seq);
633
- break;
634
- case "replay.start":
635
- this.isReplaying = true;
636
- this.replayProgress = {
637
- total: message.total,
638
- received: 0
639
- };
640
- this.handlers.onReplayStart?.(message.total);
641
- break;
642
- case "replay.progress":
643
- this.replayProgress.received = message.received;
644
- this.handlers.onReplayProgress?.(message.received, this.replayProgress.total);
645
- break;
646
- case "replay.complete":
647
- this.isReplaying = false;
648
- this.handlers.onReplayComplete?.(message.total);
649
- break;
650
- case "replay.truncated":
651
- this.handlers.onReplayTruncated?.(message.data);
652
- break;
653
- case "stream.gap":
654
- this.handlers.onStreamGap?.(message.data);
655
- break;
656
- case "stream.dead":
657
- this.handlers.onStreamDead?.(message.data);
658
- break;
659
- case "error":
660
- this.handlers.onError?.(message.message, message.code);
661
- break;
662
- case "token.expiring":
663
- invokeClientCallback("onTokenExpiring", () => this.handlers.onTokenExpiring?.(message.data.secondsRemaining), this.handlers.onError);
664
- this.tokenRefresher.refresh();
665
- break;
666
- case "token.expired":
667
- this.handlers.onTokenExpired?.();
668
- break;
669
- case "backpressure.warning":
670
- this.handlers.onBackpressureWarning?.(message.data.droppedCount, message.data.since, message.data.totalDropped);
671
- break;
672
- }
673
- }
674
- deliverMessage(message) {
675
- invokeClientCallback("message dispatch", () => this.dispatchMessage(message), this.handlers.onError);
676
- invokeClientCallback("onMessage", () => this.handlers.onMessage?.(message), this.handlers.onError);
677
- }
678
- trackExecutionContext(raw) {
679
- if (typeof raw !== "object" || raw === null) return;
680
- const eventData = raw;
681
- if (eventData.executionId) {
682
- this.currentExecutionId = eventData.executionId;
683
- this.saveReplayState();
684
- }
685
- if (eventData.type === "execution.started" && eventData.sessionId) {
686
- this.currentSessionId = eventData.sessionId;
687
- this.saveReplayState();
688
- }
689
- }
690
973
  send(message) {
691
974
  if (this.ws?.readyState === WebSocket.OPEN) {
692
975
  this.ws.send(JSON.stringify(message));
693
- this.messagesSent++;
976
+ this.counters.messagesSent++;
694
977
  }
695
978
  }
696
979
  async sendWithResponse(message) {
697
- if (!this.connectionEstablishedForSocket || !this.isConnected()) await this.waitForConnectionEstablished();
698
- if (!this.connectionEstablishedForSocket || !this.isConnected()) throw new Error("Connection closed before request could be sent");
699
- return new Promise((resolve, reject) => {
700
- const id = `msg_${++this.messageIdCounter}`;
701
- this.pendingCallbacks.set(id, {
702
- resolve,
703
- reject
704
- });
705
- setTimeout(() => {
706
- if (this.pendingCallbacks.has(id)) {
707
- this.pendingCallbacks.delete(id);
708
- reject(/* @__PURE__ */ new Error("Request timeout"));
709
- }
710
- }, 1e4);
711
- this.send({
712
- ...message,
713
- id
714
- });
715
- });
716
- }
717
- waitForConnectionEstablished() {
718
- if (this.connectionEstablishedForSocket && this.isConnected()) return Promise.resolve();
719
- if (this.state === "disconnected") return Promise.reject(/* @__PURE__ */ new Error("Client is not connected"));
720
- return this.connectionWaiters.wait();
721
- }
722
- restoreSubscriptions() {
723
- const channels = this.#config.channels;
724
- const replayOptions = {};
725
- if (this.lastEventId) replayOptions.lastEventId = this.lastEventId;
726
- if (this.currentExecutionId) replayOptions.executionId = this.currentExecutionId;
727
- if (this.currentSessionId) replayOptions.sessionId = this.currentSessionId;
728
- const hasReplayCursor = this.lastEventId !== null;
729
- if (channels.length === 0 && !hasReplayCursor) return;
730
- if (hasReplayCursor) {
731
- this.isReplaying = true;
732
- this.replayProgress = {
733
- total: 0,
734
- received: 0
735
- };
736
- }
737
- this.send({
738
- type: "subscribe",
739
- channels,
740
- ...hasReplayCursor ? { replayOptions } : {}
741
- });
742
- }
743
- startPingInterval() {
744
- this.stopPingInterval();
745
- this.pingInterval = setInterval(() => {
746
- this.sendPing();
747
- }, this.#config.pingIntervalMs);
748
- }
749
- stopPingInterval() {
750
- if (this.pingInterval) {
751
- clearInterval(this.pingInterval);
752
- this.pingInterval = null;
753
- }
754
- }
755
- sendPing() {
756
- if (this.ws?.readyState !== WebSocket.OPEN) return;
757
- const timeSinceLastPong = this.lastPongAt ? Date.now() - this.lastPongAt : 0;
758
- if (this.lastPongAt && timeSinceLastPong > this.#config.pongTimeoutMs) {
759
- this.missedPongCount++;
760
- this.connectionMetrics = {
761
- ...this.connectionMetrics,
762
- missedPongCount: this.missedPongCount
763
- };
764
- this.updateConnectionQuality();
765
- if (this.missedPongCount >= this.#config.maxMissedPongs) {
766
- this.ws?.close(4e3, "Pong timeout - connection unresponsive");
767
- return;
768
- }
769
- }
770
- this.lastPingAt = Date.now();
771
- this.lastPingSentAt = Date.now();
772
- this.send({ type: "ping" });
773
- this.pongTimeout = setTimeout(() => {
774
- this.missedPongCount++;
775
- this.connectionMetrics = {
776
- ...this.connectionMetrics,
777
- missedPongCount: this.missedPongCount
778
- };
779
- this.updateConnectionQuality();
780
- if (this.missedPongCount >= this.#config.maxMissedPongs) this.ws?.close(4e3, "Pong timeout - connection unresponsive");
781
- }, this.#config.pongTimeoutMs);
782
- }
783
- clearPongTimeout() {
784
- if (this.pongTimeout) {
785
- clearTimeout(this.pongTimeout);
786
- this.pongTimeout = null;
787
- }
788
- }
789
- scheduleReconnect() {
790
- if (this.reconnectTimer) return;
791
- this.reconnectAttempts++;
792
- const delay = Math.min(this.#config.initialReconnectDelayMs * 2 ** (this.reconnectAttempts - 1), this.#config.maxReconnectDelayMs);
793
- const jitter = delay * .3 * (Math.random() * 2 - 1);
794
- this.reconnectTimer = setTimeout(() => {
795
- this.reconnectTimer = null;
796
- if (this.state === "reconnecting" && this.ws === null) this.connectWebSocket();
797
- }, delay + jitter);
798
- }
799
- cleanup() {
800
- this.stopPingInterval();
801
- this.clearPongTimeout();
802
- if (this.reconnectTimer) {
803
- clearTimeout(this.reconnectTimer);
804
- this.reconnectTimer = null;
805
- }
806
- for (const [id, callback] of this.pendingCallbacks) {
807
- callback.reject(/* @__PURE__ */ new Error("Connection closed"));
808
- this.pendingCallbacks.delete(id);
809
- }
810
- }
811
- updateConnectionMetrics(latency, pongTime) {
812
- const avgLatency = this.pingLatencyHistory.length > 0 ? this.pingLatencyHistory.reduce((a, b) => a + b, 0) / this.pingLatencyHistory.length : null;
813
- this.connectionMetrics = {
814
- ...this.connectionMetrics,
815
- lastPingLatencyMs: latency,
816
- avgPingLatencyMs: avgLatency,
817
- missedPongCount: this.missedPongCount,
818
- lastPongAt: pongTime
819
- };
820
- this.updateConnectionQuality();
821
- }
822
- updateConnectionQuality() {
823
- const isConnected = this.state === "connected";
824
- const quality = calculateConnectionQuality(this.connectionMetrics, isConnected);
825
- if (this.connectionMetrics.quality !== quality) {
826
- this.connectionMetrics = {
827
- ...this.connectionMetrics,
828
- quality
829
- };
830
- invokeClientCallback("onMetricsChange", () => this.handlers.onMetricsChange?.(this.connectionMetrics), this.handlers.onError);
831
- }
832
- }
833
- trackReconnection() {
834
- const now = Date.now();
835
- this.connectionMetrics = {
836
- ...this.connectionMetrics,
837
- reconnectCount: this.connectionMetrics.reconnectCount + 1,
838
- lastReconnectAt: now
839
- };
840
- this.pingLatencyHistory = [];
841
- this.updateConnectionQuality();
842
- }
843
- loadReplayState() {
844
- const state = this.replayStateStore.load();
845
- this.lastEventId = state.lastEventId;
846
- this.currentExecutionId = state.executionId;
847
- this.currentSessionId = state.sessionId;
848
- }
849
- saveReplayState() {
850
- this.replayStateStore.save({
851
- lastEventId: this.lastEventId,
852
- executionId: this.currentExecutionId,
853
- sessionId: this.currentSessionId
854
- });
980
+ await this.connectionWaiters.awaitEstablished(() => this.state, "Connection closed before request could be sent");
981
+ return this.inbound.requests.request((id) => this.send({
982
+ ...message,
983
+ id
984
+ }));
855
985
  }
856
986
  };
857
987
  //#endregion