@jsenv/core 27.6.1 → 27.8.1

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