baro-ai 0.54.0 → 0.55.0

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