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