@digipair/skill-client-websocket 0.49.2 → 0.49.3

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