@looplia/looplia-cli 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3713 @@
1
+ #!/usr/bin/env bun
2
+ import {
3
+ __commonJS,
4
+ __require,
5
+ __toESM,
6
+ init_esm_shims
7
+ } from "./chunk-Y55L47HC.js";
8
+
9
+ // ../../node_modules/ws/lib/constants.js
10
+ var require_constants = __commonJS({
11
+ "../../node_modules/ws/lib/constants.js"(exports, module) {
12
+ "use strict";
13
+ init_esm_shims();
14
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
15
+ var hasBlob = typeof Blob !== "undefined";
16
+ if (hasBlob) BINARY_TYPES.push("blob");
17
+ module.exports = {
18
+ BINARY_TYPES,
19
+ CLOSE_TIMEOUT: 3e4,
20
+ EMPTY_BUFFER: Buffer.alloc(0),
21
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
22
+ hasBlob,
23
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
24
+ kListener: /* @__PURE__ */ Symbol("kListener"),
25
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
26
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
27
+ NOOP: () => {
28
+ }
29
+ };
30
+ }
31
+ });
32
+
33
+ // ../../node_modules/ws/lib/buffer-util.js
34
+ var require_buffer_util = __commonJS({
35
+ "../../node_modules/ws/lib/buffer-util.js"(exports, module) {
36
+ "use strict";
37
+ init_esm_shims();
38
+ var { EMPTY_BUFFER } = require_constants();
39
+ var FastBuffer = Buffer[Symbol.species];
40
+ function concat(list, totalLength) {
41
+ if (list.length === 0) return EMPTY_BUFFER;
42
+ if (list.length === 1) return list[0];
43
+ const target = Buffer.allocUnsafe(totalLength);
44
+ let offset = 0;
45
+ for (let i = 0; i < list.length; i++) {
46
+ const buf = list[i];
47
+ target.set(buf, offset);
48
+ offset += buf.length;
49
+ }
50
+ if (offset < totalLength) {
51
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
52
+ }
53
+ return target;
54
+ }
55
+ function _mask(source, mask, output, offset, length) {
56
+ for (let i = 0; i < length; i++) {
57
+ output[offset + i] = source[i] ^ mask[i & 3];
58
+ }
59
+ }
60
+ function _unmask(buffer, mask) {
61
+ for (let i = 0; i < buffer.length; i++) {
62
+ buffer[i] ^= mask[i & 3];
63
+ }
64
+ }
65
+ function toArrayBuffer(buf) {
66
+ if (buf.length === buf.buffer.byteLength) {
67
+ return buf.buffer;
68
+ }
69
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
70
+ }
71
+ function toBuffer(data) {
72
+ toBuffer.readOnly = true;
73
+ if (Buffer.isBuffer(data)) return data;
74
+ let buf;
75
+ if (data instanceof ArrayBuffer) {
76
+ buf = new FastBuffer(data);
77
+ } else if (ArrayBuffer.isView(data)) {
78
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
79
+ } else {
80
+ buf = Buffer.from(data);
81
+ toBuffer.readOnly = false;
82
+ }
83
+ return buf;
84
+ }
85
+ module.exports = {
86
+ concat,
87
+ mask: _mask,
88
+ toArrayBuffer,
89
+ toBuffer,
90
+ unmask: _unmask
91
+ };
92
+ if (!process.env.WS_NO_BUFFER_UTIL) {
93
+ try {
94
+ const bufferUtil = __require("bufferutil");
95
+ module.exports.mask = function(source, mask, output, offset, length) {
96
+ if (length < 48) _mask(source, mask, output, offset, length);
97
+ else bufferUtil.mask(source, mask, output, offset, length);
98
+ };
99
+ module.exports.unmask = function(buffer, mask) {
100
+ if (buffer.length < 32) _unmask(buffer, mask);
101
+ else bufferUtil.unmask(buffer, mask);
102
+ };
103
+ } catch (e) {
104
+ }
105
+ }
106
+ }
107
+ });
108
+
109
+ // ../../node_modules/ws/lib/limiter.js
110
+ var require_limiter = __commonJS({
111
+ "../../node_modules/ws/lib/limiter.js"(exports, module) {
112
+ "use strict";
113
+ init_esm_shims();
114
+ var kDone = /* @__PURE__ */ Symbol("kDone");
115
+ var kRun = /* @__PURE__ */ Symbol("kRun");
116
+ var Limiter = class {
117
+ /**
118
+ * Creates a new `Limiter`.
119
+ *
120
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
121
+ * to run concurrently
122
+ */
123
+ constructor(concurrency) {
124
+ this[kDone] = () => {
125
+ this.pending--;
126
+ this[kRun]();
127
+ };
128
+ this.concurrency = concurrency || Infinity;
129
+ this.jobs = [];
130
+ this.pending = 0;
131
+ }
132
+ /**
133
+ * Adds a job to the queue.
134
+ *
135
+ * @param {Function} job The job to run
136
+ * @public
137
+ */
138
+ add(job) {
139
+ this.jobs.push(job);
140
+ this[kRun]();
141
+ }
142
+ /**
143
+ * Removes a job from the queue and runs it if possible.
144
+ *
145
+ * @private
146
+ */
147
+ [kRun]() {
148
+ if (this.pending === this.concurrency) return;
149
+ if (this.jobs.length) {
150
+ const job = this.jobs.shift();
151
+ this.pending++;
152
+ job(this[kDone]);
153
+ }
154
+ }
155
+ };
156
+ module.exports = Limiter;
157
+ }
158
+ });
159
+
160
+ // ../../node_modules/ws/lib/permessage-deflate.js
161
+ var require_permessage_deflate = __commonJS({
162
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports, module) {
163
+ "use strict";
164
+ init_esm_shims();
165
+ var zlib = __require("zlib");
166
+ var bufferUtil = require_buffer_util();
167
+ var Limiter = require_limiter();
168
+ var { kStatusCode } = require_constants();
169
+ var FastBuffer = Buffer[Symbol.species];
170
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
171
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
172
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
173
+ var kCallback = /* @__PURE__ */ Symbol("callback");
174
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
175
+ var kError = /* @__PURE__ */ Symbol("error");
176
+ var zlibLimiter;
177
+ var PerMessageDeflate = class {
178
+ /**
179
+ * Creates a PerMessageDeflate instance.
180
+ *
181
+ * @param {Object} [options] Configuration options
182
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
183
+ * for, or request, a custom client window size
184
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
185
+ * acknowledge disabling of client context takeover
186
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
187
+ * calls to zlib
188
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
189
+ * use of a custom server window size
190
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
191
+ * disabling of server context takeover
192
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
193
+ * messages should not be compressed if context takeover is disabled
194
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
195
+ * deflate
196
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
197
+ * inflate
198
+ * @param {Boolean} [isServer=false] Create the instance in either server or
199
+ * client mode
200
+ * @param {Number} [maxPayload=0] The maximum allowed message length
201
+ */
202
+ constructor(options, isServer, maxPayload) {
203
+ this._maxPayload = maxPayload | 0;
204
+ this._options = options || {};
205
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
206
+ this._isServer = !!isServer;
207
+ this._deflate = null;
208
+ this._inflate = null;
209
+ this.params = null;
210
+ if (!zlibLimiter) {
211
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
212
+ zlibLimiter = new Limiter(concurrency);
213
+ }
214
+ }
215
+ /**
216
+ * @type {String}
217
+ */
218
+ static get extensionName() {
219
+ return "permessage-deflate";
220
+ }
221
+ /**
222
+ * Create an extension negotiation offer.
223
+ *
224
+ * @return {Object} Extension parameters
225
+ * @public
226
+ */
227
+ offer() {
228
+ const params = {};
229
+ if (this._options.serverNoContextTakeover) {
230
+ params.server_no_context_takeover = true;
231
+ }
232
+ if (this._options.clientNoContextTakeover) {
233
+ params.client_no_context_takeover = true;
234
+ }
235
+ if (this._options.serverMaxWindowBits) {
236
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
237
+ }
238
+ if (this._options.clientMaxWindowBits) {
239
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
240
+ } else if (this._options.clientMaxWindowBits == null) {
241
+ params.client_max_window_bits = true;
242
+ }
243
+ return params;
244
+ }
245
+ /**
246
+ * Accept an extension negotiation offer/response.
247
+ *
248
+ * @param {Array} configurations The extension negotiation offers/reponse
249
+ * @return {Object} Accepted configuration
250
+ * @public
251
+ */
252
+ accept(configurations) {
253
+ configurations = this.normalizeParams(configurations);
254
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
255
+ return this.params;
256
+ }
257
+ /**
258
+ * Releases all resources used by the extension.
259
+ *
260
+ * @public
261
+ */
262
+ cleanup() {
263
+ if (this._inflate) {
264
+ this._inflate.close();
265
+ this._inflate = null;
266
+ }
267
+ if (this._deflate) {
268
+ const callback = this._deflate[kCallback];
269
+ this._deflate.close();
270
+ this._deflate = null;
271
+ if (callback) {
272
+ callback(
273
+ new Error(
274
+ "The deflate stream was closed while data was being processed"
275
+ )
276
+ );
277
+ }
278
+ }
279
+ }
280
+ /**
281
+ * Accept an extension negotiation offer.
282
+ *
283
+ * @param {Array} offers The extension negotiation offers
284
+ * @return {Object} Accepted configuration
285
+ * @private
286
+ */
287
+ acceptAsServer(offers) {
288
+ const opts = this._options;
289
+ const accepted = offers.find((params) => {
290
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
291
+ return false;
292
+ }
293
+ return true;
294
+ });
295
+ if (!accepted) {
296
+ throw new Error("None of the extension offers can be accepted");
297
+ }
298
+ if (opts.serverNoContextTakeover) {
299
+ accepted.server_no_context_takeover = true;
300
+ }
301
+ if (opts.clientNoContextTakeover) {
302
+ accepted.client_no_context_takeover = true;
303
+ }
304
+ if (typeof opts.serverMaxWindowBits === "number") {
305
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
306
+ }
307
+ if (typeof opts.clientMaxWindowBits === "number") {
308
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
309
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
310
+ delete accepted.client_max_window_bits;
311
+ }
312
+ return accepted;
313
+ }
314
+ /**
315
+ * Accept the extension negotiation response.
316
+ *
317
+ * @param {Array} response The extension negotiation response
318
+ * @return {Object} Accepted configuration
319
+ * @private
320
+ */
321
+ acceptAsClient(response) {
322
+ const params = response[0];
323
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
324
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
325
+ }
326
+ if (!params.client_max_window_bits) {
327
+ if (typeof this._options.clientMaxWindowBits === "number") {
328
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
329
+ }
330
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
331
+ throw new Error(
332
+ 'Unexpected or invalid parameter "client_max_window_bits"'
333
+ );
334
+ }
335
+ return params;
336
+ }
337
+ /**
338
+ * Normalize parameters.
339
+ *
340
+ * @param {Array} configurations The extension negotiation offers/reponse
341
+ * @return {Array} The offers/response with normalized parameters
342
+ * @private
343
+ */
344
+ normalizeParams(configurations) {
345
+ configurations.forEach((params) => {
346
+ Object.keys(params).forEach((key) => {
347
+ let value = params[key];
348
+ if (value.length > 1) {
349
+ throw new Error(`Parameter "${key}" must have only a single value`);
350
+ }
351
+ value = value[0];
352
+ if (key === "client_max_window_bits") {
353
+ if (value !== true) {
354
+ const num = +value;
355
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
356
+ throw new TypeError(
357
+ `Invalid value for parameter "${key}": ${value}`
358
+ );
359
+ }
360
+ value = num;
361
+ } else if (!this._isServer) {
362
+ throw new TypeError(
363
+ `Invalid value for parameter "${key}": ${value}`
364
+ );
365
+ }
366
+ } else if (key === "server_max_window_bits") {
367
+ const num = +value;
368
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
369
+ throw new TypeError(
370
+ `Invalid value for parameter "${key}": ${value}`
371
+ );
372
+ }
373
+ value = num;
374
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
375
+ if (value !== true) {
376
+ throw new TypeError(
377
+ `Invalid value for parameter "${key}": ${value}`
378
+ );
379
+ }
380
+ } else {
381
+ throw new Error(`Unknown parameter "${key}"`);
382
+ }
383
+ params[key] = value;
384
+ });
385
+ });
386
+ return configurations;
387
+ }
388
+ /**
389
+ * Decompress data. Concurrency limited.
390
+ *
391
+ * @param {Buffer} data Compressed data
392
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
393
+ * @param {Function} callback Callback
394
+ * @public
395
+ */
396
+ decompress(data, fin, callback) {
397
+ zlibLimiter.add((done) => {
398
+ this._decompress(data, fin, (err, result) => {
399
+ done();
400
+ callback(err, result);
401
+ });
402
+ });
403
+ }
404
+ /**
405
+ * Compress data. Concurrency limited.
406
+ *
407
+ * @param {(Buffer|String)} data Data to compress
408
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
409
+ * @param {Function} callback Callback
410
+ * @public
411
+ */
412
+ compress(data, fin, callback) {
413
+ zlibLimiter.add((done) => {
414
+ this._compress(data, fin, (err, result) => {
415
+ done();
416
+ callback(err, result);
417
+ });
418
+ });
419
+ }
420
+ /**
421
+ * Decompress data.
422
+ *
423
+ * @param {Buffer} data Compressed data
424
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
425
+ * @param {Function} callback Callback
426
+ * @private
427
+ */
428
+ _decompress(data, fin, callback) {
429
+ const endpoint = this._isServer ? "client" : "server";
430
+ if (!this._inflate) {
431
+ const key = `${endpoint}_max_window_bits`;
432
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
433
+ this._inflate = zlib.createInflateRaw({
434
+ ...this._options.zlibInflateOptions,
435
+ windowBits
436
+ });
437
+ this._inflate[kPerMessageDeflate] = this;
438
+ this._inflate[kTotalLength] = 0;
439
+ this._inflate[kBuffers] = [];
440
+ this._inflate.on("error", inflateOnError);
441
+ this._inflate.on("data", inflateOnData);
442
+ }
443
+ this._inflate[kCallback] = callback;
444
+ this._inflate.write(data);
445
+ if (fin) this._inflate.write(TRAILER);
446
+ this._inflate.flush(() => {
447
+ const err = this._inflate[kError];
448
+ if (err) {
449
+ this._inflate.close();
450
+ this._inflate = null;
451
+ callback(err);
452
+ return;
453
+ }
454
+ const data2 = bufferUtil.concat(
455
+ this._inflate[kBuffers],
456
+ this._inflate[kTotalLength]
457
+ );
458
+ if (this._inflate._readableState.endEmitted) {
459
+ this._inflate.close();
460
+ this._inflate = null;
461
+ } else {
462
+ this._inflate[kTotalLength] = 0;
463
+ this._inflate[kBuffers] = [];
464
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
465
+ this._inflate.reset();
466
+ }
467
+ }
468
+ callback(null, data2);
469
+ });
470
+ }
471
+ /**
472
+ * Compress data.
473
+ *
474
+ * @param {(Buffer|String)} data Data to compress
475
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
476
+ * @param {Function} callback Callback
477
+ * @private
478
+ */
479
+ _compress(data, fin, callback) {
480
+ const endpoint = this._isServer ? "server" : "client";
481
+ if (!this._deflate) {
482
+ const key = `${endpoint}_max_window_bits`;
483
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
484
+ this._deflate = zlib.createDeflateRaw({
485
+ ...this._options.zlibDeflateOptions,
486
+ windowBits
487
+ });
488
+ this._deflate[kTotalLength] = 0;
489
+ this._deflate[kBuffers] = [];
490
+ this._deflate.on("data", deflateOnData);
491
+ }
492
+ this._deflate[kCallback] = callback;
493
+ this._deflate.write(data);
494
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
495
+ if (!this._deflate) {
496
+ return;
497
+ }
498
+ let data2 = bufferUtil.concat(
499
+ this._deflate[kBuffers],
500
+ this._deflate[kTotalLength]
501
+ );
502
+ if (fin) {
503
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
504
+ }
505
+ this._deflate[kCallback] = null;
506
+ this._deflate[kTotalLength] = 0;
507
+ this._deflate[kBuffers] = [];
508
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
509
+ this._deflate.reset();
510
+ }
511
+ callback(null, data2);
512
+ });
513
+ }
514
+ };
515
+ module.exports = PerMessageDeflate;
516
+ function deflateOnData(chunk) {
517
+ this[kBuffers].push(chunk);
518
+ this[kTotalLength] += chunk.length;
519
+ }
520
+ function inflateOnData(chunk) {
521
+ this[kTotalLength] += chunk.length;
522
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
523
+ this[kBuffers].push(chunk);
524
+ return;
525
+ }
526
+ this[kError] = new RangeError("Max payload size exceeded");
527
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
528
+ this[kError][kStatusCode] = 1009;
529
+ this.removeListener("data", inflateOnData);
530
+ this.reset();
531
+ }
532
+ function inflateOnError(err) {
533
+ this[kPerMessageDeflate]._inflate = null;
534
+ if (this[kError]) {
535
+ this[kCallback](this[kError]);
536
+ return;
537
+ }
538
+ err[kStatusCode] = 1007;
539
+ this[kCallback](err);
540
+ }
541
+ }
542
+ });
543
+
544
+ // ../../node_modules/ws/lib/validation.js
545
+ var require_validation = __commonJS({
546
+ "../../node_modules/ws/lib/validation.js"(exports, module) {
547
+ "use strict";
548
+ init_esm_shims();
549
+ var { isUtf8 } = __require("buffer");
550
+ var { hasBlob } = require_constants();
551
+ var tokenChars = [
552
+ 0,
553
+ 0,
554
+ 0,
555
+ 0,
556
+ 0,
557
+ 0,
558
+ 0,
559
+ 0,
560
+ 0,
561
+ 0,
562
+ 0,
563
+ 0,
564
+ 0,
565
+ 0,
566
+ 0,
567
+ 0,
568
+ // 0 - 15
569
+ 0,
570
+ 0,
571
+ 0,
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ // 16 - 31
586
+ 0,
587
+ 1,
588
+ 0,
589
+ 1,
590
+ 1,
591
+ 1,
592
+ 1,
593
+ 1,
594
+ 0,
595
+ 0,
596
+ 1,
597
+ 1,
598
+ 0,
599
+ 1,
600
+ 1,
601
+ 0,
602
+ // 32 - 47
603
+ 1,
604
+ 1,
605
+ 1,
606
+ 1,
607
+ 1,
608
+ 1,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 1,
613
+ 0,
614
+ 0,
615
+ 0,
616
+ 0,
617
+ 0,
618
+ 0,
619
+ // 48 - 63
620
+ 0,
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ // 64 - 79
637
+ 1,
638
+ 1,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 0,
649
+ 0,
650
+ 0,
651
+ 1,
652
+ 1,
653
+ // 80 - 95
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ // 96 - 111
671
+ 1,
672
+ 1,
673
+ 1,
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 0,
683
+ 1,
684
+ 0,
685
+ 1,
686
+ 0
687
+ // 112 - 127
688
+ ];
689
+ function isValidStatusCode(code) {
690
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
691
+ }
692
+ function _isValidUTF8(buf) {
693
+ const len = buf.length;
694
+ let i = 0;
695
+ while (i < len) {
696
+ if ((buf[i] & 128) === 0) {
697
+ i++;
698
+ } else if ((buf[i] & 224) === 192) {
699
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
700
+ return false;
701
+ }
702
+ i += 2;
703
+ } else if ((buf[i] & 240) === 224) {
704
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
705
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
706
+ return false;
707
+ }
708
+ i += 3;
709
+ } else if ((buf[i] & 248) === 240) {
710
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
711
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
712
+ return false;
713
+ }
714
+ i += 4;
715
+ } else {
716
+ return false;
717
+ }
718
+ }
719
+ return true;
720
+ }
721
+ function isBlob(value) {
722
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
723
+ }
724
+ module.exports = {
725
+ isBlob,
726
+ isValidStatusCode,
727
+ isValidUTF8: _isValidUTF8,
728
+ tokenChars
729
+ };
730
+ if (isUtf8) {
731
+ module.exports.isValidUTF8 = function(buf) {
732
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
733
+ };
734
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
735
+ try {
736
+ const isValidUTF8 = __require("utf-8-validate");
737
+ module.exports.isValidUTF8 = function(buf) {
738
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
739
+ };
740
+ } catch (e) {
741
+ }
742
+ }
743
+ }
744
+ });
745
+
746
+ // ../../node_modules/ws/lib/receiver.js
747
+ var require_receiver = __commonJS({
748
+ "../../node_modules/ws/lib/receiver.js"(exports, module) {
749
+ "use strict";
750
+ init_esm_shims();
751
+ var { Writable } = __require("stream");
752
+ var PerMessageDeflate = require_permessage_deflate();
753
+ var {
754
+ BINARY_TYPES,
755
+ EMPTY_BUFFER,
756
+ kStatusCode,
757
+ kWebSocket
758
+ } = require_constants();
759
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
760
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
761
+ var FastBuffer = Buffer[Symbol.species];
762
+ var GET_INFO = 0;
763
+ var GET_PAYLOAD_LENGTH_16 = 1;
764
+ var GET_PAYLOAD_LENGTH_64 = 2;
765
+ var GET_MASK = 3;
766
+ var GET_DATA = 4;
767
+ var INFLATING = 5;
768
+ var DEFER_EVENT = 6;
769
+ var Receiver2 = class extends Writable {
770
+ /**
771
+ * Creates a Receiver instance.
772
+ *
773
+ * @param {Object} [options] Options object
774
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
775
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
776
+ * multiple times in the same tick
777
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
778
+ * @param {Object} [options.extensions] An object containing the negotiated
779
+ * extensions
780
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
781
+ * client or server mode
782
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
783
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
784
+ * not to skip UTF-8 validation for text and close messages
785
+ */
786
+ constructor(options = {}) {
787
+ super();
788
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
789
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
790
+ this._extensions = options.extensions || {};
791
+ this._isServer = !!options.isServer;
792
+ this._maxPayload = options.maxPayload | 0;
793
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
794
+ this[kWebSocket] = void 0;
795
+ this._bufferedBytes = 0;
796
+ this._buffers = [];
797
+ this._compressed = false;
798
+ this._payloadLength = 0;
799
+ this._mask = void 0;
800
+ this._fragmented = 0;
801
+ this._masked = false;
802
+ this._fin = false;
803
+ this._opcode = 0;
804
+ this._totalPayloadLength = 0;
805
+ this._messageLength = 0;
806
+ this._fragments = [];
807
+ this._errored = false;
808
+ this._loop = false;
809
+ this._state = GET_INFO;
810
+ }
811
+ /**
812
+ * Implements `Writable.prototype._write()`.
813
+ *
814
+ * @param {Buffer} chunk The chunk of data to write
815
+ * @param {String} encoding The character encoding of `chunk`
816
+ * @param {Function} cb Callback
817
+ * @private
818
+ */
819
+ _write(chunk, encoding, cb) {
820
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
821
+ this._bufferedBytes += chunk.length;
822
+ this._buffers.push(chunk);
823
+ this.startLoop(cb);
824
+ }
825
+ /**
826
+ * Consumes `n` bytes from the buffered data.
827
+ *
828
+ * @param {Number} n The number of bytes to consume
829
+ * @return {Buffer} The consumed bytes
830
+ * @private
831
+ */
832
+ consume(n) {
833
+ this._bufferedBytes -= n;
834
+ if (n === this._buffers[0].length) return this._buffers.shift();
835
+ if (n < this._buffers[0].length) {
836
+ const buf = this._buffers[0];
837
+ this._buffers[0] = new FastBuffer(
838
+ buf.buffer,
839
+ buf.byteOffset + n,
840
+ buf.length - n
841
+ );
842
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
843
+ }
844
+ const dst = Buffer.allocUnsafe(n);
845
+ do {
846
+ const buf = this._buffers[0];
847
+ const offset = dst.length - n;
848
+ if (n >= buf.length) {
849
+ dst.set(this._buffers.shift(), offset);
850
+ } else {
851
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
852
+ this._buffers[0] = new FastBuffer(
853
+ buf.buffer,
854
+ buf.byteOffset + n,
855
+ buf.length - n
856
+ );
857
+ }
858
+ n -= buf.length;
859
+ } while (n > 0);
860
+ return dst;
861
+ }
862
+ /**
863
+ * Starts the parsing loop.
864
+ *
865
+ * @param {Function} cb Callback
866
+ * @private
867
+ */
868
+ startLoop(cb) {
869
+ this._loop = true;
870
+ do {
871
+ switch (this._state) {
872
+ case GET_INFO:
873
+ this.getInfo(cb);
874
+ break;
875
+ case GET_PAYLOAD_LENGTH_16:
876
+ this.getPayloadLength16(cb);
877
+ break;
878
+ case GET_PAYLOAD_LENGTH_64:
879
+ this.getPayloadLength64(cb);
880
+ break;
881
+ case GET_MASK:
882
+ this.getMask();
883
+ break;
884
+ case GET_DATA:
885
+ this.getData(cb);
886
+ break;
887
+ case INFLATING:
888
+ case DEFER_EVENT:
889
+ this._loop = false;
890
+ return;
891
+ }
892
+ } while (this._loop);
893
+ if (!this._errored) cb();
894
+ }
895
+ /**
896
+ * Reads the first two bytes of a frame.
897
+ *
898
+ * @param {Function} cb Callback
899
+ * @private
900
+ */
901
+ getInfo(cb) {
902
+ if (this._bufferedBytes < 2) {
903
+ this._loop = false;
904
+ return;
905
+ }
906
+ const buf = this.consume(2);
907
+ if ((buf[0] & 48) !== 0) {
908
+ const error = this.createError(
909
+ RangeError,
910
+ "RSV2 and RSV3 must be clear",
911
+ true,
912
+ 1002,
913
+ "WS_ERR_UNEXPECTED_RSV_2_3"
914
+ );
915
+ cb(error);
916
+ return;
917
+ }
918
+ const compressed = (buf[0] & 64) === 64;
919
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
920
+ const error = this.createError(
921
+ RangeError,
922
+ "RSV1 must be clear",
923
+ true,
924
+ 1002,
925
+ "WS_ERR_UNEXPECTED_RSV_1"
926
+ );
927
+ cb(error);
928
+ return;
929
+ }
930
+ this._fin = (buf[0] & 128) === 128;
931
+ this._opcode = buf[0] & 15;
932
+ this._payloadLength = buf[1] & 127;
933
+ if (this._opcode === 0) {
934
+ if (compressed) {
935
+ const error = this.createError(
936
+ RangeError,
937
+ "RSV1 must be clear",
938
+ true,
939
+ 1002,
940
+ "WS_ERR_UNEXPECTED_RSV_1"
941
+ );
942
+ cb(error);
943
+ return;
944
+ }
945
+ if (!this._fragmented) {
946
+ const error = this.createError(
947
+ RangeError,
948
+ "invalid opcode 0",
949
+ true,
950
+ 1002,
951
+ "WS_ERR_INVALID_OPCODE"
952
+ );
953
+ cb(error);
954
+ return;
955
+ }
956
+ this._opcode = this._fragmented;
957
+ } else if (this._opcode === 1 || this._opcode === 2) {
958
+ if (this._fragmented) {
959
+ const error = this.createError(
960
+ RangeError,
961
+ `invalid opcode ${this._opcode}`,
962
+ true,
963
+ 1002,
964
+ "WS_ERR_INVALID_OPCODE"
965
+ );
966
+ cb(error);
967
+ return;
968
+ }
969
+ this._compressed = compressed;
970
+ } else if (this._opcode > 7 && this._opcode < 11) {
971
+ if (!this._fin) {
972
+ const error = this.createError(
973
+ RangeError,
974
+ "FIN must be set",
975
+ true,
976
+ 1002,
977
+ "WS_ERR_EXPECTED_FIN"
978
+ );
979
+ cb(error);
980
+ return;
981
+ }
982
+ if (compressed) {
983
+ const error = this.createError(
984
+ RangeError,
985
+ "RSV1 must be clear",
986
+ true,
987
+ 1002,
988
+ "WS_ERR_UNEXPECTED_RSV_1"
989
+ );
990
+ cb(error);
991
+ return;
992
+ }
993
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
994
+ const error = this.createError(
995
+ RangeError,
996
+ `invalid payload length ${this._payloadLength}`,
997
+ true,
998
+ 1002,
999
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1000
+ );
1001
+ cb(error);
1002
+ return;
1003
+ }
1004
+ } else {
1005
+ const error = this.createError(
1006
+ RangeError,
1007
+ `invalid opcode ${this._opcode}`,
1008
+ true,
1009
+ 1002,
1010
+ "WS_ERR_INVALID_OPCODE"
1011
+ );
1012
+ cb(error);
1013
+ return;
1014
+ }
1015
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1016
+ this._masked = (buf[1] & 128) === 128;
1017
+ if (this._isServer) {
1018
+ if (!this._masked) {
1019
+ const error = this.createError(
1020
+ RangeError,
1021
+ "MASK must be set",
1022
+ true,
1023
+ 1002,
1024
+ "WS_ERR_EXPECTED_MASK"
1025
+ );
1026
+ cb(error);
1027
+ return;
1028
+ }
1029
+ } else if (this._masked) {
1030
+ const error = this.createError(
1031
+ RangeError,
1032
+ "MASK must be clear",
1033
+ true,
1034
+ 1002,
1035
+ "WS_ERR_UNEXPECTED_MASK"
1036
+ );
1037
+ cb(error);
1038
+ return;
1039
+ }
1040
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1041
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1042
+ else this.haveLength(cb);
1043
+ }
1044
+ /**
1045
+ * Gets extended payload length (7+16).
1046
+ *
1047
+ * @param {Function} cb Callback
1048
+ * @private
1049
+ */
1050
+ getPayloadLength16(cb) {
1051
+ if (this._bufferedBytes < 2) {
1052
+ this._loop = false;
1053
+ return;
1054
+ }
1055
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1056
+ this.haveLength(cb);
1057
+ }
1058
+ /**
1059
+ * Gets extended payload length (7+64).
1060
+ *
1061
+ * @param {Function} cb Callback
1062
+ * @private
1063
+ */
1064
+ getPayloadLength64(cb) {
1065
+ if (this._bufferedBytes < 8) {
1066
+ this._loop = false;
1067
+ return;
1068
+ }
1069
+ const buf = this.consume(8);
1070
+ const num = buf.readUInt32BE(0);
1071
+ if (num > Math.pow(2, 53 - 32) - 1) {
1072
+ const error = this.createError(
1073
+ RangeError,
1074
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1075
+ false,
1076
+ 1009,
1077
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1078
+ );
1079
+ cb(error);
1080
+ return;
1081
+ }
1082
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1083
+ this.haveLength(cb);
1084
+ }
1085
+ /**
1086
+ * Payload length has been read.
1087
+ *
1088
+ * @param {Function} cb Callback
1089
+ * @private
1090
+ */
1091
+ haveLength(cb) {
1092
+ if (this._payloadLength && this._opcode < 8) {
1093
+ this._totalPayloadLength += this._payloadLength;
1094
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1095
+ const error = this.createError(
1096
+ RangeError,
1097
+ "Max payload size exceeded",
1098
+ false,
1099
+ 1009,
1100
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1101
+ );
1102
+ cb(error);
1103
+ return;
1104
+ }
1105
+ }
1106
+ if (this._masked) this._state = GET_MASK;
1107
+ else this._state = GET_DATA;
1108
+ }
1109
+ /**
1110
+ * Reads mask bytes.
1111
+ *
1112
+ * @private
1113
+ */
1114
+ getMask() {
1115
+ if (this._bufferedBytes < 4) {
1116
+ this._loop = false;
1117
+ return;
1118
+ }
1119
+ this._mask = this.consume(4);
1120
+ this._state = GET_DATA;
1121
+ }
1122
+ /**
1123
+ * Reads data bytes.
1124
+ *
1125
+ * @param {Function} cb Callback
1126
+ * @private
1127
+ */
1128
+ getData(cb) {
1129
+ let data = EMPTY_BUFFER;
1130
+ if (this._payloadLength) {
1131
+ if (this._bufferedBytes < this._payloadLength) {
1132
+ this._loop = false;
1133
+ return;
1134
+ }
1135
+ data = this.consume(this._payloadLength);
1136
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1137
+ unmask(data, this._mask);
1138
+ }
1139
+ }
1140
+ if (this._opcode > 7) {
1141
+ this.controlMessage(data, cb);
1142
+ return;
1143
+ }
1144
+ if (this._compressed) {
1145
+ this._state = INFLATING;
1146
+ this.decompress(data, cb);
1147
+ return;
1148
+ }
1149
+ if (data.length) {
1150
+ this._messageLength = this._totalPayloadLength;
1151
+ this._fragments.push(data);
1152
+ }
1153
+ this.dataMessage(cb);
1154
+ }
1155
+ /**
1156
+ * Decompresses data.
1157
+ *
1158
+ * @param {Buffer} data Compressed data
1159
+ * @param {Function} cb Callback
1160
+ * @private
1161
+ */
1162
+ decompress(data, cb) {
1163
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1164
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1165
+ if (err) return cb(err);
1166
+ if (buf.length) {
1167
+ this._messageLength += buf.length;
1168
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1169
+ const error = this.createError(
1170
+ RangeError,
1171
+ "Max payload size exceeded",
1172
+ false,
1173
+ 1009,
1174
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1175
+ );
1176
+ cb(error);
1177
+ return;
1178
+ }
1179
+ this._fragments.push(buf);
1180
+ }
1181
+ this.dataMessage(cb);
1182
+ if (this._state === GET_INFO) this.startLoop(cb);
1183
+ });
1184
+ }
1185
+ /**
1186
+ * Handles a data message.
1187
+ *
1188
+ * @param {Function} cb Callback
1189
+ * @private
1190
+ */
1191
+ dataMessage(cb) {
1192
+ if (!this._fin) {
1193
+ this._state = GET_INFO;
1194
+ return;
1195
+ }
1196
+ const messageLength = this._messageLength;
1197
+ const fragments = this._fragments;
1198
+ this._totalPayloadLength = 0;
1199
+ this._messageLength = 0;
1200
+ this._fragmented = 0;
1201
+ this._fragments = [];
1202
+ if (this._opcode === 2) {
1203
+ let data;
1204
+ if (this._binaryType === "nodebuffer") {
1205
+ data = concat(fragments, messageLength);
1206
+ } else if (this._binaryType === "arraybuffer") {
1207
+ data = toArrayBuffer(concat(fragments, messageLength));
1208
+ } else if (this._binaryType === "blob") {
1209
+ data = new Blob(fragments);
1210
+ } else {
1211
+ data = fragments;
1212
+ }
1213
+ if (this._allowSynchronousEvents) {
1214
+ this.emit("message", data, true);
1215
+ this._state = GET_INFO;
1216
+ } else {
1217
+ this._state = DEFER_EVENT;
1218
+ setImmediate(() => {
1219
+ this.emit("message", data, true);
1220
+ this._state = GET_INFO;
1221
+ this.startLoop(cb);
1222
+ });
1223
+ }
1224
+ } else {
1225
+ const buf = concat(fragments, messageLength);
1226
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1227
+ const error = this.createError(
1228
+ Error,
1229
+ "invalid UTF-8 sequence",
1230
+ true,
1231
+ 1007,
1232
+ "WS_ERR_INVALID_UTF8"
1233
+ );
1234
+ cb(error);
1235
+ return;
1236
+ }
1237
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1238
+ this.emit("message", buf, false);
1239
+ this._state = GET_INFO;
1240
+ } else {
1241
+ this._state = DEFER_EVENT;
1242
+ setImmediate(() => {
1243
+ this.emit("message", buf, false);
1244
+ this._state = GET_INFO;
1245
+ this.startLoop(cb);
1246
+ });
1247
+ }
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Handles a control message.
1252
+ *
1253
+ * @param {Buffer} data Data to handle
1254
+ * @return {(Error|RangeError|undefined)} A possible error
1255
+ * @private
1256
+ */
1257
+ controlMessage(data, cb) {
1258
+ if (this._opcode === 8) {
1259
+ if (data.length === 0) {
1260
+ this._loop = false;
1261
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1262
+ this.end();
1263
+ } else {
1264
+ const code = data.readUInt16BE(0);
1265
+ if (!isValidStatusCode(code)) {
1266
+ const error = this.createError(
1267
+ RangeError,
1268
+ `invalid status code ${code}`,
1269
+ true,
1270
+ 1002,
1271
+ "WS_ERR_INVALID_CLOSE_CODE"
1272
+ );
1273
+ cb(error);
1274
+ return;
1275
+ }
1276
+ const buf = new FastBuffer(
1277
+ data.buffer,
1278
+ data.byteOffset + 2,
1279
+ data.length - 2
1280
+ );
1281
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1282
+ const error = this.createError(
1283
+ Error,
1284
+ "invalid UTF-8 sequence",
1285
+ true,
1286
+ 1007,
1287
+ "WS_ERR_INVALID_UTF8"
1288
+ );
1289
+ cb(error);
1290
+ return;
1291
+ }
1292
+ this._loop = false;
1293
+ this.emit("conclude", code, buf);
1294
+ this.end();
1295
+ }
1296
+ this._state = GET_INFO;
1297
+ return;
1298
+ }
1299
+ if (this._allowSynchronousEvents) {
1300
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1301
+ this._state = GET_INFO;
1302
+ } else {
1303
+ this._state = DEFER_EVENT;
1304
+ setImmediate(() => {
1305
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1306
+ this._state = GET_INFO;
1307
+ this.startLoop(cb);
1308
+ });
1309
+ }
1310
+ }
1311
+ /**
1312
+ * Builds an error object.
1313
+ *
1314
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1315
+ * @param {String} message The error message
1316
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1317
+ * `message`
1318
+ * @param {Number} statusCode The status code
1319
+ * @param {String} errorCode The exposed error code
1320
+ * @return {(Error|RangeError)} The error
1321
+ * @private
1322
+ */
1323
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1324
+ this._loop = false;
1325
+ this._errored = true;
1326
+ const err = new ErrorCtor(
1327
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1328
+ );
1329
+ Error.captureStackTrace(err, this.createError);
1330
+ err.code = errorCode;
1331
+ err[kStatusCode] = statusCode;
1332
+ return err;
1333
+ }
1334
+ };
1335
+ module.exports = Receiver2;
1336
+ }
1337
+ });
1338
+
1339
+ // ../../node_modules/ws/lib/sender.js
1340
+ var require_sender = __commonJS({
1341
+ "../../node_modules/ws/lib/sender.js"(exports, module) {
1342
+ "use strict";
1343
+ init_esm_shims();
1344
+ var { Duplex } = __require("stream");
1345
+ var { randomFillSync } = __require("crypto");
1346
+ var PerMessageDeflate = require_permessage_deflate();
1347
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1348
+ var { isBlob, isValidStatusCode } = require_validation();
1349
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1350
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1351
+ var maskBuffer = Buffer.alloc(4);
1352
+ var RANDOM_POOL_SIZE = 8 * 1024;
1353
+ var randomPool;
1354
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1355
+ var DEFAULT = 0;
1356
+ var DEFLATING = 1;
1357
+ var GET_BLOB_DATA = 2;
1358
+ var Sender2 = class _Sender {
1359
+ /**
1360
+ * Creates a Sender instance.
1361
+ *
1362
+ * @param {Duplex} socket The connection socket
1363
+ * @param {Object} [extensions] An object containing the negotiated extensions
1364
+ * @param {Function} [generateMask] The function used to generate the masking
1365
+ * key
1366
+ */
1367
+ constructor(socket, extensions, generateMask) {
1368
+ this._extensions = extensions || {};
1369
+ if (generateMask) {
1370
+ this._generateMask = generateMask;
1371
+ this._maskBuffer = Buffer.alloc(4);
1372
+ }
1373
+ this._socket = socket;
1374
+ this._firstFragment = true;
1375
+ this._compress = false;
1376
+ this._bufferedBytes = 0;
1377
+ this._queue = [];
1378
+ this._state = DEFAULT;
1379
+ this.onerror = NOOP;
1380
+ this[kWebSocket] = void 0;
1381
+ }
1382
+ /**
1383
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1384
+ *
1385
+ * @param {(Buffer|String)} data The data to frame
1386
+ * @param {Object} options Options object
1387
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1388
+ * FIN bit
1389
+ * @param {Function} [options.generateMask] The function used to generate the
1390
+ * masking key
1391
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1392
+ * `data`
1393
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1394
+ * key
1395
+ * @param {Number} options.opcode The opcode
1396
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1397
+ * modified
1398
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1399
+ * RSV1 bit
1400
+ * @return {(Buffer|String)[]} The framed data
1401
+ * @public
1402
+ */
1403
+ static frame(data, options) {
1404
+ let mask;
1405
+ let merge = false;
1406
+ let offset = 2;
1407
+ let skipMasking = false;
1408
+ if (options.mask) {
1409
+ mask = options.maskBuffer || maskBuffer;
1410
+ if (options.generateMask) {
1411
+ options.generateMask(mask);
1412
+ } else {
1413
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1414
+ if (randomPool === void 0) {
1415
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1416
+ }
1417
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1418
+ randomPoolPointer = 0;
1419
+ }
1420
+ mask[0] = randomPool[randomPoolPointer++];
1421
+ mask[1] = randomPool[randomPoolPointer++];
1422
+ mask[2] = randomPool[randomPoolPointer++];
1423
+ mask[3] = randomPool[randomPoolPointer++];
1424
+ }
1425
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1426
+ offset = 6;
1427
+ }
1428
+ let dataLength;
1429
+ if (typeof data === "string") {
1430
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1431
+ dataLength = options[kByteLength];
1432
+ } else {
1433
+ data = Buffer.from(data);
1434
+ dataLength = data.length;
1435
+ }
1436
+ } else {
1437
+ dataLength = data.length;
1438
+ merge = options.mask && options.readOnly && !skipMasking;
1439
+ }
1440
+ let payloadLength = dataLength;
1441
+ if (dataLength >= 65536) {
1442
+ offset += 8;
1443
+ payloadLength = 127;
1444
+ } else if (dataLength > 125) {
1445
+ offset += 2;
1446
+ payloadLength = 126;
1447
+ }
1448
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1449
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1450
+ if (options.rsv1) target[0] |= 64;
1451
+ target[1] = payloadLength;
1452
+ if (payloadLength === 126) {
1453
+ target.writeUInt16BE(dataLength, 2);
1454
+ } else if (payloadLength === 127) {
1455
+ target[2] = target[3] = 0;
1456
+ target.writeUIntBE(dataLength, 4, 6);
1457
+ }
1458
+ if (!options.mask) return [target, data];
1459
+ target[1] |= 128;
1460
+ target[offset - 4] = mask[0];
1461
+ target[offset - 3] = mask[1];
1462
+ target[offset - 2] = mask[2];
1463
+ target[offset - 1] = mask[3];
1464
+ if (skipMasking) return [target, data];
1465
+ if (merge) {
1466
+ applyMask(data, mask, target, offset, dataLength);
1467
+ return [target];
1468
+ }
1469
+ applyMask(data, mask, data, 0, dataLength);
1470
+ return [target, data];
1471
+ }
1472
+ /**
1473
+ * Sends a close message to the other peer.
1474
+ *
1475
+ * @param {Number} [code] The status code component of the body
1476
+ * @param {(String|Buffer)} [data] The message component of the body
1477
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1478
+ * @param {Function} [cb] Callback
1479
+ * @public
1480
+ */
1481
+ close(code, data, mask, cb) {
1482
+ let buf;
1483
+ if (code === void 0) {
1484
+ buf = EMPTY_BUFFER;
1485
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1486
+ throw new TypeError("First argument must be a valid error code number");
1487
+ } else if (data === void 0 || !data.length) {
1488
+ buf = Buffer.allocUnsafe(2);
1489
+ buf.writeUInt16BE(code, 0);
1490
+ } else {
1491
+ const length = Buffer.byteLength(data);
1492
+ if (length > 123) {
1493
+ throw new RangeError("The message must not be greater than 123 bytes");
1494
+ }
1495
+ buf = Buffer.allocUnsafe(2 + length);
1496
+ buf.writeUInt16BE(code, 0);
1497
+ if (typeof data === "string") {
1498
+ buf.write(data, 2);
1499
+ } else {
1500
+ buf.set(data, 2);
1501
+ }
1502
+ }
1503
+ const options = {
1504
+ [kByteLength]: buf.length,
1505
+ fin: true,
1506
+ generateMask: this._generateMask,
1507
+ mask,
1508
+ maskBuffer: this._maskBuffer,
1509
+ opcode: 8,
1510
+ readOnly: false,
1511
+ rsv1: false
1512
+ };
1513
+ if (this._state !== DEFAULT) {
1514
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1515
+ } else {
1516
+ this.sendFrame(_Sender.frame(buf, options), cb);
1517
+ }
1518
+ }
1519
+ /**
1520
+ * Sends a ping message to the other peer.
1521
+ *
1522
+ * @param {*} data The message to send
1523
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1524
+ * @param {Function} [cb] Callback
1525
+ * @public
1526
+ */
1527
+ ping(data, mask, cb) {
1528
+ let byteLength;
1529
+ let readOnly;
1530
+ if (typeof data === "string") {
1531
+ byteLength = Buffer.byteLength(data);
1532
+ readOnly = false;
1533
+ } else if (isBlob(data)) {
1534
+ byteLength = data.size;
1535
+ readOnly = false;
1536
+ } else {
1537
+ data = toBuffer(data);
1538
+ byteLength = data.length;
1539
+ readOnly = toBuffer.readOnly;
1540
+ }
1541
+ if (byteLength > 125) {
1542
+ throw new RangeError("The data size must not be greater than 125 bytes");
1543
+ }
1544
+ const options = {
1545
+ [kByteLength]: byteLength,
1546
+ fin: true,
1547
+ generateMask: this._generateMask,
1548
+ mask,
1549
+ maskBuffer: this._maskBuffer,
1550
+ opcode: 9,
1551
+ readOnly,
1552
+ rsv1: false
1553
+ };
1554
+ if (isBlob(data)) {
1555
+ if (this._state !== DEFAULT) {
1556
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1557
+ } else {
1558
+ this.getBlobData(data, false, options, cb);
1559
+ }
1560
+ } else if (this._state !== DEFAULT) {
1561
+ this.enqueue([this.dispatch, data, false, options, cb]);
1562
+ } else {
1563
+ this.sendFrame(_Sender.frame(data, options), cb);
1564
+ }
1565
+ }
1566
+ /**
1567
+ * Sends a pong message to the other peer.
1568
+ *
1569
+ * @param {*} data The message to send
1570
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1571
+ * @param {Function} [cb] Callback
1572
+ * @public
1573
+ */
1574
+ pong(data, mask, cb) {
1575
+ let byteLength;
1576
+ let readOnly;
1577
+ if (typeof data === "string") {
1578
+ byteLength = Buffer.byteLength(data);
1579
+ readOnly = false;
1580
+ } else if (isBlob(data)) {
1581
+ byteLength = data.size;
1582
+ readOnly = false;
1583
+ } else {
1584
+ data = toBuffer(data);
1585
+ byteLength = data.length;
1586
+ readOnly = toBuffer.readOnly;
1587
+ }
1588
+ if (byteLength > 125) {
1589
+ throw new RangeError("The data size must not be greater than 125 bytes");
1590
+ }
1591
+ const options = {
1592
+ [kByteLength]: byteLength,
1593
+ fin: true,
1594
+ generateMask: this._generateMask,
1595
+ mask,
1596
+ maskBuffer: this._maskBuffer,
1597
+ opcode: 10,
1598
+ readOnly,
1599
+ rsv1: false
1600
+ };
1601
+ if (isBlob(data)) {
1602
+ if (this._state !== DEFAULT) {
1603
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1604
+ } else {
1605
+ this.getBlobData(data, false, options, cb);
1606
+ }
1607
+ } else if (this._state !== DEFAULT) {
1608
+ this.enqueue([this.dispatch, data, false, options, cb]);
1609
+ } else {
1610
+ this.sendFrame(_Sender.frame(data, options), cb);
1611
+ }
1612
+ }
1613
+ /**
1614
+ * Sends a data message to the other peer.
1615
+ *
1616
+ * @param {*} data The message to send
1617
+ * @param {Object} options Options object
1618
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1619
+ * or text
1620
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1621
+ * compress `data`
1622
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1623
+ * last one
1624
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1625
+ * `data`
1626
+ * @param {Function} [cb] Callback
1627
+ * @public
1628
+ */
1629
+ send(data, options, cb) {
1630
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1631
+ let opcode = options.binary ? 2 : 1;
1632
+ let rsv1 = options.compress;
1633
+ let byteLength;
1634
+ let readOnly;
1635
+ if (typeof data === "string") {
1636
+ byteLength = Buffer.byteLength(data);
1637
+ readOnly = false;
1638
+ } else if (isBlob(data)) {
1639
+ byteLength = data.size;
1640
+ readOnly = false;
1641
+ } else {
1642
+ data = toBuffer(data);
1643
+ byteLength = data.length;
1644
+ readOnly = toBuffer.readOnly;
1645
+ }
1646
+ if (this._firstFragment) {
1647
+ this._firstFragment = false;
1648
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1649
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1650
+ }
1651
+ this._compress = rsv1;
1652
+ } else {
1653
+ rsv1 = false;
1654
+ opcode = 0;
1655
+ }
1656
+ if (options.fin) this._firstFragment = true;
1657
+ const opts = {
1658
+ [kByteLength]: byteLength,
1659
+ fin: options.fin,
1660
+ generateMask: this._generateMask,
1661
+ mask: options.mask,
1662
+ maskBuffer: this._maskBuffer,
1663
+ opcode,
1664
+ readOnly,
1665
+ rsv1
1666
+ };
1667
+ if (isBlob(data)) {
1668
+ if (this._state !== DEFAULT) {
1669
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1670
+ } else {
1671
+ this.getBlobData(data, this._compress, opts, cb);
1672
+ }
1673
+ } else if (this._state !== DEFAULT) {
1674
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1675
+ } else {
1676
+ this.dispatch(data, this._compress, opts, cb);
1677
+ }
1678
+ }
1679
+ /**
1680
+ * Gets the contents of a blob as binary data.
1681
+ *
1682
+ * @param {Blob} blob The blob
1683
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1684
+ * the data
1685
+ * @param {Object} options Options object
1686
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1687
+ * FIN bit
1688
+ * @param {Function} [options.generateMask] The function used to generate the
1689
+ * masking key
1690
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1691
+ * `data`
1692
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1693
+ * key
1694
+ * @param {Number} options.opcode The opcode
1695
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1696
+ * modified
1697
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1698
+ * RSV1 bit
1699
+ * @param {Function} [cb] Callback
1700
+ * @private
1701
+ */
1702
+ getBlobData(blob, compress, options, cb) {
1703
+ this._bufferedBytes += options[kByteLength];
1704
+ this._state = GET_BLOB_DATA;
1705
+ blob.arrayBuffer().then((arrayBuffer) => {
1706
+ if (this._socket.destroyed) {
1707
+ const err = new Error(
1708
+ "The socket was closed while the blob was being read"
1709
+ );
1710
+ process.nextTick(callCallbacks, this, err, cb);
1711
+ return;
1712
+ }
1713
+ this._bufferedBytes -= options[kByteLength];
1714
+ const data = toBuffer(arrayBuffer);
1715
+ if (!compress) {
1716
+ this._state = DEFAULT;
1717
+ this.sendFrame(_Sender.frame(data, options), cb);
1718
+ this.dequeue();
1719
+ } else {
1720
+ this.dispatch(data, compress, options, cb);
1721
+ }
1722
+ }).catch((err) => {
1723
+ process.nextTick(onError, this, err, cb);
1724
+ });
1725
+ }
1726
+ /**
1727
+ * Dispatches a message.
1728
+ *
1729
+ * @param {(Buffer|String)} data The message to send
1730
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1731
+ * `data`
1732
+ * @param {Object} options Options object
1733
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1734
+ * FIN bit
1735
+ * @param {Function} [options.generateMask] The function used to generate the
1736
+ * masking key
1737
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1738
+ * `data`
1739
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1740
+ * key
1741
+ * @param {Number} options.opcode The opcode
1742
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1743
+ * modified
1744
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1745
+ * RSV1 bit
1746
+ * @param {Function} [cb] Callback
1747
+ * @private
1748
+ */
1749
+ dispatch(data, compress, options, cb) {
1750
+ if (!compress) {
1751
+ this.sendFrame(_Sender.frame(data, options), cb);
1752
+ return;
1753
+ }
1754
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1755
+ this._bufferedBytes += options[kByteLength];
1756
+ this._state = DEFLATING;
1757
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1758
+ if (this._socket.destroyed) {
1759
+ const err = new Error(
1760
+ "The socket was closed while data was being compressed"
1761
+ );
1762
+ callCallbacks(this, err, cb);
1763
+ return;
1764
+ }
1765
+ this._bufferedBytes -= options[kByteLength];
1766
+ this._state = DEFAULT;
1767
+ options.readOnly = false;
1768
+ this.sendFrame(_Sender.frame(buf, options), cb);
1769
+ this.dequeue();
1770
+ });
1771
+ }
1772
+ /**
1773
+ * Executes queued send operations.
1774
+ *
1775
+ * @private
1776
+ */
1777
+ dequeue() {
1778
+ while (this._state === DEFAULT && this._queue.length) {
1779
+ const params = this._queue.shift();
1780
+ this._bufferedBytes -= params[3][kByteLength];
1781
+ Reflect.apply(params[0], this, params.slice(1));
1782
+ }
1783
+ }
1784
+ /**
1785
+ * Enqueues a send operation.
1786
+ *
1787
+ * @param {Array} params Send operation parameters.
1788
+ * @private
1789
+ */
1790
+ enqueue(params) {
1791
+ this._bufferedBytes += params[3][kByteLength];
1792
+ this._queue.push(params);
1793
+ }
1794
+ /**
1795
+ * Sends a frame.
1796
+ *
1797
+ * @param {(Buffer | String)[]} list The frame to send
1798
+ * @param {Function} [cb] Callback
1799
+ * @private
1800
+ */
1801
+ sendFrame(list, cb) {
1802
+ if (list.length === 2) {
1803
+ this._socket.cork();
1804
+ this._socket.write(list[0]);
1805
+ this._socket.write(list[1], cb);
1806
+ this._socket.uncork();
1807
+ } else {
1808
+ this._socket.write(list[0], cb);
1809
+ }
1810
+ }
1811
+ };
1812
+ module.exports = Sender2;
1813
+ function callCallbacks(sender, err, cb) {
1814
+ if (typeof cb === "function") cb(err);
1815
+ for (let i = 0; i < sender._queue.length; i++) {
1816
+ const params = sender._queue[i];
1817
+ const callback = params[params.length - 1];
1818
+ if (typeof callback === "function") callback(err);
1819
+ }
1820
+ }
1821
+ function onError(sender, err, cb) {
1822
+ callCallbacks(sender, err, cb);
1823
+ sender.onerror(err);
1824
+ }
1825
+ }
1826
+ });
1827
+
1828
+ // ../../node_modules/ws/lib/event-target.js
1829
+ var require_event_target = __commonJS({
1830
+ "../../node_modules/ws/lib/event-target.js"(exports, module) {
1831
+ "use strict";
1832
+ init_esm_shims();
1833
+ var { kForOnEventAttribute, kListener } = require_constants();
1834
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1835
+ var kData = /* @__PURE__ */ Symbol("kData");
1836
+ var kError = /* @__PURE__ */ Symbol("kError");
1837
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1838
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1839
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1840
+ var kType = /* @__PURE__ */ Symbol("kType");
1841
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1842
+ var Event = class {
1843
+ /**
1844
+ * Create a new `Event`.
1845
+ *
1846
+ * @param {String} type The name of the event
1847
+ * @throws {TypeError} If the `type` argument is not specified
1848
+ */
1849
+ constructor(type) {
1850
+ this[kTarget] = null;
1851
+ this[kType] = type;
1852
+ }
1853
+ /**
1854
+ * @type {*}
1855
+ */
1856
+ get target() {
1857
+ return this[kTarget];
1858
+ }
1859
+ /**
1860
+ * @type {String}
1861
+ */
1862
+ get type() {
1863
+ return this[kType];
1864
+ }
1865
+ };
1866
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1867
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1868
+ var CloseEvent = class extends Event {
1869
+ /**
1870
+ * Create a new `CloseEvent`.
1871
+ *
1872
+ * @param {String} type The name of the event
1873
+ * @param {Object} [options] A dictionary object that allows for setting
1874
+ * attributes via object members of the same name
1875
+ * @param {Number} [options.code=0] The status code explaining why the
1876
+ * connection was closed
1877
+ * @param {String} [options.reason=''] A human-readable string explaining why
1878
+ * the connection was closed
1879
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1880
+ * connection was cleanly closed
1881
+ */
1882
+ constructor(type, options = {}) {
1883
+ super(type);
1884
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1885
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1886
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1887
+ }
1888
+ /**
1889
+ * @type {Number}
1890
+ */
1891
+ get code() {
1892
+ return this[kCode];
1893
+ }
1894
+ /**
1895
+ * @type {String}
1896
+ */
1897
+ get reason() {
1898
+ return this[kReason];
1899
+ }
1900
+ /**
1901
+ * @type {Boolean}
1902
+ */
1903
+ get wasClean() {
1904
+ return this[kWasClean];
1905
+ }
1906
+ };
1907
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1908
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1909
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1910
+ var ErrorEvent = class extends Event {
1911
+ /**
1912
+ * Create a new `ErrorEvent`.
1913
+ *
1914
+ * @param {String} type The name of the event
1915
+ * @param {Object} [options] A dictionary object that allows for setting
1916
+ * attributes via object members of the same name
1917
+ * @param {*} [options.error=null] The error that generated this event
1918
+ * @param {String} [options.message=''] The error message
1919
+ */
1920
+ constructor(type, options = {}) {
1921
+ super(type);
1922
+ this[kError] = options.error === void 0 ? null : options.error;
1923
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1924
+ }
1925
+ /**
1926
+ * @type {*}
1927
+ */
1928
+ get error() {
1929
+ return this[kError];
1930
+ }
1931
+ /**
1932
+ * @type {String}
1933
+ */
1934
+ get message() {
1935
+ return this[kMessage];
1936
+ }
1937
+ };
1938
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1939
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1940
+ var MessageEvent = class extends Event {
1941
+ /**
1942
+ * Create a new `MessageEvent`.
1943
+ *
1944
+ * @param {String} type The name of the event
1945
+ * @param {Object} [options] A dictionary object that allows for setting
1946
+ * attributes via object members of the same name
1947
+ * @param {*} [options.data=null] The message content
1948
+ */
1949
+ constructor(type, options = {}) {
1950
+ super(type);
1951
+ this[kData] = options.data === void 0 ? null : options.data;
1952
+ }
1953
+ /**
1954
+ * @type {*}
1955
+ */
1956
+ get data() {
1957
+ return this[kData];
1958
+ }
1959
+ };
1960
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1961
+ var EventTarget = {
1962
+ /**
1963
+ * Register an event listener.
1964
+ *
1965
+ * @param {String} type A string representing the event type to listen for
1966
+ * @param {(Function|Object)} handler The listener to add
1967
+ * @param {Object} [options] An options object specifies characteristics about
1968
+ * the event listener
1969
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1970
+ * listener should be invoked at most once after being added. If `true`,
1971
+ * the listener would be automatically removed when invoked.
1972
+ * @public
1973
+ */
1974
+ addEventListener(type, handler, options = {}) {
1975
+ for (const listener of this.listeners(type)) {
1976
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1977
+ return;
1978
+ }
1979
+ }
1980
+ let wrapper;
1981
+ if (type === "message") {
1982
+ wrapper = function onMessage(data, isBinary) {
1983
+ const event = new MessageEvent("message", {
1984
+ data: isBinary ? data : data.toString()
1985
+ });
1986
+ event[kTarget] = this;
1987
+ callListener(handler, this, event);
1988
+ };
1989
+ } else if (type === "close") {
1990
+ wrapper = function onClose(code, message) {
1991
+ const event = new CloseEvent("close", {
1992
+ code,
1993
+ reason: message.toString(),
1994
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1995
+ });
1996
+ event[kTarget] = this;
1997
+ callListener(handler, this, event);
1998
+ };
1999
+ } else if (type === "error") {
2000
+ wrapper = function onError(error) {
2001
+ const event = new ErrorEvent("error", {
2002
+ error,
2003
+ message: error.message
2004
+ });
2005
+ event[kTarget] = this;
2006
+ callListener(handler, this, event);
2007
+ };
2008
+ } else if (type === "open") {
2009
+ wrapper = function onOpen() {
2010
+ const event = new Event("open");
2011
+ event[kTarget] = this;
2012
+ callListener(handler, this, event);
2013
+ };
2014
+ } else {
2015
+ return;
2016
+ }
2017
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2018
+ wrapper[kListener] = handler;
2019
+ if (options.once) {
2020
+ this.once(type, wrapper);
2021
+ } else {
2022
+ this.on(type, wrapper);
2023
+ }
2024
+ },
2025
+ /**
2026
+ * Remove an event listener.
2027
+ *
2028
+ * @param {String} type A string representing the event type to remove
2029
+ * @param {(Function|Object)} handler The listener to remove
2030
+ * @public
2031
+ */
2032
+ removeEventListener(type, handler) {
2033
+ for (const listener of this.listeners(type)) {
2034
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2035
+ this.removeListener(type, listener);
2036
+ break;
2037
+ }
2038
+ }
2039
+ }
2040
+ };
2041
+ module.exports = {
2042
+ CloseEvent,
2043
+ ErrorEvent,
2044
+ Event,
2045
+ EventTarget,
2046
+ MessageEvent
2047
+ };
2048
+ function callListener(listener, thisArg, event) {
2049
+ if (typeof listener === "object" && listener.handleEvent) {
2050
+ listener.handleEvent.call(listener, event);
2051
+ } else {
2052
+ listener.call(thisArg, event);
2053
+ }
2054
+ }
2055
+ }
2056
+ });
2057
+
2058
+ // ../../node_modules/ws/lib/extension.js
2059
+ var require_extension = __commonJS({
2060
+ "../../node_modules/ws/lib/extension.js"(exports, module) {
2061
+ "use strict";
2062
+ init_esm_shims();
2063
+ var { tokenChars } = require_validation();
2064
+ function push(dest, name, elem) {
2065
+ if (dest[name] === void 0) dest[name] = [elem];
2066
+ else dest[name].push(elem);
2067
+ }
2068
+ function parse(header) {
2069
+ const offers = /* @__PURE__ */ Object.create(null);
2070
+ let params = /* @__PURE__ */ Object.create(null);
2071
+ let mustUnescape = false;
2072
+ let isEscaping = false;
2073
+ let inQuotes = false;
2074
+ let extensionName;
2075
+ let paramName;
2076
+ let start = -1;
2077
+ let code = -1;
2078
+ let end = -1;
2079
+ let i = 0;
2080
+ for (; i < header.length; i++) {
2081
+ code = header.charCodeAt(i);
2082
+ if (extensionName === void 0) {
2083
+ if (end === -1 && tokenChars[code] === 1) {
2084
+ if (start === -1) start = i;
2085
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2086
+ if (end === -1 && start !== -1) end = i;
2087
+ } else if (code === 59 || code === 44) {
2088
+ if (start === -1) {
2089
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2090
+ }
2091
+ if (end === -1) end = i;
2092
+ const name = header.slice(start, end);
2093
+ if (code === 44) {
2094
+ push(offers, name, params);
2095
+ params = /* @__PURE__ */ Object.create(null);
2096
+ } else {
2097
+ extensionName = name;
2098
+ }
2099
+ start = end = -1;
2100
+ } else {
2101
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2102
+ }
2103
+ } else if (paramName === void 0) {
2104
+ if (end === -1 && tokenChars[code] === 1) {
2105
+ if (start === -1) start = i;
2106
+ } else if (code === 32 || code === 9) {
2107
+ if (end === -1 && start !== -1) end = i;
2108
+ } else if (code === 59 || code === 44) {
2109
+ if (start === -1) {
2110
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2111
+ }
2112
+ if (end === -1) end = i;
2113
+ push(params, header.slice(start, end), true);
2114
+ if (code === 44) {
2115
+ push(offers, extensionName, params);
2116
+ params = /* @__PURE__ */ Object.create(null);
2117
+ extensionName = void 0;
2118
+ }
2119
+ start = end = -1;
2120
+ } else if (code === 61 && start !== -1 && end === -1) {
2121
+ paramName = header.slice(start, i);
2122
+ start = end = -1;
2123
+ } else {
2124
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2125
+ }
2126
+ } else {
2127
+ if (isEscaping) {
2128
+ if (tokenChars[code] !== 1) {
2129
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2130
+ }
2131
+ if (start === -1) start = i;
2132
+ else if (!mustUnescape) mustUnescape = true;
2133
+ isEscaping = false;
2134
+ } else if (inQuotes) {
2135
+ if (tokenChars[code] === 1) {
2136
+ if (start === -1) start = i;
2137
+ } else if (code === 34 && start !== -1) {
2138
+ inQuotes = false;
2139
+ end = i;
2140
+ } else if (code === 92) {
2141
+ isEscaping = true;
2142
+ } else {
2143
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2144
+ }
2145
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2146
+ inQuotes = true;
2147
+ } else if (end === -1 && tokenChars[code] === 1) {
2148
+ if (start === -1) start = i;
2149
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2150
+ if (end === -1) end = i;
2151
+ } else if (code === 59 || code === 44) {
2152
+ if (start === -1) {
2153
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2154
+ }
2155
+ if (end === -1) end = i;
2156
+ let value = header.slice(start, end);
2157
+ if (mustUnescape) {
2158
+ value = value.replace(/\\/g, "");
2159
+ mustUnescape = false;
2160
+ }
2161
+ push(params, paramName, value);
2162
+ if (code === 44) {
2163
+ push(offers, extensionName, params);
2164
+ params = /* @__PURE__ */ Object.create(null);
2165
+ extensionName = void 0;
2166
+ }
2167
+ paramName = void 0;
2168
+ start = end = -1;
2169
+ } else {
2170
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2171
+ }
2172
+ }
2173
+ }
2174
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2175
+ throw new SyntaxError("Unexpected end of input");
2176
+ }
2177
+ if (end === -1) end = i;
2178
+ const token = header.slice(start, end);
2179
+ if (extensionName === void 0) {
2180
+ push(offers, token, params);
2181
+ } else {
2182
+ if (paramName === void 0) {
2183
+ push(params, token, true);
2184
+ } else if (mustUnescape) {
2185
+ push(params, paramName, token.replace(/\\/g, ""));
2186
+ } else {
2187
+ push(params, paramName, token);
2188
+ }
2189
+ push(offers, extensionName, params);
2190
+ }
2191
+ return offers;
2192
+ }
2193
+ function format(extensions) {
2194
+ return Object.keys(extensions).map((extension) => {
2195
+ let configurations = extensions[extension];
2196
+ if (!Array.isArray(configurations)) configurations = [configurations];
2197
+ return configurations.map((params) => {
2198
+ return [extension].concat(
2199
+ Object.keys(params).map((k) => {
2200
+ let values = params[k];
2201
+ if (!Array.isArray(values)) values = [values];
2202
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2203
+ })
2204
+ ).join("; ");
2205
+ }).join(", ");
2206
+ }).join(", ");
2207
+ }
2208
+ module.exports = { format, parse };
2209
+ }
2210
+ });
2211
+
2212
+ // ../../node_modules/ws/lib/websocket.js
2213
+ var require_websocket = __commonJS({
2214
+ "../../node_modules/ws/lib/websocket.js"(exports, module) {
2215
+ "use strict";
2216
+ init_esm_shims();
2217
+ var EventEmitter = __require("events");
2218
+ var https = __require("https");
2219
+ var http = __require("http");
2220
+ var net = __require("net");
2221
+ var tls = __require("tls");
2222
+ var { randomBytes, createHash } = __require("crypto");
2223
+ var { Duplex, Readable } = __require("stream");
2224
+ var { URL } = __require("url");
2225
+ var PerMessageDeflate = require_permessage_deflate();
2226
+ var Receiver2 = require_receiver();
2227
+ var Sender2 = require_sender();
2228
+ var { isBlob } = require_validation();
2229
+ var {
2230
+ BINARY_TYPES,
2231
+ CLOSE_TIMEOUT,
2232
+ EMPTY_BUFFER,
2233
+ GUID,
2234
+ kForOnEventAttribute,
2235
+ kListener,
2236
+ kStatusCode,
2237
+ kWebSocket,
2238
+ NOOP
2239
+ } = require_constants();
2240
+ var {
2241
+ EventTarget: { addEventListener, removeEventListener }
2242
+ } = require_event_target();
2243
+ var { format, parse } = require_extension();
2244
+ var { toBuffer } = require_buffer_util();
2245
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2246
+ var protocolVersions = [8, 13];
2247
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2248
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2249
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2250
+ /**
2251
+ * Create a new `WebSocket`.
2252
+ *
2253
+ * @param {(String|URL)} address The URL to which to connect
2254
+ * @param {(String|String[])} [protocols] The subprotocols
2255
+ * @param {Object} [options] Connection options
2256
+ */
2257
+ constructor(address, protocols, options) {
2258
+ super();
2259
+ this._binaryType = BINARY_TYPES[0];
2260
+ this._closeCode = 1006;
2261
+ this._closeFrameReceived = false;
2262
+ this._closeFrameSent = false;
2263
+ this._closeMessage = EMPTY_BUFFER;
2264
+ this._closeTimer = null;
2265
+ this._errorEmitted = false;
2266
+ this._extensions = {};
2267
+ this._paused = false;
2268
+ this._protocol = "";
2269
+ this._readyState = _WebSocket.CONNECTING;
2270
+ this._receiver = null;
2271
+ this._sender = null;
2272
+ this._socket = null;
2273
+ if (address !== null) {
2274
+ this._bufferedAmount = 0;
2275
+ this._isServer = false;
2276
+ this._redirects = 0;
2277
+ if (protocols === void 0) {
2278
+ protocols = [];
2279
+ } else if (!Array.isArray(protocols)) {
2280
+ if (typeof protocols === "object" && protocols !== null) {
2281
+ options = protocols;
2282
+ protocols = [];
2283
+ } else {
2284
+ protocols = [protocols];
2285
+ }
2286
+ }
2287
+ initAsClient(this, address, protocols, options);
2288
+ } else {
2289
+ this._autoPong = options.autoPong;
2290
+ this._closeTimeout = options.closeTimeout;
2291
+ this._isServer = true;
2292
+ }
2293
+ }
2294
+ /**
2295
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2296
+ * instead of "blob".
2297
+ *
2298
+ * @type {String}
2299
+ */
2300
+ get binaryType() {
2301
+ return this._binaryType;
2302
+ }
2303
+ set binaryType(type) {
2304
+ if (!BINARY_TYPES.includes(type)) return;
2305
+ this._binaryType = type;
2306
+ if (this._receiver) this._receiver._binaryType = type;
2307
+ }
2308
+ /**
2309
+ * @type {Number}
2310
+ */
2311
+ get bufferedAmount() {
2312
+ if (!this._socket) return this._bufferedAmount;
2313
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2314
+ }
2315
+ /**
2316
+ * @type {String}
2317
+ */
2318
+ get extensions() {
2319
+ return Object.keys(this._extensions).join();
2320
+ }
2321
+ /**
2322
+ * @type {Boolean}
2323
+ */
2324
+ get isPaused() {
2325
+ return this._paused;
2326
+ }
2327
+ /**
2328
+ * @type {Function}
2329
+ */
2330
+ /* istanbul ignore next */
2331
+ get onclose() {
2332
+ return null;
2333
+ }
2334
+ /**
2335
+ * @type {Function}
2336
+ */
2337
+ /* istanbul ignore next */
2338
+ get onerror() {
2339
+ return null;
2340
+ }
2341
+ /**
2342
+ * @type {Function}
2343
+ */
2344
+ /* istanbul ignore next */
2345
+ get onopen() {
2346
+ return null;
2347
+ }
2348
+ /**
2349
+ * @type {Function}
2350
+ */
2351
+ /* istanbul ignore next */
2352
+ get onmessage() {
2353
+ return null;
2354
+ }
2355
+ /**
2356
+ * @type {String}
2357
+ */
2358
+ get protocol() {
2359
+ return this._protocol;
2360
+ }
2361
+ /**
2362
+ * @type {Number}
2363
+ */
2364
+ get readyState() {
2365
+ return this._readyState;
2366
+ }
2367
+ /**
2368
+ * @type {String}
2369
+ */
2370
+ get url() {
2371
+ return this._url;
2372
+ }
2373
+ /**
2374
+ * Set up the socket and the internal resources.
2375
+ *
2376
+ * @param {Duplex} socket The network socket between the server and client
2377
+ * @param {Buffer} head The first packet of the upgraded stream
2378
+ * @param {Object} options Options object
2379
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2380
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2381
+ * multiple times in the same tick
2382
+ * @param {Function} [options.generateMask] The function used to generate the
2383
+ * masking key
2384
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2385
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2386
+ * not to skip UTF-8 validation for text and close messages
2387
+ * @private
2388
+ */
2389
+ setSocket(socket, head, options) {
2390
+ const receiver = new Receiver2({
2391
+ allowSynchronousEvents: options.allowSynchronousEvents,
2392
+ binaryType: this.binaryType,
2393
+ extensions: this._extensions,
2394
+ isServer: this._isServer,
2395
+ maxPayload: options.maxPayload,
2396
+ skipUTF8Validation: options.skipUTF8Validation
2397
+ });
2398
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2399
+ this._receiver = receiver;
2400
+ this._sender = sender;
2401
+ this._socket = socket;
2402
+ receiver[kWebSocket] = this;
2403
+ sender[kWebSocket] = this;
2404
+ socket[kWebSocket] = this;
2405
+ receiver.on("conclude", receiverOnConclude);
2406
+ receiver.on("drain", receiverOnDrain);
2407
+ receiver.on("error", receiverOnError);
2408
+ receiver.on("message", receiverOnMessage);
2409
+ receiver.on("ping", receiverOnPing);
2410
+ receiver.on("pong", receiverOnPong);
2411
+ sender.onerror = senderOnError;
2412
+ if (socket.setTimeout) socket.setTimeout(0);
2413
+ if (socket.setNoDelay) socket.setNoDelay();
2414
+ if (head.length > 0) socket.unshift(head);
2415
+ socket.on("close", socketOnClose);
2416
+ socket.on("data", socketOnData);
2417
+ socket.on("end", socketOnEnd);
2418
+ socket.on("error", socketOnError);
2419
+ this._readyState = _WebSocket.OPEN;
2420
+ this.emit("open");
2421
+ }
2422
+ /**
2423
+ * Emit the `'close'` event.
2424
+ *
2425
+ * @private
2426
+ */
2427
+ emitClose() {
2428
+ if (!this._socket) {
2429
+ this._readyState = _WebSocket.CLOSED;
2430
+ this.emit("close", this._closeCode, this._closeMessage);
2431
+ return;
2432
+ }
2433
+ if (this._extensions[PerMessageDeflate.extensionName]) {
2434
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
2435
+ }
2436
+ this._receiver.removeAllListeners();
2437
+ this._readyState = _WebSocket.CLOSED;
2438
+ this.emit("close", this._closeCode, this._closeMessage);
2439
+ }
2440
+ /**
2441
+ * Start a closing handshake.
2442
+ *
2443
+ * +----------+ +-----------+ +----------+
2444
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2445
+ * | +----------+ +-----------+ +----------+ |
2446
+ * +----------+ +-----------+ |
2447
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2448
+ * +----------+ +-----------+ |
2449
+ * | | | +---+ |
2450
+ * +------------------------+-->|fin| - - - -
2451
+ * | +---+ | +---+
2452
+ * - - - - -|fin|<---------------------+
2453
+ * +---+
2454
+ *
2455
+ * @param {Number} [code] Status code explaining why the connection is closing
2456
+ * @param {(String|Buffer)} [data] The reason why the connection is
2457
+ * closing
2458
+ * @public
2459
+ */
2460
+ close(code, data) {
2461
+ if (this.readyState === _WebSocket.CLOSED) return;
2462
+ if (this.readyState === _WebSocket.CONNECTING) {
2463
+ const msg = "WebSocket was closed before the connection was established";
2464
+ abortHandshake(this, this._req, msg);
2465
+ return;
2466
+ }
2467
+ if (this.readyState === _WebSocket.CLOSING) {
2468
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2469
+ this._socket.end();
2470
+ }
2471
+ return;
2472
+ }
2473
+ this._readyState = _WebSocket.CLOSING;
2474
+ this._sender.close(code, data, !this._isServer, (err) => {
2475
+ if (err) return;
2476
+ this._closeFrameSent = true;
2477
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2478
+ this._socket.end();
2479
+ }
2480
+ });
2481
+ setCloseTimer(this);
2482
+ }
2483
+ /**
2484
+ * Pause the socket.
2485
+ *
2486
+ * @public
2487
+ */
2488
+ pause() {
2489
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2490
+ return;
2491
+ }
2492
+ this._paused = true;
2493
+ this._socket.pause();
2494
+ }
2495
+ /**
2496
+ * Send a ping.
2497
+ *
2498
+ * @param {*} [data] The data to send
2499
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2500
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2501
+ * @public
2502
+ */
2503
+ ping(data, mask, cb) {
2504
+ if (this.readyState === _WebSocket.CONNECTING) {
2505
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2506
+ }
2507
+ if (typeof data === "function") {
2508
+ cb = data;
2509
+ data = mask = void 0;
2510
+ } else if (typeof mask === "function") {
2511
+ cb = mask;
2512
+ mask = void 0;
2513
+ }
2514
+ if (typeof data === "number") data = data.toString();
2515
+ if (this.readyState !== _WebSocket.OPEN) {
2516
+ sendAfterClose(this, data, cb);
2517
+ return;
2518
+ }
2519
+ if (mask === void 0) mask = !this._isServer;
2520
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2521
+ }
2522
+ /**
2523
+ * Send a pong.
2524
+ *
2525
+ * @param {*} [data] The data to send
2526
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2527
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2528
+ * @public
2529
+ */
2530
+ pong(data, mask, cb) {
2531
+ if (this.readyState === _WebSocket.CONNECTING) {
2532
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2533
+ }
2534
+ if (typeof data === "function") {
2535
+ cb = data;
2536
+ data = mask = void 0;
2537
+ } else if (typeof mask === "function") {
2538
+ cb = mask;
2539
+ mask = void 0;
2540
+ }
2541
+ if (typeof data === "number") data = data.toString();
2542
+ if (this.readyState !== _WebSocket.OPEN) {
2543
+ sendAfterClose(this, data, cb);
2544
+ return;
2545
+ }
2546
+ if (mask === void 0) mask = !this._isServer;
2547
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2548
+ }
2549
+ /**
2550
+ * Resume the socket.
2551
+ *
2552
+ * @public
2553
+ */
2554
+ resume() {
2555
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2556
+ return;
2557
+ }
2558
+ this._paused = false;
2559
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2560
+ }
2561
+ /**
2562
+ * Send a data message.
2563
+ *
2564
+ * @param {*} data The message to send
2565
+ * @param {Object} [options] Options object
2566
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2567
+ * text
2568
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2569
+ * `data`
2570
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2571
+ * last one
2572
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2573
+ * @param {Function} [cb] Callback which is executed when data is written out
2574
+ * @public
2575
+ */
2576
+ send(data, options, cb) {
2577
+ if (this.readyState === _WebSocket.CONNECTING) {
2578
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2579
+ }
2580
+ if (typeof options === "function") {
2581
+ cb = options;
2582
+ options = {};
2583
+ }
2584
+ if (typeof data === "number") data = data.toString();
2585
+ if (this.readyState !== _WebSocket.OPEN) {
2586
+ sendAfterClose(this, data, cb);
2587
+ return;
2588
+ }
2589
+ const opts = {
2590
+ binary: typeof data !== "string",
2591
+ mask: !this._isServer,
2592
+ compress: true,
2593
+ fin: true,
2594
+ ...options
2595
+ };
2596
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
2597
+ opts.compress = false;
2598
+ }
2599
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2600
+ }
2601
+ /**
2602
+ * Forcibly close the connection.
2603
+ *
2604
+ * @public
2605
+ */
2606
+ terminate() {
2607
+ if (this.readyState === _WebSocket.CLOSED) return;
2608
+ if (this.readyState === _WebSocket.CONNECTING) {
2609
+ const msg = "WebSocket was closed before the connection was established";
2610
+ abortHandshake(this, this._req, msg);
2611
+ return;
2612
+ }
2613
+ if (this._socket) {
2614
+ this._readyState = _WebSocket.CLOSING;
2615
+ this._socket.destroy();
2616
+ }
2617
+ }
2618
+ };
2619
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2620
+ enumerable: true,
2621
+ value: readyStates.indexOf("CONNECTING")
2622
+ });
2623
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2624
+ enumerable: true,
2625
+ value: readyStates.indexOf("CONNECTING")
2626
+ });
2627
+ Object.defineProperty(WebSocket2, "OPEN", {
2628
+ enumerable: true,
2629
+ value: readyStates.indexOf("OPEN")
2630
+ });
2631
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2632
+ enumerable: true,
2633
+ value: readyStates.indexOf("OPEN")
2634
+ });
2635
+ Object.defineProperty(WebSocket2, "CLOSING", {
2636
+ enumerable: true,
2637
+ value: readyStates.indexOf("CLOSING")
2638
+ });
2639
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2640
+ enumerable: true,
2641
+ value: readyStates.indexOf("CLOSING")
2642
+ });
2643
+ Object.defineProperty(WebSocket2, "CLOSED", {
2644
+ enumerable: true,
2645
+ value: readyStates.indexOf("CLOSED")
2646
+ });
2647
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2648
+ enumerable: true,
2649
+ value: readyStates.indexOf("CLOSED")
2650
+ });
2651
+ [
2652
+ "binaryType",
2653
+ "bufferedAmount",
2654
+ "extensions",
2655
+ "isPaused",
2656
+ "protocol",
2657
+ "readyState",
2658
+ "url"
2659
+ ].forEach((property) => {
2660
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2661
+ });
2662
+ ["open", "error", "close", "message"].forEach((method) => {
2663
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2664
+ enumerable: true,
2665
+ get() {
2666
+ for (const listener of this.listeners(method)) {
2667
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2668
+ }
2669
+ return null;
2670
+ },
2671
+ set(handler) {
2672
+ for (const listener of this.listeners(method)) {
2673
+ if (listener[kForOnEventAttribute]) {
2674
+ this.removeListener(method, listener);
2675
+ break;
2676
+ }
2677
+ }
2678
+ if (typeof handler !== "function") return;
2679
+ this.addEventListener(method, handler, {
2680
+ [kForOnEventAttribute]: true
2681
+ });
2682
+ }
2683
+ });
2684
+ });
2685
+ WebSocket2.prototype.addEventListener = addEventListener;
2686
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2687
+ module.exports = WebSocket2;
2688
+ function initAsClient(websocket, address, protocols, options) {
2689
+ const opts = {
2690
+ allowSynchronousEvents: true,
2691
+ autoPong: true,
2692
+ closeTimeout: CLOSE_TIMEOUT,
2693
+ protocolVersion: protocolVersions[1],
2694
+ maxPayload: 100 * 1024 * 1024,
2695
+ skipUTF8Validation: false,
2696
+ perMessageDeflate: true,
2697
+ followRedirects: false,
2698
+ maxRedirects: 10,
2699
+ ...options,
2700
+ socketPath: void 0,
2701
+ hostname: void 0,
2702
+ protocol: void 0,
2703
+ timeout: void 0,
2704
+ method: "GET",
2705
+ host: void 0,
2706
+ path: void 0,
2707
+ port: void 0
2708
+ };
2709
+ websocket._autoPong = opts.autoPong;
2710
+ websocket._closeTimeout = opts.closeTimeout;
2711
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2712
+ throw new RangeError(
2713
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2714
+ );
2715
+ }
2716
+ let parsedUrl;
2717
+ if (address instanceof URL) {
2718
+ parsedUrl = address;
2719
+ } else {
2720
+ try {
2721
+ parsedUrl = new URL(address);
2722
+ } catch (e) {
2723
+ throw new SyntaxError(`Invalid URL: ${address}`);
2724
+ }
2725
+ }
2726
+ if (parsedUrl.protocol === "http:") {
2727
+ parsedUrl.protocol = "ws:";
2728
+ } else if (parsedUrl.protocol === "https:") {
2729
+ parsedUrl.protocol = "wss:";
2730
+ }
2731
+ websocket._url = parsedUrl.href;
2732
+ const isSecure = parsedUrl.protocol === "wss:";
2733
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2734
+ let invalidUrlMessage;
2735
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2736
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2737
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2738
+ invalidUrlMessage = "The URL's pathname is empty";
2739
+ } else if (parsedUrl.hash) {
2740
+ invalidUrlMessage = "The URL contains a fragment identifier";
2741
+ }
2742
+ if (invalidUrlMessage) {
2743
+ const err = new SyntaxError(invalidUrlMessage);
2744
+ if (websocket._redirects === 0) {
2745
+ throw err;
2746
+ } else {
2747
+ emitErrorAndClose(websocket, err);
2748
+ return;
2749
+ }
2750
+ }
2751
+ const defaultPort = isSecure ? 443 : 80;
2752
+ const key = randomBytes(16).toString("base64");
2753
+ const request = isSecure ? https.request : http.request;
2754
+ const protocolSet = /* @__PURE__ */ new Set();
2755
+ let perMessageDeflate;
2756
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2757
+ opts.defaultPort = opts.defaultPort || defaultPort;
2758
+ opts.port = parsedUrl.port || defaultPort;
2759
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2760
+ opts.headers = {
2761
+ ...opts.headers,
2762
+ "Sec-WebSocket-Version": opts.protocolVersion,
2763
+ "Sec-WebSocket-Key": key,
2764
+ Connection: "Upgrade",
2765
+ Upgrade: "websocket"
2766
+ };
2767
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2768
+ opts.timeout = opts.handshakeTimeout;
2769
+ if (opts.perMessageDeflate) {
2770
+ perMessageDeflate = new PerMessageDeflate(
2771
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2772
+ false,
2773
+ opts.maxPayload
2774
+ );
2775
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2776
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2777
+ });
2778
+ }
2779
+ if (protocols.length) {
2780
+ for (const protocol of protocols) {
2781
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2782
+ throw new SyntaxError(
2783
+ "An invalid or duplicated subprotocol was specified"
2784
+ );
2785
+ }
2786
+ protocolSet.add(protocol);
2787
+ }
2788
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2789
+ }
2790
+ if (opts.origin) {
2791
+ if (opts.protocolVersion < 13) {
2792
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2793
+ } else {
2794
+ opts.headers.Origin = opts.origin;
2795
+ }
2796
+ }
2797
+ if (parsedUrl.username || parsedUrl.password) {
2798
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2799
+ }
2800
+ if (isIpcUrl) {
2801
+ const parts = opts.path.split(":");
2802
+ opts.socketPath = parts[0];
2803
+ opts.path = parts[1];
2804
+ }
2805
+ let req;
2806
+ if (opts.followRedirects) {
2807
+ if (websocket._redirects === 0) {
2808
+ websocket._originalIpc = isIpcUrl;
2809
+ websocket._originalSecure = isSecure;
2810
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2811
+ const headers = options && options.headers;
2812
+ options = { ...options, headers: {} };
2813
+ if (headers) {
2814
+ for (const [key2, value] of Object.entries(headers)) {
2815
+ options.headers[key2.toLowerCase()] = value;
2816
+ }
2817
+ }
2818
+ } else if (websocket.listenerCount("redirect") === 0) {
2819
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2820
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2821
+ delete opts.headers.authorization;
2822
+ delete opts.headers.cookie;
2823
+ if (!isSameHost) delete opts.headers.host;
2824
+ opts.auth = void 0;
2825
+ }
2826
+ }
2827
+ if (opts.auth && !options.headers.authorization) {
2828
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2829
+ }
2830
+ req = websocket._req = request(opts);
2831
+ if (websocket._redirects) {
2832
+ websocket.emit("redirect", websocket.url, req);
2833
+ }
2834
+ } else {
2835
+ req = websocket._req = request(opts);
2836
+ }
2837
+ if (opts.timeout) {
2838
+ req.on("timeout", () => {
2839
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2840
+ });
2841
+ }
2842
+ req.on("error", (err) => {
2843
+ if (req === null || req[kAborted]) return;
2844
+ req = websocket._req = null;
2845
+ emitErrorAndClose(websocket, err);
2846
+ });
2847
+ req.on("response", (res) => {
2848
+ const location = res.headers.location;
2849
+ const statusCode = res.statusCode;
2850
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2851
+ if (++websocket._redirects > opts.maxRedirects) {
2852
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2853
+ return;
2854
+ }
2855
+ req.abort();
2856
+ let addr;
2857
+ try {
2858
+ addr = new URL(location, address);
2859
+ } catch (e) {
2860
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2861
+ emitErrorAndClose(websocket, err);
2862
+ return;
2863
+ }
2864
+ initAsClient(websocket, addr, protocols, options);
2865
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2866
+ abortHandshake(
2867
+ websocket,
2868
+ req,
2869
+ `Unexpected server response: ${res.statusCode}`
2870
+ );
2871
+ }
2872
+ });
2873
+ req.on("upgrade", (res, socket, head) => {
2874
+ websocket.emit("upgrade", res);
2875
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2876
+ req = websocket._req = null;
2877
+ const upgrade = res.headers.upgrade;
2878
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2879
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2880
+ return;
2881
+ }
2882
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2883
+ if (res.headers["sec-websocket-accept"] !== digest) {
2884
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2885
+ return;
2886
+ }
2887
+ const serverProt = res.headers["sec-websocket-protocol"];
2888
+ let protError;
2889
+ if (serverProt !== void 0) {
2890
+ if (!protocolSet.size) {
2891
+ protError = "Server sent a subprotocol but none was requested";
2892
+ } else if (!protocolSet.has(serverProt)) {
2893
+ protError = "Server sent an invalid subprotocol";
2894
+ }
2895
+ } else if (protocolSet.size) {
2896
+ protError = "Server sent no subprotocol";
2897
+ }
2898
+ if (protError) {
2899
+ abortHandshake(websocket, socket, protError);
2900
+ return;
2901
+ }
2902
+ if (serverProt) websocket._protocol = serverProt;
2903
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2904
+ if (secWebSocketExtensions !== void 0) {
2905
+ if (!perMessageDeflate) {
2906
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2907
+ abortHandshake(websocket, socket, message);
2908
+ return;
2909
+ }
2910
+ let extensions;
2911
+ try {
2912
+ extensions = parse(secWebSocketExtensions);
2913
+ } catch (err) {
2914
+ const message = "Invalid Sec-WebSocket-Extensions header";
2915
+ abortHandshake(websocket, socket, message);
2916
+ return;
2917
+ }
2918
+ const extensionNames = Object.keys(extensions);
2919
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2920
+ const message = "Server indicated an extension that was not requested";
2921
+ abortHandshake(websocket, socket, message);
2922
+ return;
2923
+ }
2924
+ try {
2925
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2926
+ } catch (err) {
2927
+ const message = "Invalid Sec-WebSocket-Extensions header";
2928
+ abortHandshake(websocket, socket, message);
2929
+ return;
2930
+ }
2931
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2932
+ }
2933
+ websocket.setSocket(socket, head, {
2934
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2935
+ generateMask: opts.generateMask,
2936
+ maxPayload: opts.maxPayload,
2937
+ skipUTF8Validation: opts.skipUTF8Validation
2938
+ });
2939
+ });
2940
+ if (opts.finishRequest) {
2941
+ opts.finishRequest(req, websocket);
2942
+ } else {
2943
+ req.end();
2944
+ }
2945
+ }
2946
+ function emitErrorAndClose(websocket, err) {
2947
+ websocket._readyState = WebSocket2.CLOSING;
2948
+ websocket._errorEmitted = true;
2949
+ websocket.emit("error", err);
2950
+ websocket.emitClose();
2951
+ }
2952
+ function netConnect(options) {
2953
+ options.path = options.socketPath;
2954
+ return net.connect(options);
2955
+ }
2956
+ function tlsConnect(options) {
2957
+ options.path = void 0;
2958
+ if (!options.servername && options.servername !== "") {
2959
+ options.servername = net.isIP(options.host) ? "" : options.host;
2960
+ }
2961
+ return tls.connect(options);
2962
+ }
2963
+ function abortHandshake(websocket, stream, message) {
2964
+ websocket._readyState = WebSocket2.CLOSING;
2965
+ const err = new Error(message);
2966
+ Error.captureStackTrace(err, abortHandshake);
2967
+ if (stream.setHeader) {
2968
+ stream[kAborted] = true;
2969
+ stream.abort();
2970
+ if (stream.socket && !stream.socket.destroyed) {
2971
+ stream.socket.destroy();
2972
+ }
2973
+ process.nextTick(emitErrorAndClose, websocket, err);
2974
+ } else {
2975
+ stream.destroy(err);
2976
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2977
+ stream.once("close", websocket.emitClose.bind(websocket));
2978
+ }
2979
+ }
2980
+ function sendAfterClose(websocket, data, cb) {
2981
+ if (data) {
2982
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2983
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
2984
+ else websocket._bufferedAmount += length;
2985
+ }
2986
+ if (cb) {
2987
+ const err = new Error(
2988
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
2989
+ );
2990
+ process.nextTick(cb, err);
2991
+ }
2992
+ }
2993
+ function receiverOnConclude(code, reason) {
2994
+ const websocket = this[kWebSocket];
2995
+ websocket._closeFrameReceived = true;
2996
+ websocket._closeMessage = reason;
2997
+ websocket._closeCode = code;
2998
+ if (websocket._socket[kWebSocket] === void 0) return;
2999
+ websocket._socket.removeListener("data", socketOnData);
3000
+ process.nextTick(resume, websocket._socket);
3001
+ if (code === 1005) websocket.close();
3002
+ else websocket.close(code, reason);
3003
+ }
3004
+ function receiverOnDrain() {
3005
+ const websocket = this[kWebSocket];
3006
+ if (!websocket.isPaused) websocket._socket.resume();
3007
+ }
3008
+ function receiverOnError(err) {
3009
+ const websocket = this[kWebSocket];
3010
+ if (websocket._socket[kWebSocket] !== void 0) {
3011
+ websocket._socket.removeListener("data", socketOnData);
3012
+ process.nextTick(resume, websocket._socket);
3013
+ websocket.close(err[kStatusCode]);
3014
+ }
3015
+ if (!websocket._errorEmitted) {
3016
+ websocket._errorEmitted = true;
3017
+ websocket.emit("error", err);
3018
+ }
3019
+ }
3020
+ function receiverOnFinish() {
3021
+ this[kWebSocket].emitClose();
3022
+ }
3023
+ function receiverOnMessage(data, isBinary) {
3024
+ this[kWebSocket].emit("message", data, isBinary);
3025
+ }
3026
+ function receiverOnPing(data) {
3027
+ const websocket = this[kWebSocket];
3028
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3029
+ websocket.emit("ping", data);
3030
+ }
3031
+ function receiverOnPong(data) {
3032
+ this[kWebSocket].emit("pong", data);
3033
+ }
3034
+ function resume(stream) {
3035
+ stream.resume();
3036
+ }
3037
+ function senderOnError(err) {
3038
+ const websocket = this[kWebSocket];
3039
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3040
+ if (websocket.readyState === WebSocket2.OPEN) {
3041
+ websocket._readyState = WebSocket2.CLOSING;
3042
+ setCloseTimer(websocket);
3043
+ }
3044
+ this._socket.end();
3045
+ if (!websocket._errorEmitted) {
3046
+ websocket._errorEmitted = true;
3047
+ websocket.emit("error", err);
3048
+ }
3049
+ }
3050
+ function setCloseTimer(websocket) {
3051
+ websocket._closeTimer = setTimeout(
3052
+ websocket._socket.destroy.bind(websocket._socket),
3053
+ websocket._closeTimeout
3054
+ );
3055
+ }
3056
+ function socketOnClose() {
3057
+ const websocket = this[kWebSocket];
3058
+ this.removeListener("close", socketOnClose);
3059
+ this.removeListener("data", socketOnData);
3060
+ this.removeListener("end", socketOnEnd);
3061
+ websocket._readyState = WebSocket2.CLOSING;
3062
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3063
+ const chunk = this.read(this._readableState.length);
3064
+ websocket._receiver.write(chunk);
3065
+ }
3066
+ websocket._receiver.end();
3067
+ this[kWebSocket] = void 0;
3068
+ clearTimeout(websocket._closeTimer);
3069
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3070
+ websocket.emitClose();
3071
+ } else {
3072
+ websocket._receiver.on("error", receiverOnFinish);
3073
+ websocket._receiver.on("finish", receiverOnFinish);
3074
+ }
3075
+ }
3076
+ function socketOnData(chunk) {
3077
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3078
+ this.pause();
3079
+ }
3080
+ }
3081
+ function socketOnEnd() {
3082
+ const websocket = this[kWebSocket];
3083
+ websocket._readyState = WebSocket2.CLOSING;
3084
+ websocket._receiver.end();
3085
+ this.end();
3086
+ }
3087
+ function socketOnError() {
3088
+ const websocket = this[kWebSocket];
3089
+ this.removeListener("error", socketOnError);
3090
+ this.on("error", NOOP);
3091
+ if (websocket) {
3092
+ websocket._readyState = WebSocket2.CLOSING;
3093
+ this.destroy();
3094
+ }
3095
+ }
3096
+ }
3097
+ });
3098
+
3099
+ // ../../node_modules/ws/lib/stream.js
3100
+ var require_stream = __commonJS({
3101
+ "../../node_modules/ws/lib/stream.js"(exports, module) {
3102
+ "use strict";
3103
+ init_esm_shims();
3104
+ var WebSocket2 = require_websocket();
3105
+ var { Duplex } = __require("stream");
3106
+ function emitClose(stream) {
3107
+ stream.emit("close");
3108
+ }
3109
+ function duplexOnEnd() {
3110
+ if (!this.destroyed && this._writableState.finished) {
3111
+ this.destroy();
3112
+ }
3113
+ }
3114
+ function duplexOnError(err) {
3115
+ this.removeListener("error", duplexOnError);
3116
+ this.destroy();
3117
+ if (this.listenerCount("error") === 0) {
3118
+ this.emit("error", err);
3119
+ }
3120
+ }
3121
+ function createWebSocketStream2(ws, options) {
3122
+ let terminateOnDestroy = true;
3123
+ const duplex = new Duplex({
3124
+ ...options,
3125
+ autoDestroy: false,
3126
+ emitClose: false,
3127
+ objectMode: false,
3128
+ writableObjectMode: false
3129
+ });
3130
+ ws.on("message", function message(msg, isBinary) {
3131
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3132
+ if (!duplex.push(data)) ws.pause();
3133
+ });
3134
+ ws.once("error", function error(err) {
3135
+ if (duplex.destroyed) return;
3136
+ terminateOnDestroy = false;
3137
+ duplex.destroy(err);
3138
+ });
3139
+ ws.once("close", function close() {
3140
+ if (duplex.destroyed) return;
3141
+ duplex.push(null);
3142
+ });
3143
+ duplex._destroy = function(err, callback) {
3144
+ if (ws.readyState === ws.CLOSED) {
3145
+ callback(err);
3146
+ process.nextTick(emitClose, duplex);
3147
+ return;
3148
+ }
3149
+ let called = false;
3150
+ ws.once("error", function error(err2) {
3151
+ called = true;
3152
+ callback(err2);
3153
+ });
3154
+ ws.once("close", function close() {
3155
+ if (!called) callback(err);
3156
+ process.nextTick(emitClose, duplex);
3157
+ });
3158
+ if (terminateOnDestroy) ws.terminate();
3159
+ };
3160
+ duplex._final = function(callback) {
3161
+ if (ws.readyState === ws.CONNECTING) {
3162
+ ws.once("open", function open() {
3163
+ duplex._final(callback);
3164
+ });
3165
+ return;
3166
+ }
3167
+ if (ws._socket === null) return;
3168
+ if (ws._socket._writableState.finished) {
3169
+ callback();
3170
+ if (duplex._readableState.endEmitted) duplex.destroy();
3171
+ } else {
3172
+ ws._socket.once("finish", function finish() {
3173
+ callback();
3174
+ });
3175
+ ws.close();
3176
+ }
3177
+ };
3178
+ duplex._read = function() {
3179
+ if (ws.isPaused) ws.resume();
3180
+ };
3181
+ duplex._write = function(chunk, encoding, callback) {
3182
+ if (ws.readyState === ws.CONNECTING) {
3183
+ ws.once("open", function open() {
3184
+ duplex._write(chunk, encoding, callback);
3185
+ });
3186
+ return;
3187
+ }
3188
+ ws.send(chunk, callback);
3189
+ };
3190
+ duplex.on("end", duplexOnEnd);
3191
+ duplex.on("error", duplexOnError);
3192
+ return duplex;
3193
+ }
3194
+ module.exports = createWebSocketStream2;
3195
+ }
3196
+ });
3197
+
3198
+ // ../../node_modules/ws/lib/subprotocol.js
3199
+ var require_subprotocol = __commonJS({
3200
+ "../../node_modules/ws/lib/subprotocol.js"(exports, module) {
3201
+ "use strict";
3202
+ init_esm_shims();
3203
+ var { tokenChars } = require_validation();
3204
+ function parse(header) {
3205
+ const protocols = /* @__PURE__ */ new Set();
3206
+ let start = -1;
3207
+ let end = -1;
3208
+ let i = 0;
3209
+ for (i; i < header.length; i++) {
3210
+ const code = header.charCodeAt(i);
3211
+ if (end === -1 && tokenChars[code] === 1) {
3212
+ if (start === -1) start = i;
3213
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3214
+ if (end === -1 && start !== -1) end = i;
3215
+ } else if (code === 44) {
3216
+ if (start === -1) {
3217
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3218
+ }
3219
+ if (end === -1) end = i;
3220
+ const protocol2 = header.slice(start, end);
3221
+ if (protocols.has(protocol2)) {
3222
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3223
+ }
3224
+ protocols.add(protocol2);
3225
+ start = end = -1;
3226
+ } else {
3227
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3228
+ }
3229
+ }
3230
+ if (start === -1 || end !== -1) {
3231
+ throw new SyntaxError("Unexpected end of input");
3232
+ }
3233
+ const protocol = header.slice(start, i);
3234
+ if (protocols.has(protocol)) {
3235
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3236
+ }
3237
+ protocols.add(protocol);
3238
+ return protocols;
3239
+ }
3240
+ module.exports = { parse };
3241
+ }
3242
+ });
3243
+
3244
+ // ../../node_modules/ws/lib/websocket-server.js
3245
+ var require_websocket_server = __commonJS({
3246
+ "../../node_modules/ws/lib/websocket-server.js"(exports, module) {
3247
+ "use strict";
3248
+ init_esm_shims();
3249
+ var EventEmitter = __require("events");
3250
+ var http = __require("http");
3251
+ var { Duplex } = __require("stream");
3252
+ var { createHash } = __require("crypto");
3253
+ var extension = require_extension();
3254
+ var PerMessageDeflate = require_permessage_deflate();
3255
+ var subprotocol = require_subprotocol();
3256
+ var WebSocket2 = require_websocket();
3257
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3258
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3259
+ var RUNNING = 0;
3260
+ var CLOSING = 1;
3261
+ var CLOSED = 2;
3262
+ var WebSocketServer2 = class extends EventEmitter {
3263
+ /**
3264
+ * Create a `WebSocketServer` instance.
3265
+ *
3266
+ * @param {Object} options Configuration options
3267
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3268
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3269
+ * multiple times in the same tick
3270
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3271
+ * automatically send a pong in response to a ping
3272
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3273
+ * pending connections
3274
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3275
+ * track clients
3276
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3277
+ * wait for the closing handshake to finish after `websocket.close()` is
3278
+ * called
3279
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3280
+ * @param {String} [options.host] The hostname where to bind the server
3281
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3282
+ * size
3283
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3284
+ * @param {String} [options.path] Accept only connections matching this path
3285
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3286
+ * permessage-deflate
3287
+ * @param {Number} [options.port] The port where to bind the server
3288
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3289
+ * server to use
3290
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3291
+ * not to skip UTF-8 validation for text and close messages
3292
+ * @param {Function} [options.verifyClient] A hook to reject connections
3293
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3294
+ * class to use. It must be the `WebSocket` class or class that extends it
3295
+ * @param {Function} [callback] A listener for the `listening` event
3296
+ */
3297
+ constructor(options, callback) {
3298
+ super();
3299
+ options = {
3300
+ allowSynchronousEvents: true,
3301
+ autoPong: true,
3302
+ maxPayload: 100 * 1024 * 1024,
3303
+ skipUTF8Validation: false,
3304
+ perMessageDeflate: false,
3305
+ handleProtocols: null,
3306
+ clientTracking: true,
3307
+ closeTimeout: CLOSE_TIMEOUT,
3308
+ verifyClient: null,
3309
+ noServer: false,
3310
+ backlog: null,
3311
+ // use default (511 as implemented in net.js)
3312
+ server: null,
3313
+ host: null,
3314
+ path: null,
3315
+ port: null,
3316
+ WebSocket: WebSocket2,
3317
+ ...options
3318
+ };
3319
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3320
+ throw new TypeError(
3321
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3322
+ );
3323
+ }
3324
+ if (options.port != null) {
3325
+ this._server = http.createServer((req, res) => {
3326
+ const body = http.STATUS_CODES[426];
3327
+ res.writeHead(426, {
3328
+ "Content-Length": body.length,
3329
+ "Content-Type": "text/plain"
3330
+ });
3331
+ res.end(body);
3332
+ });
3333
+ this._server.listen(
3334
+ options.port,
3335
+ options.host,
3336
+ options.backlog,
3337
+ callback
3338
+ );
3339
+ } else if (options.server) {
3340
+ this._server = options.server;
3341
+ }
3342
+ if (this._server) {
3343
+ const emitConnection = this.emit.bind(this, "connection");
3344
+ this._removeListeners = addListeners(this._server, {
3345
+ listening: this.emit.bind(this, "listening"),
3346
+ error: this.emit.bind(this, "error"),
3347
+ upgrade: (req, socket, head) => {
3348
+ this.handleUpgrade(req, socket, head, emitConnection);
3349
+ }
3350
+ });
3351
+ }
3352
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3353
+ if (options.clientTracking) {
3354
+ this.clients = /* @__PURE__ */ new Set();
3355
+ this._shouldEmitClose = false;
3356
+ }
3357
+ this.options = options;
3358
+ this._state = RUNNING;
3359
+ }
3360
+ /**
3361
+ * Returns the bound address, the address family name, and port of the server
3362
+ * as reported by the operating system if listening on an IP socket.
3363
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3364
+ * returned as a string.
3365
+ *
3366
+ * @return {(Object|String|null)} The address of the server
3367
+ * @public
3368
+ */
3369
+ address() {
3370
+ if (this.options.noServer) {
3371
+ throw new Error('The server is operating in "noServer" mode');
3372
+ }
3373
+ if (!this._server) return null;
3374
+ return this._server.address();
3375
+ }
3376
+ /**
3377
+ * Stop the server from accepting new connections and emit the `'close'` event
3378
+ * when all existing connections are closed.
3379
+ *
3380
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3381
+ * @public
3382
+ */
3383
+ close(cb) {
3384
+ if (this._state === CLOSED) {
3385
+ if (cb) {
3386
+ this.once("close", () => {
3387
+ cb(new Error("The server is not running"));
3388
+ });
3389
+ }
3390
+ process.nextTick(emitClose, this);
3391
+ return;
3392
+ }
3393
+ if (cb) this.once("close", cb);
3394
+ if (this._state === CLOSING) return;
3395
+ this._state = CLOSING;
3396
+ if (this.options.noServer || this.options.server) {
3397
+ if (this._server) {
3398
+ this._removeListeners();
3399
+ this._removeListeners = this._server = null;
3400
+ }
3401
+ if (this.clients) {
3402
+ if (!this.clients.size) {
3403
+ process.nextTick(emitClose, this);
3404
+ } else {
3405
+ this._shouldEmitClose = true;
3406
+ }
3407
+ } else {
3408
+ process.nextTick(emitClose, this);
3409
+ }
3410
+ } else {
3411
+ const server = this._server;
3412
+ this._removeListeners();
3413
+ this._removeListeners = this._server = null;
3414
+ server.close(() => {
3415
+ emitClose(this);
3416
+ });
3417
+ }
3418
+ }
3419
+ /**
3420
+ * See if a given request should be handled by this server instance.
3421
+ *
3422
+ * @param {http.IncomingMessage} req Request object to inspect
3423
+ * @return {Boolean} `true` if the request is valid, else `false`
3424
+ * @public
3425
+ */
3426
+ shouldHandle(req) {
3427
+ if (this.options.path) {
3428
+ const index = req.url.indexOf("?");
3429
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3430
+ if (pathname !== this.options.path) return false;
3431
+ }
3432
+ return true;
3433
+ }
3434
+ /**
3435
+ * Handle a HTTP Upgrade request.
3436
+ *
3437
+ * @param {http.IncomingMessage} req The request object
3438
+ * @param {Duplex} socket The network socket between the server and client
3439
+ * @param {Buffer} head The first packet of the upgraded stream
3440
+ * @param {Function} cb Callback
3441
+ * @public
3442
+ */
3443
+ handleUpgrade(req, socket, head, cb) {
3444
+ socket.on("error", socketOnError);
3445
+ const key = req.headers["sec-websocket-key"];
3446
+ const upgrade = req.headers.upgrade;
3447
+ const version = +req.headers["sec-websocket-version"];
3448
+ if (req.method !== "GET") {
3449
+ const message = "Invalid HTTP method";
3450
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3451
+ return;
3452
+ }
3453
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3454
+ const message = "Invalid Upgrade header";
3455
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3456
+ return;
3457
+ }
3458
+ if (key === void 0 || !keyRegex.test(key)) {
3459
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3460
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3461
+ return;
3462
+ }
3463
+ if (version !== 13 && version !== 8) {
3464
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3465
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3466
+ "Sec-WebSocket-Version": "13, 8"
3467
+ });
3468
+ return;
3469
+ }
3470
+ if (!this.shouldHandle(req)) {
3471
+ abortHandshake(socket, 400);
3472
+ return;
3473
+ }
3474
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3475
+ let protocols = /* @__PURE__ */ new Set();
3476
+ if (secWebSocketProtocol !== void 0) {
3477
+ try {
3478
+ protocols = subprotocol.parse(secWebSocketProtocol);
3479
+ } catch (err) {
3480
+ const message = "Invalid Sec-WebSocket-Protocol header";
3481
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3482
+ return;
3483
+ }
3484
+ }
3485
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3486
+ const extensions = {};
3487
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3488
+ const perMessageDeflate = new PerMessageDeflate(
3489
+ this.options.perMessageDeflate,
3490
+ true,
3491
+ this.options.maxPayload
3492
+ );
3493
+ try {
3494
+ const offers = extension.parse(secWebSocketExtensions);
3495
+ if (offers[PerMessageDeflate.extensionName]) {
3496
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3497
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3498
+ }
3499
+ } catch (err) {
3500
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3501
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3502
+ return;
3503
+ }
3504
+ }
3505
+ if (this.options.verifyClient) {
3506
+ const info = {
3507
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3508
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3509
+ req
3510
+ };
3511
+ if (this.options.verifyClient.length === 2) {
3512
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3513
+ if (!verified) {
3514
+ return abortHandshake(socket, code || 401, message, headers);
3515
+ }
3516
+ this.completeUpgrade(
3517
+ extensions,
3518
+ key,
3519
+ protocols,
3520
+ req,
3521
+ socket,
3522
+ head,
3523
+ cb
3524
+ );
3525
+ });
3526
+ return;
3527
+ }
3528
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3529
+ }
3530
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3531
+ }
3532
+ /**
3533
+ * Upgrade the connection to WebSocket.
3534
+ *
3535
+ * @param {Object} extensions The accepted extensions
3536
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3537
+ * @param {Set} protocols The subprotocols
3538
+ * @param {http.IncomingMessage} req The request object
3539
+ * @param {Duplex} socket The network socket between the server and client
3540
+ * @param {Buffer} head The first packet of the upgraded stream
3541
+ * @param {Function} cb Callback
3542
+ * @throws {Error} If called more than once with the same socket
3543
+ * @private
3544
+ */
3545
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3546
+ if (!socket.readable || !socket.writable) return socket.destroy();
3547
+ if (socket[kWebSocket]) {
3548
+ throw new Error(
3549
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3550
+ );
3551
+ }
3552
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3553
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3554
+ const headers = [
3555
+ "HTTP/1.1 101 Switching Protocols",
3556
+ "Upgrade: websocket",
3557
+ "Connection: Upgrade",
3558
+ `Sec-WebSocket-Accept: ${digest}`
3559
+ ];
3560
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3561
+ if (protocols.size) {
3562
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3563
+ if (protocol) {
3564
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3565
+ ws._protocol = protocol;
3566
+ }
3567
+ }
3568
+ if (extensions[PerMessageDeflate.extensionName]) {
3569
+ const params = extensions[PerMessageDeflate.extensionName].params;
3570
+ const value = extension.format({
3571
+ [PerMessageDeflate.extensionName]: [params]
3572
+ });
3573
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3574
+ ws._extensions = extensions;
3575
+ }
3576
+ this.emit("headers", headers, req);
3577
+ socket.write(headers.concat("\r\n").join("\r\n"));
3578
+ socket.removeListener("error", socketOnError);
3579
+ ws.setSocket(socket, head, {
3580
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3581
+ maxPayload: this.options.maxPayload,
3582
+ skipUTF8Validation: this.options.skipUTF8Validation
3583
+ });
3584
+ if (this.clients) {
3585
+ this.clients.add(ws);
3586
+ ws.on("close", () => {
3587
+ this.clients.delete(ws);
3588
+ if (this._shouldEmitClose && !this.clients.size) {
3589
+ process.nextTick(emitClose, this);
3590
+ }
3591
+ });
3592
+ }
3593
+ cb(ws, req);
3594
+ }
3595
+ };
3596
+ module.exports = WebSocketServer2;
3597
+ function addListeners(server, map) {
3598
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3599
+ return function removeListeners() {
3600
+ for (const event of Object.keys(map)) {
3601
+ server.removeListener(event, map[event]);
3602
+ }
3603
+ };
3604
+ }
3605
+ function emitClose(server) {
3606
+ server._state = CLOSED;
3607
+ server.emit("close");
3608
+ }
3609
+ function socketOnError() {
3610
+ this.destroy();
3611
+ }
3612
+ function abortHandshake(socket, code, message, headers) {
3613
+ message = message || http.STATUS_CODES[code];
3614
+ headers = {
3615
+ Connection: "close",
3616
+ "Content-Type": "text/html",
3617
+ "Content-Length": Buffer.byteLength(message),
3618
+ ...headers
3619
+ };
3620
+ socket.once("finish", socket.destroy);
3621
+ socket.end(
3622
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3623
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3624
+ );
3625
+ }
3626
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3627
+ if (server.listenerCount("wsClientError")) {
3628
+ const err = new Error(message);
3629
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3630
+ server.emit("wsClientError", err, socket, req);
3631
+ } else {
3632
+ abortHandshake(socket, code, message, headers);
3633
+ }
3634
+ }
3635
+ }
3636
+ });
3637
+
3638
+ // ../../node_modules/ink/build/devtools.js
3639
+ init_esm_shims();
3640
+
3641
+ // ../../node_modules/ink/build/devtools-window-polyfill.js
3642
+ init_esm_shims();
3643
+
3644
+ // ../../node_modules/ws/wrapper.mjs
3645
+ init_esm_shims();
3646
+ var import_stream = __toESM(require_stream(), 1);
3647
+ var import_receiver = __toESM(require_receiver(), 1);
3648
+ var import_sender = __toESM(require_sender(), 1);
3649
+ var import_websocket = __toESM(require_websocket(), 1);
3650
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3651
+ var wrapper_default = import_websocket.default;
3652
+
3653
+ // ../../node_modules/ink/build/devtools-window-polyfill.js
3654
+ var customGlobal = global;
3655
+ customGlobal.WebSocket ||= wrapper_default;
3656
+ customGlobal.window ||= global;
3657
+ customGlobal.self ||= global;
3658
+ customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = [
3659
+ {
3660
+ // ComponentFilterElementType
3661
+ type: 1,
3662
+ // ElementTypeHostComponent
3663
+ value: 7,
3664
+ isEnabled: true
3665
+ },
3666
+ {
3667
+ // ComponentFilterDisplayName
3668
+ type: 2,
3669
+ value: "InternalApp",
3670
+ isEnabled: true,
3671
+ isValid: true
3672
+ },
3673
+ {
3674
+ // ComponentFilterDisplayName
3675
+ type: 2,
3676
+ value: "InternalAppContext",
3677
+ isEnabled: true,
3678
+ isValid: true
3679
+ },
3680
+ {
3681
+ // ComponentFilterDisplayName
3682
+ type: 2,
3683
+ value: "InternalStdoutContext",
3684
+ isEnabled: true,
3685
+ isValid: true
3686
+ },
3687
+ {
3688
+ // ComponentFilterDisplayName
3689
+ type: 2,
3690
+ value: "InternalStderrContext",
3691
+ isEnabled: true,
3692
+ isValid: true
3693
+ },
3694
+ {
3695
+ // ComponentFilterDisplayName
3696
+ type: 2,
3697
+ value: "InternalStdinContext",
3698
+ isEnabled: true,
3699
+ isValid: true
3700
+ },
3701
+ {
3702
+ // ComponentFilterDisplayName
3703
+ type: 2,
3704
+ value: "InternalFocusContext",
3705
+ isEnabled: true,
3706
+ isValid: true
3707
+ }
3708
+ ];
3709
+
3710
+ // ../../node_modules/ink/build/devtools.js
3711
+ import devtools from "react-devtools-core";
3712
+ devtools.initialize();
3713
+ devtools.connectToDevTools();