@blinkdotnew/dev-sdk 2.3.10 → 2.4.0

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