crossws 0.3.0 → 0.3.2

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