@estuary-ai/sdk 0.1.24 → 0.1.26

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.mjs CHANGED
@@ -1,6 +1,3868 @@
1
- import { EstuaryError } from './chunk-W5QYPYX3.mjs';
2
- export { ErrorCode, EstuaryError } from './chunk-W5QYPYX3.mjs';
3
- import { io } from 'socket.io-client';
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/errors.ts
12
+ var ErrorCode, EstuaryError;
13
+ var init_errors = __esm({
14
+ "src/errors.ts"() {
15
+ ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
16
+ ErrorCode2["CONNECTION_FAILED"] = "CONNECTION_FAILED";
17
+ ErrorCode2["AUTH_FAILED"] = "AUTH_FAILED";
18
+ ErrorCode2["CONNECTION_TIMEOUT"] = "CONNECTION_TIMEOUT";
19
+ ErrorCode2["QUOTA_EXCEEDED"] = "QUOTA_EXCEEDED";
20
+ ErrorCode2["VOICE_NOT_SUPPORTED"] = "VOICE_NOT_SUPPORTED";
21
+ ErrorCode2["VOICE_ALREADY_ACTIVE"] = "VOICE_ALREADY_ACTIVE";
22
+ ErrorCode2["VOICE_NOT_ACTIVE"] = "VOICE_NOT_ACTIVE";
23
+ ErrorCode2["LIVEKIT_UNAVAILABLE"] = "LIVEKIT_UNAVAILABLE";
24
+ ErrorCode2["MICROPHONE_DENIED"] = "MICROPHONE_DENIED";
25
+ ErrorCode2["NOT_CONNECTED"] = "NOT_CONNECTED";
26
+ ErrorCode2["REST_ERROR"] = "REST_ERROR";
27
+ ErrorCode2["UNKNOWN"] = "UNKNOWN";
28
+ return ErrorCode2;
29
+ })(ErrorCode || {});
30
+ EstuaryError = class extends Error {
31
+ code;
32
+ details;
33
+ constructor(code, message, details) {
34
+ super(message);
35
+ this.name = "EstuaryError";
36
+ this.code = code;
37
+ this.details = details;
38
+ }
39
+ };
40
+ }
41
+ });
42
+
43
+ // src/audio/audio-utils.ts
44
+ function resample(input, fromRate, toRate) {
45
+ const ratio = fromRate / toRate;
46
+ const outputLength = Math.round(input.length / ratio);
47
+ const output = new Float32Array(outputLength);
48
+ for (let i = 0; i < outputLength; i++) {
49
+ const srcIndex = i * ratio;
50
+ const low = Math.floor(srcIndex);
51
+ const high = Math.min(low + 1, input.length - 1);
52
+ const frac = srcIndex - low;
53
+ output[i] = input[low] * (1 - frac) + input[high] * frac;
54
+ }
55
+ return output;
56
+ }
57
+ function float32ToInt16(float32) {
58
+ const int16 = new Int16Array(float32.length);
59
+ for (let i = 0; i < float32.length; i++) {
60
+ const clamped = Math.max(-1, Math.min(1, float32[i]));
61
+ int16[i] = clamped < 0 ? clamped * 32768 : clamped * 32767;
62
+ }
63
+ return int16;
64
+ }
65
+ function uint8ArrayToBase64(bytes) {
66
+ if (typeof btoa === "function") {
67
+ let binary = "";
68
+ for (let i = 0; i < bytes.length; i++) {
69
+ binary += String.fromCharCode(bytes[i]);
70
+ }
71
+ return btoa(binary);
72
+ }
73
+ return Buffer.from(bytes).toString("base64");
74
+ }
75
+ var init_audio_utils = __esm({
76
+ "src/audio/audio-utils.ts"() {
77
+ }
78
+ });
79
+
80
+ // src/voice/websocket-voice.ts
81
+ var websocket_voice_exports = {};
82
+ __export(websocket_voice_exports, {
83
+ WebSocketVoiceManager: () => WebSocketVoiceManager
84
+ });
85
+ var WebSocketVoiceManager;
86
+ var init_websocket_voice = __esm({
87
+ "src/voice/websocket-voice.ts"() {
88
+ init_errors();
89
+ init_audio_utils();
90
+ WebSocketVoiceManager = class {
91
+ socketManager;
92
+ sampleRate;
93
+ logger;
94
+ audioContext = null;
95
+ mediaStream = null;
96
+ scriptProcessor = null;
97
+ sourceNode = null;
98
+ zeroGainNode = null;
99
+ _isMuted = false;
100
+ _isSuppressed = false;
101
+ _isActive = false;
102
+ constructor(socketManager, sampleRate, logger) {
103
+ this.socketManager = socketManager;
104
+ this.sampleRate = sampleRate;
105
+ this.logger = logger;
106
+ }
107
+ get isMuted() {
108
+ return this._isMuted;
109
+ }
110
+ get isActive() {
111
+ return this._isActive;
112
+ }
113
+ async start() {
114
+ if (this._isActive) {
115
+ throw new EstuaryError("VOICE_ALREADY_ACTIVE" /* VOICE_ALREADY_ACTIVE */, "Voice is already active");
116
+ }
117
+ if (typeof AudioContext === "undefined" && typeof globalThis.webkitAudioContext === "undefined") {
118
+ throw new EstuaryError("VOICE_NOT_SUPPORTED" /* VOICE_NOT_SUPPORTED */, "AudioContext is not available in this environment");
119
+ }
120
+ let stream;
121
+ try {
122
+ stream = await navigator.mediaDevices.getUserMedia({
123
+ audio: {
124
+ sampleRate: this.sampleRate,
125
+ channelCount: 1,
126
+ echoCancellation: true,
127
+ noiseSuppression: true,
128
+ autoGainControl: true
129
+ }
130
+ });
131
+ } catch (err) {
132
+ throw new EstuaryError(
133
+ "MICROPHONE_DENIED" /* MICROPHONE_DENIED */,
134
+ "Microphone access denied",
135
+ err
136
+ );
137
+ }
138
+ this.mediaStream = stream;
139
+ const AudioCtx = globalThis.AudioContext || globalThis.webkitAudioContext;
140
+ this.audioContext = new AudioCtx({ sampleRate: this.sampleRate });
141
+ this.sourceNode = this.audioContext.createMediaStreamSource(stream);
142
+ this.scriptProcessor = this.audioContext.createScriptProcessor(4096, 1, 1);
143
+ const nativeRate = this.audioContext.sampleRate;
144
+ const targetRate = this.sampleRate;
145
+ this.scriptProcessor.onaudioprocess = (event) => {
146
+ if (this._isMuted || this._isSuppressed) return;
147
+ const inputData = event.inputBuffer.getChannelData(0);
148
+ let pcmFloat;
149
+ if (nativeRate !== targetRate) {
150
+ pcmFloat = resample(inputData, nativeRate, targetRate);
151
+ } else {
152
+ pcmFloat = inputData;
153
+ }
154
+ const pcm16 = float32ToInt16(pcmFloat);
155
+ const base64 = uint8ArrayToBase64(new Uint8Array(pcm16.buffer));
156
+ try {
157
+ this.socketManager.emitEvent("stream_audio", { audio: base64 });
158
+ } catch {
159
+ }
160
+ };
161
+ this.sourceNode.connect(this.scriptProcessor);
162
+ this.zeroGainNode = this.audioContext.createGain();
163
+ this.zeroGainNode.gain.value = 0;
164
+ this.scriptProcessor.connect(this.zeroGainNode);
165
+ this.zeroGainNode.connect(this.audioContext.destination);
166
+ this._isActive = true;
167
+ this.socketManager.emitEvent("start_voice");
168
+ this.logger.debug("WebSocket voice started");
169
+ }
170
+ async stop() {
171
+ if (!this._isActive) return;
172
+ try {
173
+ this.socketManager.emitEvent("stop_voice");
174
+ } catch {
175
+ }
176
+ this.cleanup();
177
+ this._isActive = false;
178
+ this._isMuted = false;
179
+ this._isSuppressed = false;
180
+ this.logger.debug("WebSocket voice stopped");
181
+ }
182
+ toggleMute() {
183
+ if (!this._isActive || !this.mediaStream) return;
184
+ this._isMuted = !this._isMuted;
185
+ for (const track of this.mediaStream.getAudioTracks()) {
186
+ track.enabled = !this._isMuted;
187
+ }
188
+ this.logger.debug("Mute toggled:", this._isMuted);
189
+ }
190
+ setSuppressed(suppressed) {
191
+ this._isSuppressed = suppressed;
192
+ this.logger.debug("Audio suppression:", suppressed ? "on" : "off");
193
+ }
194
+ dispose() {
195
+ this.cleanup();
196
+ this._isActive = false;
197
+ this._isMuted = false;
198
+ this._isSuppressed = false;
199
+ }
200
+ cleanup() {
201
+ if (this.scriptProcessor) {
202
+ this.scriptProcessor.onaudioprocess = null;
203
+ this.scriptProcessor.disconnect();
204
+ this.scriptProcessor = null;
205
+ }
206
+ if (this.zeroGainNode) {
207
+ this.zeroGainNode.disconnect();
208
+ this.zeroGainNode = null;
209
+ }
210
+ if (this.sourceNode) {
211
+ this.sourceNode.disconnect();
212
+ this.sourceNode = null;
213
+ }
214
+ if (this.mediaStream) {
215
+ for (const track of this.mediaStream.getTracks()) {
216
+ track.stop();
217
+ }
218
+ this.mediaStream = null;
219
+ }
220
+ if (this.audioContext) {
221
+ this.audioContext.close().catch(() => {
222
+ });
223
+ this.audioContext = null;
224
+ }
225
+ }
226
+ };
227
+ }
228
+ });
229
+
230
+ // src/voice/livekit-voice.ts
231
+ var livekit_voice_exports = {};
232
+ __export(livekit_voice_exports, {
233
+ LiveKitVoiceManager: () => LiveKitVoiceManager
234
+ });
235
+ var LiveKitVoiceManager;
236
+ var init_livekit_voice = __esm({
237
+ "src/voice/livekit-voice.ts"() {
238
+ init_errors();
239
+ LiveKitVoiceManager = class {
240
+ socketManager;
241
+ logger;
242
+ room = null;
243
+ // livekit-client Room (dynamically imported)
244
+ _isMuted = false;
245
+ _isActive = false;
246
+ speakingStateCallback = null;
247
+ audioLevelCallback = null;
248
+ // Audio analyser (via livekit-client's createAudioAnalyser)
249
+ calculateVolume = null;
250
+ analyserCleanup = null;
251
+ audioLevelPollTimer = null;
252
+ _isBotSpeaking = false;
253
+ constructor(socketManager, logger) {
254
+ this.socketManager = socketManager;
255
+ this.logger = logger;
256
+ }
257
+ get isMuted() {
258
+ return this._isMuted;
259
+ }
260
+ get isActive() {
261
+ return this._isActive;
262
+ }
263
+ setSpeakingStateCallback(cb) {
264
+ this.speakingStateCallback = cb;
265
+ }
266
+ setAudioLevelCallback(cb) {
267
+ this.audioLevelCallback = cb;
268
+ }
269
+ async start() {
270
+ if (this._isActive) {
271
+ throw new EstuaryError("VOICE_ALREADY_ACTIVE" /* VOICE_ALREADY_ACTIVE */, "Voice is already active");
272
+ }
273
+ let Room;
274
+ let RoomEvent;
275
+ let Track;
276
+ try {
277
+ const lk = await import('livekit-client');
278
+ Room = lk.Room;
279
+ RoomEvent = lk.RoomEvent;
280
+ Track = lk.Track;
281
+ } catch {
282
+ throw new EstuaryError(
283
+ "LIVEKIT_UNAVAILABLE" /* LIVEKIT_UNAVAILABLE */,
284
+ "livekit-client package is not installed"
285
+ );
286
+ }
287
+ const tokenData = await this.requestToken();
288
+ this.room = new Room({
289
+ adaptiveStream: true,
290
+ dynacast: true,
291
+ audioCaptureDefaults: {
292
+ echoCancellation: true,
293
+ noiseSuppression: true,
294
+ autoGainControl: true
295
+ }
296
+ });
297
+ this.room.on(RoomEvent.TrackSubscribed, (track, _publication, participant) => {
298
+ if (track.kind === Track.Kind.Audio) {
299
+ this.logger.debug("Bot audio track subscribed from", participant.identity);
300
+ const audioElement = track.attach();
301
+ audioElement.autoplay = true;
302
+ audioElement.style.display = "none";
303
+ if (typeof document !== "undefined") {
304
+ document.body.appendChild(audioElement);
305
+ }
306
+ audioElement.play().catch(() => {
307
+ });
308
+ this.setupAnalyser(track);
309
+ if (this._isBotSpeaking) {
310
+ setTimeout(() => this.startAudioLevelPolling(), 50);
311
+ }
312
+ }
313
+ });
314
+ this.room.on(RoomEvent.TrackUnsubscribed, (track) => {
315
+ if (track.kind === Track.Kind.Audio) {
316
+ this.teardownAnalyser();
317
+ track.detach().forEach((el) => el.remove());
318
+ }
319
+ });
320
+ this.room.on(RoomEvent.Disconnected, () => {
321
+ this.logger.debug("LiveKit room disconnected");
322
+ this._isActive = false;
323
+ this._isBotSpeaking = false;
324
+ this.teardownAnalyser();
325
+ this.speakingStateCallback?.(false);
326
+ });
327
+ try {
328
+ await this.room.connect(tokenData.url, tokenData.token);
329
+ this.logger.debug("Connected to LiveKit room:", tokenData.room);
330
+ } catch (err) {
331
+ this.room = null;
332
+ const reason = err instanceof Error ? `: ${err.message}` : "";
333
+ throw new EstuaryError(
334
+ "CONNECTION_FAILED" /* CONNECTION_FAILED */,
335
+ `Failed to connect to LiveKit room${reason}`,
336
+ err
337
+ );
338
+ }
339
+ this.room.on(
340
+ RoomEvent.ParticipantAttributesChanged,
341
+ (changedAttributes, participant) => {
342
+ if (participant === this.room?.localParticipant) return;
343
+ const state = changedAttributes["estuary.state"];
344
+ if (state === "speaking") {
345
+ this._isBotSpeaking = true;
346
+ this.speakingStateCallback?.(true);
347
+ this.startAudioLevelPolling();
348
+ } else if (state === "idle") {
349
+ this._isBotSpeaking = false;
350
+ this.stopAudioLevelPolling();
351
+ this.speakingStateCallback?.(false);
352
+ this.audioLevelCallback?.(0);
353
+ }
354
+ }
355
+ );
356
+ try {
357
+ await this.room.localParticipant.setMicrophoneEnabled(true);
358
+ this.logger.debug("Microphone enabled");
359
+ } catch (err) {
360
+ this.room.disconnect();
361
+ this.room = null;
362
+ const reason = err instanceof Error ? `: ${err.message}` : "";
363
+ throw new EstuaryError(
364
+ "MICROPHONE_DENIED" /* MICROPHONE_DENIED */,
365
+ `Failed to enable microphone${reason}`,
366
+ err
367
+ );
368
+ }
369
+ this.socketManager.emitEvent("livekit_join", { room: tokenData.room });
370
+ this._isActive = true;
371
+ this.logger.debug("LiveKit voice started");
372
+ }
373
+ async stop() {
374
+ if (!this._isActive) return;
375
+ try {
376
+ this.socketManager.emitEvent("livekit_leave");
377
+ } catch {
378
+ }
379
+ this._isBotSpeaking = false;
380
+ this.teardownAnalyser();
381
+ this.speakingStateCallback?.(false);
382
+ if (this.room) {
383
+ for (const [, publication] of this.room.localParticipant.trackPublications) {
384
+ if (publication.track) {
385
+ publication.track.stop();
386
+ }
387
+ }
388
+ this.room.disconnect();
389
+ this.room = null;
390
+ }
391
+ this._isActive = false;
392
+ this._isMuted = false;
393
+ this.logger.debug("LiveKit voice stopped");
394
+ }
395
+ toggleMute() {
396
+ if (!this._isActive || !this.room) return;
397
+ this._isMuted = !this._isMuted;
398
+ this.room.localParticipant.setMicrophoneEnabled(!this._isMuted);
399
+ this.logger.debug("Mute toggled:", this._isMuted);
400
+ }
401
+ dispose() {
402
+ this.speakingStateCallback = null;
403
+ this.audioLevelCallback = null;
404
+ this._isBotSpeaking = false;
405
+ this.teardownAnalyser();
406
+ if (this.room) {
407
+ this.room.disconnect();
408
+ this.room = null;
409
+ }
410
+ this._isActive = false;
411
+ this._isMuted = false;
412
+ }
413
+ // ─── Audio Analyser (livekit-client built-in) ───────────────────
414
+ async setupAnalyser(track) {
415
+ this.teardownAnalyser();
416
+ try {
417
+ const { createAudioAnalyser } = await import('livekit-client');
418
+ const { analyser, calculateVolume, cleanup } = createAudioAnalyser(track, {
419
+ fftSize: 256,
420
+ smoothingTimeConstant: 0.3
421
+ });
422
+ if (analyser.context.state === "suspended") {
423
+ await analyser.context.resume();
424
+ }
425
+ this.calculateVolume = calculateVolume;
426
+ this.analyserCleanup = cleanup;
427
+ this.logger.debug("Audio analyser created for bot track");
428
+ } catch (err) {
429
+ this.logger.debug("Failed to create audio analyser:", err);
430
+ }
431
+ }
432
+ teardownAnalyser() {
433
+ this.stopAudioLevelPolling();
434
+ if (this.analyserCleanup) {
435
+ this.analyserCleanup().catch(() => {
436
+ });
437
+ this.analyserCleanup = null;
438
+ }
439
+ this.calculateVolume = null;
440
+ }
441
+ startAudioLevelPolling() {
442
+ if (this.audioLevelPollTimer !== null) return;
443
+ if (!this.calculateVolume) return;
444
+ this.audioLevelPollTimer = setInterval(() => {
445
+ if (!this.calculateVolume) {
446
+ this.stopAudioLevelPolling();
447
+ return;
448
+ }
449
+ const vol = this.calculateVolume();
450
+ this.audioLevelCallback?.(vol);
451
+ }, 33);
452
+ }
453
+ stopAudioLevelPolling() {
454
+ if (this.audioLevelPollTimer !== null) {
455
+ clearInterval(this.audioLevelPollTimer);
456
+ this.audioLevelPollTimer = null;
457
+ }
458
+ }
459
+ // ─── Private ────────────────────────────────────────────────────
460
+ requestToken() {
461
+ return new Promise((resolve, reject) => {
462
+ const timeout = setTimeout(() => {
463
+ this.socketManager.onLiveKitToken(() => {
464
+ });
465
+ reject(new EstuaryError(
466
+ "CONNECTION_TIMEOUT" /* CONNECTION_TIMEOUT */,
467
+ "Timed out waiting for LiveKit token"
468
+ ));
469
+ }, 1e4);
470
+ this.socketManager.onLiveKitToken((data) => {
471
+ clearTimeout(timeout);
472
+ resolve(data);
473
+ });
474
+ this.socketManager.emitEvent("livekit_token");
475
+ });
476
+ }
477
+ };
478
+ }
479
+ });
480
+
481
+ // ../node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/commons.js
482
+ var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
483
+ PACKET_TYPES["open"] = "0";
484
+ PACKET_TYPES["close"] = "1";
485
+ PACKET_TYPES["ping"] = "2";
486
+ PACKET_TYPES["pong"] = "3";
487
+ PACKET_TYPES["message"] = "4";
488
+ PACKET_TYPES["upgrade"] = "5";
489
+ PACKET_TYPES["noop"] = "6";
490
+ var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
491
+ Object.keys(PACKET_TYPES).forEach((key) => {
492
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
493
+ });
494
+ var ERROR_PACKET = { type: "error", data: "parser error" };
495
+
496
+ // ../node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/encodePacket.browser.js
497
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
498
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
499
+ var isView = (obj) => {
500
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
501
+ };
502
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
503
+ if (withNativeBlob && data instanceof Blob) {
504
+ if (supportsBinary) {
505
+ return callback(data);
506
+ } else {
507
+ return encodeBlobAsBase64(data, callback);
508
+ }
509
+ } else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
510
+ if (supportsBinary) {
511
+ return callback(data);
512
+ } else {
513
+ return encodeBlobAsBase64(new Blob([data]), callback);
514
+ }
515
+ }
516
+ return callback(PACKET_TYPES[type] + (data || ""));
517
+ };
518
+ var encodeBlobAsBase64 = (data, callback) => {
519
+ const fileReader = new FileReader();
520
+ fileReader.onload = function() {
521
+ const content = fileReader.result.split(",")[1];
522
+ callback("b" + (content || ""));
523
+ };
524
+ return fileReader.readAsDataURL(data);
525
+ };
526
+ function toArray(data) {
527
+ if (data instanceof Uint8Array) {
528
+ return data;
529
+ } else if (data instanceof ArrayBuffer) {
530
+ return new Uint8Array(data);
531
+ } else {
532
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
533
+ }
534
+ }
535
+ var TEXT_ENCODER;
536
+ function encodePacketToBinary(packet, callback) {
537
+ if (withNativeBlob && packet.data instanceof Blob) {
538
+ return packet.data.arrayBuffer().then(toArray).then(callback);
539
+ } else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
540
+ return callback(toArray(packet.data));
541
+ }
542
+ encodePacket(packet, false, (encoded) => {
543
+ if (!TEXT_ENCODER) {
544
+ TEXT_ENCODER = new TextEncoder();
545
+ }
546
+ callback(TEXT_ENCODER.encode(encoded));
547
+ });
548
+ }
549
+
550
+ // ../node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
551
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
552
+ var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
553
+ for (let i = 0; i < chars.length; i++) {
554
+ lookup[chars.charCodeAt(i)] = i;
555
+ }
556
+ var decode = (base64) => {
557
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
558
+ if (base64[base64.length - 1] === "=") {
559
+ bufferLength--;
560
+ if (base64[base64.length - 2] === "=") {
561
+ bufferLength--;
562
+ }
563
+ }
564
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
565
+ for (i = 0; i < len; i += 4) {
566
+ encoded1 = lookup[base64.charCodeAt(i)];
567
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
568
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
569
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
570
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
571
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
572
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
573
+ }
574
+ return arraybuffer;
575
+ };
576
+
577
+ // ../node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/decodePacket.browser.js
578
+ var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
579
+ var decodePacket = (encodedPacket, binaryType) => {
580
+ if (typeof encodedPacket !== "string") {
581
+ return {
582
+ type: "message",
583
+ data: mapBinary(encodedPacket, binaryType)
584
+ };
585
+ }
586
+ const type = encodedPacket.charAt(0);
587
+ if (type === "b") {
588
+ return {
589
+ type: "message",
590
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
591
+ };
592
+ }
593
+ const packetType = PACKET_TYPES_REVERSE[type];
594
+ if (!packetType) {
595
+ return ERROR_PACKET;
596
+ }
597
+ return encodedPacket.length > 1 ? {
598
+ type: PACKET_TYPES_REVERSE[type],
599
+ data: encodedPacket.substring(1)
600
+ } : {
601
+ type: PACKET_TYPES_REVERSE[type]
602
+ };
603
+ };
604
+ var decodeBase64Packet = (data, binaryType) => {
605
+ if (withNativeArrayBuffer2) {
606
+ const decoded = decode(data);
607
+ return mapBinary(decoded, binaryType);
608
+ } else {
609
+ return { base64: true, data };
610
+ }
611
+ };
612
+ var mapBinary = (data, binaryType) => {
613
+ switch (binaryType) {
614
+ case "blob":
615
+ if (data instanceof Blob) {
616
+ return data;
617
+ } else {
618
+ return new Blob([data]);
619
+ }
620
+ case "arraybuffer":
621
+ default:
622
+ if (data instanceof ArrayBuffer) {
623
+ return data;
624
+ } else {
625
+ return data.buffer;
626
+ }
627
+ }
628
+ };
629
+
630
+ // ../node_modules/.pnpm/engine.io-parser@5.2.3/node_modules/engine.io-parser/build/esm/index.js
631
+ var SEPARATOR = String.fromCharCode(30);
632
+ var encodePayload = (packets, callback) => {
633
+ const length = packets.length;
634
+ const encodedPackets = new Array(length);
635
+ let count = 0;
636
+ packets.forEach((packet, i) => {
637
+ encodePacket(packet, false, (encodedPacket) => {
638
+ encodedPackets[i] = encodedPacket;
639
+ if (++count === length) {
640
+ callback(encodedPackets.join(SEPARATOR));
641
+ }
642
+ });
643
+ });
644
+ };
645
+ var decodePayload = (encodedPayload, binaryType) => {
646
+ const encodedPackets = encodedPayload.split(SEPARATOR);
647
+ const packets = [];
648
+ for (let i = 0; i < encodedPackets.length; i++) {
649
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
650
+ packets.push(decodedPacket);
651
+ if (decodedPacket.type === "error") {
652
+ break;
653
+ }
654
+ }
655
+ return packets;
656
+ };
657
+ function createPacketEncoderStream() {
658
+ return new TransformStream({
659
+ transform(packet, controller) {
660
+ encodePacketToBinary(packet, (encodedPacket) => {
661
+ const payloadLength = encodedPacket.length;
662
+ let header;
663
+ if (payloadLength < 126) {
664
+ header = new Uint8Array(1);
665
+ new DataView(header.buffer).setUint8(0, payloadLength);
666
+ } else if (payloadLength < 65536) {
667
+ header = new Uint8Array(3);
668
+ const view = new DataView(header.buffer);
669
+ view.setUint8(0, 126);
670
+ view.setUint16(1, payloadLength);
671
+ } else {
672
+ header = new Uint8Array(9);
673
+ const view = new DataView(header.buffer);
674
+ view.setUint8(0, 127);
675
+ view.setBigUint64(1, BigInt(payloadLength));
676
+ }
677
+ if (packet.data && typeof packet.data !== "string") {
678
+ header[0] |= 128;
679
+ }
680
+ controller.enqueue(header);
681
+ controller.enqueue(encodedPacket);
682
+ });
683
+ }
684
+ });
685
+ }
686
+ var TEXT_DECODER;
687
+ function totalLength(chunks) {
688
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
689
+ }
690
+ function concatChunks(chunks, size) {
691
+ if (chunks[0].length === size) {
692
+ return chunks.shift();
693
+ }
694
+ const buffer = new Uint8Array(size);
695
+ let j = 0;
696
+ for (let i = 0; i < size; i++) {
697
+ buffer[i] = chunks[0][j++];
698
+ if (j === chunks[0].length) {
699
+ chunks.shift();
700
+ j = 0;
701
+ }
702
+ }
703
+ if (chunks.length && j < chunks[0].length) {
704
+ chunks[0] = chunks[0].slice(j);
705
+ }
706
+ return buffer;
707
+ }
708
+ function createPacketDecoderStream(maxPayload, binaryType) {
709
+ if (!TEXT_DECODER) {
710
+ TEXT_DECODER = new TextDecoder();
711
+ }
712
+ const chunks = [];
713
+ let state = 0;
714
+ let expectedLength = -1;
715
+ let isBinary2 = false;
716
+ return new TransformStream({
717
+ transform(chunk, controller) {
718
+ chunks.push(chunk);
719
+ while (true) {
720
+ if (state === 0) {
721
+ if (totalLength(chunks) < 1) {
722
+ break;
723
+ }
724
+ const header = concatChunks(chunks, 1);
725
+ isBinary2 = (header[0] & 128) === 128;
726
+ expectedLength = header[0] & 127;
727
+ if (expectedLength < 126) {
728
+ state = 3;
729
+ } else if (expectedLength === 126) {
730
+ state = 1;
731
+ } else {
732
+ state = 2;
733
+ }
734
+ } else if (state === 1) {
735
+ if (totalLength(chunks) < 2) {
736
+ break;
737
+ }
738
+ const headerArray = concatChunks(chunks, 2);
739
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
740
+ state = 3;
741
+ } else if (state === 2) {
742
+ if (totalLength(chunks) < 8) {
743
+ break;
744
+ }
745
+ const headerArray = concatChunks(chunks, 8);
746
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
747
+ const n = view.getUint32(0);
748
+ if (n > Math.pow(2, 53 - 32) - 1) {
749
+ controller.enqueue(ERROR_PACKET);
750
+ break;
751
+ }
752
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
753
+ state = 3;
754
+ } else {
755
+ if (totalLength(chunks) < expectedLength) {
756
+ break;
757
+ }
758
+ const data = concatChunks(chunks, expectedLength);
759
+ controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
760
+ state = 0;
761
+ }
762
+ if (expectedLength === 0 || expectedLength > maxPayload) {
763
+ controller.enqueue(ERROR_PACKET);
764
+ break;
765
+ }
766
+ }
767
+ }
768
+ });
769
+ }
770
+ var protocol = 4;
771
+
772
+ // ../node_modules/.pnpm/@socket.io+component-emitter@3.1.2/node_modules/@socket.io/component-emitter/lib/esm/index.js
773
+ function Emitter(obj) {
774
+ if (obj) return mixin(obj);
775
+ }
776
+ function mixin(obj) {
777
+ for (var key in Emitter.prototype) {
778
+ obj[key] = Emitter.prototype[key];
779
+ }
780
+ return obj;
781
+ }
782
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
783
+ this._callbacks = this._callbacks || {};
784
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
785
+ return this;
786
+ };
787
+ Emitter.prototype.once = function(event, fn) {
788
+ function on2() {
789
+ this.off(event, on2);
790
+ fn.apply(this, arguments);
791
+ }
792
+ on2.fn = fn;
793
+ this.on(event, on2);
794
+ return this;
795
+ };
796
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
797
+ this._callbacks = this._callbacks || {};
798
+ if (0 == arguments.length) {
799
+ this._callbacks = {};
800
+ return this;
801
+ }
802
+ var callbacks = this._callbacks["$" + event];
803
+ if (!callbacks) return this;
804
+ if (1 == arguments.length) {
805
+ delete this._callbacks["$" + event];
806
+ return this;
807
+ }
808
+ var cb;
809
+ for (var i = 0; i < callbacks.length; i++) {
810
+ cb = callbacks[i];
811
+ if (cb === fn || cb.fn === fn) {
812
+ callbacks.splice(i, 1);
813
+ break;
814
+ }
815
+ }
816
+ if (callbacks.length === 0) {
817
+ delete this._callbacks["$" + event];
818
+ }
819
+ return this;
820
+ };
821
+ Emitter.prototype.emit = function(event) {
822
+ this._callbacks = this._callbacks || {};
823
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
824
+ for (var i = 1; i < arguments.length; i++) {
825
+ args[i - 1] = arguments[i];
826
+ }
827
+ if (callbacks) {
828
+ callbacks = callbacks.slice(0);
829
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
830
+ callbacks[i].apply(this, args);
831
+ }
832
+ }
833
+ return this;
834
+ };
835
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
836
+ Emitter.prototype.listeners = function(event) {
837
+ this._callbacks = this._callbacks || {};
838
+ return this._callbacks["$" + event] || [];
839
+ };
840
+ Emitter.prototype.hasListeners = function(event) {
841
+ return !!this.listeners(event).length;
842
+ };
843
+
844
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/globals.js
845
+ var nextTick = (() => {
846
+ const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
847
+ if (isPromiseAvailable) {
848
+ return (cb) => Promise.resolve().then(cb);
849
+ } else {
850
+ return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
851
+ }
852
+ })();
853
+ var globalThisShim = (() => {
854
+ if (typeof self !== "undefined") {
855
+ return self;
856
+ } else if (typeof window !== "undefined") {
857
+ return window;
858
+ } else {
859
+ return Function("return this")();
860
+ }
861
+ })();
862
+ var defaultBinaryType = "arraybuffer";
863
+ function createCookieJar() {
864
+ }
865
+
866
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/util.js
867
+ function pick(obj, ...attr) {
868
+ return attr.reduce((acc, k) => {
869
+ if (obj.hasOwnProperty(k)) {
870
+ acc[k] = obj[k];
871
+ }
872
+ return acc;
873
+ }, {});
874
+ }
875
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
876
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
877
+ function installTimerFunctions(obj, opts) {
878
+ if (opts.useNativeTimers) {
879
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
880
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
881
+ } else {
882
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
883
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
884
+ }
885
+ }
886
+ var BASE64_OVERHEAD = 1.33;
887
+ function byteLength(obj) {
888
+ if (typeof obj === "string") {
889
+ return utf8Length(obj);
890
+ }
891
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
892
+ }
893
+ function utf8Length(str) {
894
+ let c = 0, length = 0;
895
+ for (let i = 0, l = str.length; i < l; i++) {
896
+ c = str.charCodeAt(i);
897
+ if (c < 128) {
898
+ length += 1;
899
+ } else if (c < 2048) {
900
+ length += 2;
901
+ } else if (c < 55296 || c >= 57344) {
902
+ length += 3;
903
+ } else {
904
+ i++;
905
+ length += 4;
906
+ }
907
+ }
908
+ return length;
909
+ }
910
+ function randomString() {
911
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
912
+ }
913
+
914
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/parseqs.js
915
+ function encode(obj) {
916
+ let str = "";
917
+ for (let i in obj) {
918
+ if (obj.hasOwnProperty(i)) {
919
+ if (str.length)
920
+ str += "&";
921
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
922
+ }
923
+ }
924
+ return str;
925
+ }
926
+ function decode2(qs) {
927
+ let qry = {};
928
+ let pairs = qs.split("&");
929
+ for (let i = 0, l = pairs.length; i < l; i++) {
930
+ let pair = pairs[i].split("=");
931
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
932
+ }
933
+ return qry;
934
+ }
935
+
936
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transport.js
937
+ var TransportError = class extends Error {
938
+ constructor(reason, description, context) {
939
+ super(reason);
940
+ this.description = description;
941
+ this.context = context;
942
+ this.type = "TransportError";
943
+ }
944
+ };
945
+ var Transport = class extends Emitter {
946
+ /**
947
+ * Transport abstract constructor.
948
+ *
949
+ * @param {Object} opts - options
950
+ * @protected
951
+ */
952
+ constructor(opts) {
953
+ super();
954
+ this.writable = false;
955
+ installTimerFunctions(this, opts);
956
+ this.opts = opts;
957
+ this.query = opts.query;
958
+ this.socket = opts.socket;
959
+ this.supportsBinary = !opts.forceBase64;
960
+ }
961
+ /**
962
+ * Emits an error.
963
+ *
964
+ * @param {String} reason
965
+ * @param description
966
+ * @param context - the error context
967
+ * @return {Transport} for chaining
968
+ * @protected
969
+ */
970
+ onError(reason, description, context) {
971
+ super.emitReserved("error", new TransportError(reason, description, context));
972
+ return this;
973
+ }
974
+ /**
975
+ * Opens the transport.
976
+ */
977
+ open() {
978
+ this.readyState = "opening";
979
+ this.doOpen();
980
+ return this;
981
+ }
982
+ /**
983
+ * Closes the transport.
984
+ */
985
+ close() {
986
+ if (this.readyState === "opening" || this.readyState === "open") {
987
+ this.doClose();
988
+ this.onClose();
989
+ }
990
+ return this;
991
+ }
992
+ /**
993
+ * Sends multiple packets.
994
+ *
995
+ * @param {Array} packets
996
+ */
997
+ send(packets) {
998
+ if (this.readyState === "open") {
999
+ this.write(packets);
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Called upon open
1004
+ *
1005
+ * @protected
1006
+ */
1007
+ onOpen() {
1008
+ this.readyState = "open";
1009
+ this.writable = true;
1010
+ super.emitReserved("open");
1011
+ }
1012
+ /**
1013
+ * Called with data.
1014
+ *
1015
+ * @param {String} data
1016
+ * @protected
1017
+ */
1018
+ onData(data) {
1019
+ const packet = decodePacket(data, this.socket.binaryType);
1020
+ this.onPacket(packet);
1021
+ }
1022
+ /**
1023
+ * Called with a decoded packet.
1024
+ *
1025
+ * @protected
1026
+ */
1027
+ onPacket(packet) {
1028
+ super.emitReserved("packet", packet);
1029
+ }
1030
+ /**
1031
+ * Called upon close.
1032
+ *
1033
+ * @protected
1034
+ */
1035
+ onClose(details) {
1036
+ this.readyState = "closed";
1037
+ super.emitReserved("close", details);
1038
+ }
1039
+ /**
1040
+ * Pauses the transport, in order not to lose packets during an upgrade.
1041
+ *
1042
+ * @param onPause
1043
+ */
1044
+ pause(onPause) {
1045
+ }
1046
+ createUri(schema, query = {}) {
1047
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
1048
+ }
1049
+ _hostname() {
1050
+ const hostname = this.opts.hostname;
1051
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
1052
+ }
1053
+ _port() {
1054
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
1055
+ return ":" + this.opts.port;
1056
+ } else {
1057
+ return "";
1058
+ }
1059
+ }
1060
+ _query(query) {
1061
+ const encodedQuery = encode(query);
1062
+ return encodedQuery.length ? "?" + encodedQuery : "";
1063
+ }
1064
+ };
1065
+
1066
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/polling.js
1067
+ var Polling = class extends Transport {
1068
+ constructor() {
1069
+ super(...arguments);
1070
+ this._polling = false;
1071
+ }
1072
+ get name() {
1073
+ return "polling";
1074
+ }
1075
+ /**
1076
+ * Opens the socket (triggers polling). We write a PING message to determine
1077
+ * when the transport is open.
1078
+ *
1079
+ * @protected
1080
+ */
1081
+ doOpen() {
1082
+ this._poll();
1083
+ }
1084
+ /**
1085
+ * Pauses polling.
1086
+ *
1087
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
1088
+ * @package
1089
+ */
1090
+ pause(onPause) {
1091
+ this.readyState = "pausing";
1092
+ const pause = () => {
1093
+ this.readyState = "paused";
1094
+ onPause();
1095
+ };
1096
+ if (this._polling || !this.writable) {
1097
+ let total = 0;
1098
+ if (this._polling) {
1099
+ total++;
1100
+ this.once("pollComplete", function() {
1101
+ --total || pause();
1102
+ });
1103
+ }
1104
+ if (!this.writable) {
1105
+ total++;
1106
+ this.once("drain", function() {
1107
+ --total || pause();
1108
+ });
1109
+ }
1110
+ } else {
1111
+ pause();
1112
+ }
1113
+ }
1114
+ /**
1115
+ * Starts polling cycle.
1116
+ *
1117
+ * @private
1118
+ */
1119
+ _poll() {
1120
+ this._polling = true;
1121
+ this.doPoll();
1122
+ this.emitReserved("poll");
1123
+ }
1124
+ /**
1125
+ * Overloads onData to detect payloads.
1126
+ *
1127
+ * @protected
1128
+ */
1129
+ onData(data) {
1130
+ const callback = (packet) => {
1131
+ if ("opening" === this.readyState && packet.type === "open") {
1132
+ this.onOpen();
1133
+ }
1134
+ if ("close" === packet.type) {
1135
+ this.onClose({ description: "transport closed by the server" });
1136
+ return false;
1137
+ }
1138
+ this.onPacket(packet);
1139
+ };
1140
+ decodePayload(data, this.socket.binaryType).forEach(callback);
1141
+ if ("closed" !== this.readyState) {
1142
+ this._polling = false;
1143
+ this.emitReserved("pollComplete");
1144
+ if ("open" === this.readyState) {
1145
+ this._poll();
1146
+ }
1147
+ }
1148
+ }
1149
+ /**
1150
+ * For polling, send a close packet.
1151
+ *
1152
+ * @protected
1153
+ */
1154
+ doClose() {
1155
+ const close = () => {
1156
+ this.write([{ type: "close" }]);
1157
+ };
1158
+ if ("open" === this.readyState) {
1159
+ close();
1160
+ } else {
1161
+ this.once("open", close);
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Writes a packets payload.
1166
+ *
1167
+ * @param {Array} packets - data packets
1168
+ * @protected
1169
+ */
1170
+ write(packets) {
1171
+ this.writable = false;
1172
+ encodePayload(packets, (data) => {
1173
+ this.doWrite(data, () => {
1174
+ this.writable = true;
1175
+ this.emitReserved("drain");
1176
+ });
1177
+ });
1178
+ }
1179
+ /**
1180
+ * Generates uri for connection.
1181
+ *
1182
+ * @private
1183
+ */
1184
+ uri() {
1185
+ const schema = this.opts.secure ? "https" : "http";
1186
+ const query = this.query || {};
1187
+ if (false !== this.opts.timestampRequests) {
1188
+ query[this.opts.timestampParam] = randomString();
1189
+ }
1190
+ if (!this.supportsBinary && !query.sid) {
1191
+ query.b64 = 1;
1192
+ }
1193
+ return this.createUri(schema, query);
1194
+ }
1195
+ };
1196
+
1197
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/has-cors.js
1198
+ var value = false;
1199
+ try {
1200
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
1201
+ } catch (err) {
1202
+ }
1203
+ var hasCORS = value;
1204
+
1205
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/polling-xhr.js
1206
+ function empty() {
1207
+ }
1208
+ var BaseXHR = class extends Polling {
1209
+ /**
1210
+ * XHR Polling constructor.
1211
+ *
1212
+ * @param {Object} opts
1213
+ * @package
1214
+ */
1215
+ constructor(opts) {
1216
+ super(opts);
1217
+ if (typeof location !== "undefined") {
1218
+ const isSSL = "https:" === location.protocol;
1219
+ let port = location.port;
1220
+ if (!port) {
1221
+ port = isSSL ? "443" : "80";
1222
+ }
1223
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
1224
+ }
1225
+ }
1226
+ /**
1227
+ * Sends data.
1228
+ *
1229
+ * @param {String} data to send.
1230
+ * @param {Function} called upon flush.
1231
+ * @private
1232
+ */
1233
+ doWrite(data, fn) {
1234
+ const req = this.request({
1235
+ method: "POST",
1236
+ data
1237
+ });
1238
+ req.on("success", fn);
1239
+ req.on("error", (xhrStatus, context) => {
1240
+ this.onError("xhr post error", xhrStatus, context);
1241
+ });
1242
+ }
1243
+ /**
1244
+ * Starts a poll cycle.
1245
+ *
1246
+ * @private
1247
+ */
1248
+ doPoll() {
1249
+ const req = this.request();
1250
+ req.on("data", this.onData.bind(this));
1251
+ req.on("error", (xhrStatus, context) => {
1252
+ this.onError("xhr poll error", xhrStatus, context);
1253
+ });
1254
+ this.pollXhr = req;
1255
+ }
1256
+ };
1257
+ var Request = class _Request extends Emitter {
1258
+ /**
1259
+ * Request constructor
1260
+ *
1261
+ * @param {Object} options
1262
+ * @package
1263
+ */
1264
+ constructor(createRequest, uri, opts) {
1265
+ super();
1266
+ this.createRequest = createRequest;
1267
+ installTimerFunctions(this, opts);
1268
+ this._opts = opts;
1269
+ this._method = opts.method || "GET";
1270
+ this._uri = uri;
1271
+ this._data = void 0 !== opts.data ? opts.data : null;
1272
+ this._create();
1273
+ }
1274
+ /**
1275
+ * Creates the XHR object and sends the request.
1276
+ *
1277
+ * @private
1278
+ */
1279
+ _create() {
1280
+ var _a;
1281
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
1282
+ opts.xdomain = !!this._opts.xd;
1283
+ const xhr = this._xhr = this.createRequest(opts);
1284
+ try {
1285
+ xhr.open(this._method, this._uri, true);
1286
+ try {
1287
+ if (this._opts.extraHeaders) {
1288
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
1289
+ for (let i in this._opts.extraHeaders) {
1290
+ if (this._opts.extraHeaders.hasOwnProperty(i)) {
1291
+ xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
1292
+ }
1293
+ }
1294
+ }
1295
+ } catch (e) {
1296
+ }
1297
+ if ("POST" === this._method) {
1298
+ try {
1299
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
1300
+ } catch (e) {
1301
+ }
1302
+ }
1303
+ try {
1304
+ xhr.setRequestHeader("Accept", "*/*");
1305
+ } catch (e) {
1306
+ }
1307
+ (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
1308
+ if ("withCredentials" in xhr) {
1309
+ xhr.withCredentials = this._opts.withCredentials;
1310
+ }
1311
+ if (this._opts.requestTimeout) {
1312
+ xhr.timeout = this._opts.requestTimeout;
1313
+ }
1314
+ xhr.onreadystatechange = () => {
1315
+ var _a2;
1316
+ if (xhr.readyState === 3) {
1317
+ (_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
1318
+ // @ts-ignore
1319
+ xhr.getResponseHeader("set-cookie")
1320
+ );
1321
+ }
1322
+ if (4 !== xhr.readyState)
1323
+ return;
1324
+ if (200 === xhr.status || 1223 === xhr.status) {
1325
+ this._onLoad();
1326
+ } else {
1327
+ this.setTimeoutFn(() => {
1328
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
1329
+ }, 0);
1330
+ }
1331
+ };
1332
+ xhr.send(this._data);
1333
+ } catch (e) {
1334
+ this.setTimeoutFn(() => {
1335
+ this._onError(e);
1336
+ }, 0);
1337
+ return;
1338
+ }
1339
+ if (typeof document !== "undefined") {
1340
+ this._index = _Request.requestsCount++;
1341
+ _Request.requests[this._index] = this;
1342
+ }
1343
+ }
1344
+ /**
1345
+ * Called upon error.
1346
+ *
1347
+ * @private
1348
+ */
1349
+ _onError(err) {
1350
+ this.emitReserved("error", err, this._xhr);
1351
+ this._cleanup(true);
1352
+ }
1353
+ /**
1354
+ * Cleans up house.
1355
+ *
1356
+ * @private
1357
+ */
1358
+ _cleanup(fromError) {
1359
+ if ("undefined" === typeof this._xhr || null === this._xhr) {
1360
+ return;
1361
+ }
1362
+ this._xhr.onreadystatechange = empty;
1363
+ if (fromError) {
1364
+ try {
1365
+ this._xhr.abort();
1366
+ } catch (e) {
1367
+ }
1368
+ }
1369
+ if (typeof document !== "undefined") {
1370
+ delete _Request.requests[this._index];
1371
+ }
1372
+ this._xhr = null;
1373
+ }
1374
+ /**
1375
+ * Called upon load.
1376
+ *
1377
+ * @private
1378
+ */
1379
+ _onLoad() {
1380
+ const data = this._xhr.responseText;
1381
+ if (data !== null) {
1382
+ this.emitReserved("data", data);
1383
+ this.emitReserved("success");
1384
+ this._cleanup();
1385
+ }
1386
+ }
1387
+ /**
1388
+ * Aborts the request.
1389
+ *
1390
+ * @package
1391
+ */
1392
+ abort() {
1393
+ this._cleanup();
1394
+ }
1395
+ };
1396
+ Request.requestsCount = 0;
1397
+ Request.requests = {};
1398
+ if (typeof document !== "undefined") {
1399
+ if (typeof attachEvent === "function") {
1400
+ attachEvent("onunload", unloadHandler);
1401
+ } else if (typeof addEventListener === "function") {
1402
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
1403
+ addEventListener(terminationEvent, unloadHandler, false);
1404
+ }
1405
+ }
1406
+ function unloadHandler() {
1407
+ for (let i in Request.requests) {
1408
+ if (Request.requests.hasOwnProperty(i)) {
1409
+ Request.requests[i].abort();
1410
+ }
1411
+ }
1412
+ }
1413
+ var hasXHR2 = (function() {
1414
+ const xhr = newRequest({
1415
+ xdomain: false
1416
+ });
1417
+ return xhr && xhr.responseType !== null;
1418
+ })();
1419
+ var XHR = class extends BaseXHR {
1420
+ constructor(opts) {
1421
+ super(opts);
1422
+ const forceBase64 = opts && opts.forceBase64;
1423
+ this.supportsBinary = hasXHR2 && !forceBase64;
1424
+ }
1425
+ request(opts = {}) {
1426
+ Object.assign(opts, { xd: this.xd }, this.opts);
1427
+ return new Request(newRequest, this.uri(), opts);
1428
+ }
1429
+ };
1430
+ function newRequest(opts) {
1431
+ const xdomain = opts.xdomain;
1432
+ try {
1433
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
1434
+ return new XMLHttpRequest();
1435
+ }
1436
+ } catch (e) {
1437
+ }
1438
+ if (!xdomain) {
1439
+ try {
1440
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
1441
+ } catch (e) {
1442
+ }
1443
+ }
1444
+ }
1445
+
1446
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/websocket.js
1447
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
1448
+ var BaseWS = class extends Transport {
1449
+ get name() {
1450
+ return "websocket";
1451
+ }
1452
+ doOpen() {
1453
+ const uri = this.uri();
1454
+ const protocols = this.opts.protocols;
1455
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1456
+ if (this.opts.extraHeaders) {
1457
+ opts.headers = this.opts.extraHeaders;
1458
+ }
1459
+ try {
1460
+ this.ws = this.createSocket(uri, protocols, opts);
1461
+ } catch (err) {
1462
+ return this.emitReserved("error", err);
1463
+ }
1464
+ this.ws.binaryType = this.socket.binaryType;
1465
+ this.addEventListeners();
1466
+ }
1467
+ /**
1468
+ * Adds event listeners to the socket
1469
+ *
1470
+ * @private
1471
+ */
1472
+ addEventListeners() {
1473
+ this.ws.onopen = () => {
1474
+ if (this.opts.autoUnref) {
1475
+ this.ws._socket.unref();
1476
+ }
1477
+ this.onOpen();
1478
+ };
1479
+ this.ws.onclose = (closeEvent) => this.onClose({
1480
+ description: "websocket connection closed",
1481
+ context: closeEvent
1482
+ });
1483
+ this.ws.onmessage = (ev) => this.onData(ev.data);
1484
+ this.ws.onerror = (e) => this.onError("websocket error", e);
1485
+ }
1486
+ write(packets) {
1487
+ this.writable = false;
1488
+ for (let i = 0; i < packets.length; i++) {
1489
+ const packet = packets[i];
1490
+ const lastPacket = i === packets.length - 1;
1491
+ encodePacket(packet, this.supportsBinary, (data) => {
1492
+ try {
1493
+ this.doWrite(packet, data);
1494
+ } catch (e) {
1495
+ }
1496
+ if (lastPacket) {
1497
+ nextTick(() => {
1498
+ this.writable = true;
1499
+ this.emitReserved("drain");
1500
+ }, this.setTimeoutFn);
1501
+ }
1502
+ });
1503
+ }
1504
+ }
1505
+ doClose() {
1506
+ if (typeof this.ws !== "undefined") {
1507
+ this.ws.onerror = () => {
1508
+ };
1509
+ this.ws.close();
1510
+ this.ws = null;
1511
+ }
1512
+ }
1513
+ /**
1514
+ * Generates uri for connection.
1515
+ *
1516
+ * @private
1517
+ */
1518
+ uri() {
1519
+ const schema = this.opts.secure ? "wss" : "ws";
1520
+ const query = this.query || {};
1521
+ if (this.opts.timestampRequests) {
1522
+ query[this.opts.timestampParam] = randomString();
1523
+ }
1524
+ if (!this.supportsBinary) {
1525
+ query.b64 = 1;
1526
+ }
1527
+ return this.createUri(schema, query);
1528
+ }
1529
+ };
1530
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1531
+ var WS = class extends BaseWS {
1532
+ createSocket(uri, protocols, opts) {
1533
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
1534
+ }
1535
+ doWrite(_packet, data) {
1536
+ this.ws.send(data);
1537
+ }
1538
+ };
1539
+
1540
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/webtransport.js
1541
+ var WT = class extends Transport {
1542
+ get name() {
1543
+ return "webtransport";
1544
+ }
1545
+ doOpen() {
1546
+ try {
1547
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1548
+ } catch (err) {
1549
+ return this.emitReserved("error", err);
1550
+ }
1551
+ this._transport.closed.then(() => {
1552
+ this.onClose();
1553
+ }).catch((err) => {
1554
+ this.onError("webtransport error", err);
1555
+ });
1556
+ this._transport.ready.then(() => {
1557
+ this._transport.createBidirectionalStream().then((stream) => {
1558
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1559
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
1560
+ const encoderStream = createPacketEncoderStream();
1561
+ encoderStream.readable.pipeTo(stream.writable);
1562
+ this._writer = encoderStream.writable.getWriter();
1563
+ const read = () => {
1564
+ reader.read().then(({ done, value: value2 }) => {
1565
+ if (done) {
1566
+ return;
1567
+ }
1568
+ this.onPacket(value2);
1569
+ read();
1570
+ }).catch((err) => {
1571
+ });
1572
+ };
1573
+ read();
1574
+ const packet = { type: "open" };
1575
+ if (this.query.sid) {
1576
+ packet.data = `{"sid":"${this.query.sid}"}`;
1577
+ }
1578
+ this._writer.write(packet).then(() => this.onOpen());
1579
+ });
1580
+ });
1581
+ }
1582
+ write(packets) {
1583
+ this.writable = false;
1584
+ for (let i = 0; i < packets.length; i++) {
1585
+ const packet = packets[i];
1586
+ const lastPacket = i === packets.length - 1;
1587
+ this._writer.write(packet).then(() => {
1588
+ if (lastPacket) {
1589
+ nextTick(() => {
1590
+ this.writable = true;
1591
+ this.emitReserved("drain");
1592
+ }, this.setTimeoutFn);
1593
+ }
1594
+ });
1595
+ }
1596
+ }
1597
+ doClose() {
1598
+ var _a;
1599
+ (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
1600
+ }
1601
+ };
1602
+
1603
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/transports/index.js
1604
+ var transports = {
1605
+ websocket: WS,
1606
+ webtransport: WT,
1607
+ polling: XHR
1608
+ };
1609
+
1610
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/contrib/parseuri.js
1611
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1612
+ var parts = [
1613
+ "source",
1614
+ "protocol",
1615
+ "authority",
1616
+ "userInfo",
1617
+ "user",
1618
+ "password",
1619
+ "host",
1620
+ "port",
1621
+ "relative",
1622
+ "path",
1623
+ "directory",
1624
+ "file",
1625
+ "query",
1626
+ "anchor"
1627
+ ];
1628
+ function parse(str) {
1629
+ if (str.length > 8e3) {
1630
+ throw "URI too long";
1631
+ }
1632
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
1633
+ if (b != -1 && e != -1) {
1634
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
1635
+ }
1636
+ let m = re.exec(str || ""), uri = {}, i = 14;
1637
+ while (i--) {
1638
+ uri[parts[i]] = m[i] || "";
1639
+ }
1640
+ if (b != -1 && e != -1) {
1641
+ uri.source = src;
1642
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
1643
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
1644
+ uri.ipv6uri = true;
1645
+ }
1646
+ uri.pathNames = pathNames(uri, uri["path"]);
1647
+ uri.queryKey = queryKey(uri, uri["query"]);
1648
+ return uri;
1649
+ }
1650
+ function pathNames(obj, path) {
1651
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
1652
+ if (path.slice(0, 1) == "/" || path.length === 0) {
1653
+ names.splice(0, 1);
1654
+ }
1655
+ if (path.slice(-1) == "/") {
1656
+ names.splice(names.length - 1, 1);
1657
+ }
1658
+ return names;
1659
+ }
1660
+ function queryKey(uri, query) {
1661
+ const data = {};
1662
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
1663
+ if ($1) {
1664
+ data[$1] = $2;
1665
+ }
1666
+ });
1667
+ return data;
1668
+ }
1669
+
1670
+ // ../node_modules/.pnpm/engine.io-client@6.6.4/node_modules/engine.io-client/build/esm/socket.js
1671
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
1672
+ var OFFLINE_EVENT_LISTENERS = [];
1673
+ if (withEventListeners) {
1674
+ addEventListener("offline", () => {
1675
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
1676
+ }, false);
1677
+ }
1678
+ var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends Emitter {
1679
+ /**
1680
+ * Socket constructor.
1681
+ *
1682
+ * @param {String|Object} uri - uri or options
1683
+ * @param {Object} opts - options
1684
+ */
1685
+ constructor(uri, opts) {
1686
+ super();
1687
+ this.binaryType = defaultBinaryType;
1688
+ this.writeBuffer = [];
1689
+ this._prevBufferLen = 0;
1690
+ this._pingInterval = -1;
1691
+ this._pingTimeout = -1;
1692
+ this._maxPayload = -1;
1693
+ this._pingTimeoutTime = Infinity;
1694
+ if (uri && "object" === typeof uri) {
1695
+ opts = uri;
1696
+ uri = null;
1697
+ }
1698
+ if (uri) {
1699
+ const parsedUri = parse(uri);
1700
+ opts.hostname = parsedUri.host;
1701
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
1702
+ opts.port = parsedUri.port;
1703
+ if (parsedUri.query)
1704
+ opts.query = parsedUri.query;
1705
+ } else if (opts.host) {
1706
+ opts.hostname = parse(opts.host).host;
1707
+ }
1708
+ installTimerFunctions(this, opts);
1709
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
1710
+ if (opts.hostname && !opts.port) {
1711
+ opts.port = this.secure ? "443" : "80";
1712
+ }
1713
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
1714
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
1715
+ this.transports = [];
1716
+ this._transportsByName = {};
1717
+ opts.transports.forEach((t) => {
1718
+ const transportName = t.prototype.name;
1719
+ this.transports.push(transportName);
1720
+ this._transportsByName[transportName] = t;
1721
+ });
1722
+ this.opts = Object.assign({
1723
+ path: "/engine.io",
1724
+ agent: false,
1725
+ withCredentials: false,
1726
+ upgrade: true,
1727
+ timestampParam: "t",
1728
+ rememberUpgrade: false,
1729
+ addTrailingSlash: true,
1730
+ rejectUnauthorized: true,
1731
+ perMessageDeflate: {
1732
+ threshold: 1024
1733
+ },
1734
+ transportOptions: {},
1735
+ closeOnBeforeunload: false
1736
+ }, opts);
1737
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
1738
+ if (typeof this.opts.query === "string") {
1739
+ this.opts.query = decode2(this.opts.query);
1740
+ }
1741
+ if (withEventListeners) {
1742
+ if (this.opts.closeOnBeforeunload) {
1743
+ this._beforeunloadEventListener = () => {
1744
+ if (this.transport) {
1745
+ this.transport.removeAllListeners();
1746
+ this.transport.close();
1747
+ }
1748
+ };
1749
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
1750
+ }
1751
+ if (this.hostname !== "localhost") {
1752
+ this._offlineEventListener = () => {
1753
+ this._onClose("transport close", {
1754
+ description: "network connection lost"
1755
+ });
1756
+ };
1757
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
1758
+ }
1759
+ }
1760
+ if (this.opts.withCredentials) {
1761
+ this._cookieJar = createCookieJar();
1762
+ }
1763
+ this._open();
1764
+ }
1765
+ /**
1766
+ * Creates transport of the given type.
1767
+ *
1768
+ * @param {String} name - transport name
1769
+ * @return {Transport}
1770
+ * @private
1771
+ */
1772
+ createTransport(name) {
1773
+ const query = Object.assign({}, this.opts.query);
1774
+ query.EIO = protocol;
1775
+ query.transport = name;
1776
+ if (this.id)
1777
+ query.sid = this.id;
1778
+ const opts = Object.assign({}, this.opts, {
1779
+ query,
1780
+ socket: this,
1781
+ hostname: this.hostname,
1782
+ secure: this.secure,
1783
+ port: this.port
1784
+ }, this.opts.transportOptions[name]);
1785
+ return new this._transportsByName[name](opts);
1786
+ }
1787
+ /**
1788
+ * Initializes transport to use and starts probe.
1789
+ *
1790
+ * @private
1791
+ */
1792
+ _open() {
1793
+ if (this.transports.length === 0) {
1794
+ this.setTimeoutFn(() => {
1795
+ this.emitReserved("error", "No transports available");
1796
+ }, 0);
1797
+ return;
1798
+ }
1799
+ const transportName = this.opts.rememberUpgrade && _SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
1800
+ this.readyState = "opening";
1801
+ const transport = this.createTransport(transportName);
1802
+ transport.open();
1803
+ this.setTransport(transport);
1804
+ }
1805
+ /**
1806
+ * Sets the current transport. Disables the existing one (if any).
1807
+ *
1808
+ * @private
1809
+ */
1810
+ setTransport(transport) {
1811
+ if (this.transport) {
1812
+ this.transport.removeAllListeners();
1813
+ }
1814
+ this.transport = transport;
1815
+ transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
1816
+ }
1817
+ /**
1818
+ * Called when connection is deemed open.
1819
+ *
1820
+ * @private
1821
+ */
1822
+ onOpen() {
1823
+ this.readyState = "open";
1824
+ _SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
1825
+ this.emitReserved("open");
1826
+ this.flush();
1827
+ }
1828
+ /**
1829
+ * Handles a packet.
1830
+ *
1831
+ * @private
1832
+ */
1833
+ _onPacket(packet) {
1834
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1835
+ this.emitReserved("packet", packet);
1836
+ this.emitReserved("heartbeat");
1837
+ switch (packet.type) {
1838
+ case "open":
1839
+ this.onHandshake(JSON.parse(packet.data));
1840
+ break;
1841
+ case "ping":
1842
+ this._sendPacket("pong");
1843
+ this.emitReserved("ping");
1844
+ this.emitReserved("pong");
1845
+ this._resetPingTimeout();
1846
+ break;
1847
+ case "error":
1848
+ const err = new Error("server error");
1849
+ err.code = packet.data;
1850
+ this._onError(err);
1851
+ break;
1852
+ case "message":
1853
+ this.emitReserved("data", packet.data);
1854
+ this.emitReserved("message", packet.data);
1855
+ break;
1856
+ }
1857
+ }
1858
+ }
1859
+ /**
1860
+ * Called upon handshake completion.
1861
+ *
1862
+ * @param {Object} data - handshake obj
1863
+ * @private
1864
+ */
1865
+ onHandshake(data) {
1866
+ this.emitReserved("handshake", data);
1867
+ this.id = data.sid;
1868
+ this.transport.query.sid = data.sid;
1869
+ this._pingInterval = data.pingInterval;
1870
+ this._pingTimeout = data.pingTimeout;
1871
+ this._maxPayload = data.maxPayload;
1872
+ this.onOpen();
1873
+ if ("closed" === this.readyState)
1874
+ return;
1875
+ this._resetPingTimeout();
1876
+ }
1877
+ /**
1878
+ * Sets and resets ping timeout timer based on server pings.
1879
+ *
1880
+ * @private
1881
+ */
1882
+ _resetPingTimeout() {
1883
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1884
+ const delay = this._pingInterval + this._pingTimeout;
1885
+ this._pingTimeoutTime = Date.now() + delay;
1886
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
1887
+ this._onClose("ping timeout");
1888
+ }, delay);
1889
+ if (this.opts.autoUnref) {
1890
+ this._pingTimeoutTimer.unref();
1891
+ }
1892
+ }
1893
+ /**
1894
+ * Called on `drain` event
1895
+ *
1896
+ * @private
1897
+ */
1898
+ _onDrain() {
1899
+ this.writeBuffer.splice(0, this._prevBufferLen);
1900
+ this._prevBufferLen = 0;
1901
+ if (0 === this.writeBuffer.length) {
1902
+ this.emitReserved("drain");
1903
+ } else {
1904
+ this.flush();
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Flush write buffers.
1909
+ *
1910
+ * @private
1911
+ */
1912
+ flush() {
1913
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
1914
+ const packets = this._getWritablePackets();
1915
+ this.transport.send(packets);
1916
+ this._prevBufferLen = packets.length;
1917
+ this.emitReserved("flush");
1918
+ }
1919
+ }
1920
+ /**
1921
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
1922
+ * long-polling)
1923
+ *
1924
+ * @private
1925
+ */
1926
+ _getWritablePackets() {
1927
+ const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
1928
+ if (!shouldCheckPayloadSize) {
1929
+ return this.writeBuffer;
1930
+ }
1931
+ let payloadSize = 1;
1932
+ for (let i = 0; i < this.writeBuffer.length; i++) {
1933
+ const data = this.writeBuffer[i].data;
1934
+ if (data) {
1935
+ payloadSize += byteLength(data);
1936
+ }
1937
+ if (i > 0 && payloadSize > this._maxPayload) {
1938
+ return this.writeBuffer.slice(0, i);
1939
+ }
1940
+ payloadSize += 2;
1941
+ }
1942
+ return this.writeBuffer;
1943
+ }
1944
+ /**
1945
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
1946
+ *
1947
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
1948
+ * `write()` method then the message would not be buffered by the Socket.IO client.
1949
+ *
1950
+ * @return {boolean}
1951
+ * @private
1952
+ */
1953
+ /* private */
1954
+ _hasPingExpired() {
1955
+ if (!this._pingTimeoutTime)
1956
+ return true;
1957
+ const hasExpired = Date.now() > this._pingTimeoutTime;
1958
+ if (hasExpired) {
1959
+ this._pingTimeoutTime = 0;
1960
+ nextTick(() => {
1961
+ this._onClose("ping timeout");
1962
+ }, this.setTimeoutFn);
1963
+ }
1964
+ return hasExpired;
1965
+ }
1966
+ /**
1967
+ * Sends a message.
1968
+ *
1969
+ * @param {String} msg - message.
1970
+ * @param {Object} options.
1971
+ * @param {Function} fn - callback function.
1972
+ * @return {Socket} for chaining.
1973
+ */
1974
+ write(msg, options, fn) {
1975
+ this._sendPacket("message", msg, options, fn);
1976
+ return this;
1977
+ }
1978
+ /**
1979
+ * Sends a message. Alias of {@link Socket#write}.
1980
+ *
1981
+ * @param {String} msg - message.
1982
+ * @param {Object} options.
1983
+ * @param {Function} fn - callback function.
1984
+ * @return {Socket} for chaining.
1985
+ */
1986
+ send(msg, options, fn) {
1987
+ this._sendPacket("message", msg, options, fn);
1988
+ return this;
1989
+ }
1990
+ /**
1991
+ * Sends a packet.
1992
+ *
1993
+ * @param {String} type: packet type.
1994
+ * @param {String} data.
1995
+ * @param {Object} options.
1996
+ * @param {Function} fn - callback function.
1997
+ * @private
1998
+ */
1999
+ _sendPacket(type, data, options, fn) {
2000
+ if ("function" === typeof data) {
2001
+ fn = data;
2002
+ data = void 0;
2003
+ }
2004
+ if ("function" === typeof options) {
2005
+ fn = options;
2006
+ options = null;
2007
+ }
2008
+ if ("closing" === this.readyState || "closed" === this.readyState) {
2009
+ return;
2010
+ }
2011
+ options = options || {};
2012
+ options.compress = false !== options.compress;
2013
+ const packet = {
2014
+ type,
2015
+ data,
2016
+ options
2017
+ };
2018
+ this.emitReserved("packetCreate", packet);
2019
+ this.writeBuffer.push(packet);
2020
+ if (fn)
2021
+ this.once("flush", fn);
2022
+ this.flush();
2023
+ }
2024
+ /**
2025
+ * Closes the connection.
2026
+ */
2027
+ close() {
2028
+ const close = () => {
2029
+ this._onClose("forced close");
2030
+ this.transport.close();
2031
+ };
2032
+ const cleanupAndClose = () => {
2033
+ this.off("upgrade", cleanupAndClose);
2034
+ this.off("upgradeError", cleanupAndClose);
2035
+ close();
2036
+ };
2037
+ const waitForUpgrade = () => {
2038
+ this.once("upgrade", cleanupAndClose);
2039
+ this.once("upgradeError", cleanupAndClose);
2040
+ };
2041
+ if ("opening" === this.readyState || "open" === this.readyState) {
2042
+ this.readyState = "closing";
2043
+ if (this.writeBuffer.length) {
2044
+ this.once("drain", () => {
2045
+ if (this.upgrading) {
2046
+ waitForUpgrade();
2047
+ } else {
2048
+ close();
2049
+ }
2050
+ });
2051
+ } else if (this.upgrading) {
2052
+ waitForUpgrade();
2053
+ } else {
2054
+ close();
2055
+ }
2056
+ }
2057
+ return this;
2058
+ }
2059
+ /**
2060
+ * Called upon transport error
2061
+ *
2062
+ * @private
2063
+ */
2064
+ _onError(err) {
2065
+ _SocketWithoutUpgrade.priorWebsocketSuccess = false;
2066
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
2067
+ this.transports.shift();
2068
+ return this._open();
2069
+ }
2070
+ this.emitReserved("error", err);
2071
+ this._onClose("transport error", err);
2072
+ }
2073
+ /**
2074
+ * Called upon transport close.
2075
+ *
2076
+ * @private
2077
+ */
2078
+ _onClose(reason, description) {
2079
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2080
+ this.clearTimeoutFn(this._pingTimeoutTimer);
2081
+ this.transport.removeAllListeners("close");
2082
+ this.transport.close();
2083
+ this.transport.removeAllListeners();
2084
+ if (withEventListeners) {
2085
+ if (this._beforeunloadEventListener) {
2086
+ removeEventListener("beforeunload", this._beforeunloadEventListener, false);
2087
+ }
2088
+ if (this._offlineEventListener) {
2089
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
2090
+ if (i !== -1) {
2091
+ OFFLINE_EVENT_LISTENERS.splice(i, 1);
2092
+ }
2093
+ }
2094
+ }
2095
+ this.readyState = "closed";
2096
+ this.id = null;
2097
+ this.emitReserved("close", reason, description);
2098
+ this.writeBuffer = [];
2099
+ this._prevBufferLen = 0;
2100
+ }
2101
+ }
2102
+ };
2103
+ SocketWithoutUpgrade.protocol = protocol;
2104
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
2105
+ constructor() {
2106
+ super(...arguments);
2107
+ this._upgrades = [];
2108
+ }
2109
+ onOpen() {
2110
+ super.onOpen();
2111
+ if ("open" === this.readyState && this.opts.upgrade) {
2112
+ for (let i = 0; i < this._upgrades.length; i++) {
2113
+ this._probe(this._upgrades[i]);
2114
+ }
2115
+ }
2116
+ }
2117
+ /**
2118
+ * Probes a transport.
2119
+ *
2120
+ * @param {String} name - transport name
2121
+ * @private
2122
+ */
2123
+ _probe(name) {
2124
+ let transport = this.createTransport(name);
2125
+ let failed = false;
2126
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
2127
+ const onTransportOpen = () => {
2128
+ if (failed)
2129
+ return;
2130
+ transport.send([{ type: "ping", data: "probe" }]);
2131
+ transport.once("packet", (msg) => {
2132
+ if (failed)
2133
+ return;
2134
+ if ("pong" === msg.type && "probe" === msg.data) {
2135
+ this.upgrading = true;
2136
+ this.emitReserved("upgrading", transport);
2137
+ if (!transport)
2138
+ return;
2139
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
2140
+ this.transport.pause(() => {
2141
+ if (failed)
2142
+ return;
2143
+ if ("closed" === this.readyState)
2144
+ return;
2145
+ cleanup();
2146
+ this.setTransport(transport);
2147
+ transport.send([{ type: "upgrade" }]);
2148
+ this.emitReserved("upgrade", transport);
2149
+ transport = null;
2150
+ this.upgrading = false;
2151
+ this.flush();
2152
+ });
2153
+ } else {
2154
+ const err = new Error("probe error");
2155
+ err.transport = transport.name;
2156
+ this.emitReserved("upgradeError", err);
2157
+ }
2158
+ });
2159
+ };
2160
+ function freezeTransport() {
2161
+ if (failed)
2162
+ return;
2163
+ failed = true;
2164
+ cleanup();
2165
+ transport.close();
2166
+ transport = null;
2167
+ }
2168
+ const onerror = (err) => {
2169
+ const error = new Error("probe error: " + err);
2170
+ error.transport = transport.name;
2171
+ freezeTransport();
2172
+ this.emitReserved("upgradeError", error);
2173
+ };
2174
+ function onTransportClose() {
2175
+ onerror("transport closed");
2176
+ }
2177
+ function onclose() {
2178
+ onerror("socket closed");
2179
+ }
2180
+ function onupgrade(to) {
2181
+ if (transport && to.name !== transport.name) {
2182
+ freezeTransport();
2183
+ }
2184
+ }
2185
+ const cleanup = () => {
2186
+ transport.removeListener("open", onTransportOpen);
2187
+ transport.removeListener("error", onerror);
2188
+ transport.removeListener("close", onTransportClose);
2189
+ this.off("close", onclose);
2190
+ this.off("upgrading", onupgrade);
2191
+ };
2192
+ transport.once("open", onTransportOpen);
2193
+ transport.once("error", onerror);
2194
+ transport.once("close", onTransportClose);
2195
+ this.once("close", onclose);
2196
+ this.once("upgrading", onupgrade);
2197
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
2198
+ this.setTimeoutFn(() => {
2199
+ if (!failed) {
2200
+ transport.open();
2201
+ }
2202
+ }, 200);
2203
+ } else {
2204
+ transport.open();
2205
+ }
2206
+ }
2207
+ onHandshake(data) {
2208
+ this._upgrades = this._filterUpgrades(data.upgrades);
2209
+ super.onHandshake(data);
2210
+ }
2211
+ /**
2212
+ * Filters upgrades, returning only those matching client transports.
2213
+ *
2214
+ * @param {Array} upgrades - server upgrades
2215
+ * @private
2216
+ */
2217
+ _filterUpgrades(upgrades) {
2218
+ const filteredUpgrades = [];
2219
+ for (let i = 0; i < upgrades.length; i++) {
2220
+ if (~this.transports.indexOf(upgrades[i]))
2221
+ filteredUpgrades.push(upgrades[i]);
2222
+ }
2223
+ return filteredUpgrades;
2224
+ }
2225
+ };
2226
+ var Socket = class extends SocketWithUpgrade {
2227
+ constructor(uri, opts = {}) {
2228
+ const o = typeof uri === "object" ? uri : opts;
2229
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") {
2230
+ o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
2231
+ }
2232
+ super(uri, o);
2233
+ }
2234
+ };
2235
+
2236
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/url.js
2237
+ function url(uri, path = "", loc) {
2238
+ let obj = uri;
2239
+ loc = loc || typeof location !== "undefined" && location;
2240
+ if (null == uri)
2241
+ uri = loc.protocol + "//" + loc.host;
2242
+ if (typeof uri === "string") {
2243
+ if ("/" === uri.charAt(0)) {
2244
+ if ("/" === uri.charAt(1)) {
2245
+ uri = loc.protocol + uri;
2246
+ } else {
2247
+ uri = loc.host + uri;
2248
+ }
2249
+ }
2250
+ if (!/^(https?|wss?):\/\//.test(uri)) {
2251
+ if ("undefined" !== typeof loc) {
2252
+ uri = loc.protocol + "//" + uri;
2253
+ } else {
2254
+ uri = "https://" + uri;
2255
+ }
2256
+ }
2257
+ obj = parse(uri);
2258
+ }
2259
+ if (!obj.port) {
2260
+ if (/^(http|ws)$/.test(obj.protocol)) {
2261
+ obj.port = "80";
2262
+ } else if (/^(http|ws)s$/.test(obj.protocol)) {
2263
+ obj.port = "443";
2264
+ }
2265
+ }
2266
+ obj.path = obj.path || "/";
2267
+ const ipv6 = obj.host.indexOf(":") !== -1;
2268
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
2269
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
2270
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
2271
+ return obj;
2272
+ }
2273
+
2274
+ // ../node_modules/.pnpm/socket.io-parser@4.2.5/node_modules/socket.io-parser/build/esm/index.js
2275
+ var esm_exports = {};
2276
+ __export(esm_exports, {
2277
+ Decoder: () => Decoder,
2278
+ Encoder: () => Encoder,
2279
+ PacketType: () => PacketType,
2280
+ isPacketValid: () => isPacketValid,
2281
+ protocol: () => protocol3
2282
+ });
2283
+
2284
+ // ../node_modules/.pnpm/socket.io-parser@4.2.5/node_modules/socket.io-parser/build/esm/is-binary.js
2285
+ var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
2286
+ var isView2 = (obj) => {
2287
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
2288
+ };
2289
+ var toString = Object.prototype.toString;
2290
+ var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
2291
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
2292
+ function isBinary(obj) {
2293
+ return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
2294
+ }
2295
+ function hasBinary(obj, toJSON) {
2296
+ if (!obj || typeof obj !== "object") {
2297
+ return false;
2298
+ }
2299
+ if (Array.isArray(obj)) {
2300
+ for (let i = 0, l = obj.length; i < l; i++) {
2301
+ if (hasBinary(obj[i])) {
2302
+ return true;
2303
+ }
2304
+ }
2305
+ return false;
2306
+ }
2307
+ if (isBinary(obj)) {
2308
+ return true;
2309
+ }
2310
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
2311
+ return hasBinary(obj.toJSON(), true);
2312
+ }
2313
+ for (const key in obj) {
2314
+ if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
2315
+ return true;
2316
+ }
2317
+ }
2318
+ return false;
2319
+ }
2320
+
2321
+ // ../node_modules/.pnpm/socket.io-parser@4.2.5/node_modules/socket.io-parser/build/esm/binary.js
2322
+ function deconstructPacket(packet) {
2323
+ const buffers = [];
2324
+ const packetData = packet.data;
2325
+ const pack = packet;
2326
+ pack.data = _deconstructPacket(packetData, buffers);
2327
+ pack.attachments = buffers.length;
2328
+ return { packet: pack, buffers };
2329
+ }
2330
+ function _deconstructPacket(data, buffers) {
2331
+ if (!data)
2332
+ return data;
2333
+ if (isBinary(data)) {
2334
+ const placeholder = { _placeholder: true, num: buffers.length };
2335
+ buffers.push(data);
2336
+ return placeholder;
2337
+ } else if (Array.isArray(data)) {
2338
+ const newData = new Array(data.length);
2339
+ for (let i = 0; i < data.length; i++) {
2340
+ newData[i] = _deconstructPacket(data[i], buffers);
2341
+ }
2342
+ return newData;
2343
+ } else if (typeof data === "object" && !(data instanceof Date)) {
2344
+ const newData = {};
2345
+ for (const key in data) {
2346
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2347
+ newData[key] = _deconstructPacket(data[key], buffers);
2348
+ }
2349
+ }
2350
+ return newData;
2351
+ }
2352
+ return data;
2353
+ }
2354
+ function reconstructPacket(packet, buffers) {
2355
+ packet.data = _reconstructPacket(packet.data, buffers);
2356
+ delete packet.attachments;
2357
+ return packet;
2358
+ }
2359
+ function _reconstructPacket(data, buffers) {
2360
+ if (!data)
2361
+ return data;
2362
+ if (data && data._placeholder === true) {
2363
+ const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
2364
+ if (isIndexValid) {
2365
+ return buffers[data.num];
2366
+ } else {
2367
+ throw new Error("illegal attachments");
2368
+ }
2369
+ } else if (Array.isArray(data)) {
2370
+ for (let i = 0; i < data.length; i++) {
2371
+ data[i] = _reconstructPacket(data[i], buffers);
2372
+ }
2373
+ } else if (typeof data === "object") {
2374
+ for (const key in data) {
2375
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2376
+ data[key] = _reconstructPacket(data[key], buffers);
2377
+ }
2378
+ }
2379
+ }
2380
+ return data;
2381
+ }
2382
+
2383
+ // ../node_modules/.pnpm/socket.io-parser@4.2.5/node_modules/socket.io-parser/build/esm/index.js
2384
+ var RESERVED_EVENTS = [
2385
+ "connect",
2386
+ // used on the client side
2387
+ "connect_error",
2388
+ // used on the client side
2389
+ "disconnect",
2390
+ // used on both sides
2391
+ "disconnecting",
2392
+ // used on the server side
2393
+ "newListener",
2394
+ // used by the Node.js EventEmitter
2395
+ "removeListener"
2396
+ // used by the Node.js EventEmitter
2397
+ ];
2398
+ var protocol3 = 5;
2399
+ var PacketType;
2400
+ (function(PacketType2) {
2401
+ PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
2402
+ PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
2403
+ PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
2404
+ PacketType2[PacketType2["ACK"] = 3] = "ACK";
2405
+ PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
2406
+ PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
2407
+ PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
2408
+ })(PacketType || (PacketType = {}));
2409
+ var Encoder = class {
2410
+ /**
2411
+ * Encoder constructor
2412
+ *
2413
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
2414
+ */
2415
+ constructor(replacer) {
2416
+ this.replacer = replacer;
2417
+ }
2418
+ /**
2419
+ * Encode a packet as a single string if non-binary, or as a
2420
+ * buffer sequence, depending on packet type.
2421
+ *
2422
+ * @param {Object} obj - packet object
2423
+ */
2424
+ encode(obj) {
2425
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
2426
+ if (hasBinary(obj)) {
2427
+ return this.encodeAsBinary({
2428
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
2429
+ nsp: obj.nsp,
2430
+ data: obj.data,
2431
+ id: obj.id
2432
+ });
2433
+ }
2434
+ }
2435
+ return [this.encodeAsString(obj)];
2436
+ }
2437
+ /**
2438
+ * Encode packet as string.
2439
+ */
2440
+ encodeAsString(obj) {
2441
+ let str = "" + obj.type;
2442
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
2443
+ str += obj.attachments + "-";
2444
+ }
2445
+ if (obj.nsp && "/" !== obj.nsp) {
2446
+ str += obj.nsp + ",";
2447
+ }
2448
+ if (null != obj.id) {
2449
+ str += obj.id;
2450
+ }
2451
+ if (null != obj.data) {
2452
+ str += JSON.stringify(obj.data, this.replacer);
2453
+ }
2454
+ return str;
2455
+ }
2456
+ /**
2457
+ * Encode packet as 'buffer sequence' by removing blobs, and
2458
+ * deconstructing packet into object with placeholders and
2459
+ * a list of buffers.
2460
+ */
2461
+ encodeAsBinary(obj) {
2462
+ const deconstruction = deconstructPacket(obj);
2463
+ const pack = this.encodeAsString(deconstruction.packet);
2464
+ const buffers = deconstruction.buffers;
2465
+ buffers.unshift(pack);
2466
+ return buffers;
2467
+ }
2468
+ };
2469
+ var Decoder = class _Decoder extends Emitter {
2470
+ /**
2471
+ * Decoder constructor
2472
+ *
2473
+ * @param {function} reviver - custom reviver to pass down to JSON.stringify
2474
+ */
2475
+ constructor(reviver) {
2476
+ super();
2477
+ this.reviver = reviver;
2478
+ }
2479
+ /**
2480
+ * Decodes an encoded packet string into packet JSON.
2481
+ *
2482
+ * @param {String} obj - encoded packet
2483
+ */
2484
+ add(obj) {
2485
+ let packet;
2486
+ if (typeof obj === "string") {
2487
+ if (this.reconstructor) {
2488
+ throw new Error("got plaintext data when reconstructing a packet");
2489
+ }
2490
+ packet = this.decodeString(obj);
2491
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2492
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2493
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2494
+ this.reconstructor = new BinaryReconstructor(packet);
2495
+ if (packet.attachments === 0) {
2496
+ super.emitReserved("decoded", packet);
2497
+ }
2498
+ } else {
2499
+ super.emitReserved("decoded", packet);
2500
+ }
2501
+ } else if (isBinary(obj) || obj.base64) {
2502
+ if (!this.reconstructor) {
2503
+ throw new Error("got binary data when not reconstructing a packet");
2504
+ } else {
2505
+ packet = this.reconstructor.takeBinaryData(obj);
2506
+ if (packet) {
2507
+ this.reconstructor = null;
2508
+ super.emitReserved("decoded", packet);
2509
+ }
2510
+ }
2511
+ } else {
2512
+ throw new Error("Unknown type: " + obj);
2513
+ }
2514
+ }
2515
+ /**
2516
+ * Decode a packet String (JSON data)
2517
+ *
2518
+ * @param {String} str
2519
+ * @return {Object} packet
2520
+ */
2521
+ decodeString(str) {
2522
+ let i = 0;
2523
+ const p = {
2524
+ type: Number(str.charAt(0))
2525
+ };
2526
+ if (PacketType[p.type] === void 0) {
2527
+ throw new Error("unknown packet type " + p.type);
2528
+ }
2529
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
2530
+ const start = i + 1;
2531
+ while (str.charAt(++i) !== "-" && i != str.length) {
2532
+ }
2533
+ const buf = str.substring(start, i);
2534
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
2535
+ throw new Error("Illegal attachments");
2536
+ }
2537
+ p.attachments = Number(buf);
2538
+ }
2539
+ if ("/" === str.charAt(i + 1)) {
2540
+ const start = i + 1;
2541
+ while (++i) {
2542
+ const c = str.charAt(i);
2543
+ if ("," === c)
2544
+ break;
2545
+ if (i === str.length)
2546
+ break;
2547
+ }
2548
+ p.nsp = str.substring(start, i);
2549
+ } else {
2550
+ p.nsp = "/";
2551
+ }
2552
+ const next = str.charAt(i + 1);
2553
+ if ("" !== next && Number(next) == next) {
2554
+ const start = i + 1;
2555
+ while (++i) {
2556
+ const c = str.charAt(i);
2557
+ if (null == c || Number(c) != c) {
2558
+ --i;
2559
+ break;
2560
+ }
2561
+ if (i === str.length)
2562
+ break;
2563
+ }
2564
+ p.id = Number(str.substring(start, i + 1));
2565
+ }
2566
+ if (str.charAt(++i)) {
2567
+ const payload = this.tryParse(str.substr(i));
2568
+ if (_Decoder.isPayloadValid(p.type, payload)) {
2569
+ p.data = payload;
2570
+ } else {
2571
+ throw new Error("invalid payload");
2572
+ }
2573
+ }
2574
+ return p;
2575
+ }
2576
+ tryParse(str) {
2577
+ try {
2578
+ return JSON.parse(str, this.reviver);
2579
+ } catch (e) {
2580
+ return false;
2581
+ }
2582
+ }
2583
+ static isPayloadValid(type, payload) {
2584
+ switch (type) {
2585
+ case PacketType.CONNECT:
2586
+ return isObject(payload);
2587
+ case PacketType.DISCONNECT:
2588
+ return payload === void 0;
2589
+ case PacketType.CONNECT_ERROR:
2590
+ return typeof payload === "string" || isObject(payload);
2591
+ case PacketType.EVENT:
2592
+ case PacketType.BINARY_EVENT:
2593
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2594
+ case PacketType.ACK:
2595
+ case PacketType.BINARY_ACK:
2596
+ return Array.isArray(payload);
2597
+ }
2598
+ }
2599
+ /**
2600
+ * Deallocates a parser's resources
2601
+ */
2602
+ destroy() {
2603
+ if (this.reconstructor) {
2604
+ this.reconstructor.finishedReconstruction();
2605
+ this.reconstructor = null;
2606
+ }
2607
+ }
2608
+ };
2609
+ var BinaryReconstructor = class {
2610
+ constructor(packet) {
2611
+ this.packet = packet;
2612
+ this.buffers = [];
2613
+ this.reconPack = packet;
2614
+ }
2615
+ /**
2616
+ * Method to be called when binary data received from connection
2617
+ * after a BINARY_EVENT packet.
2618
+ *
2619
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
2620
+ * @return {null | Object} returns null if more binary data is expected or
2621
+ * a reconstructed packet object if all buffers have been received.
2622
+ */
2623
+ takeBinaryData(binData) {
2624
+ this.buffers.push(binData);
2625
+ if (this.buffers.length === this.reconPack.attachments) {
2626
+ const packet = reconstructPacket(this.reconPack, this.buffers);
2627
+ this.finishedReconstruction();
2628
+ return packet;
2629
+ }
2630
+ return null;
2631
+ }
2632
+ /**
2633
+ * Cleans up binary packet reconstruction variables.
2634
+ */
2635
+ finishedReconstruction() {
2636
+ this.reconPack = null;
2637
+ this.buffers = [];
2638
+ }
2639
+ };
2640
+ function isNamespaceValid(nsp) {
2641
+ return typeof nsp === "string";
2642
+ }
2643
+ var isInteger = Number.isInteger || function(value2) {
2644
+ return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
2645
+ };
2646
+ function isAckIdValid(id) {
2647
+ return id === void 0 || isInteger(id);
2648
+ }
2649
+ function isObject(value2) {
2650
+ return Object.prototype.toString.call(value2) === "[object Object]";
2651
+ }
2652
+ function isDataValid(type, payload) {
2653
+ switch (type) {
2654
+ case PacketType.CONNECT:
2655
+ return payload === void 0 || isObject(payload);
2656
+ case PacketType.DISCONNECT:
2657
+ return payload === void 0;
2658
+ case PacketType.EVENT:
2659
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2660
+ case PacketType.ACK:
2661
+ return Array.isArray(payload);
2662
+ case PacketType.CONNECT_ERROR:
2663
+ return typeof payload === "string" || isObject(payload);
2664
+ default:
2665
+ return false;
2666
+ }
2667
+ }
2668
+ function isPacketValid(packet) {
2669
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
2670
+ }
2671
+
2672
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/on.js
2673
+ function on(obj, ev, fn) {
2674
+ obj.on(ev, fn);
2675
+ return function subDestroy() {
2676
+ obj.off(ev, fn);
2677
+ };
2678
+ }
2679
+
2680
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/socket.js
2681
+ var RESERVED_EVENTS2 = Object.freeze({
2682
+ connect: 1,
2683
+ connect_error: 1,
2684
+ disconnect: 1,
2685
+ disconnecting: 1,
2686
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
2687
+ newListener: 1,
2688
+ removeListener: 1
2689
+ });
2690
+ var Socket2 = class extends Emitter {
2691
+ /**
2692
+ * `Socket` constructor.
2693
+ */
2694
+ constructor(io, nsp, opts) {
2695
+ super();
2696
+ this.connected = false;
2697
+ this.recovered = false;
2698
+ this.receiveBuffer = [];
2699
+ this.sendBuffer = [];
2700
+ this._queue = [];
2701
+ this._queueSeq = 0;
2702
+ this.ids = 0;
2703
+ this.acks = {};
2704
+ this.flags = {};
2705
+ this.io = io;
2706
+ this.nsp = nsp;
2707
+ if (opts && opts.auth) {
2708
+ this.auth = opts.auth;
2709
+ }
2710
+ this._opts = Object.assign({}, opts);
2711
+ if (this.io._autoConnect)
2712
+ this.open();
2713
+ }
2714
+ /**
2715
+ * Whether the socket is currently disconnected
2716
+ *
2717
+ * @example
2718
+ * const socket = io();
2719
+ *
2720
+ * socket.on("connect", () => {
2721
+ * console.log(socket.disconnected); // false
2722
+ * });
2723
+ *
2724
+ * socket.on("disconnect", () => {
2725
+ * console.log(socket.disconnected); // true
2726
+ * });
2727
+ */
2728
+ get disconnected() {
2729
+ return !this.connected;
2730
+ }
2731
+ /**
2732
+ * Subscribe to open, close and packet events
2733
+ *
2734
+ * @private
2735
+ */
2736
+ subEvents() {
2737
+ if (this.subs)
2738
+ return;
2739
+ const io = this.io;
2740
+ this.subs = [
2741
+ on(io, "open", this.onopen.bind(this)),
2742
+ on(io, "packet", this.onpacket.bind(this)),
2743
+ on(io, "error", this.onerror.bind(this)),
2744
+ on(io, "close", this.onclose.bind(this))
2745
+ ];
2746
+ }
2747
+ /**
2748
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
2749
+ *
2750
+ * @example
2751
+ * const socket = io();
2752
+ *
2753
+ * console.log(socket.active); // true
2754
+ *
2755
+ * socket.on("disconnect", (reason) => {
2756
+ * if (reason === "io server disconnect") {
2757
+ * // the disconnection was initiated by the server, you need to manually reconnect
2758
+ * console.log(socket.active); // false
2759
+ * }
2760
+ * // else the socket will automatically try to reconnect
2761
+ * console.log(socket.active); // true
2762
+ * });
2763
+ */
2764
+ get active() {
2765
+ return !!this.subs;
2766
+ }
2767
+ /**
2768
+ * "Opens" the socket.
2769
+ *
2770
+ * @example
2771
+ * const socket = io({
2772
+ * autoConnect: false
2773
+ * });
2774
+ *
2775
+ * socket.connect();
2776
+ */
2777
+ connect() {
2778
+ if (this.connected)
2779
+ return this;
2780
+ this.subEvents();
2781
+ if (!this.io["_reconnecting"])
2782
+ this.io.open();
2783
+ if ("open" === this.io._readyState)
2784
+ this.onopen();
2785
+ return this;
2786
+ }
2787
+ /**
2788
+ * Alias for {@link connect()}.
2789
+ */
2790
+ open() {
2791
+ return this.connect();
2792
+ }
2793
+ /**
2794
+ * Sends a `message` event.
2795
+ *
2796
+ * This method mimics the WebSocket.send() method.
2797
+ *
2798
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
2799
+ *
2800
+ * @example
2801
+ * socket.send("hello");
2802
+ *
2803
+ * // this is equivalent to
2804
+ * socket.emit("message", "hello");
2805
+ *
2806
+ * @return self
2807
+ */
2808
+ send(...args) {
2809
+ args.unshift("message");
2810
+ this.emit.apply(this, args);
2811
+ return this;
2812
+ }
2813
+ /**
2814
+ * Override `emit`.
2815
+ * If the event is in `events`, it's emitted normally.
2816
+ *
2817
+ * @example
2818
+ * socket.emit("hello", "world");
2819
+ *
2820
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
2821
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
2822
+ *
2823
+ * // with an acknowledgement from the server
2824
+ * socket.emit("hello", "world", (val) => {
2825
+ * // ...
2826
+ * });
2827
+ *
2828
+ * @return self
2829
+ */
2830
+ emit(ev, ...args) {
2831
+ var _a, _b, _c;
2832
+ if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
2833
+ throw new Error('"' + ev.toString() + '" is a reserved event name');
2834
+ }
2835
+ args.unshift(ev);
2836
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
2837
+ this._addToQueue(args);
2838
+ return this;
2839
+ }
2840
+ const packet = {
2841
+ type: PacketType.EVENT,
2842
+ data: args
2843
+ };
2844
+ packet.options = {};
2845
+ packet.options.compress = this.flags.compress !== false;
2846
+ if ("function" === typeof args[args.length - 1]) {
2847
+ const id = this.ids++;
2848
+ const ack = args.pop();
2849
+ this._registerAckCallback(id, ack);
2850
+ packet.id = id;
2851
+ }
2852
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
2853
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
2854
+ const discardPacket = this.flags.volatile && !isTransportWritable;
2855
+ if (discardPacket) ; else if (isConnected) {
2856
+ this.notifyOutgoingListeners(packet);
2857
+ this.packet(packet);
2858
+ } else {
2859
+ this.sendBuffer.push(packet);
2860
+ }
2861
+ this.flags = {};
2862
+ return this;
2863
+ }
2864
+ /**
2865
+ * @private
2866
+ */
2867
+ _registerAckCallback(id, ack) {
2868
+ var _a;
2869
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
2870
+ if (timeout === void 0) {
2871
+ this.acks[id] = ack;
2872
+ return;
2873
+ }
2874
+ const timer = this.io.setTimeoutFn(() => {
2875
+ delete this.acks[id];
2876
+ for (let i = 0; i < this.sendBuffer.length; i++) {
2877
+ if (this.sendBuffer[i].id === id) {
2878
+ this.sendBuffer.splice(i, 1);
2879
+ }
2880
+ }
2881
+ ack.call(this, new Error("operation has timed out"));
2882
+ }, timeout);
2883
+ const fn = (...args) => {
2884
+ this.io.clearTimeoutFn(timer);
2885
+ ack.apply(this, args);
2886
+ };
2887
+ fn.withError = true;
2888
+ this.acks[id] = fn;
2889
+ }
2890
+ /**
2891
+ * Emits an event and waits for an acknowledgement
2892
+ *
2893
+ * @example
2894
+ * // without timeout
2895
+ * const response = await socket.emitWithAck("hello", "world");
2896
+ *
2897
+ * // with a specific timeout
2898
+ * try {
2899
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
2900
+ * } catch (err) {
2901
+ * // the server did not acknowledge the event in the given delay
2902
+ * }
2903
+ *
2904
+ * @return a Promise that will be fulfilled when the server acknowledges the event
2905
+ */
2906
+ emitWithAck(ev, ...args) {
2907
+ return new Promise((resolve, reject) => {
2908
+ const fn = (arg1, arg2) => {
2909
+ return arg1 ? reject(arg1) : resolve(arg2);
2910
+ };
2911
+ fn.withError = true;
2912
+ args.push(fn);
2913
+ this.emit(ev, ...args);
2914
+ });
2915
+ }
2916
+ /**
2917
+ * Add the packet to the queue.
2918
+ * @param args
2919
+ * @private
2920
+ */
2921
+ _addToQueue(args) {
2922
+ let ack;
2923
+ if (typeof args[args.length - 1] === "function") {
2924
+ ack = args.pop();
2925
+ }
2926
+ const packet = {
2927
+ id: this._queueSeq++,
2928
+ tryCount: 0,
2929
+ pending: false,
2930
+ args,
2931
+ flags: Object.assign({ fromQueue: true }, this.flags)
2932
+ };
2933
+ args.push((err, ...responseArgs) => {
2934
+ if (packet !== this._queue[0]) ;
2935
+ const hasError = err !== null;
2936
+ if (hasError) {
2937
+ if (packet.tryCount > this._opts.retries) {
2938
+ this._queue.shift();
2939
+ if (ack) {
2940
+ ack(err);
2941
+ }
2942
+ }
2943
+ } else {
2944
+ this._queue.shift();
2945
+ if (ack) {
2946
+ ack(null, ...responseArgs);
2947
+ }
2948
+ }
2949
+ packet.pending = false;
2950
+ return this._drainQueue();
2951
+ });
2952
+ this._queue.push(packet);
2953
+ this._drainQueue();
2954
+ }
2955
+ /**
2956
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
2957
+ * @param force - whether to resend a packet that has not been acknowledged yet
2958
+ *
2959
+ * @private
2960
+ */
2961
+ _drainQueue(force = false) {
2962
+ if (!this.connected || this._queue.length === 0) {
2963
+ return;
2964
+ }
2965
+ const packet = this._queue[0];
2966
+ if (packet.pending && !force) {
2967
+ return;
2968
+ }
2969
+ packet.pending = true;
2970
+ packet.tryCount++;
2971
+ this.flags = packet.flags;
2972
+ this.emit.apply(this, packet.args);
2973
+ }
2974
+ /**
2975
+ * Sends a packet.
2976
+ *
2977
+ * @param packet
2978
+ * @private
2979
+ */
2980
+ packet(packet) {
2981
+ packet.nsp = this.nsp;
2982
+ this.io._packet(packet);
2983
+ }
2984
+ /**
2985
+ * Called upon engine `open`.
2986
+ *
2987
+ * @private
2988
+ */
2989
+ onopen() {
2990
+ if (typeof this.auth == "function") {
2991
+ this.auth((data) => {
2992
+ this._sendConnectPacket(data);
2993
+ });
2994
+ } else {
2995
+ this._sendConnectPacket(this.auth);
2996
+ }
2997
+ }
2998
+ /**
2999
+ * Sends a CONNECT packet to initiate the Socket.IO session.
3000
+ *
3001
+ * @param data
3002
+ * @private
3003
+ */
3004
+ _sendConnectPacket(data) {
3005
+ this.packet({
3006
+ type: PacketType.CONNECT,
3007
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
3008
+ });
3009
+ }
3010
+ /**
3011
+ * Called upon engine or manager `error`.
3012
+ *
3013
+ * @param err
3014
+ * @private
3015
+ */
3016
+ onerror(err) {
3017
+ if (!this.connected) {
3018
+ this.emitReserved("connect_error", err);
3019
+ }
3020
+ }
3021
+ /**
3022
+ * Called upon engine `close`.
3023
+ *
3024
+ * @param reason
3025
+ * @param description
3026
+ * @private
3027
+ */
3028
+ onclose(reason, description) {
3029
+ this.connected = false;
3030
+ delete this.id;
3031
+ this.emitReserved("disconnect", reason, description);
3032
+ this._clearAcks();
3033
+ }
3034
+ /**
3035
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
3036
+ * the server.
3037
+ *
3038
+ * @private
3039
+ */
3040
+ _clearAcks() {
3041
+ Object.keys(this.acks).forEach((id) => {
3042
+ const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
3043
+ if (!isBuffered) {
3044
+ const ack = this.acks[id];
3045
+ delete this.acks[id];
3046
+ if (ack.withError) {
3047
+ ack.call(this, new Error("socket has been disconnected"));
3048
+ }
3049
+ }
3050
+ });
3051
+ }
3052
+ /**
3053
+ * Called with socket packet.
3054
+ *
3055
+ * @param packet
3056
+ * @private
3057
+ */
3058
+ onpacket(packet) {
3059
+ const sameNamespace = packet.nsp === this.nsp;
3060
+ if (!sameNamespace)
3061
+ return;
3062
+ switch (packet.type) {
3063
+ case PacketType.CONNECT:
3064
+ if (packet.data && packet.data.sid) {
3065
+ this.onconnect(packet.data.sid, packet.data.pid);
3066
+ } else {
3067
+ this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
3068
+ }
3069
+ break;
3070
+ case PacketType.EVENT:
3071
+ case PacketType.BINARY_EVENT:
3072
+ this.onevent(packet);
3073
+ break;
3074
+ case PacketType.ACK:
3075
+ case PacketType.BINARY_ACK:
3076
+ this.onack(packet);
3077
+ break;
3078
+ case PacketType.DISCONNECT:
3079
+ this.ondisconnect();
3080
+ break;
3081
+ case PacketType.CONNECT_ERROR:
3082
+ this.destroy();
3083
+ const err = new Error(packet.data.message);
3084
+ err.data = packet.data.data;
3085
+ this.emitReserved("connect_error", err);
3086
+ break;
3087
+ }
3088
+ }
3089
+ /**
3090
+ * Called upon a server event.
3091
+ *
3092
+ * @param packet
3093
+ * @private
3094
+ */
3095
+ onevent(packet) {
3096
+ const args = packet.data || [];
3097
+ if (null != packet.id) {
3098
+ args.push(this.ack(packet.id));
3099
+ }
3100
+ if (this.connected) {
3101
+ this.emitEvent(args);
3102
+ } else {
3103
+ this.receiveBuffer.push(Object.freeze(args));
3104
+ }
3105
+ }
3106
+ emitEvent(args) {
3107
+ if (this._anyListeners && this._anyListeners.length) {
3108
+ const listeners = this._anyListeners.slice();
3109
+ for (const listener of listeners) {
3110
+ listener.apply(this, args);
3111
+ }
3112
+ }
3113
+ super.emit.apply(this, args);
3114
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") {
3115
+ this._lastOffset = args[args.length - 1];
3116
+ }
3117
+ }
3118
+ /**
3119
+ * Produces an ack callback to emit with an event.
3120
+ *
3121
+ * @private
3122
+ */
3123
+ ack(id) {
3124
+ const self2 = this;
3125
+ let sent = false;
3126
+ return function(...args) {
3127
+ if (sent)
3128
+ return;
3129
+ sent = true;
3130
+ self2.packet({
3131
+ type: PacketType.ACK,
3132
+ id,
3133
+ data: args
3134
+ });
3135
+ };
3136
+ }
3137
+ /**
3138
+ * Called upon a server acknowledgement.
3139
+ *
3140
+ * @param packet
3141
+ * @private
3142
+ */
3143
+ onack(packet) {
3144
+ const ack = this.acks[packet.id];
3145
+ if (typeof ack !== "function") {
3146
+ return;
3147
+ }
3148
+ delete this.acks[packet.id];
3149
+ if (ack.withError) {
3150
+ packet.data.unshift(null);
3151
+ }
3152
+ ack.apply(this, packet.data);
3153
+ }
3154
+ /**
3155
+ * Called upon server connect.
3156
+ *
3157
+ * @private
3158
+ */
3159
+ onconnect(id, pid) {
3160
+ this.id = id;
3161
+ this.recovered = pid && this._pid === pid;
3162
+ this._pid = pid;
3163
+ this.connected = true;
3164
+ this.emitBuffered();
3165
+ this._drainQueue(true);
3166
+ this.emitReserved("connect");
3167
+ }
3168
+ /**
3169
+ * Emit buffered events (received and emitted).
3170
+ *
3171
+ * @private
3172
+ */
3173
+ emitBuffered() {
3174
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
3175
+ this.receiveBuffer = [];
3176
+ this.sendBuffer.forEach((packet) => {
3177
+ this.notifyOutgoingListeners(packet);
3178
+ this.packet(packet);
3179
+ });
3180
+ this.sendBuffer = [];
3181
+ }
3182
+ /**
3183
+ * Called upon server disconnect.
3184
+ *
3185
+ * @private
3186
+ */
3187
+ ondisconnect() {
3188
+ this.destroy();
3189
+ this.onclose("io server disconnect");
3190
+ }
3191
+ /**
3192
+ * Called upon forced client/server side disconnections,
3193
+ * this method ensures the manager stops tracking us and
3194
+ * that reconnections don't get triggered for this.
3195
+ *
3196
+ * @private
3197
+ */
3198
+ destroy() {
3199
+ if (this.subs) {
3200
+ this.subs.forEach((subDestroy) => subDestroy());
3201
+ this.subs = void 0;
3202
+ }
3203
+ this.io["_destroy"](this);
3204
+ }
3205
+ /**
3206
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
3207
+ *
3208
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
3209
+ *
3210
+ * @example
3211
+ * const socket = io();
3212
+ *
3213
+ * socket.on("disconnect", (reason) => {
3214
+ * // console.log(reason); prints "io client disconnect"
3215
+ * });
3216
+ *
3217
+ * socket.disconnect();
3218
+ *
3219
+ * @return self
3220
+ */
3221
+ disconnect() {
3222
+ if (this.connected) {
3223
+ this.packet({ type: PacketType.DISCONNECT });
3224
+ }
3225
+ this.destroy();
3226
+ if (this.connected) {
3227
+ this.onclose("io client disconnect");
3228
+ }
3229
+ return this;
3230
+ }
3231
+ /**
3232
+ * Alias for {@link disconnect()}.
3233
+ *
3234
+ * @return self
3235
+ */
3236
+ close() {
3237
+ return this.disconnect();
3238
+ }
3239
+ /**
3240
+ * Sets the compress flag.
3241
+ *
3242
+ * @example
3243
+ * socket.compress(false).emit("hello");
3244
+ *
3245
+ * @param compress - if `true`, compresses the sending data
3246
+ * @return self
3247
+ */
3248
+ compress(compress) {
3249
+ this.flags.compress = compress;
3250
+ return this;
3251
+ }
3252
+ /**
3253
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
3254
+ * ready to send messages.
3255
+ *
3256
+ * @example
3257
+ * socket.volatile.emit("hello"); // the server may or may not receive it
3258
+ *
3259
+ * @returns self
3260
+ */
3261
+ get volatile() {
3262
+ this.flags.volatile = true;
3263
+ return this;
3264
+ }
3265
+ /**
3266
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
3267
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
3268
+ *
3269
+ * @example
3270
+ * socket.timeout(5000).emit("my-event", (err) => {
3271
+ * if (err) {
3272
+ * // the server did not acknowledge the event in the given delay
3273
+ * }
3274
+ * });
3275
+ *
3276
+ * @returns self
3277
+ */
3278
+ timeout(timeout) {
3279
+ this.flags.timeout = timeout;
3280
+ return this;
3281
+ }
3282
+ /**
3283
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3284
+ * callback.
3285
+ *
3286
+ * @example
3287
+ * socket.onAny((event, ...args) => {
3288
+ * console.log(`got ${event}`);
3289
+ * });
3290
+ *
3291
+ * @param listener
3292
+ */
3293
+ onAny(listener) {
3294
+ this._anyListeners = this._anyListeners || [];
3295
+ this._anyListeners.push(listener);
3296
+ return this;
3297
+ }
3298
+ /**
3299
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3300
+ * callback. The listener is added to the beginning of the listeners array.
3301
+ *
3302
+ * @example
3303
+ * socket.prependAny((event, ...args) => {
3304
+ * console.log(`got event ${event}`);
3305
+ * });
3306
+ *
3307
+ * @param listener
3308
+ */
3309
+ prependAny(listener) {
3310
+ this._anyListeners = this._anyListeners || [];
3311
+ this._anyListeners.unshift(listener);
3312
+ return this;
3313
+ }
3314
+ /**
3315
+ * Removes the listener that will be fired when any event is emitted.
3316
+ *
3317
+ * @example
3318
+ * const catchAllListener = (event, ...args) => {
3319
+ * console.log(`got event ${event}`);
3320
+ * }
3321
+ *
3322
+ * socket.onAny(catchAllListener);
3323
+ *
3324
+ * // remove a specific listener
3325
+ * socket.offAny(catchAllListener);
3326
+ *
3327
+ * // or remove all listeners
3328
+ * socket.offAny();
3329
+ *
3330
+ * @param listener
3331
+ */
3332
+ offAny(listener) {
3333
+ if (!this._anyListeners) {
3334
+ return this;
3335
+ }
3336
+ if (listener) {
3337
+ const listeners = this._anyListeners;
3338
+ for (let i = 0; i < listeners.length; i++) {
3339
+ if (listener === listeners[i]) {
3340
+ listeners.splice(i, 1);
3341
+ return this;
3342
+ }
3343
+ }
3344
+ } else {
3345
+ this._anyListeners = [];
3346
+ }
3347
+ return this;
3348
+ }
3349
+ /**
3350
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3351
+ * e.g. to remove listeners.
3352
+ */
3353
+ listenersAny() {
3354
+ return this._anyListeners || [];
3355
+ }
3356
+ /**
3357
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3358
+ * callback.
3359
+ *
3360
+ * Note: acknowledgements sent to the server are not included.
3361
+ *
3362
+ * @example
3363
+ * socket.onAnyOutgoing((event, ...args) => {
3364
+ * console.log(`sent event ${event}`);
3365
+ * });
3366
+ *
3367
+ * @param listener
3368
+ */
3369
+ onAnyOutgoing(listener) {
3370
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3371
+ this._anyOutgoingListeners.push(listener);
3372
+ return this;
3373
+ }
3374
+ /**
3375
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3376
+ * callback. The listener is added to the beginning of the listeners array.
3377
+ *
3378
+ * Note: acknowledgements sent to the server are not included.
3379
+ *
3380
+ * @example
3381
+ * socket.prependAnyOutgoing((event, ...args) => {
3382
+ * console.log(`sent event ${event}`);
3383
+ * });
3384
+ *
3385
+ * @param listener
3386
+ */
3387
+ prependAnyOutgoing(listener) {
3388
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3389
+ this._anyOutgoingListeners.unshift(listener);
3390
+ return this;
3391
+ }
3392
+ /**
3393
+ * Removes the listener that will be fired when any event is emitted.
3394
+ *
3395
+ * @example
3396
+ * const catchAllListener = (event, ...args) => {
3397
+ * console.log(`sent event ${event}`);
3398
+ * }
3399
+ *
3400
+ * socket.onAnyOutgoing(catchAllListener);
3401
+ *
3402
+ * // remove a specific listener
3403
+ * socket.offAnyOutgoing(catchAllListener);
3404
+ *
3405
+ * // or remove all listeners
3406
+ * socket.offAnyOutgoing();
3407
+ *
3408
+ * @param [listener] - the catch-all listener (optional)
3409
+ */
3410
+ offAnyOutgoing(listener) {
3411
+ if (!this._anyOutgoingListeners) {
3412
+ return this;
3413
+ }
3414
+ if (listener) {
3415
+ const listeners = this._anyOutgoingListeners;
3416
+ for (let i = 0; i < listeners.length; i++) {
3417
+ if (listener === listeners[i]) {
3418
+ listeners.splice(i, 1);
3419
+ return this;
3420
+ }
3421
+ }
3422
+ } else {
3423
+ this._anyOutgoingListeners = [];
3424
+ }
3425
+ return this;
3426
+ }
3427
+ /**
3428
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3429
+ * e.g. to remove listeners.
3430
+ */
3431
+ listenersAnyOutgoing() {
3432
+ return this._anyOutgoingListeners || [];
3433
+ }
3434
+ /**
3435
+ * Notify the listeners for each packet sent
3436
+ *
3437
+ * @param packet
3438
+ *
3439
+ * @private
3440
+ */
3441
+ notifyOutgoingListeners(packet) {
3442
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
3443
+ const listeners = this._anyOutgoingListeners.slice();
3444
+ for (const listener of listeners) {
3445
+ listener.apply(this, packet.data);
3446
+ }
3447
+ }
3448
+ }
3449
+ };
3450
+
3451
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/contrib/backo2.js
3452
+ function Backoff(opts) {
3453
+ opts = opts || {};
3454
+ this.ms = opts.min || 100;
3455
+ this.max = opts.max || 1e4;
3456
+ this.factor = opts.factor || 2;
3457
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3458
+ this.attempts = 0;
3459
+ }
3460
+ Backoff.prototype.duration = function() {
3461
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
3462
+ if (this.jitter) {
3463
+ var rand = Math.random();
3464
+ var deviation = Math.floor(rand * this.jitter * ms);
3465
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3466
+ }
3467
+ return Math.min(ms, this.max) | 0;
3468
+ };
3469
+ Backoff.prototype.reset = function() {
3470
+ this.attempts = 0;
3471
+ };
3472
+ Backoff.prototype.setMin = function(min) {
3473
+ this.ms = min;
3474
+ };
3475
+ Backoff.prototype.setMax = function(max) {
3476
+ this.max = max;
3477
+ };
3478
+ Backoff.prototype.setJitter = function(jitter) {
3479
+ this.jitter = jitter;
3480
+ };
3481
+
3482
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/manager.js
3483
+ var Manager = class extends Emitter {
3484
+ constructor(uri, opts) {
3485
+ var _a;
3486
+ super();
3487
+ this.nsps = {};
3488
+ this.subs = [];
3489
+ if (uri && "object" === typeof uri) {
3490
+ opts = uri;
3491
+ uri = void 0;
3492
+ }
3493
+ opts = opts || {};
3494
+ opts.path = opts.path || "/socket.io";
3495
+ this.opts = opts;
3496
+ installTimerFunctions(this, opts);
3497
+ this.reconnection(opts.reconnection !== false);
3498
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3499
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
3500
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
3501
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3502
+ this.backoff = new Backoff({
3503
+ min: this.reconnectionDelay(),
3504
+ max: this.reconnectionDelayMax(),
3505
+ jitter: this.randomizationFactor()
3506
+ });
3507
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
3508
+ this._readyState = "closed";
3509
+ this.uri = uri;
3510
+ const _parser = opts.parser || esm_exports;
3511
+ this.encoder = new _parser.Encoder();
3512
+ this.decoder = new _parser.Decoder();
3513
+ this._autoConnect = opts.autoConnect !== false;
3514
+ if (this._autoConnect)
3515
+ this.open();
3516
+ }
3517
+ reconnection(v) {
3518
+ if (!arguments.length)
3519
+ return this._reconnection;
3520
+ this._reconnection = !!v;
3521
+ if (!v) {
3522
+ this.skipReconnect = true;
3523
+ }
3524
+ return this;
3525
+ }
3526
+ reconnectionAttempts(v) {
3527
+ if (v === void 0)
3528
+ return this._reconnectionAttempts;
3529
+ this._reconnectionAttempts = v;
3530
+ return this;
3531
+ }
3532
+ reconnectionDelay(v) {
3533
+ var _a;
3534
+ if (v === void 0)
3535
+ return this._reconnectionDelay;
3536
+ this._reconnectionDelay = v;
3537
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3538
+ return this;
3539
+ }
3540
+ randomizationFactor(v) {
3541
+ var _a;
3542
+ if (v === void 0)
3543
+ return this._randomizationFactor;
3544
+ this._randomizationFactor = v;
3545
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3546
+ return this;
3547
+ }
3548
+ reconnectionDelayMax(v) {
3549
+ var _a;
3550
+ if (v === void 0)
3551
+ return this._reconnectionDelayMax;
3552
+ this._reconnectionDelayMax = v;
3553
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3554
+ return this;
3555
+ }
3556
+ timeout(v) {
3557
+ if (!arguments.length)
3558
+ return this._timeout;
3559
+ this._timeout = v;
3560
+ return this;
3561
+ }
3562
+ /**
3563
+ * Starts trying to reconnect if reconnection is enabled and we have not
3564
+ * started reconnecting yet
3565
+ *
3566
+ * @private
3567
+ */
3568
+ maybeReconnectOnOpen() {
3569
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
3570
+ this.reconnect();
3571
+ }
3572
+ }
3573
+ /**
3574
+ * Sets the current transport `socket`.
3575
+ *
3576
+ * @param {Function} fn - optional, callback
3577
+ * @return self
3578
+ * @public
3579
+ */
3580
+ open(fn) {
3581
+ if (~this._readyState.indexOf("open"))
3582
+ return this;
3583
+ this.engine = new Socket(this.uri, this.opts);
3584
+ const socket = this.engine;
3585
+ const self2 = this;
3586
+ this._readyState = "opening";
3587
+ this.skipReconnect = false;
3588
+ const openSubDestroy = on(socket, "open", function() {
3589
+ self2.onopen();
3590
+ fn && fn();
3591
+ });
3592
+ const onError = (err) => {
3593
+ this.cleanup();
3594
+ this._readyState = "closed";
3595
+ this.emitReserved("error", err);
3596
+ if (fn) {
3597
+ fn(err);
3598
+ } else {
3599
+ this.maybeReconnectOnOpen();
3600
+ }
3601
+ };
3602
+ const errorSub = on(socket, "error", onError);
3603
+ if (false !== this._timeout) {
3604
+ const timeout = this._timeout;
3605
+ const timer = this.setTimeoutFn(() => {
3606
+ openSubDestroy();
3607
+ onError(new Error("timeout"));
3608
+ socket.close();
3609
+ }, timeout);
3610
+ if (this.opts.autoUnref) {
3611
+ timer.unref();
3612
+ }
3613
+ this.subs.push(() => {
3614
+ this.clearTimeoutFn(timer);
3615
+ });
3616
+ }
3617
+ this.subs.push(openSubDestroy);
3618
+ this.subs.push(errorSub);
3619
+ return this;
3620
+ }
3621
+ /**
3622
+ * Alias for open()
3623
+ *
3624
+ * @return self
3625
+ * @public
3626
+ */
3627
+ connect(fn) {
3628
+ return this.open(fn);
3629
+ }
3630
+ /**
3631
+ * Called upon transport open.
3632
+ *
3633
+ * @private
3634
+ */
3635
+ onopen() {
3636
+ this.cleanup();
3637
+ this._readyState = "open";
3638
+ this.emitReserved("open");
3639
+ const socket = this.engine;
3640
+ this.subs.push(
3641
+ on(socket, "ping", this.onping.bind(this)),
3642
+ on(socket, "data", this.ondata.bind(this)),
3643
+ on(socket, "error", this.onerror.bind(this)),
3644
+ on(socket, "close", this.onclose.bind(this)),
3645
+ // @ts-ignore
3646
+ on(this.decoder, "decoded", this.ondecoded.bind(this))
3647
+ );
3648
+ }
3649
+ /**
3650
+ * Called upon a ping.
3651
+ *
3652
+ * @private
3653
+ */
3654
+ onping() {
3655
+ this.emitReserved("ping");
3656
+ }
3657
+ /**
3658
+ * Called with data.
3659
+ *
3660
+ * @private
3661
+ */
3662
+ ondata(data) {
3663
+ try {
3664
+ this.decoder.add(data);
3665
+ } catch (e) {
3666
+ this.onclose("parse error", e);
3667
+ }
3668
+ }
3669
+ /**
3670
+ * Called when parser fully decodes a packet.
3671
+ *
3672
+ * @private
3673
+ */
3674
+ ondecoded(packet) {
3675
+ nextTick(() => {
3676
+ this.emitReserved("packet", packet);
3677
+ }, this.setTimeoutFn);
3678
+ }
3679
+ /**
3680
+ * Called upon socket error.
3681
+ *
3682
+ * @private
3683
+ */
3684
+ onerror(err) {
3685
+ this.emitReserved("error", err);
3686
+ }
3687
+ /**
3688
+ * Creates a new socket for the given `nsp`.
3689
+ *
3690
+ * @return {Socket}
3691
+ * @public
3692
+ */
3693
+ socket(nsp, opts) {
3694
+ let socket = this.nsps[nsp];
3695
+ if (!socket) {
3696
+ socket = new Socket2(this, nsp, opts);
3697
+ this.nsps[nsp] = socket;
3698
+ } else if (this._autoConnect && !socket.active) {
3699
+ socket.connect();
3700
+ }
3701
+ return socket;
3702
+ }
3703
+ /**
3704
+ * Called upon a socket close.
3705
+ *
3706
+ * @param socket
3707
+ * @private
3708
+ */
3709
+ _destroy(socket) {
3710
+ const nsps = Object.keys(this.nsps);
3711
+ for (const nsp of nsps) {
3712
+ const socket2 = this.nsps[nsp];
3713
+ if (socket2.active) {
3714
+ return;
3715
+ }
3716
+ }
3717
+ this._close();
3718
+ }
3719
+ /**
3720
+ * Writes a packet.
3721
+ *
3722
+ * @param packet
3723
+ * @private
3724
+ */
3725
+ _packet(packet) {
3726
+ const encodedPackets = this.encoder.encode(packet);
3727
+ for (let i = 0; i < encodedPackets.length; i++) {
3728
+ this.engine.write(encodedPackets[i], packet.options);
3729
+ }
3730
+ }
3731
+ /**
3732
+ * Clean up transport subscriptions and packet buffer.
3733
+ *
3734
+ * @private
3735
+ */
3736
+ cleanup() {
3737
+ this.subs.forEach((subDestroy) => subDestroy());
3738
+ this.subs.length = 0;
3739
+ this.decoder.destroy();
3740
+ }
3741
+ /**
3742
+ * Close the current socket.
3743
+ *
3744
+ * @private
3745
+ */
3746
+ _close() {
3747
+ this.skipReconnect = true;
3748
+ this._reconnecting = false;
3749
+ this.onclose("forced close");
3750
+ }
3751
+ /**
3752
+ * Alias for close()
3753
+ *
3754
+ * @private
3755
+ */
3756
+ disconnect() {
3757
+ return this._close();
3758
+ }
3759
+ /**
3760
+ * Called when:
3761
+ *
3762
+ * - the low-level engine is closed
3763
+ * - the parser encountered a badly formatted packet
3764
+ * - all sockets are disconnected
3765
+ *
3766
+ * @private
3767
+ */
3768
+ onclose(reason, description) {
3769
+ var _a;
3770
+ this.cleanup();
3771
+ (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
3772
+ this.backoff.reset();
3773
+ this._readyState = "closed";
3774
+ this.emitReserved("close", reason, description);
3775
+ if (this._reconnection && !this.skipReconnect) {
3776
+ this.reconnect();
3777
+ }
3778
+ }
3779
+ /**
3780
+ * Attempt a reconnection.
3781
+ *
3782
+ * @private
3783
+ */
3784
+ reconnect() {
3785
+ if (this._reconnecting || this.skipReconnect)
3786
+ return this;
3787
+ const self2 = this;
3788
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
3789
+ this.backoff.reset();
3790
+ this.emitReserved("reconnect_failed");
3791
+ this._reconnecting = false;
3792
+ } else {
3793
+ const delay = this.backoff.duration();
3794
+ this._reconnecting = true;
3795
+ const timer = this.setTimeoutFn(() => {
3796
+ if (self2.skipReconnect)
3797
+ return;
3798
+ this.emitReserved("reconnect_attempt", self2.backoff.attempts);
3799
+ if (self2.skipReconnect)
3800
+ return;
3801
+ self2.open((err) => {
3802
+ if (err) {
3803
+ self2._reconnecting = false;
3804
+ self2.reconnect();
3805
+ this.emitReserved("reconnect_error", err);
3806
+ } else {
3807
+ self2.onreconnect();
3808
+ }
3809
+ });
3810
+ }, delay);
3811
+ if (this.opts.autoUnref) {
3812
+ timer.unref();
3813
+ }
3814
+ this.subs.push(() => {
3815
+ this.clearTimeoutFn(timer);
3816
+ });
3817
+ }
3818
+ }
3819
+ /**
3820
+ * Called upon successful reconnect.
3821
+ *
3822
+ * @private
3823
+ */
3824
+ onreconnect() {
3825
+ const attempt = this.backoff.attempts;
3826
+ this._reconnecting = false;
3827
+ this.backoff.reset();
3828
+ this.emitReserved("reconnect", attempt);
3829
+ }
3830
+ };
3831
+
3832
+ // ../node_modules/.pnpm/socket.io-client@4.8.3/node_modules/socket.io-client/build/esm/index.js
3833
+ var cache = {};
3834
+ function lookup2(uri, opts) {
3835
+ if (typeof uri === "object") {
3836
+ opts = uri;
3837
+ uri = void 0;
3838
+ }
3839
+ opts = opts || {};
3840
+ const parsed = url(uri, opts.path || "/socket.io");
3841
+ const source = parsed.source;
3842
+ const id = parsed.id;
3843
+ const path = parsed.path;
3844
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
3845
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
3846
+ let io;
3847
+ if (newConnection) {
3848
+ io = new Manager(source, opts);
3849
+ } else {
3850
+ if (!cache[id]) {
3851
+ cache[id] = new Manager(source, opts);
3852
+ }
3853
+ io = cache[id];
3854
+ }
3855
+ if (parsed.query && !opts.query) {
3856
+ opts.query = parsed.queryKey;
3857
+ }
3858
+ return io.socket(parsed.path, opts);
3859
+ }
3860
+ Object.assign(lookup2, {
3861
+ Manager,
3862
+ Socket: Socket2,
3863
+ io: lookup2,
3864
+ connect: lookup2
3865
+ });
4
3866
 
5
3867
  // src/utils/event-emitter.ts
6
3868
  var TypedEventEmitter = class {
@@ -61,6 +3923,9 @@ var TypedEventEmitter = class {
61
3923
  }
62
3924
  };
63
3925
 
3926
+ // src/connection/socket-manager.ts
3927
+ init_errors();
3928
+
64
3929
  // src/types.ts
65
3930
  var ConnectionState = /* @__PURE__ */ ((ConnectionState2) => {
66
3931
  ConnectionState2["Disconnected"] = "disconnected";
@@ -180,9 +4045,9 @@ var SocketManager = class extends TypedEventEmitter {
180
4045
  }
181
4046
  this.setConnectionState("connecting" /* Connecting */);
182
4047
  this.reconnectAttempt = 0;
183
- const url = `${this.config.serverUrl}/sdk`;
184
- this.logger.debug("Connecting to", url);
185
- this.socket = io(url, {
4048
+ const url2 = `${this.config.serverUrl}/sdk`;
4049
+ this.logger.debug("Connecting to", url2);
4050
+ this.socket = lookup2(url2, {
186
4051
  transports: ["websocket"],
187
4052
  timeout: 1e4,
188
4053
  reconnection: false,
@@ -361,30 +4226,31 @@ async function isLiveKitAvailable() {
361
4226
  }
362
4227
  async function createVoiceManager(transport, socketManager, sampleRate, logger) {
363
4228
  if (transport === "websocket") {
364
- const { WebSocketVoiceManager } = await import('./websocket-voice-6DMYBGHP.mjs');
365
- return new WebSocketVoiceManager(socketManager, sampleRate, logger);
4229
+ const { WebSocketVoiceManager: WebSocketVoiceManager2 } = await Promise.resolve().then(() => (init_websocket_voice(), websocket_voice_exports));
4230
+ return new WebSocketVoiceManager2(socketManager, sampleRate, logger);
366
4231
  }
367
4232
  if (transport === "livekit") {
368
4233
  if (await isLiveKitAvailable()) {
369
- const { LiveKitVoiceManager } = await import('./livekit-voice-PV3TGH2Q.mjs');
370
- return new LiveKitVoiceManager(socketManager, logger);
4234
+ const { LiveKitVoiceManager: LiveKitVoiceManager2 } = await Promise.resolve().then(() => (init_livekit_voice(), livekit_voice_exports));
4235
+ return new LiveKitVoiceManager2(socketManager, logger);
371
4236
  }
372
4237
  logger.warn("livekit-client not installed, falling back to WebSocket voice");
373
- const { WebSocketVoiceManager } = await import('./websocket-voice-6DMYBGHP.mjs');
374
- return new WebSocketVoiceManager(socketManager, sampleRate, logger);
4238
+ const { WebSocketVoiceManager: WebSocketVoiceManager2 } = await Promise.resolve().then(() => (init_websocket_voice(), websocket_voice_exports));
4239
+ return new WebSocketVoiceManager2(socketManager, sampleRate, logger);
375
4240
  }
376
4241
  if (transport === "auto") {
377
4242
  if (await isLiveKitAvailable()) {
378
- const { LiveKitVoiceManager } = await import('./livekit-voice-PV3TGH2Q.mjs');
379
- return new LiveKitVoiceManager(socketManager, logger);
4243
+ const { LiveKitVoiceManager: LiveKitVoiceManager2 } = await Promise.resolve().then(() => (init_livekit_voice(), livekit_voice_exports));
4244
+ return new LiveKitVoiceManager2(socketManager, logger);
380
4245
  }
381
- const { WebSocketVoiceManager } = await import('./websocket-voice-6DMYBGHP.mjs');
382
- return new WebSocketVoiceManager(socketManager, sampleRate, logger);
4246
+ const { WebSocketVoiceManager: WebSocketVoiceManager2 } = await Promise.resolve().then(() => (init_websocket_voice(), websocket_voice_exports));
4247
+ return new WebSocketVoiceManager2(socketManager, sampleRate, logger);
383
4248
  }
384
4249
  return null;
385
4250
  }
386
4251
 
387
4252
  // src/rest/rest-client.ts
4253
+ init_errors();
388
4254
  var DEFAULT_TIMEOUT_MS = 1e4;
389
4255
  var RestClient = class {
390
4256
  baseUrl;
@@ -396,39 +4262,39 @@ var RestClient = class {
396
4262
  this.timeoutMs = timeoutMs;
397
4263
  }
398
4264
  async get(path, params) {
399
- const url = this.buildUrl(path, params);
400
- return this.request(url, { method: "GET" });
4265
+ const url2 = this.buildUrl(path, params);
4266
+ return this.request(url2, { method: "GET" });
401
4267
  }
402
4268
  async post(path, body) {
403
- const url = this.buildUrl(path);
4269
+ const url2 = this.buildUrl(path);
404
4270
  const init = { method: "POST" };
405
4271
  if (body !== void 0) {
406
4272
  init.headers = { "Content-Type": "application/json" };
407
4273
  init.body = JSON.stringify(body);
408
4274
  }
409
- return this.request(url, init);
4275
+ return this.request(url2, init);
410
4276
  }
411
4277
  async delete(path, params) {
412
- const url = this.buildUrl(path, params);
413
- return this.request(url, { method: "DELETE" });
4278
+ const url2 = this.buildUrl(path, params);
4279
+ return this.request(url2, { method: "DELETE" });
414
4280
  }
415
4281
  dispose() {
416
4282
  }
417
4283
  buildUrl(path, params) {
418
- const url = new URL(path, this.baseUrl);
4284
+ const url2 = new URL(path, this.baseUrl);
419
4285
  if (params) {
420
- for (const [key, value] of Object.entries(params)) {
421
- if (value !== void 0) {
422
- url.searchParams.set(key, String(value));
4286
+ for (const [key, value2] of Object.entries(params)) {
4287
+ if (value2 !== void 0) {
4288
+ url2.searchParams.set(key, String(value2));
423
4289
  }
424
4290
  }
425
4291
  }
426
- return url.toString();
4292
+ return url2.toString();
427
4293
  }
428
- async request(url, init) {
4294
+ async request(url2, init) {
429
4295
  const headers = new Headers(init.headers);
430
4296
  headers.set("X-API-Key", this.apiKey);
431
- const response = await fetch(url, {
4297
+ const response = await fetch(url2, {
432
4298
  ...init,
433
4299
  headers,
434
4300
  signal: AbortSignal.timeout(this.timeoutMs)
@@ -705,6 +4571,9 @@ var Logger = class {
705
4571
  }
706
4572
  };
707
4573
 
4574
+ // src/client.ts
4575
+ init_errors();
4576
+
708
4577
  // src/utils/action-parser.ts
709
4578
  var ACTION_TAG_RE = /<action\s+([^>]*?)\/>/gi;
710
4579
  var ATTR_RE = /(\w+)\s*=\s*"([^"]*)"|(\w+)\s*=\s*'([^']*)'/g;
@@ -713,8 +4582,8 @@ function parseAttributes(attrString) {
713
4582
  let match;
714
4583
  while ((match = ATTR_RE.exec(attrString)) !== null) {
715
4584
  const key = match[1] ?? match[3];
716
- const value = match[2] ?? match[4];
717
- attrs[key] = value;
4585
+ const value2 = match[2] ?? match[4];
4586
+ attrs[key] = value2;
718
4587
  }
719
4588
  return attrs;
720
4589
  }
@@ -1044,6 +4913,9 @@ var EstuaryClient = class extends TypedEventEmitter {
1044
4913
  }
1045
4914
  };
1046
4915
 
1047
- export { ConnectionState, EstuaryClient, parseActions };
4916
+ // src/index.ts
4917
+ init_errors();
4918
+
4919
+ export { ConnectionState, ErrorCode, EstuaryClient, EstuaryError, parseActions };
1048
4920
  //# sourceMappingURL=index.mjs.map
1049
4921
  //# sourceMappingURL=index.mjs.map