github-router 0.3.30 → 0.3.32

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