File size: 21,571 Bytes
24b2921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import { io } from "/vendor/socket.io.esm.min.js";
import { getCsrfToken, getRuntimeId, invalidateCsrfToken } from "/js/api.js";
import { getCurrentUserISOString } from "/js/time-utils.js";

const MAX_PAYLOAD_BYTES = 50 * 1024 * 1024; // 50MB hard cap per contract
const DEFAULT_TIMEOUT_MS = 0;

const _UUID_HEX = [..."0123456789abcdef"];
const _OPTION_KEYS = new Set(["correlationId", "includeHandlers", "excludeHandlers", "excludeSids"]);

/**
 * @param {unknown} value
 * @param {string} fieldName
 * @returns {Record<string, any>}
 */
function assertPlainObject(value, fieldName) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${fieldName} must be a plain object`);
  }
  return /** @type {Record<string, any>} */ (value);
}

/**
 * @returns {string}
 */
function generateUuid() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }

  const buffer = new Uint8Array(16);
  if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
    crypto.getRandomValues(buffer);
  } else {
    for (let i = 0; i < buffer.length; i += 1) {
      buffer[i] = Math.floor(Math.random() * 256);
    }
  }

  buffer[6] = (buffer[6] & 0x0f) | 0x40; // version 4
  buffer[8] = (buffer[8] & 0x3f) | 0x80; // variant 10

  let uuid = "";
  for (let i = 0; i < buffer.length; i += 1) {
    if (i === 4 || i === 6 || i === 8 || i === 10) {
      uuid += "-";
    }
    uuid += _UUID_HEX[buffer[i] >> 4];
    uuid += _UUID_HEX[buffer[i] & 0x0f];
  }
  return uuid;
}

/**
 * @param {unknown} value
 * @param {string} fieldName
 * @param {{ allowEmpty?: boolean }} [options]
 * @returns {string[] | undefined}
 */
function normalizeStringList(value, fieldName, options = {}) {
  if (value == null) return undefined;
  const raw = Array.isArray(value) ? value : [value];
  const normalized = [];
  for (const item of raw) {
    if (typeof item !== "string" || item.trim().length === 0) {
      throw new Error(`${fieldName} must contain non-empty strings`);
    }
    normalized.push(item.trim());
  }
  const deduped = Array.from(new Set(normalized));
  if (!options.allowEmpty && deduped.length === 0) {
    throw new Error(`${fieldName} must contain at least one value`);
  }
  return deduped.length > 0 ? deduped : undefined;
}

/**
 * @param {unknown} value
 * @returns {string[] | undefined}
 */
function normalizeSidList(value) {
  return normalizeStringList(value, "excludeSids", { allowEmpty: true });
}

/**
 * @param {unknown} value
 * @returns {string | undefined}
 */
function normalizeCorrelationId(value) {
  if (value == null) return undefined;
  if (typeof value !== "string") {
    throw new Error("correlationId must be a non-empty string");
  }
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error("correlationId must be a non-empty string");
  }
  return trimmed;
}

/**
 * @param {unknown} value
 * @returns {string}
 */
function normalizeNamespace(value) {
  if (typeof value !== "string") {
    throw new Error("namespace must be a non-empty string");
  }
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error("namespace must be a non-empty string");
  }
  if (trimmed === "/") {
    return "/";
  }
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
}

function hasWildcardPattern(value) {
  return typeof value === "string" && value.includes("*");
}

function compileEventPattern(value) {
  const escaped = value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
  return new RegExp(`^${escaped.replaceAll("*", ".*")}$`);
}

/**
 * Generate a correlation identifier using UUIDv4 semantics.
 *
 * @param {string} [prefix]
 * @returns {string}
 */
export function createCorrelationId(prefix) {
  const uuid = generateUuid();
  if (typeof prefix !== "string" || prefix.trim().length === 0) {
    return uuid;
  }

  const normalizedPrefix = prefix.trim();
  const suffix = normalizedPrefix.endsWith("-") ? "" : "-";
  return `${normalizedPrefix}${suffix}${uuid}`;
}

/**
 * @typedef {Object} NormalizedProducerOptions
 * @property {string[]=} includeHandlers
 * @property {string[]=} excludeHandlers
 * @property {string[]=} excludeSids
 * @property {string=} correlationId
 */

/**
 * Normalise producer options used for emit/request/broadcast helpers.
 *
 * @param {Record<string, any> | undefined} options
 * @returns {NormalizedProducerOptions}
 */
export function normalizeProducerOptions(options) {
  if (options == null) return {};
  const source = assertPlainObject(options, "options");

  const unknownKeys = Object.keys(source).filter((key) => !_OPTION_KEYS.has(key));
  if (unknownKeys.length > 0) {
    throw new Error(`Unsupported producer option(s): ${unknownKeys.join(", ")}`);
  }

  const normalized = {};

  const includeHandlers = normalizeStringList(source.includeHandlers, "includeHandlers");
  if (includeHandlers) {
    normalized.includeHandlers = includeHandlers;
  }

  const excludeHandlers = normalizeStringList(
    source.excludeHandlers,
    "excludeHandlers",
    { allowEmpty: true },
  );
  if (excludeHandlers && excludeHandlers.length > 0) {
    normalized.excludeHandlers = excludeHandlers;
  }

  const excludeSids = normalizeSidList(source.excludeSids);
  if (excludeSids && excludeSids.length > 0) {
    normalized.excludeSids = excludeSids;
  }

  const correlationId = normalizeCorrelationId(source.correlationId);
  if (correlationId) {
    normalized.correlationId = correlationId;
  }

  if (normalized.includeHandlers && normalized.excludeHandlers) {
    throw new Error("includeHandlers and excludeHandlers cannot be used together");
  }

  return normalized;
}

/**
 * @typedef {Object} ServerDeliveryEnvelope
 * @property {string} handlerId
 * @property {string} eventId
 * @property {string} correlationId
 * @property {string} ts
 * @property {Record<string, any>} data
 */

/**
 * Validate a server-sent delivery envelope before invoking subscribers.
 *
 * @param {unknown} envelope
 * @returns {ServerDeliveryEnvelope}
 */
export function validateServerEnvelope(envelope) {
  const value = assertPlainObject(envelope, "envelope");

  const handlerId = normalizeCorrelationId(value.handlerId)?.trim();
  if (!handlerId) {
    throw new Error("Server envelope missing handlerId");
  }

  const eventId = normalizeCorrelationId(value.eventId)?.trim();
  if (!eventId) {
    throw new Error("Server envelope missing eventId");
  }

  const correlationId = normalizeCorrelationId(value.correlationId);
  if (!correlationId) {
    throw new Error("Server envelope missing correlationId");
  }

  if (typeof value.ts !== "string" || value.ts.trim().length === 0) {
    throw new Error("Server envelope missing timestamp");
  }
  const timestamp = value.ts.trim();
  if (Number.isNaN(Date.parse(timestamp))) {
    throw new Error("Server envelope timestamp is invalid");
  }

  let data = value.data;
  if (data == null) {
    data = {};
  } else if (typeof data !== "object" || Array.isArray(data)) {
    throw new Error("Server envelope data must be a plain object");
  }

  const normalized = {
    handlerId,
    eventId,
    correlationId,
    ts: timestamp,
    data: Object.freeze({ ...data }),
  };

  return Object.freeze(normalized);
}

class WebSocketClient {
  constructor(namespace = "/") {
    this.namespace = normalizeNamespace(namespace);
    this.socket = null;
    this.connected = false;
    this.connecting = false;
    this.connectPromise = null;
    this.subscriptions = new Map(); // eventType -> { handler, callbacks: Set<Function> }
    this.connectCallbacks = new Set();
    this.disconnectCallbacks = new Set();
    this.errorCallbacks = new Set();
    this.isDevelopment = Boolean(window.runtimeInfo?.isDevelopment);
    this._manualDisconnect = false;
    this._hasConnectedOnce = false;
    this._lastRuntimeId = null;
    this._csrfInvalidatedForConnectError = false;
    this._connectErrorRetryTimer = null;
    this._connectErrorRetryAttempt = 0;
    this._handlers = new Set();
  }

  /**
   * Declare WS handler paths to activate on connect (e.g. "ws_webui").
   * Must be called before connect().
   * @param {string[]} handlers
   */
  addHandlers(handlers) {
    if (!Array.isArray(handlers)) return;
    let changed = false;
    for (const h of handlers) {
      if (typeof h === "string" && h.trim()) {
        const key = h.trim();
        if (!this._handlers.has(key)) {
          this._handlers.add(key);
          changed = true;
        }
      }
    }
    // If new handlers were added while already connected, reconnect so the
    // updated handler list is sent to the server via the auth callback.
    if (changed && this.socket && this.socket.connected) {
      this.debugLog("addHandlers: reconnecting to activate new handlers", [...this._handlers]);
      this.socket.disconnect();
      this.socket.connect();
    }
  }

  _clearConnectErrorRetryTimer() {
    if (this._connectErrorRetryTimer) {
      clearTimeout(this._connectErrorRetryTimer);
      this._connectErrorRetryTimer = null;
    }
  }

  _scheduleConnectErrorRetry(reason) {
    if (this._manualDisconnect) return;
    if (this.connected) return;
    if (!this.socket) return;
    if (this.socket.connected) return;
    if (this._connectErrorRetryTimer) return;

    const attempt = Math.max(0, Number(this._connectErrorRetryAttempt) || 0);
    const baseMs = 250;
    const capMs = 10000;
    const delayMs = Math.min(capMs, baseMs * 2 ** attempt);
    this._connectErrorRetryAttempt = attempt + 1;

    this.debugLog("schedule connect retry", { reason, attempt, delayMs });
    this._connectErrorRetryTimer = setTimeout(() => {
      this._connectErrorRetryTimer = null;
      if (this._manualDisconnect) return;
      if (this.connected) return;
      this.connect().catch(() => {});
    }, delayMs);
  }

  buildPayload(data) {
    const ts = getCurrentUserISOString();
    if (data == null) {
      return { ts, data: {} };
    }
    if (typeof data !== "object" || Array.isArray(data)) {
      throw new Error("WebSocket payload must be a plain object");
    }
    return { ts, data: { ...data } };
  }

  applyProducerOptions(payload, normalizedOptions, allowances) {
    const result = payload;

    if (normalizedOptions.includeHandlers) {
      if (!allowances.includeHandlers) {
        throw new Error("This operation does not support includeHandlers");
      }
      result.includeHandlers = [...normalizedOptions.includeHandlers];
    }

    if (normalizedOptions.excludeHandlers) {
      if (!allowances.excludeHandlers) {
        throw new Error("This operation does not support excludeHandlers");
      }
      result.excludeHandlers = [...normalizedOptions.excludeHandlers];
    }

    if (normalizedOptions.excludeSids) {
      if (!allowances.excludeSids) {
        throw new Error("This operation does not support excludeSids");
      }
      result.excludeSids = [...normalizedOptions.excludeSids];
    }

    if (normalizedOptions.correlationId) {
      result.correlationId = normalizedOptions.correlationId;
    }

    return result;
  }

  setDevelopmentFlag(value) {
    const normalized = Boolean(value);
    this.isDevelopment = normalized;
    window.runtimeInfo = { ...(window.runtimeInfo || {}), isDevelopment: normalized };
  }

  debugLog(...args) {
    if (this.isDevelopment) {
      console.debug(`[websocket:${this.namespace}]`, ...args);
    }
  }

  async connect() {
    if (this.connected) return;
    if (this.connectPromise) return this.connectPromise;

    this._manualDisconnect = false;
    this.connecting = true;
    this.connectPromise = (async () => {
      if (!this.socket) {
        this.initializeSocket();
      }

      if (this.socket.connected) return;

      // Ensure the current runtime-bound session + CSRF cookies exist before initiating
      // the Engine.IO handshake. This is required for seamless reconnect after backend
      // restarts that rotate runtime_id and session cookie names.
      try {
        await getCsrfToken();
      } catch (error) {
        this.debugLog("csrf prefetch failed - continuing", {
          error: error instanceof Error ? error.message : String(error),
        });
      }

      await new Promise((resolve, reject) => {
        const onConnect = () => {
          this.socket.off("connect_error", onError);
          resolve();
        };
        const onError = (error) => {
          this.socket.off("connect", onConnect);
          reject(error instanceof Error ? error : new Error(String(error)));
        };

        this.socket.once("connect", onConnect);
        this.socket.once("connect_error", onError);
        this.socket.connect();
      });
    })()
      .catch((error) => {
        throw new Error(`WebSocket connection failed: ${error.message || error}`);
      })
      .finally(() => {
        this.connecting = false;
        this.connectPromise = null;
      });

    return this.connectPromise;
  }

  async disconnect() {
    if (!this.socket) return;
    this._manualDisconnect = true;
    this.socket.disconnect();
    this.connected = false;
  }

  isConnected() {
    return this.connected;
  }

  async emit(eventType, data, options = {}) {
    const correlationId =
      normalizeCorrelationId(options?.correlationId) || createCorrelationId("emit");
    const payload = this.buildPayload(data);
    payload.correlationId = correlationId;

    this.debugLog("emit", {
      eventType,
      correlationId,
    });
    this.ensurePayloadSize(payload);
    await this.connect();
    if (!this.isConnected()) {
      throw new Error("Not connected");
    }
    this.socket.emit(eventType, payload);
  }

  async request(eventType, data, options = {}) {
    const correlationId =
      normalizeCorrelationId(options?.correlationId) ||
      createCorrelationId("request");
    const payload = this.buildPayload(data);
    payload.correlationId = correlationId;

    const timeoutMs = Number(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
    this.debugLog("request", { eventType, correlationId, timeoutMs });
    if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
      throw new Error("timeoutMs must be a non-negative number");
    }
    this.ensurePayloadSize(payload);
    await this.connect();
    if (!this.isConnected()) {
      throw new Error("Not connected");
    }

    return new Promise((resolve, reject) => {
      if (timeoutMs > 0) {
      this.socket
          .timeout(timeoutMs)
          .emit(eventType, payload, (err, response) => {
          if (err) {
            reject(new Error("Request timeout"));
            return;
          }
            resolve(this.normalizeRequestResponse(response));
          });
        return;
      }

      this.socket.emit(eventType, payload, (response) => {
        resolve(this.normalizeRequestResponse(response));
        });
    });
  }

  normalizeRequestResponse(response) {
    if (!response || typeof response !== "object") {
      return { correlationId: null, results: [] };
    }
    const correlationId =
      typeof response.correlationId === "string" && response.correlationId.trim().length > 0
        ? response.correlationId.trim()
        : null;
    const results = Array.isArray(response.results) ? response.results : [];
    return { correlationId, results };
  }

  async on(eventType, callback) {
    if (typeof callback !== "function") {
      throw new Error("Callback must be a function");
    }

    await this.connect();

    if (!this.subscriptions.has(eventType)) {
      const isWildcard = hasWildcardPattern(eventType);
      const eventPattern = isWildcard ? compileEventPattern(eventType) : null;
      const handler = (...args) => {
        const entry = this.subscriptions.get(eventType);
        if (!entry) return;
        const currentIsWildcard = Boolean(entry.eventPattern);
        const payload = isWildcard ? args[1] : args[0];
        const incomingEventType = isWildcard ? args[0] : eventType;
        if (currentIsWildcard) {
          if (typeof incomingEventType !== "string") return;
          if (!entry.eventPattern.test(incomingEventType)) return;
        }
        let envelope;
        try {
          envelope = validateServerEnvelope(payload);
        } catch (error) {
          console.error("WebSocket envelope validation failed:", error);
          this.invokeErrorCallbacks(error);
          return;
        }

        entry.callbacks.forEach((cb) => {
          try {
            if (currentIsWildcard) {
              cb(incomingEventType, envelope);
              return;
            }
            cb(envelope);
          } catch (error) {
            console.error("WebSocket callback error:", error);
          }
        });
      };

      this.subscriptions.set(eventType, {
        eventPattern,
        handler,
        callbacks: new Set(),
      });

      if (isWildcard) {
        this.socket.onAny(handler);
      } else {
        this.socket.on(eventType, handler);
      }
    }

    const entry = this.subscriptions.get(eventType);
    entry.callbacks.add(callback);
  }

  off(eventType, callback) {
    const entry = this.subscriptions.get(eventType);
    if (!entry) return;

    if (callback) {
      entry.callbacks.delete(callback);
    } else {
      entry.callbacks.clear();
    }

    if (entry.callbacks.size === 0) {
      if (this.socket) {
        if (entry.eventPattern) {
          this.socket.offAny(entry.handler);
        } else {
          this.socket.off(eventType, entry.handler);
        }
      }
      this.subscriptions.delete(eventType);
    }
  }

  onConnect(callback) {
    if (typeof callback === "function") {
      this.connectCallbacks.add(callback);
    }
  }

  onDisconnect(callback) {
    if (typeof callback === "function") {
      this.disconnectCallbacks.add(callback);
    }
  }

  onError(callback) {
    if (typeof callback === "function") {
      this.errorCallbacks.add(callback);
    }
  }

  initializeSocket() {
    this.socket = io(this.namespace, {
      autoConnect: false,
      reconnection: true,
      transports: ["websocket", "polling"],
      withCredentials: true,
      auth: (cb) => {
        const handlers = [...this._handlers];
        getCsrfToken()
          .then((token) => cb({ csrf_token: token, handlers }))
          .catch((error) => {
            console.error("[websocket] failed to fetch CSRF token for connect", error);
            cb({ handlers });
          });
      },
    });

    this.socket.on("connect", () => {
      this.connected = true;
      this._csrfInvalidatedForConnectError = false;
      this._connectErrorRetryAttempt = 0;
      this._clearConnectErrorRetryTimer();

      const runtimeId = getRuntimeId();
      const runtimeChanged = Boolean(
        this._lastRuntimeId &&
          runtimeId &&
          this._lastRuntimeId !== runtimeId
      );
      const firstConnect = !this._hasConnectedOnce;
      this._hasConnectedOnce = true;
      this._lastRuntimeId = runtimeId;

      this.debugLog("socket connected", {
        sid: this.socket.id,
        runtimeId,
        runtimeChanged,
        firstConnect,
      });
      this.connectCallbacks.forEach((cb) => {
        try {
          cb({ runtimeId, runtimeChanged, firstConnect });
        } catch (error) {
          console.error("WebSocket onConnect callback error:", error);
        }
      });
    });

    this.socket.on("disconnect", (reason) => {
      this.connected = false;
      this.debugLog("socket disconnected", { reason });
      this.disconnectCallbacks.forEach((cb) => {
        try {
          cb(reason);
        } catch (error) {
          console.error("WebSocket onDisconnect callback error:", error);
        }
      });
    });

    this.socket.on("connect_error", (error) => {
      this.debugLog("socket connect_error", error);
      this.invokeErrorCallbacks(error);
      if (!this._csrfInvalidatedForConnectError) {
        this._csrfInvalidatedForConnectError = true;
        invalidateCsrfToken();
      }
      this._scheduleConnectErrorRetry("connect_error");
    });

    this.socket.on("error", (error) => {
      this.debugLog("socket error", error);
      this.invokeErrorCallbacks(error);
    });
  }

  invokeErrorCallbacks(error) {
    this.errorCallbacks.forEach((cb) => {
      try {
        cb(error);
      } catch (err) {
        console.error("WebSocket onError callback error:", err);
      }
    });
  }

  ensurePayloadSize(data) {
    const size = this.calculatePayloadSize(data);
    if (size > MAX_PAYLOAD_BYTES) {
      throw new Error("Payload too large");
    }
  }

  calculatePayloadSize(data) {
    try {
      return new TextEncoder().encode(JSON.stringify(data ?? null)).length;
    } catch (_error) {
      // Fallback: rough estimate if stringify fails
      const stringified = String(data);
      return stringified.length * 2;
    }
  }
}

const _namespacedClients = new Map();

/**
 * Create a new Socket.IO client bound to a specific namespace.
 *
 * @param {string} namespace
 * @returns {WebSocketClient}
 */
export function createNamespacedClient(namespace) {
  return new WebSocketClient(namespace);
}

/**
 * Return a cached Socket.IO client for the given namespace (one per browser tab/window).
 *
 * @param {string} namespace
 * @returns {WebSocketClient}
 */
export function getNamespacedClient(namespace) {
  const key = normalizeNamespace(namespace);
  const existing = _namespacedClients.get(key);
  if (existing) return existing;
  const client = new WebSocketClient(key);
  _namespacedClients.set(key, client);
  return client;
}