crossws 0.0.0 → 0.0.1

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