@scalemule/sdk 0.0.62 → 0.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -36,6 +36,28 @@ type ApiError = {
36
36
  status: number;
37
37
  /** Additional context (field errors, retryAfter, etc.) */
38
38
  details?: Record<string, unknown>;
39
+ /**
40
+ * Name of the input field this error is about, when the backend
41
+ * attributes it to one (e.g., 'email'). Used by ScaleMule Signals to
42
+ * route the message to the owning form control instead of a toast.
43
+ */
44
+ field?: string;
45
+ /**
46
+ * Correlation id for this request. Taken from the response envelope
47
+ * (`meta.request_id`) and falling back to the `x-request-id` response
48
+ * header echoed by the gateway.
49
+ */
50
+ requestId?: string;
51
+ /** Distributed-trace id, when the backend supplies `meta.trace_id`. */
52
+ traceId?: string;
53
+ /** Backend hint that retrying the same request may succeed. */
54
+ retryable?: boolean;
55
+ /**
56
+ * The raw `error` object from the response body, unmodified. Escape hatch
57
+ * for consumers (such as `@scalemule/signals` `fromError`) that need
58
+ * fields the SDK does not model yet.
59
+ */
60
+ problem?: unknown;
39
61
  };
40
62
  /**
41
63
  * Paginated response envelope.
@@ -777,7 +799,6 @@ interface DirectoryUserDetail {
777
799
  created_at: string;
778
800
  locale?: string;
779
801
  time_zone?: string;
780
- external_role?: string;
781
802
  auth_methods: string[];
782
803
  }
783
804
  interface DirectoryUsersListResponse {
@@ -2011,7 +2032,11 @@ declare class RealtimeService extends ServiceModule {
2011
2032
  private reconnectAttempt;
2012
2033
  private reconnectTimer;
2013
2034
  private heartbeatTimer;
2035
+ private connectWatchdogTimer;
2014
2036
  private authenticated;
2037
+ private lastInboundAt;
2038
+ private wakeHandler;
2039
+ private visibilityHandler;
2015
2040
  /** Current connection status */
2016
2041
  get status(): ConnectionStatus;
2017
2042
  /**
@@ -2051,10 +2076,23 @@ declare class RealtimeService extends ServiceModule {
2051
2076
  private dispatchPresence;
2052
2077
  private sendWs;
2053
2078
  private scheduleReconnect;
2079
+ /** Drop the current socket without triggering its onclose reconnect path. */
2080
+ private teardownSocket;
2081
+ /** Tear down a dead-but-open socket and reconnect. */
2082
+ private forceReconnect;
2083
+ /**
2084
+ * Browsers suspend timers and silently kill sockets during sleep or network
2085
+ * changes. When the page wakes (tab visible, window focused, network back),
2086
+ * verify the connection instead of waiting for the next heartbeat tick.
2087
+ */
2088
+ private installWakeListeners;
2089
+ private removeWakeListeners;
2090
+ private handleWake;
2054
2091
  private getReconnectDelay;
2055
2092
  private startHeartbeat;
2056
2093
  private clearHeartbeat;
2057
2094
  private clearTimers;
2095
+ private clearConnectWatchdog;
2058
2096
  private setStatus;
2059
2097
  }
2060
2098
 
package/dist/index.d.ts CHANGED
@@ -36,6 +36,28 @@ type ApiError = {
36
36
  status: number;
37
37
  /** Additional context (field errors, retryAfter, etc.) */
38
38
  details?: Record<string, unknown>;
39
+ /**
40
+ * Name of the input field this error is about, when the backend
41
+ * attributes it to one (e.g., 'email'). Used by ScaleMule Signals to
42
+ * route the message to the owning form control instead of a toast.
43
+ */
44
+ field?: string;
45
+ /**
46
+ * Correlation id for this request. Taken from the response envelope
47
+ * (`meta.request_id`) and falling back to the `x-request-id` response
48
+ * header echoed by the gateway.
49
+ */
50
+ requestId?: string;
51
+ /** Distributed-trace id, when the backend supplies `meta.trace_id`. */
52
+ traceId?: string;
53
+ /** Backend hint that retrying the same request may succeed. */
54
+ retryable?: boolean;
55
+ /**
56
+ * The raw `error` object from the response body, unmodified. Escape hatch
57
+ * for consumers (such as `@scalemule/signals` `fromError`) that need
58
+ * fields the SDK does not model yet.
59
+ */
60
+ problem?: unknown;
39
61
  };
40
62
  /**
41
63
  * Paginated response envelope.
@@ -777,7 +799,6 @@ interface DirectoryUserDetail {
777
799
  created_at: string;
778
800
  locale?: string;
779
801
  time_zone?: string;
780
- external_role?: string;
781
802
  auth_methods: string[];
782
803
  }
783
804
  interface DirectoryUsersListResponse {
@@ -2011,7 +2032,11 @@ declare class RealtimeService extends ServiceModule {
2011
2032
  private reconnectAttempt;
2012
2033
  private reconnectTimer;
2013
2034
  private heartbeatTimer;
2035
+ private connectWatchdogTimer;
2014
2036
  private authenticated;
2037
+ private lastInboundAt;
2038
+ private wakeHandler;
2039
+ private visibilityHandler;
2015
2040
  /** Current connection status */
2016
2041
  get status(): ConnectionStatus;
2017
2042
  /**
@@ -2051,10 +2076,23 @@ declare class RealtimeService extends ServiceModule {
2051
2076
  private dispatchPresence;
2052
2077
  private sendWs;
2053
2078
  private scheduleReconnect;
2079
+ /** Drop the current socket without triggering its onclose reconnect path. */
2080
+ private teardownSocket;
2081
+ /** Tear down a dead-but-open socket and reconnect. */
2082
+ private forceReconnect;
2083
+ /**
2084
+ * Browsers suspend timers and silently kill sockets during sleep or network
2085
+ * changes. When the page wakes (tab visible, window focused, network back),
2086
+ * verify the connection instead of waiting for the next heartbeat tick.
2087
+ */
2088
+ private installWakeListeners;
2089
+ private removeWakeListeners;
2090
+ private handleWake;
2054
2091
  private getReconnectDelay;
2055
2092
  private startHeartbeat;
2056
2093
  private clearHeartbeat;
2057
2094
  private clearTimers;
2095
+ private clearConnectWatchdog;
2058
2096
  private setStatus;
2059
2097
  }
2060
2098
 
package/dist/index.js CHANGED
@@ -1230,6 +1230,15 @@ var ScaleMuleClient = class {
1230
1230
  status: response.status,
1231
1231
  details: responseData?.error?.details || responseData?.details
1232
1232
  };
1233
+ const field = responseData?.error?.field;
1234
+ if (field !== void 0) error.field = field;
1235
+ const requestId = responseData?.meta?.request_id ?? response.headers.get("x-request-id") ?? void 0;
1236
+ if (requestId !== void 0) error.requestId = requestId;
1237
+ const traceId = responseData?.meta?.trace_id;
1238
+ if (traceId !== void 0) error.traceId = traceId;
1239
+ const retryable = responseData?.error?.retryable;
1240
+ if (retryable !== void 0) error.retryable = retryable;
1241
+ if (responseData?.error !== void 0) error.problem = responseData.error;
1233
1242
  if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
1234
1243
  if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
1235
1244
  let isPrimaryRefresh = false;
@@ -4152,6 +4161,9 @@ function sleep3(ms) {
4152
4161
  var DEFAULT_RECONNECT_BASE_MS = 1e3;
4153
4162
  var MAX_RECONNECT_MS = 3e4;
4154
4163
  var HEARTBEAT_INTERVAL_MS = 3e4;
4164
+ var TICKET_FETCH_TIMEOUT_MS = 1e4;
4165
+ var CONNECT_WATCHDOG_MS = 2e4;
4166
+ var LIVENESS_TIMEOUT_MS = 75e3;
4155
4167
  var RealtimeService = class extends ServiceModule {
4156
4168
  constructor() {
4157
4169
  super(...arguments);
@@ -4165,7 +4177,11 @@ var RealtimeService = class extends ServiceModule {
4165
4177
  this.reconnectAttempt = 0;
4166
4178
  this.reconnectTimer = null;
4167
4179
  this.heartbeatTimer = null;
4180
+ this.connectWatchdogTimer = null;
4168
4181
  this.authenticated = false;
4182
+ this.lastInboundAt = 0;
4183
+ this.wakeHandler = null;
4184
+ this.visibilityHandler = null;
4169
4185
  }
4170
4186
  /** Current connection status */
4171
4187
  get status() {
@@ -4269,6 +4285,7 @@ var RealtimeService = class extends ServiceModule {
4269
4285
  /** Disconnect and clean up all subscriptions. */
4270
4286
  disconnect() {
4271
4287
  this.clearTimers();
4288
+ this.removeWakeListeners();
4272
4289
  this.subscriptions.clear();
4273
4290
  this.presenceCallbacks.clear();
4274
4291
  this.statusCallbacks.clear();
@@ -4287,6 +4304,15 @@ var RealtimeService = class extends ServiceModule {
4287
4304
  connect() {
4288
4305
  if (this._status === "connecting" || this._status === "connected") return;
4289
4306
  this.setStatus(this.reconnectAttempt > 0 ? "reconnecting" : "connecting");
4307
+ this.installWakeListeners();
4308
+ this.clearConnectWatchdog();
4309
+ this.connectWatchdogTimer = setTimeout(() => {
4310
+ this.connectWatchdogTimer = null;
4311
+ if (this._status !== "connected") {
4312
+ this.teardownSocket();
4313
+ this.scheduleReconnect();
4314
+ }
4315
+ }, CONNECT_WATCHDOG_MS);
4290
4316
  this.fetchTicketAndConnect();
4291
4317
  }
4292
4318
  async fetchTicketAndConnect() {
@@ -4297,10 +4323,18 @@ var RealtimeService = class extends ServiceModule {
4297
4323
  if (apiKey) headers["x-api-key"] = apiKey;
4298
4324
  const token = this.client.getSessionToken();
4299
4325
  if (token) headers["Authorization"] = `Bearer ${token}`;
4300
- const ticketRes = await fetch(`${baseUrl}/v1/realtime/ws/ticket`, {
4301
- method: "POST",
4302
- headers
4303
- });
4326
+ const abort = new AbortController();
4327
+ const abortTimer = setTimeout(() => abort.abort(), TICKET_FETCH_TIMEOUT_MS);
4328
+ let ticketRes;
4329
+ try {
4330
+ ticketRes = await fetch(`${baseUrl}/v1/realtime/ws/ticket`, {
4331
+ method: "POST",
4332
+ headers,
4333
+ signal: abort.signal
4334
+ });
4335
+ } finally {
4336
+ clearTimeout(abortTimer);
4337
+ }
4304
4338
  let wsUrl;
4305
4339
  if (ticketRes.ok) {
4306
4340
  const ticketData = await ticketRes.json();
@@ -4318,6 +4352,7 @@ var RealtimeService = class extends ServiceModule {
4318
4352
  }
4319
4353
  this.ws.onopen = () => {
4320
4354
  this.reconnectAttempt = 0;
4355
+ this.lastInboundAt = Date.now();
4321
4356
  if (!this.usedTicketAuth) {
4322
4357
  this.authenticate();
4323
4358
  }
@@ -4335,6 +4370,7 @@ var RealtimeService = class extends ServiceModule {
4335
4370
  }
4336
4371
  };
4337
4372
  this.ws.onmessage = (event) => {
4373
+ this.lastInboundAt = Date.now();
4338
4374
  try {
4339
4375
  const msg = JSON.parse(event.data);
4340
4376
  this.handleMessage(msg);
@@ -4375,6 +4411,10 @@ var RealtimeService = class extends ServiceModule {
4375
4411
  break;
4376
4412
  case "error":
4377
4413
  break;
4414
+ case "reconnect":
4415
+ this.reconnectAttempt = 0;
4416
+ this.forceReconnect();
4417
+ break;
4378
4418
  case "presence_state":
4379
4419
  this.dispatchPresence({
4380
4420
  type: "state",
@@ -4429,6 +4469,7 @@ var RealtimeService = class extends ServiceModule {
4429
4469
  // Private: Reconnection
4430
4470
  // --------------------------------------------------------------------------
4431
4471
  scheduleReconnect() {
4472
+ this.clearConnectWatchdog();
4432
4473
  if (this.subscriptions.size === 0 && this.presenceCallbacks.size === 0) {
4433
4474
  this.setStatus("disconnected");
4434
4475
  return;
@@ -4436,10 +4477,83 @@ var RealtimeService = class extends ServiceModule {
4436
4477
  this.setStatus("reconnecting");
4437
4478
  const delay = this.getReconnectDelay();
4438
4479
  this.reconnectTimer = setTimeout(() => {
4480
+ this.reconnectTimer = null;
4439
4481
  this.reconnectAttempt++;
4440
4482
  this.connect();
4441
4483
  }, delay);
4442
4484
  }
4485
+ /** Drop the current socket without triggering its onclose reconnect path. */
4486
+ teardownSocket() {
4487
+ if (this.ws) {
4488
+ this.ws.onclose = null;
4489
+ this.ws.onerror = null;
4490
+ try {
4491
+ this.ws.close();
4492
+ } catch {
4493
+ }
4494
+ this.ws = null;
4495
+ }
4496
+ this.authenticated = false;
4497
+ this.clearHeartbeat();
4498
+ }
4499
+ /** Tear down a dead-but-open socket and reconnect. */
4500
+ forceReconnect() {
4501
+ this.teardownSocket();
4502
+ this.scheduleReconnect();
4503
+ }
4504
+ // --------------------------------------------------------------------------
4505
+ // Private: Wake / network-change recovery
4506
+ // --------------------------------------------------------------------------
4507
+ /**
4508
+ * Browsers suspend timers and silently kill sockets during sleep or network
4509
+ * changes. When the page wakes (tab visible, window focused, network back),
4510
+ * verify the connection instead of waiting for the next heartbeat tick.
4511
+ */
4512
+ installWakeListeners() {
4513
+ if (this.wakeHandler || typeof window === "undefined") return;
4514
+ this.wakeHandler = () => this.handleWake();
4515
+ window.addEventListener("online", this.wakeHandler);
4516
+ window.addEventListener("focus", this.wakeHandler);
4517
+ if (typeof document !== "undefined") {
4518
+ this.visibilityHandler = () => {
4519
+ if (document.visibilityState === "visible") this.handleWake();
4520
+ };
4521
+ document.addEventListener("visibilitychange", this.visibilityHandler);
4522
+ }
4523
+ }
4524
+ removeWakeListeners() {
4525
+ if (typeof window !== "undefined" && this.wakeHandler) {
4526
+ window.removeEventListener("online", this.wakeHandler);
4527
+ window.removeEventListener("focus", this.wakeHandler);
4528
+ }
4529
+ if (typeof document !== "undefined" && this.visibilityHandler) {
4530
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
4531
+ }
4532
+ this.wakeHandler = null;
4533
+ this.visibilityHandler = null;
4534
+ }
4535
+ handleWake() {
4536
+ if (this.subscriptions.size === 0 && this.presenceCallbacks.size === 0) return;
4537
+ if (this._status === "connected") {
4538
+ if (Date.now() - this.lastInboundAt > LIVENESS_TIMEOUT_MS) {
4539
+ this.reconnectAttempt = 0;
4540
+ this.forceReconnect();
4541
+ } else if (this.ws?.readyState === WebSocket.OPEN) {
4542
+ this.ws.send("ping");
4543
+ }
4544
+ return;
4545
+ }
4546
+ if (this._status === "reconnecting" && this.reconnectTimer) {
4547
+ clearTimeout(this.reconnectTimer);
4548
+ this.reconnectTimer = null;
4549
+ this.reconnectAttempt = 0;
4550
+ this.connect();
4551
+ return;
4552
+ }
4553
+ if (this._status === "disconnected") {
4554
+ this.connect();
4555
+ }
4556
+ }
4443
4557
  getReconnectDelay() {
4444
4558
  const exponential = DEFAULT_RECONNECT_BASE_MS * Math.pow(2, this.reconnectAttempt);
4445
4559
  const jitter = Math.random() * 0.3 * exponential;
@@ -4451,6 +4565,10 @@ var RealtimeService = class extends ServiceModule {
4451
4565
  startHeartbeat() {
4452
4566
  this.clearHeartbeat();
4453
4567
  this.heartbeatTimer = setInterval(() => {
4568
+ if (Date.now() - this.lastInboundAt > LIVENESS_TIMEOUT_MS) {
4569
+ this.forceReconnect();
4570
+ return;
4571
+ }
4454
4572
  if (this.ws?.readyState === WebSocket.OPEN) {
4455
4573
  this.ws.send("ping");
4456
4574
  }
@@ -4464,17 +4582,27 @@ var RealtimeService = class extends ServiceModule {
4464
4582
  }
4465
4583
  clearTimers() {
4466
4584
  this.clearHeartbeat();
4585
+ this.clearConnectWatchdog();
4467
4586
  if (this.reconnectTimer) {
4468
4587
  clearTimeout(this.reconnectTimer);
4469
4588
  this.reconnectTimer = null;
4470
4589
  }
4471
4590
  }
4591
+ clearConnectWatchdog() {
4592
+ if (this.connectWatchdogTimer) {
4593
+ clearTimeout(this.connectWatchdogTimer);
4594
+ this.connectWatchdogTimer = null;
4595
+ }
4596
+ }
4472
4597
  // --------------------------------------------------------------------------
4473
4598
  // Private: Status
4474
4599
  // --------------------------------------------------------------------------
4475
4600
  setStatus(status) {
4476
4601
  if (this._status === status) return;
4477
4602
  this._status = status;
4603
+ if (status === "connected") {
4604
+ this.clearConnectWatchdog();
4605
+ }
4478
4606
  for (const cb of this.statusCallbacks) {
4479
4607
  try {
4480
4608
  cb(status);
package/dist/index.mjs CHANGED
@@ -1126,6 +1126,15 @@ var ScaleMuleClient = class {
1126
1126
  status: response.status,
1127
1127
  details: responseData?.error?.details || responseData?.details
1128
1128
  };
1129
+ const field = responseData?.error?.field;
1130
+ if (field !== void 0) error.field = field;
1131
+ const requestId = responseData?.meta?.request_id ?? response.headers.get("x-request-id") ?? void 0;
1132
+ if (requestId !== void 0) error.requestId = requestId;
1133
+ const traceId = responseData?.meta?.trace_id;
1134
+ if (traceId !== void 0) error.traceId = traceId;
1135
+ const retryable = responseData?.error?.retryable;
1136
+ if (retryable !== void 0) error.retryable = retryable;
1137
+ if (responseData?.error !== void 0) error.problem = responseData.error;
1129
1138
  if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
1130
1139
  if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
1131
1140
  let isPrimaryRefresh = false;
@@ -4048,6 +4057,9 @@ function sleep3(ms) {
4048
4057
  var DEFAULT_RECONNECT_BASE_MS = 1e3;
4049
4058
  var MAX_RECONNECT_MS = 3e4;
4050
4059
  var HEARTBEAT_INTERVAL_MS = 3e4;
4060
+ var TICKET_FETCH_TIMEOUT_MS = 1e4;
4061
+ var CONNECT_WATCHDOG_MS = 2e4;
4062
+ var LIVENESS_TIMEOUT_MS = 75e3;
4051
4063
  var RealtimeService = class extends ServiceModule {
4052
4064
  constructor() {
4053
4065
  super(...arguments);
@@ -4061,7 +4073,11 @@ var RealtimeService = class extends ServiceModule {
4061
4073
  this.reconnectAttempt = 0;
4062
4074
  this.reconnectTimer = null;
4063
4075
  this.heartbeatTimer = null;
4076
+ this.connectWatchdogTimer = null;
4064
4077
  this.authenticated = false;
4078
+ this.lastInboundAt = 0;
4079
+ this.wakeHandler = null;
4080
+ this.visibilityHandler = null;
4065
4081
  }
4066
4082
  /** Current connection status */
4067
4083
  get status() {
@@ -4165,6 +4181,7 @@ var RealtimeService = class extends ServiceModule {
4165
4181
  /** Disconnect and clean up all subscriptions. */
4166
4182
  disconnect() {
4167
4183
  this.clearTimers();
4184
+ this.removeWakeListeners();
4168
4185
  this.subscriptions.clear();
4169
4186
  this.presenceCallbacks.clear();
4170
4187
  this.statusCallbacks.clear();
@@ -4183,6 +4200,15 @@ var RealtimeService = class extends ServiceModule {
4183
4200
  connect() {
4184
4201
  if (this._status === "connecting" || this._status === "connected") return;
4185
4202
  this.setStatus(this.reconnectAttempt > 0 ? "reconnecting" : "connecting");
4203
+ this.installWakeListeners();
4204
+ this.clearConnectWatchdog();
4205
+ this.connectWatchdogTimer = setTimeout(() => {
4206
+ this.connectWatchdogTimer = null;
4207
+ if (this._status !== "connected") {
4208
+ this.teardownSocket();
4209
+ this.scheduleReconnect();
4210
+ }
4211
+ }, CONNECT_WATCHDOG_MS);
4186
4212
  this.fetchTicketAndConnect();
4187
4213
  }
4188
4214
  async fetchTicketAndConnect() {
@@ -4193,10 +4219,18 @@ var RealtimeService = class extends ServiceModule {
4193
4219
  if (apiKey) headers["x-api-key"] = apiKey;
4194
4220
  const token = this.client.getSessionToken();
4195
4221
  if (token) headers["Authorization"] = `Bearer ${token}`;
4196
- const ticketRes = await fetch(`${baseUrl}/v1/realtime/ws/ticket`, {
4197
- method: "POST",
4198
- headers
4199
- });
4222
+ const abort = new AbortController();
4223
+ const abortTimer = setTimeout(() => abort.abort(), TICKET_FETCH_TIMEOUT_MS);
4224
+ let ticketRes;
4225
+ try {
4226
+ ticketRes = await fetch(`${baseUrl}/v1/realtime/ws/ticket`, {
4227
+ method: "POST",
4228
+ headers,
4229
+ signal: abort.signal
4230
+ });
4231
+ } finally {
4232
+ clearTimeout(abortTimer);
4233
+ }
4200
4234
  let wsUrl;
4201
4235
  if (ticketRes.ok) {
4202
4236
  const ticketData = await ticketRes.json();
@@ -4214,6 +4248,7 @@ var RealtimeService = class extends ServiceModule {
4214
4248
  }
4215
4249
  this.ws.onopen = () => {
4216
4250
  this.reconnectAttempt = 0;
4251
+ this.lastInboundAt = Date.now();
4217
4252
  if (!this.usedTicketAuth) {
4218
4253
  this.authenticate();
4219
4254
  }
@@ -4231,6 +4266,7 @@ var RealtimeService = class extends ServiceModule {
4231
4266
  }
4232
4267
  };
4233
4268
  this.ws.onmessage = (event) => {
4269
+ this.lastInboundAt = Date.now();
4234
4270
  try {
4235
4271
  const msg = JSON.parse(event.data);
4236
4272
  this.handleMessage(msg);
@@ -4271,6 +4307,10 @@ var RealtimeService = class extends ServiceModule {
4271
4307
  break;
4272
4308
  case "error":
4273
4309
  break;
4310
+ case "reconnect":
4311
+ this.reconnectAttempt = 0;
4312
+ this.forceReconnect();
4313
+ break;
4274
4314
  case "presence_state":
4275
4315
  this.dispatchPresence({
4276
4316
  type: "state",
@@ -4325,6 +4365,7 @@ var RealtimeService = class extends ServiceModule {
4325
4365
  // Private: Reconnection
4326
4366
  // --------------------------------------------------------------------------
4327
4367
  scheduleReconnect() {
4368
+ this.clearConnectWatchdog();
4328
4369
  if (this.subscriptions.size === 0 && this.presenceCallbacks.size === 0) {
4329
4370
  this.setStatus("disconnected");
4330
4371
  return;
@@ -4332,10 +4373,83 @@ var RealtimeService = class extends ServiceModule {
4332
4373
  this.setStatus("reconnecting");
4333
4374
  const delay = this.getReconnectDelay();
4334
4375
  this.reconnectTimer = setTimeout(() => {
4376
+ this.reconnectTimer = null;
4335
4377
  this.reconnectAttempt++;
4336
4378
  this.connect();
4337
4379
  }, delay);
4338
4380
  }
4381
+ /** Drop the current socket without triggering its onclose reconnect path. */
4382
+ teardownSocket() {
4383
+ if (this.ws) {
4384
+ this.ws.onclose = null;
4385
+ this.ws.onerror = null;
4386
+ try {
4387
+ this.ws.close();
4388
+ } catch {
4389
+ }
4390
+ this.ws = null;
4391
+ }
4392
+ this.authenticated = false;
4393
+ this.clearHeartbeat();
4394
+ }
4395
+ /** Tear down a dead-but-open socket and reconnect. */
4396
+ forceReconnect() {
4397
+ this.teardownSocket();
4398
+ this.scheduleReconnect();
4399
+ }
4400
+ // --------------------------------------------------------------------------
4401
+ // Private: Wake / network-change recovery
4402
+ // --------------------------------------------------------------------------
4403
+ /**
4404
+ * Browsers suspend timers and silently kill sockets during sleep or network
4405
+ * changes. When the page wakes (tab visible, window focused, network back),
4406
+ * verify the connection instead of waiting for the next heartbeat tick.
4407
+ */
4408
+ installWakeListeners() {
4409
+ if (this.wakeHandler || typeof window === "undefined") return;
4410
+ this.wakeHandler = () => this.handleWake();
4411
+ window.addEventListener("online", this.wakeHandler);
4412
+ window.addEventListener("focus", this.wakeHandler);
4413
+ if (typeof document !== "undefined") {
4414
+ this.visibilityHandler = () => {
4415
+ if (document.visibilityState === "visible") this.handleWake();
4416
+ };
4417
+ document.addEventListener("visibilitychange", this.visibilityHandler);
4418
+ }
4419
+ }
4420
+ removeWakeListeners() {
4421
+ if (typeof window !== "undefined" && this.wakeHandler) {
4422
+ window.removeEventListener("online", this.wakeHandler);
4423
+ window.removeEventListener("focus", this.wakeHandler);
4424
+ }
4425
+ if (typeof document !== "undefined" && this.visibilityHandler) {
4426
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
4427
+ }
4428
+ this.wakeHandler = null;
4429
+ this.visibilityHandler = null;
4430
+ }
4431
+ handleWake() {
4432
+ if (this.subscriptions.size === 0 && this.presenceCallbacks.size === 0) return;
4433
+ if (this._status === "connected") {
4434
+ if (Date.now() - this.lastInboundAt > LIVENESS_TIMEOUT_MS) {
4435
+ this.reconnectAttempt = 0;
4436
+ this.forceReconnect();
4437
+ } else if (this.ws?.readyState === WebSocket.OPEN) {
4438
+ this.ws.send("ping");
4439
+ }
4440
+ return;
4441
+ }
4442
+ if (this._status === "reconnecting" && this.reconnectTimer) {
4443
+ clearTimeout(this.reconnectTimer);
4444
+ this.reconnectTimer = null;
4445
+ this.reconnectAttempt = 0;
4446
+ this.connect();
4447
+ return;
4448
+ }
4449
+ if (this._status === "disconnected") {
4450
+ this.connect();
4451
+ }
4452
+ }
4339
4453
  getReconnectDelay() {
4340
4454
  const exponential = DEFAULT_RECONNECT_BASE_MS * Math.pow(2, this.reconnectAttempt);
4341
4455
  const jitter = Math.random() * 0.3 * exponential;
@@ -4347,6 +4461,10 @@ var RealtimeService = class extends ServiceModule {
4347
4461
  startHeartbeat() {
4348
4462
  this.clearHeartbeat();
4349
4463
  this.heartbeatTimer = setInterval(() => {
4464
+ if (Date.now() - this.lastInboundAt > LIVENESS_TIMEOUT_MS) {
4465
+ this.forceReconnect();
4466
+ return;
4467
+ }
4350
4468
  if (this.ws?.readyState === WebSocket.OPEN) {
4351
4469
  this.ws.send("ping");
4352
4470
  }
@@ -4360,17 +4478,27 @@ var RealtimeService = class extends ServiceModule {
4360
4478
  }
4361
4479
  clearTimers() {
4362
4480
  this.clearHeartbeat();
4481
+ this.clearConnectWatchdog();
4363
4482
  if (this.reconnectTimer) {
4364
4483
  clearTimeout(this.reconnectTimer);
4365
4484
  this.reconnectTimer = null;
4366
4485
  }
4367
4486
  }
4487
+ clearConnectWatchdog() {
4488
+ if (this.connectWatchdogTimer) {
4489
+ clearTimeout(this.connectWatchdogTimer);
4490
+ this.connectWatchdogTimer = null;
4491
+ }
4492
+ }
4368
4493
  // --------------------------------------------------------------------------
4369
4494
  // Private: Status
4370
4495
  // --------------------------------------------------------------------------
4371
4496
  setStatus(status) {
4372
4497
  if (this._status === status) return;
4373
4498
  this._status = status;
4499
+ if (status === "connected") {
4500
+ this.clearConnectWatchdog();
4501
+ }
4374
4502
  for (const cb of this.statusCallbacks) {
4375
4503
  try {
4376
4504
  cb(status);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.62",
3
+ "version": "0.0.64",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",