fied 0.1.1 → 0.1.2

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