@goodfish/jarvy 0.15.0 → 0.17.0

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