@kevisual/router 0.0.12 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/router.js CHANGED
@@ -1,20 +1,39 @@
1
+ import require$$1, { webcrypto } from 'node:crypto';
1
2
  import http from 'node:http';
2
3
  import https from 'node:https';
3
4
  import http2 from 'node:http2';
4
5
  import url from 'node:url';
6
+ import require$$0$3 from 'node:events';
7
+ import require$$3 from 'node:net';
8
+ import require$$4 from 'node:tls';
9
+ import require$$0$2 from 'node:stream';
10
+ import require$$0 from 'node:zlib';
11
+ import require$$0$1 from 'node:buffer';
5
12
 
6
13
  const urlAlphabet =
7
14
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
8
15
 
9
- /* @ts-self-types="./index.d.ts" */
10
- let nanoid = (size = 21) => {
16
+ const POOL_SIZE_MULTIPLIER = 128;
17
+ let pool, poolOffset;
18
+ function fillPool(bytes) {
19
+ if (!pool || pool.length < bytes) {
20
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
21
+ webcrypto.getRandomValues(pool);
22
+ poolOffset = 0;
23
+ } else if (poolOffset + bytes > pool.length) {
24
+ webcrypto.getRandomValues(pool);
25
+ poolOffset = 0;
26
+ }
27
+ poolOffset += bytes;
28
+ }
29
+ function nanoid(size = 21) {
30
+ fillPool((size |= 0));
11
31
  let id = '';
12
- let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)));
13
- while (size--) {
14
- id += urlAlphabet[bytes[size] & 63];
32
+ for (let i = poolOffset - size; i < poolOffset; i++) {
33
+ id += urlAlphabet[pool[i] & 63];
15
34
  }
16
35
  return id
17
- };
36
+ }
18
37
 
19
38
  /** 自定义错误 */
20
39
  class CustomError extends Error {
@@ -6130,6 +6149,9 @@ class QueryRouter {
6130
6149
  return pick(r, pickValue);
6131
6150
  });
6132
6151
  }
6152
+ /**
6153
+ * 获取handle函数, 这里会去执行parse函数
6154
+ */
6133
6155
  getHandle(router, wrapperFn, ctx) {
6134
6156
  return async (msg, handleContext) => {
6135
6157
  try {
@@ -6374,6 +6396,10 @@ const handleServer = async (req, res) => {
6374
6396
  return data;
6375
6397
  };
6376
6398
 
6399
+ function getDefaultExportFromCjs (x) {
6400
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
6401
+ }
6402
+
6377
6403
  var dist = {};
6378
6404
 
6379
6405
  var hasRequiredDist;
@@ -6821,23 +6847,4917 @@ class Server {
6821
6847
  }
6822
6848
  }
6823
6849
 
6824
- var browser;
6825
- var hasRequiredBrowser;
6850
+ var constants;
6851
+ var hasRequiredConstants;
6852
+
6853
+ function requireConstants () {
6854
+ if (hasRequiredConstants) return constants;
6855
+ hasRequiredConstants = 1;
6856
+
6857
+ const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
6858
+ const hasBlob = typeof Blob !== 'undefined';
6859
+
6860
+ if (hasBlob) BINARY_TYPES.push('blob');
6861
+
6862
+ constants = {
6863
+ BINARY_TYPES,
6864
+ EMPTY_BUFFER: Buffer.alloc(0),
6865
+ GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
6866
+ hasBlob,
6867
+ kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
6868
+ kListener: Symbol('kListener'),
6869
+ kStatusCode: Symbol('status-code'),
6870
+ kWebSocket: Symbol('websocket'),
6871
+ NOOP: () => {}
6872
+ };
6873
+ return constants;
6874
+ }
6875
+
6876
+ var bufferUtil;
6877
+ var hasRequiredBufferUtil;
6878
+
6879
+ function requireBufferUtil () {
6880
+ if (hasRequiredBufferUtil) return bufferUtil;
6881
+ hasRequiredBufferUtil = 1;
6882
+
6883
+ const { EMPTY_BUFFER } = requireConstants();
6884
+
6885
+ const FastBuffer = Buffer[Symbol.species];
6886
+
6887
+ /**
6888
+ * Merges an array of buffers into a new buffer.
6889
+ *
6890
+ * @param {Buffer[]} list The array of buffers to concat
6891
+ * @param {Number} totalLength The total length of buffers in the list
6892
+ * @return {Buffer} The resulting buffer
6893
+ * @public
6894
+ */
6895
+ function concat(list, totalLength) {
6896
+ if (list.length === 0) return EMPTY_BUFFER;
6897
+ if (list.length === 1) return list[0];
6898
+
6899
+ const target = Buffer.allocUnsafe(totalLength);
6900
+ let offset = 0;
6901
+
6902
+ for (let i = 0; i < list.length; i++) {
6903
+ const buf = list[i];
6904
+ target.set(buf, offset);
6905
+ offset += buf.length;
6906
+ }
6907
+
6908
+ if (offset < totalLength) {
6909
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
6910
+ }
6911
+
6912
+ return target;
6913
+ }
6914
+
6915
+ /**
6916
+ * Masks a buffer using the given mask.
6917
+ *
6918
+ * @param {Buffer} source The buffer to mask
6919
+ * @param {Buffer} mask The mask to use
6920
+ * @param {Buffer} output The buffer where to store the result
6921
+ * @param {Number} offset The offset at which to start writing
6922
+ * @param {Number} length The number of bytes to mask.
6923
+ * @public
6924
+ */
6925
+ function _mask(source, mask, output, offset, length) {
6926
+ for (let i = 0; i < length; i++) {
6927
+ output[offset + i] = source[i] ^ mask[i & 3];
6928
+ }
6929
+ }
6930
+
6931
+ /**
6932
+ * Unmasks a buffer using the given mask.
6933
+ *
6934
+ * @param {Buffer} buffer The buffer to unmask
6935
+ * @param {Buffer} mask The mask to use
6936
+ * @public
6937
+ */
6938
+ function _unmask(buffer, mask) {
6939
+ for (let i = 0; i < buffer.length; i++) {
6940
+ buffer[i] ^= mask[i & 3];
6941
+ }
6942
+ }
6943
+
6944
+ /**
6945
+ * Converts a buffer to an `ArrayBuffer`.
6946
+ *
6947
+ * @param {Buffer} buf The buffer to convert
6948
+ * @return {ArrayBuffer} Converted buffer
6949
+ * @public
6950
+ */
6951
+ function toArrayBuffer(buf) {
6952
+ if (buf.length === buf.buffer.byteLength) {
6953
+ return buf.buffer;
6954
+ }
6955
+
6956
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
6957
+ }
6958
+
6959
+ /**
6960
+ * Converts `data` to a `Buffer`.
6961
+ *
6962
+ * @param {*} data The data to convert
6963
+ * @return {Buffer} The buffer
6964
+ * @throws {TypeError}
6965
+ * @public
6966
+ */
6967
+ function toBuffer(data) {
6968
+ toBuffer.readOnly = true;
6969
+
6970
+ if (Buffer.isBuffer(data)) return data;
6971
+
6972
+ let buf;
6973
+
6974
+ if (data instanceof ArrayBuffer) {
6975
+ buf = new FastBuffer(data);
6976
+ } else if (ArrayBuffer.isView(data)) {
6977
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
6978
+ } else {
6979
+ buf = Buffer.from(data);
6980
+ toBuffer.readOnly = false;
6981
+ }
6982
+
6983
+ return buf;
6984
+ }
6985
+
6986
+ bufferUtil = {
6987
+ concat,
6988
+ mask: _mask,
6989
+ toArrayBuffer,
6990
+ toBuffer,
6991
+ unmask: _unmask
6992
+ };
6993
+ return bufferUtil;
6994
+ }
6995
+
6996
+ var limiter;
6997
+ var hasRequiredLimiter;
6998
+
6999
+ function requireLimiter () {
7000
+ if (hasRequiredLimiter) return limiter;
7001
+ hasRequiredLimiter = 1;
7002
+
7003
+ const kDone = Symbol('kDone');
7004
+ const kRun = Symbol('kRun');
7005
+
7006
+ /**
7007
+ * A very simple job queue with adjustable concurrency. Adapted from
7008
+ * https://github.com/STRML/async-limiter
7009
+ */
7010
+ class Limiter {
7011
+ /**
7012
+ * Creates a new `Limiter`.
7013
+ *
7014
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
7015
+ * to run concurrently
7016
+ */
7017
+ constructor(concurrency) {
7018
+ this[kDone] = () => {
7019
+ this.pending--;
7020
+ this[kRun]();
7021
+ };
7022
+ this.concurrency = concurrency || Infinity;
7023
+ this.jobs = [];
7024
+ this.pending = 0;
7025
+ }
7026
+
7027
+ /**
7028
+ * Adds a job to the queue.
7029
+ *
7030
+ * @param {Function} job The job to run
7031
+ * @public
7032
+ */
7033
+ add(job) {
7034
+ this.jobs.push(job);
7035
+ this[kRun]();
7036
+ }
7037
+
7038
+ /**
7039
+ * Removes a job from the queue and runs it if possible.
7040
+ *
7041
+ * @private
7042
+ */
7043
+ [kRun]() {
7044
+ if (this.pending === this.concurrency) return;
7045
+
7046
+ if (this.jobs.length) {
7047
+ const job = this.jobs.shift();
7048
+
7049
+ this.pending++;
7050
+ job(this[kDone]);
7051
+ }
7052
+ }
7053
+ }
7054
+
7055
+ limiter = Limiter;
7056
+ return limiter;
7057
+ }
7058
+
7059
+ var permessageDeflate;
7060
+ var hasRequiredPermessageDeflate;
7061
+
7062
+ function requirePermessageDeflate () {
7063
+ if (hasRequiredPermessageDeflate) return permessageDeflate;
7064
+ hasRequiredPermessageDeflate = 1;
7065
+
7066
+ const zlib = require$$0;
7067
+
7068
+ const bufferUtil = requireBufferUtil();
7069
+ const Limiter = requireLimiter();
7070
+ const { kStatusCode } = requireConstants();
7071
+
7072
+ const FastBuffer = Buffer[Symbol.species];
7073
+ const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
7074
+ const kPerMessageDeflate = Symbol('permessage-deflate');
7075
+ const kTotalLength = Symbol('total-length');
7076
+ const kCallback = Symbol('callback');
7077
+ const kBuffers = Symbol('buffers');
7078
+ const kError = Symbol('error');
7079
+
7080
+ //
7081
+ // We limit zlib concurrency, which prevents severe memory fragmentation
7082
+ // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
7083
+ // and https://github.com/websockets/ws/issues/1202
7084
+ //
7085
+ // Intentionally global; it's the global thread pool that's an issue.
7086
+ //
7087
+ let zlibLimiter;
7088
+
7089
+ /**
7090
+ * permessage-deflate implementation.
7091
+ */
7092
+ class PerMessageDeflate {
7093
+ /**
7094
+ * Creates a PerMessageDeflate instance.
7095
+ *
7096
+ * @param {Object} [options] Configuration options
7097
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
7098
+ * for, or request, a custom client window size
7099
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
7100
+ * acknowledge disabling of client context takeover
7101
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
7102
+ * calls to zlib
7103
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
7104
+ * use of a custom server window size
7105
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
7106
+ * disabling of server context takeover
7107
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
7108
+ * messages should not be compressed if context takeover is disabled
7109
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
7110
+ * deflate
7111
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
7112
+ * inflate
7113
+ * @param {Boolean} [isServer=false] Create the instance in either server or
7114
+ * client mode
7115
+ * @param {Number} [maxPayload=0] The maximum allowed message length
7116
+ */
7117
+ constructor(options, isServer, maxPayload) {
7118
+ this._maxPayload = maxPayload | 0;
7119
+ this._options = options || {};
7120
+ this._threshold =
7121
+ this._options.threshold !== undefined ? this._options.threshold : 1024;
7122
+ this._isServer = !!isServer;
7123
+ this._deflate = null;
7124
+ this._inflate = null;
7125
+
7126
+ this.params = null;
7127
+
7128
+ if (!zlibLimiter) {
7129
+ const concurrency =
7130
+ this._options.concurrencyLimit !== undefined
7131
+ ? this._options.concurrencyLimit
7132
+ : 10;
7133
+ zlibLimiter = new Limiter(concurrency);
7134
+ }
7135
+ }
7136
+
7137
+ /**
7138
+ * @type {String}
7139
+ */
7140
+ static get extensionName() {
7141
+ return 'permessage-deflate';
7142
+ }
7143
+
7144
+ /**
7145
+ * Create an extension negotiation offer.
7146
+ *
7147
+ * @return {Object} Extension parameters
7148
+ * @public
7149
+ */
7150
+ offer() {
7151
+ const params = {};
7152
+
7153
+ if (this._options.serverNoContextTakeover) {
7154
+ params.server_no_context_takeover = true;
7155
+ }
7156
+ if (this._options.clientNoContextTakeover) {
7157
+ params.client_no_context_takeover = true;
7158
+ }
7159
+ if (this._options.serverMaxWindowBits) {
7160
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
7161
+ }
7162
+ if (this._options.clientMaxWindowBits) {
7163
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
7164
+ } else if (this._options.clientMaxWindowBits == null) {
7165
+ params.client_max_window_bits = true;
7166
+ }
7167
+
7168
+ return params;
7169
+ }
7170
+
7171
+ /**
7172
+ * Accept an extension negotiation offer/response.
7173
+ *
7174
+ * @param {Array} configurations The extension negotiation offers/reponse
7175
+ * @return {Object} Accepted configuration
7176
+ * @public
7177
+ */
7178
+ accept(configurations) {
7179
+ configurations = this.normalizeParams(configurations);
7180
+
7181
+ this.params = this._isServer
7182
+ ? this.acceptAsServer(configurations)
7183
+ : this.acceptAsClient(configurations);
7184
+
7185
+ return this.params;
7186
+ }
7187
+
7188
+ /**
7189
+ * Releases all resources used by the extension.
7190
+ *
7191
+ * @public
7192
+ */
7193
+ cleanup() {
7194
+ if (this._inflate) {
7195
+ this._inflate.close();
7196
+ this._inflate = null;
7197
+ }
7198
+
7199
+ if (this._deflate) {
7200
+ const callback = this._deflate[kCallback];
7201
+
7202
+ this._deflate.close();
7203
+ this._deflate = null;
7204
+
7205
+ if (callback) {
7206
+ callback(
7207
+ new Error(
7208
+ 'The deflate stream was closed while data was being processed'
7209
+ )
7210
+ );
7211
+ }
7212
+ }
7213
+ }
7214
+
7215
+ /**
7216
+ * Accept an extension negotiation offer.
7217
+ *
7218
+ * @param {Array} offers The extension negotiation offers
7219
+ * @return {Object} Accepted configuration
7220
+ * @private
7221
+ */
7222
+ acceptAsServer(offers) {
7223
+ const opts = this._options;
7224
+ const accepted = offers.find((params) => {
7225
+ if (
7226
+ (opts.serverNoContextTakeover === false &&
7227
+ params.server_no_context_takeover) ||
7228
+ (params.server_max_window_bits &&
7229
+ (opts.serverMaxWindowBits === false ||
7230
+ (typeof opts.serverMaxWindowBits === 'number' &&
7231
+ opts.serverMaxWindowBits > params.server_max_window_bits))) ||
7232
+ (typeof opts.clientMaxWindowBits === 'number' &&
7233
+ !params.client_max_window_bits)
7234
+ ) {
7235
+ return false;
7236
+ }
7237
+
7238
+ return true;
7239
+ });
7240
+
7241
+ if (!accepted) {
7242
+ throw new Error('None of the extension offers can be accepted');
7243
+ }
7244
+
7245
+ if (opts.serverNoContextTakeover) {
7246
+ accepted.server_no_context_takeover = true;
7247
+ }
7248
+ if (opts.clientNoContextTakeover) {
7249
+ accepted.client_no_context_takeover = true;
7250
+ }
7251
+ if (typeof opts.serverMaxWindowBits === 'number') {
7252
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
7253
+ }
7254
+ if (typeof opts.clientMaxWindowBits === 'number') {
7255
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
7256
+ } else if (
7257
+ accepted.client_max_window_bits === true ||
7258
+ opts.clientMaxWindowBits === false
7259
+ ) {
7260
+ delete accepted.client_max_window_bits;
7261
+ }
7262
+
7263
+ return accepted;
7264
+ }
7265
+
7266
+ /**
7267
+ * Accept the extension negotiation response.
7268
+ *
7269
+ * @param {Array} response The extension negotiation response
7270
+ * @return {Object} Accepted configuration
7271
+ * @private
7272
+ */
7273
+ acceptAsClient(response) {
7274
+ const params = response[0];
7275
+
7276
+ if (
7277
+ this._options.clientNoContextTakeover === false &&
7278
+ params.client_no_context_takeover
7279
+ ) {
7280
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
7281
+ }
7282
+
7283
+ if (!params.client_max_window_bits) {
7284
+ if (typeof this._options.clientMaxWindowBits === 'number') {
7285
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
7286
+ }
7287
+ } else if (
7288
+ this._options.clientMaxWindowBits === false ||
7289
+ (typeof this._options.clientMaxWindowBits === 'number' &&
7290
+ params.client_max_window_bits > this._options.clientMaxWindowBits)
7291
+ ) {
7292
+ throw new Error(
7293
+ 'Unexpected or invalid parameter "client_max_window_bits"'
7294
+ );
7295
+ }
7296
+
7297
+ return params;
7298
+ }
7299
+
7300
+ /**
7301
+ * Normalize parameters.
7302
+ *
7303
+ * @param {Array} configurations The extension negotiation offers/reponse
7304
+ * @return {Array} The offers/response with normalized parameters
7305
+ * @private
7306
+ */
7307
+ normalizeParams(configurations) {
7308
+ configurations.forEach((params) => {
7309
+ Object.keys(params).forEach((key) => {
7310
+ let value = params[key];
7311
+
7312
+ if (value.length > 1) {
7313
+ throw new Error(`Parameter "${key}" must have only a single value`);
7314
+ }
7315
+
7316
+ value = value[0];
7317
+
7318
+ if (key === 'client_max_window_bits') {
7319
+ if (value !== true) {
7320
+ const num = +value;
7321
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
7322
+ throw new TypeError(
7323
+ `Invalid value for parameter "${key}": ${value}`
7324
+ );
7325
+ }
7326
+ value = num;
7327
+ } else if (!this._isServer) {
7328
+ throw new TypeError(
7329
+ `Invalid value for parameter "${key}": ${value}`
7330
+ );
7331
+ }
7332
+ } else if (key === 'server_max_window_bits') {
7333
+ const num = +value;
7334
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
7335
+ throw new TypeError(
7336
+ `Invalid value for parameter "${key}": ${value}`
7337
+ );
7338
+ }
7339
+ value = num;
7340
+ } else if (
7341
+ key === 'client_no_context_takeover' ||
7342
+ key === 'server_no_context_takeover'
7343
+ ) {
7344
+ if (value !== true) {
7345
+ throw new TypeError(
7346
+ `Invalid value for parameter "${key}": ${value}`
7347
+ );
7348
+ }
7349
+ } else {
7350
+ throw new Error(`Unknown parameter "${key}"`);
7351
+ }
7352
+
7353
+ params[key] = value;
7354
+ });
7355
+ });
7356
+
7357
+ return configurations;
7358
+ }
7359
+
7360
+ /**
7361
+ * Decompress data. Concurrency limited.
7362
+ *
7363
+ * @param {Buffer} data Compressed data
7364
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
7365
+ * @param {Function} callback Callback
7366
+ * @public
7367
+ */
7368
+ decompress(data, fin, callback) {
7369
+ zlibLimiter.add((done) => {
7370
+ this._decompress(data, fin, (err, result) => {
7371
+ done();
7372
+ callback(err, result);
7373
+ });
7374
+ });
7375
+ }
7376
+
7377
+ /**
7378
+ * Compress data. Concurrency limited.
7379
+ *
7380
+ * @param {(Buffer|String)} data Data to compress
7381
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
7382
+ * @param {Function} callback Callback
7383
+ * @public
7384
+ */
7385
+ compress(data, fin, callback) {
7386
+ zlibLimiter.add((done) => {
7387
+ this._compress(data, fin, (err, result) => {
7388
+ done();
7389
+ callback(err, result);
7390
+ });
7391
+ });
7392
+ }
7393
+
7394
+ /**
7395
+ * Decompress data.
7396
+ *
7397
+ * @param {Buffer} data Compressed data
7398
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
7399
+ * @param {Function} callback Callback
7400
+ * @private
7401
+ */
7402
+ _decompress(data, fin, callback) {
7403
+ const endpoint = this._isServer ? 'client' : 'server';
7404
+
7405
+ if (!this._inflate) {
7406
+ const key = `${endpoint}_max_window_bits`;
7407
+ const windowBits =
7408
+ typeof this.params[key] !== 'number'
7409
+ ? zlib.Z_DEFAULT_WINDOWBITS
7410
+ : this.params[key];
7411
+
7412
+ this._inflate = zlib.createInflateRaw({
7413
+ ...this._options.zlibInflateOptions,
7414
+ windowBits
7415
+ });
7416
+ this._inflate[kPerMessageDeflate] = this;
7417
+ this._inflate[kTotalLength] = 0;
7418
+ this._inflate[kBuffers] = [];
7419
+ this._inflate.on('error', inflateOnError);
7420
+ this._inflate.on('data', inflateOnData);
7421
+ }
7422
+
7423
+ this._inflate[kCallback] = callback;
7424
+
7425
+ this._inflate.write(data);
7426
+ if (fin) this._inflate.write(TRAILER);
7427
+
7428
+ this._inflate.flush(() => {
7429
+ const err = this._inflate[kError];
7430
+
7431
+ if (err) {
7432
+ this._inflate.close();
7433
+ this._inflate = null;
7434
+ callback(err);
7435
+ return;
7436
+ }
7437
+
7438
+ const data = bufferUtil.concat(
7439
+ this._inflate[kBuffers],
7440
+ this._inflate[kTotalLength]
7441
+ );
7442
+
7443
+ if (this._inflate._readableState.endEmitted) {
7444
+ this._inflate.close();
7445
+ this._inflate = null;
7446
+ } else {
7447
+ this._inflate[kTotalLength] = 0;
7448
+ this._inflate[kBuffers] = [];
7449
+
7450
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
7451
+ this._inflate.reset();
7452
+ }
7453
+ }
7454
+
7455
+ callback(null, data);
7456
+ });
7457
+ }
7458
+
7459
+ /**
7460
+ * Compress data.
7461
+ *
7462
+ * @param {(Buffer|String)} data Data to compress
7463
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
7464
+ * @param {Function} callback Callback
7465
+ * @private
7466
+ */
7467
+ _compress(data, fin, callback) {
7468
+ const endpoint = this._isServer ? 'server' : 'client';
7469
+
7470
+ if (!this._deflate) {
7471
+ const key = `${endpoint}_max_window_bits`;
7472
+ const windowBits =
7473
+ typeof this.params[key] !== 'number'
7474
+ ? zlib.Z_DEFAULT_WINDOWBITS
7475
+ : this.params[key];
7476
+
7477
+ this._deflate = zlib.createDeflateRaw({
7478
+ ...this._options.zlibDeflateOptions,
7479
+ windowBits
7480
+ });
7481
+
7482
+ this._deflate[kTotalLength] = 0;
7483
+ this._deflate[kBuffers] = [];
7484
+
7485
+ this._deflate.on('data', deflateOnData);
7486
+ }
7487
+
7488
+ this._deflate[kCallback] = callback;
7489
+
7490
+ this._deflate.write(data);
7491
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
7492
+ if (!this._deflate) {
7493
+ //
7494
+ // The deflate stream was closed while data was being processed.
7495
+ //
7496
+ return;
7497
+ }
7498
+
7499
+ let data = bufferUtil.concat(
7500
+ this._deflate[kBuffers],
7501
+ this._deflate[kTotalLength]
7502
+ );
7503
+
7504
+ if (fin) {
7505
+ data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
7506
+ }
7507
+
7508
+ //
7509
+ // Ensure that the callback will not be called again in
7510
+ // `PerMessageDeflate#cleanup()`.
7511
+ //
7512
+ this._deflate[kCallback] = null;
7513
+
7514
+ this._deflate[kTotalLength] = 0;
7515
+ this._deflate[kBuffers] = [];
7516
+
7517
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
7518
+ this._deflate.reset();
7519
+ }
7520
+
7521
+ callback(null, data);
7522
+ });
7523
+ }
7524
+ }
7525
+
7526
+ permessageDeflate = PerMessageDeflate;
7527
+
7528
+ /**
7529
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
7530
+ *
7531
+ * @param {Buffer} chunk A chunk of data
7532
+ * @private
7533
+ */
7534
+ function deflateOnData(chunk) {
7535
+ this[kBuffers].push(chunk);
7536
+ this[kTotalLength] += chunk.length;
7537
+ }
7538
+
7539
+ /**
7540
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
7541
+ *
7542
+ * @param {Buffer} chunk A chunk of data
7543
+ * @private
7544
+ */
7545
+ function inflateOnData(chunk) {
7546
+ this[kTotalLength] += chunk.length;
7547
+
7548
+ if (
7549
+ this[kPerMessageDeflate]._maxPayload < 1 ||
7550
+ this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
7551
+ ) {
7552
+ this[kBuffers].push(chunk);
7553
+ return;
7554
+ }
7555
+
7556
+ this[kError] = new RangeError('Max payload size exceeded');
7557
+ this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
7558
+ this[kError][kStatusCode] = 1009;
7559
+ this.removeListener('data', inflateOnData);
7560
+ this.reset();
7561
+ }
7562
+
7563
+ /**
7564
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
7565
+ *
7566
+ * @param {Error} err The emitted error
7567
+ * @private
7568
+ */
7569
+ function inflateOnError(err) {
7570
+ //
7571
+ // There is no need to call `Zlib#close()` as the handle is automatically
7572
+ // closed when an error is emitted.
7573
+ //
7574
+ this[kPerMessageDeflate]._inflate = null;
7575
+ err[kStatusCode] = 1007;
7576
+ this[kCallback](err);
7577
+ }
7578
+ return permessageDeflate;
7579
+ }
7580
+
7581
+ var validation = {exports: {}};
7582
+
7583
+ var hasRequiredValidation;
7584
+
7585
+ function requireValidation () {
7586
+ if (hasRequiredValidation) return validation.exports;
7587
+ hasRequiredValidation = 1;
7588
+
7589
+ const { isUtf8 } = require$$0$1;
7590
+
7591
+ const { hasBlob } = requireConstants();
7592
+
7593
+ //
7594
+ // Allowed token characters:
7595
+ //
7596
+ // '!', '#', '$', '%', '&', ''', '*', '+', '-',
7597
+ // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
7598
+ //
7599
+ // tokenChars[32] === 0 // ' '
7600
+ // tokenChars[33] === 1 // '!'
7601
+ // tokenChars[34] === 0 // '"'
7602
+ // ...
7603
+ //
7604
+ // prettier-ignore
7605
+ const tokenChars = [
7606
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
7607
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
7608
+ 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
7609
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
7610
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
7611
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
7612
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
7613
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
7614
+ ];
7615
+
7616
+ /**
7617
+ * Checks if a status code is allowed in a close frame.
7618
+ *
7619
+ * @param {Number} code The status code
7620
+ * @return {Boolean} `true` if the status code is valid, else `false`
7621
+ * @public
7622
+ */
7623
+ function isValidStatusCode(code) {
7624
+ return (
7625
+ (code >= 1000 &&
7626
+ code <= 1014 &&
7627
+ code !== 1004 &&
7628
+ code !== 1005 &&
7629
+ code !== 1006) ||
7630
+ (code >= 3000 && code <= 4999)
7631
+ );
7632
+ }
7633
+
7634
+ /**
7635
+ * Checks if a given buffer contains only correct UTF-8.
7636
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
7637
+ * Markus Kuhn.
7638
+ *
7639
+ * @param {Buffer} buf The buffer to check
7640
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
7641
+ * @public
7642
+ */
7643
+ function _isValidUTF8(buf) {
7644
+ const len = buf.length;
7645
+ let i = 0;
7646
+
7647
+ while (i < len) {
7648
+ if ((buf[i] & 0x80) === 0) {
7649
+ // 0xxxxxxx
7650
+ i++;
7651
+ } else if ((buf[i] & 0xe0) === 0xc0) {
7652
+ // 110xxxxx 10xxxxxx
7653
+ if (
7654
+ i + 1 === len ||
7655
+ (buf[i + 1] & 0xc0) !== 0x80 ||
7656
+ (buf[i] & 0xfe) === 0xc0 // Overlong
7657
+ ) {
7658
+ return false;
7659
+ }
7660
+
7661
+ i += 2;
7662
+ } else if ((buf[i] & 0xf0) === 0xe0) {
7663
+ // 1110xxxx 10xxxxxx 10xxxxxx
7664
+ if (
7665
+ i + 2 >= len ||
7666
+ (buf[i + 1] & 0xc0) !== 0x80 ||
7667
+ (buf[i + 2] & 0xc0) !== 0x80 ||
7668
+ (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
7669
+ (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
7670
+ ) {
7671
+ return false;
7672
+ }
7673
+
7674
+ i += 3;
7675
+ } else if ((buf[i] & 0xf8) === 0xf0) {
7676
+ // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
7677
+ if (
7678
+ i + 3 >= len ||
7679
+ (buf[i + 1] & 0xc0) !== 0x80 ||
7680
+ (buf[i + 2] & 0xc0) !== 0x80 ||
7681
+ (buf[i + 3] & 0xc0) !== 0x80 ||
7682
+ (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
7683
+ (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
7684
+ buf[i] > 0xf4 // > U+10FFFF
7685
+ ) {
7686
+ return false;
7687
+ }
7688
+
7689
+ i += 4;
7690
+ } else {
7691
+ return false;
7692
+ }
7693
+ }
6826
7694
 
6827
- function requireBrowser () {
6828
- if (hasRequiredBrowser) return browser;
6829
- hasRequiredBrowser = 1;
7695
+ return true;
7696
+ }
6830
7697
 
6831
- browser = function () {
6832
- throw new Error(
6833
- 'ws does not work in the browser. Browser clients must use the native ' +
6834
- 'WebSocket object'
7698
+ /**
7699
+ * Determines whether a value is a `Blob`.
7700
+ *
7701
+ * @param {*} value The value to be tested
7702
+ * @return {Boolean} `true` if `value` is a `Blob`, else `false`
7703
+ * @private
7704
+ */
7705
+ function isBlob(value) {
7706
+ return (
7707
+ hasBlob &&
7708
+ typeof value === 'object' &&
7709
+ typeof value.arrayBuffer === 'function' &&
7710
+ typeof value.type === 'string' &&
7711
+ typeof value.stream === 'function' &&
7712
+ (value[Symbol.toStringTag] === 'Blob' ||
7713
+ value[Symbol.toStringTag] === 'File')
6835
7714
  );
7715
+ }
7716
+
7717
+ validation.exports = {
7718
+ isBlob,
7719
+ isValidStatusCode,
7720
+ isValidUTF8: _isValidUTF8,
7721
+ tokenChars
6836
7722
  };
6837
- return browser;
7723
+
7724
+ if (isUtf8) {
7725
+ validation.exports.isValidUTF8 = function (buf) {
7726
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
7727
+ };
7728
+ }
7729
+ return validation.exports;
7730
+ }
7731
+
7732
+ var receiver;
7733
+ var hasRequiredReceiver;
7734
+
7735
+ function requireReceiver () {
7736
+ if (hasRequiredReceiver) return receiver;
7737
+ hasRequiredReceiver = 1;
7738
+
7739
+ const { Writable } = require$$0$2;
7740
+
7741
+ const PerMessageDeflate = requirePermessageDeflate();
7742
+ const {
7743
+ BINARY_TYPES,
7744
+ EMPTY_BUFFER,
7745
+ kStatusCode,
7746
+ kWebSocket
7747
+ } = requireConstants();
7748
+ const { concat, toArrayBuffer, unmask } = requireBufferUtil();
7749
+ const { isValidStatusCode, isValidUTF8 } = requireValidation();
7750
+
7751
+ const FastBuffer = Buffer[Symbol.species];
7752
+
7753
+ const GET_INFO = 0;
7754
+ const GET_PAYLOAD_LENGTH_16 = 1;
7755
+ const GET_PAYLOAD_LENGTH_64 = 2;
7756
+ const GET_MASK = 3;
7757
+ const GET_DATA = 4;
7758
+ const INFLATING = 5;
7759
+ const DEFER_EVENT = 6;
7760
+
7761
+ /**
7762
+ * HyBi Receiver implementation.
7763
+ *
7764
+ * @extends Writable
7765
+ */
7766
+ class Receiver extends Writable {
7767
+ /**
7768
+ * Creates a Receiver instance.
7769
+ *
7770
+ * @param {Object} [options] Options object
7771
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
7772
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
7773
+ * multiple times in the same tick
7774
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
7775
+ * @param {Object} [options.extensions] An object containing the negotiated
7776
+ * extensions
7777
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
7778
+ * client or server mode
7779
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
7780
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
7781
+ * not to skip UTF-8 validation for text and close messages
7782
+ */
7783
+ constructor(options = {}) {
7784
+ super();
7785
+
7786
+ this._allowSynchronousEvents =
7787
+ options.allowSynchronousEvents !== undefined
7788
+ ? options.allowSynchronousEvents
7789
+ : true;
7790
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
7791
+ this._extensions = options.extensions || {};
7792
+ this._isServer = !!options.isServer;
7793
+ this._maxPayload = options.maxPayload | 0;
7794
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
7795
+ this[kWebSocket] = undefined;
7796
+
7797
+ this._bufferedBytes = 0;
7798
+ this._buffers = [];
7799
+
7800
+ this._compressed = false;
7801
+ this._payloadLength = 0;
7802
+ this._mask = undefined;
7803
+ this._fragmented = 0;
7804
+ this._masked = false;
7805
+ this._fin = false;
7806
+ this._opcode = 0;
7807
+
7808
+ this._totalPayloadLength = 0;
7809
+ this._messageLength = 0;
7810
+ this._fragments = [];
7811
+
7812
+ this._errored = false;
7813
+ this._loop = false;
7814
+ this._state = GET_INFO;
7815
+ }
7816
+
7817
+ /**
7818
+ * Implements `Writable.prototype._write()`.
7819
+ *
7820
+ * @param {Buffer} chunk The chunk of data to write
7821
+ * @param {String} encoding The character encoding of `chunk`
7822
+ * @param {Function} cb Callback
7823
+ * @private
7824
+ */
7825
+ _write(chunk, encoding, cb) {
7826
+ if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
7827
+
7828
+ this._bufferedBytes += chunk.length;
7829
+ this._buffers.push(chunk);
7830
+ this.startLoop(cb);
7831
+ }
7832
+
7833
+ /**
7834
+ * Consumes `n` bytes from the buffered data.
7835
+ *
7836
+ * @param {Number} n The number of bytes to consume
7837
+ * @return {Buffer} The consumed bytes
7838
+ * @private
7839
+ */
7840
+ consume(n) {
7841
+ this._bufferedBytes -= n;
7842
+
7843
+ if (n === this._buffers[0].length) return this._buffers.shift();
7844
+
7845
+ if (n < this._buffers[0].length) {
7846
+ const buf = this._buffers[0];
7847
+ this._buffers[0] = new FastBuffer(
7848
+ buf.buffer,
7849
+ buf.byteOffset + n,
7850
+ buf.length - n
7851
+ );
7852
+
7853
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
7854
+ }
7855
+
7856
+ const dst = Buffer.allocUnsafe(n);
7857
+
7858
+ do {
7859
+ const buf = this._buffers[0];
7860
+ const offset = dst.length - n;
7861
+
7862
+ if (n >= buf.length) {
7863
+ dst.set(this._buffers.shift(), offset);
7864
+ } else {
7865
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
7866
+ this._buffers[0] = new FastBuffer(
7867
+ buf.buffer,
7868
+ buf.byteOffset + n,
7869
+ buf.length - n
7870
+ );
7871
+ }
7872
+
7873
+ n -= buf.length;
7874
+ } while (n > 0);
7875
+
7876
+ return dst;
7877
+ }
7878
+
7879
+ /**
7880
+ * Starts the parsing loop.
7881
+ *
7882
+ * @param {Function} cb Callback
7883
+ * @private
7884
+ */
7885
+ startLoop(cb) {
7886
+ this._loop = true;
7887
+
7888
+ do {
7889
+ switch (this._state) {
7890
+ case GET_INFO:
7891
+ this.getInfo(cb);
7892
+ break;
7893
+ case GET_PAYLOAD_LENGTH_16:
7894
+ this.getPayloadLength16(cb);
7895
+ break;
7896
+ case GET_PAYLOAD_LENGTH_64:
7897
+ this.getPayloadLength64(cb);
7898
+ break;
7899
+ case GET_MASK:
7900
+ this.getMask();
7901
+ break;
7902
+ case GET_DATA:
7903
+ this.getData(cb);
7904
+ break;
7905
+ case INFLATING:
7906
+ case DEFER_EVENT:
7907
+ this._loop = false;
7908
+ return;
7909
+ }
7910
+ } while (this._loop);
7911
+
7912
+ if (!this._errored) cb();
7913
+ }
7914
+
7915
+ /**
7916
+ * Reads the first two bytes of a frame.
7917
+ *
7918
+ * @param {Function} cb Callback
7919
+ * @private
7920
+ */
7921
+ getInfo(cb) {
7922
+ if (this._bufferedBytes < 2) {
7923
+ this._loop = false;
7924
+ return;
7925
+ }
7926
+
7927
+ const buf = this.consume(2);
7928
+
7929
+ if ((buf[0] & 0x30) !== 0x00) {
7930
+ const error = this.createError(
7931
+ RangeError,
7932
+ 'RSV2 and RSV3 must be clear',
7933
+ true,
7934
+ 1002,
7935
+ 'WS_ERR_UNEXPECTED_RSV_2_3'
7936
+ );
7937
+
7938
+ cb(error);
7939
+ return;
7940
+ }
7941
+
7942
+ const compressed = (buf[0] & 0x40) === 0x40;
7943
+
7944
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
7945
+ const error = this.createError(
7946
+ RangeError,
7947
+ 'RSV1 must be clear',
7948
+ true,
7949
+ 1002,
7950
+ 'WS_ERR_UNEXPECTED_RSV_1'
7951
+ );
7952
+
7953
+ cb(error);
7954
+ return;
7955
+ }
7956
+
7957
+ this._fin = (buf[0] & 0x80) === 0x80;
7958
+ this._opcode = buf[0] & 0x0f;
7959
+ this._payloadLength = buf[1] & 0x7f;
7960
+
7961
+ if (this._opcode === 0x00) {
7962
+ if (compressed) {
7963
+ const error = this.createError(
7964
+ RangeError,
7965
+ 'RSV1 must be clear',
7966
+ true,
7967
+ 1002,
7968
+ 'WS_ERR_UNEXPECTED_RSV_1'
7969
+ );
7970
+
7971
+ cb(error);
7972
+ return;
7973
+ }
7974
+
7975
+ if (!this._fragmented) {
7976
+ const error = this.createError(
7977
+ RangeError,
7978
+ 'invalid opcode 0',
7979
+ true,
7980
+ 1002,
7981
+ 'WS_ERR_INVALID_OPCODE'
7982
+ );
7983
+
7984
+ cb(error);
7985
+ return;
7986
+ }
7987
+
7988
+ this._opcode = this._fragmented;
7989
+ } else if (this._opcode === 0x01 || this._opcode === 0x02) {
7990
+ if (this._fragmented) {
7991
+ const error = this.createError(
7992
+ RangeError,
7993
+ `invalid opcode ${this._opcode}`,
7994
+ true,
7995
+ 1002,
7996
+ 'WS_ERR_INVALID_OPCODE'
7997
+ );
7998
+
7999
+ cb(error);
8000
+ return;
8001
+ }
8002
+
8003
+ this._compressed = compressed;
8004
+ } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
8005
+ if (!this._fin) {
8006
+ const error = this.createError(
8007
+ RangeError,
8008
+ 'FIN must be set',
8009
+ true,
8010
+ 1002,
8011
+ 'WS_ERR_EXPECTED_FIN'
8012
+ );
8013
+
8014
+ cb(error);
8015
+ return;
8016
+ }
8017
+
8018
+ if (compressed) {
8019
+ const error = this.createError(
8020
+ RangeError,
8021
+ 'RSV1 must be clear',
8022
+ true,
8023
+ 1002,
8024
+ 'WS_ERR_UNEXPECTED_RSV_1'
8025
+ );
8026
+
8027
+ cb(error);
8028
+ return;
8029
+ }
8030
+
8031
+ if (
8032
+ this._payloadLength > 0x7d ||
8033
+ (this._opcode === 0x08 && this._payloadLength === 1)
8034
+ ) {
8035
+ const error = this.createError(
8036
+ RangeError,
8037
+ `invalid payload length ${this._payloadLength}`,
8038
+ true,
8039
+ 1002,
8040
+ 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
8041
+ );
8042
+
8043
+ cb(error);
8044
+ return;
8045
+ }
8046
+ } else {
8047
+ const error = this.createError(
8048
+ RangeError,
8049
+ `invalid opcode ${this._opcode}`,
8050
+ true,
8051
+ 1002,
8052
+ 'WS_ERR_INVALID_OPCODE'
8053
+ );
8054
+
8055
+ cb(error);
8056
+ return;
8057
+ }
8058
+
8059
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
8060
+ this._masked = (buf[1] & 0x80) === 0x80;
8061
+
8062
+ if (this._isServer) {
8063
+ if (!this._masked) {
8064
+ const error = this.createError(
8065
+ RangeError,
8066
+ 'MASK must be set',
8067
+ true,
8068
+ 1002,
8069
+ 'WS_ERR_EXPECTED_MASK'
8070
+ );
8071
+
8072
+ cb(error);
8073
+ return;
8074
+ }
8075
+ } else if (this._masked) {
8076
+ const error = this.createError(
8077
+ RangeError,
8078
+ 'MASK must be clear',
8079
+ true,
8080
+ 1002,
8081
+ 'WS_ERR_UNEXPECTED_MASK'
8082
+ );
8083
+
8084
+ cb(error);
8085
+ return;
8086
+ }
8087
+
8088
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
8089
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
8090
+ else this.haveLength(cb);
8091
+ }
8092
+
8093
+ /**
8094
+ * Gets extended payload length (7+16).
8095
+ *
8096
+ * @param {Function} cb Callback
8097
+ * @private
8098
+ */
8099
+ getPayloadLength16(cb) {
8100
+ if (this._bufferedBytes < 2) {
8101
+ this._loop = false;
8102
+ return;
8103
+ }
8104
+
8105
+ this._payloadLength = this.consume(2).readUInt16BE(0);
8106
+ this.haveLength(cb);
8107
+ }
8108
+
8109
+ /**
8110
+ * Gets extended payload length (7+64).
8111
+ *
8112
+ * @param {Function} cb Callback
8113
+ * @private
8114
+ */
8115
+ getPayloadLength64(cb) {
8116
+ if (this._bufferedBytes < 8) {
8117
+ this._loop = false;
8118
+ return;
8119
+ }
8120
+
8121
+ const buf = this.consume(8);
8122
+ const num = buf.readUInt32BE(0);
8123
+
8124
+ //
8125
+ // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
8126
+ // if payload length is greater than this number.
8127
+ //
8128
+ if (num > Math.pow(2, 53 - 32) - 1) {
8129
+ const error = this.createError(
8130
+ RangeError,
8131
+ 'Unsupported WebSocket frame: payload length > 2^53 - 1',
8132
+ false,
8133
+ 1009,
8134
+ 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
8135
+ );
8136
+
8137
+ cb(error);
8138
+ return;
8139
+ }
8140
+
8141
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
8142
+ this.haveLength(cb);
8143
+ }
8144
+
8145
+ /**
8146
+ * Payload length has been read.
8147
+ *
8148
+ * @param {Function} cb Callback
8149
+ * @private
8150
+ */
8151
+ haveLength(cb) {
8152
+ if (this._payloadLength && this._opcode < 0x08) {
8153
+ this._totalPayloadLength += this._payloadLength;
8154
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
8155
+ const error = this.createError(
8156
+ RangeError,
8157
+ 'Max payload size exceeded',
8158
+ false,
8159
+ 1009,
8160
+ 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
8161
+ );
8162
+
8163
+ cb(error);
8164
+ return;
8165
+ }
8166
+ }
8167
+
8168
+ if (this._masked) this._state = GET_MASK;
8169
+ else this._state = GET_DATA;
8170
+ }
8171
+
8172
+ /**
8173
+ * Reads mask bytes.
8174
+ *
8175
+ * @private
8176
+ */
8177
+ getMask() {
8178
+ if (this._bufferedBytes < 4) {
8179
+ this._loop = false;
8180
+ return;
8181
+ }
8182
+
8183
+ this._mask = this.consume(4);
8184
+ this._state = GET_DATA;
8185
+ }
8186
+
8187
+ /**
8188
+ * Reads data bytes.
8189
+ *
8190
+ * @param {Function} cb Callback
8191
+ * @private
8192
+ */
8193
+ getData(cb) {
8194
+ let data = EMPTY_BUFFER;
8195
+
8196
+ if (this._payloadLength) {
8197
+ if (this._bufferedBytes < this._payloadLength) {
8198
+ this._loop = false;
8199
+ return;
8200
+ }
8201
+
8202
+ data = this.consume(this._payloadLength);
8203
+
8204
+ if (
8205
+ this._masked &&
8206
+ (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
8207
+ ) {
8208
+ unmask(data, this._mask);
8209
+ }
8210
+ }
8211
+
8212
+ if (this._opcode > 0x07) {
8213
+ this.controlMessage(data, cb);
8214
+ return;
8215
+ }
8216
+
8217
+ if (this._compressed) {
8218
+ this._state = INFLATING;
8219
+ this.decompress(data, cb);
8220
+ return;
8221
+ }
8222
+
8223
+ if (data.length) {
8224
+ //
8225
+ // This message is not compressed so its length is the sum of the payload
8226
+ // length of all fragments.
8227
+ //
8228
+ this._messageLength = this._totalPayloadLength;
8229
+ this._fragments.push(data);
8230
+ }
8231
+
8232
+ this.dataMessage(cb);
8233
+ }
8234
+
8235
+ /**
8236
+ * Decompresses data.
8237
+ *
8238
+ * @param {Buffer} data Compressed data
8239
+ * @param {Function} cb Callback
8240
+ * @private
8241
+ */
8242
+ decompress(data, cb) {
8243
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
8244
+
8245
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
8246
+ if (err) return cb(err);
8247
+
8248
+ if (buf.length) {
8249
+ this._messageLength += buf.length;
8250
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
8251
+ const error = this.createError(
8252
+ RangeError,
8253
+ 'Max payload size exceeded',
8254
+ false,
8255
+ 1009,
8256
+ 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
8257
+ );
8258
+
8259
+ cb(error);
8260
+ return;
8261
+ }
8262
+
8263
+ this._fragments.push(buf);
8264
+ }
8265
+
8266
+ this.dataMessage(cb);
8267
+ if (this._state === GET_INFO) this.startLoop(cb);
8268
+ });
8269
+ }
8270
+
8271
+ /**
8272
+ * Handles a data message.
8273
+ *
8274
+ * @param {Function} cb Callback
8275
+ * @private
8276
+ */
8277
+ dataMessage(cb) {
8278
+ if (!this._fin) {
8279
+ this._state = GET_INFO;
8280
+ return;
8281
+ }
8282
+
8283
+ const messageLength = this._messageLength;
8284
+ const fragments = this._fragments;
8285
+
8286
+ this._totalPayloadLength = 0;
8287
+ this._messageLength = 0;
8288
+ this._fragmented = 0;
8289
+ this._fragments = [];
8290
+
8291
+ if (this._opcode === 2) {
8292
+ let data;
8293
+
8294
+ if (this._binaryType === 'nodebuffer') {
8295
+ data = concat(fragments, messageLength);
8296
+ } else if (this._binaryType === 'arraybuffer') {
8297
+ data = toArrayBuffer(concat(fragments, messageLength));
8298
+ } else if (this._binaryType === 'blob') {
8299
+ data = new Blob(fragments);
8300
+ } else {
8301
+ data = fragments;
8302
+ }
8303
+
8304
+ if (this._allowSynchronousEvents) {
8305
+ this.emit('message', data, true);
8306
+ this._state = GET_INFO;
8307
+ } else {
8308
+ this._state = DEFER_EVENT;
8309
+ setImmediate(() => {
8310
+ this.emit('message', data, true);
8311
+ this._state = GET_INFO;
8312
+ this.startLoop(cb);
8313
+ });
8314
+ }
8315
+ } else {
8316
+ const buf = concat(fragments, messageLength);
8317
+
8318
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
8319
+ const error = this.createError(
8320
+ Error,
8321
+ 'invalid UTF-8 sequence',
8322
+ true,
8323
+ 1007,
8324
+ 'WS_ERR_INVALID_UTF8'
8325
+ );
8326
+
8327
+ cb(error);
8328
+ return;
8329
+ }
8330
+
8331
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
8332
+ this.emit('message', buf, false);
8333
+ this._state = GET_INFO;
8334
+ } else {
8335
+ this._state = DEFER_EVENT;
8336
+ setImmediate(() => {
8337
+ this.emit('message', buf, false);
8338
+ this._state = GET_INFO;
8339
+ this.startLoop(cb);
8340
+ });
8341
+ }
8342
+ }
8343
+ }
8344
+
8345
+ /**
8346
+ * Handles a control message.
8347
+ *
8348
+ * @param {Buffer} data Data to handle
8349
+ * @return {(Error|RangeError|undefined)} A possible error
8350
+ * @private
8351
+ */
8352
+ controlMessage(data, cb) {
8353
+ if (this._opcode === 0x08) {
8354
+ if (data.length === 0) {
8355
+ this._loop = false;
8356
+ this.emit('conclude', 1005, EMPTY_BUFFER);
8357
+ this.end();
8358
+ } else {
8359
+ const code = data.readUInt16BE(0);
8360
+
8361
+ if (!isValidStatusCode(code)) {
8362
+ const error = this.createError(
8363
+ RangeError,
8364
+ `invalid status code ${code}`,
8365
+ true,
8366
+ 1002,
8367
+ 'WS_ERR_INVALID_CLOSE_CODE'
8368
+ );
8369
+
8370
+ cb(error);
8371
+ return;
8372
+ }
8373
+
8374
+ const buf = new FastBuffer(
8375
+ data.buffer,
8376
+ data.byteOffset + 2,
8377
+ data.length - 2
8378
+ );
8379
+
8380
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
8381
+ const error = this.createError(
8382
+ Error,
8383
+ 'invalid UTF-8 sequence',
8384
+ true,
8385
+ 1007,
8386
+ 'WS_ERR_INVALID_UTF8'
8387
+ );
8388
+
8389
+ cb(error);
8390
+ return;
8391
+ }
8392
+
8393
+ this._loop = false;
8394
+ this.emit('conclude', code, buf);
8395
+ this.end();
8396
+ }
8397
+
8398
+ this._state = GET_INFO;
8399
+ return;
8400
+ }
8401
+
8402
+ if (this._allowSynchronousEvents) {
8403
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
8404
+ this._state = GET_INFO;
8405
+ } else {
8406
+ this._state = DEFER_EVENT;
8407
+ setImmediate(() => {
8408
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
8409
+ this._state = GET_INFO;
8410
+ this.startLoop(cb);
8411
+ });
8412
+ }
8413
+ }
8414
+
8415
+ /**
8416
+ * Builds an error object.
8417
+ *
8418
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
8419
+ * @param {String} message The error message
8420
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
8421
+ * `message`
8422
+ * @param {Number} statusCode The status code
8423
+ * @param {String} errorCode The exposed error code
8424
+ * @return {(Error|RangeError)} The error
8425
+ * @private
8426
+ */
8427
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
8428
+ this._loop = false;
8429
+ this._errored = true;
8430
+
8431
+ const err = new ErrorCtor(
8432
+ prefix ? `Invalid WebSocket frame: ${message}` : message
8433
+ );
8434
+
8435
+ Error.captureStackTrace(err, this.createError);
8436
+ err.code = errorCode;
8437
+ err[kStatusCode] = statusCode;
8438
+ return err;
8439
+ }
8440
+ }
8441
+
8442
+ receiver = Receiver;
8443
+ return receiver;
8444
+ }
8445
+
8446
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
8447
+
8448
+ var sender;
8449
+ var hasRequiredSender;
8450
+
8451
+ function requireSender () {
8452
+ if (hasRequiredSender) return sender;
8453
+ hasRequiredSender = 1;
8454
+
8455
+ const { Duplex } = require$$0$2;
8456
+ const { randomFillSync } = require$$1;
8457
+
8458
+ const PerMessageDeflate = requirePermessageDeflate();
8459
+ const { EMPTY_BUFFER, kWebSocket, NOOP } = requireConstants();
8460
+ const { isBlob, isValidStatusCode } = requireValidation();
8461
+ const { mask: applyMask, toBuffer } = requireBufferUtil();
8462
+
8463
+ const kByteLength = Symbol('kByteLength');
8464
+ const maskBuffer = Buffer.alloc(4);
8465
+ const RANDOM_POOL_SIZE = 8 * 1024;
8466
+ let randomPool;
8467
+ let randomPoolPointer = RANDOM_POOL_SIZE;
8468
+
8469
+ const DEFAULT = 0;
8470
+ const DEFLATING = 1;
8471
+ const GET_BLOB_DATA = 2;
8472
+
8473
+ /**
8474
+ * HyBi Sender implementation.
8475
+ */
8476
+ class Sender {
8477
+ /**
8478
+ * Creates a Sender instance.
8479
+ *
8480
+ * @param {Duplex} socket The connection socket
8481
+ * @param {Object} [extensions] An object containing the negotiated extensions
8482
+ * @param {Function} [generateMask] The function used to generate the masking
8483
+ * key
8484
+ */
8485
+ constructor(socket, extensions, generateMask) {
8486
+ this._extensions = extensions || {};
8487
+
8488
+ if (generateMask) {
8489
+ this._generateMask = generateMask;
8490
+ this._maskBuffer = Buffer.alloc(4);
8491
+ }
8492
+
8493
+ this._socket = socket;
8494
+
8495
+ this._firstFragment = true;
8496
+ this._compress = false;
8497
+
8498
+ this._bufferedBytes = 0;
8499
+ this._queue = [];
8500
+ this._state = DEFAULT;
8501
+ this.onerror = NOOP;
8502
+ this[kWebSocket] = undefined;
8503
+ }
8504
+
8505
+ /**
8506
+ * Frames a piece of data according to the HyBi WebSocket protocol.
8507
+ *
8508
+ * @param {(Buffer|String)} data The data to frame
8509
+ * @param {Object} options Options object
8510
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
8511
+ * FIN bit
8512
+ * @param {Function} [options.generateMask] The function used to generate the
8513
+ * masking key
8514
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
8515
+ * `data`
8516
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
8517
+ * key
8518
+ * @param {Number} options.opcode The opcode
8519
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
8520
+ * modified
8521
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
8522
+ * RSV1 bit
8523
+ * @return {(Buffer|String)[]} The framed data
8524
+ * @public
8525
+ */
8526
+ static frame(data, options) {
8527
+ let mask;
8528
+ let merge = false;
8529
+ let offset = 2;
8530
+ let skipMasking = false;
8531
+
8532
+ if (options.mask) {
8533
+ mask = options.maskBuffer || maskBuffer;
8534
+
8535
+ if (options.generateMask) {
8536
+ options.generateMask(mask);
8537
+ } else {
8538
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
8539
+ /* istanbul ignore else */
8540
+ if (randomPool === undefined) {
8541
+ //
8542
+ // This is lazily initialized because server-sent frames must not
8543
+ // be masked so it may never be used.
8544
+ //
8545
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
8546
+ }
8547
+
8548
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
8549
+ randomPoolPointer = 0;
8550
+ }
8551
+
8552
+ mask[0] = randomPool[randomPoolPointer++];
8553
+ mask[1] = randomPool[randomPoolPointer++];
8554
+ mask[2] = randomPool[randomPoolPointer++];
8555
+ mask[3] = randomPool[randomPoolPointer++];
8556
+ }
8557
+
8558
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
8559
+ offset = 6;
8560
+ }
8561
+
8562
+ let dataLength;
8563
+
8564
+ if (typeof data === 'string') {
8565
+ if (
8566
+ (!options.mask || skipMasking) &&
8567
+ options[kByteLength] !== undefined
8568
+ ) {
8569
+ dataLength = options[kByteLength];
8570
+ } else {
8571
+ data = Buffer.from(data);
8572
+ dataLength = data.length;
8573
+ }
8574
+ } else {
8575
+ dataLength = data.length;
8576
+ merge = options.mask && options.readOnly && !skipMasking;
8577
+ }
8578
+
8579
+ let payloadLength = dataLength;
8580
+
8581
+ if (dataLength >= 65536) {
8582
+ offset += 8;
8583
+ payloadLength = 127;
8584
+ } else if (dataLength > 125) {
8585
+ offset += 2;
8586
+ payloadLength = 126;
8587
+ }
8588
+
8589
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
8590
+
8591
+ target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
8592
+ if (options.rsv1) target[0] |= 0x40;
8593
+
8594
+ target[1] = payloadLength;
8595
+
8596
+ if (payloadLength === 126) {
8597
+ target.writeUInt16BE(dataLength, 2);
8598
+ } else if (payloadLength === 127) {
8599
+ target[2] = target[3] = 0;
8600
+ target.writeUIntBE(dataLength, 4, 6);
8601
+ }
8602
+
8603
+ if (!options.mask) return [target, data];
8604
+
8605
+ target[1] |= 0x80;
8606
+ target[offset - 4] = mask[0];
8607
+ target[offset - 3] = mask[1];
8608
+ target[offset - 2] = mask[2];
8609
+ target[offset - 1] = mask[3];
8610
+
8611
+ if (skipMasking) return [target, data];
8612
+
8613
+ if (merge) {
8614
+ applyMask(data, mask, target, offset, dataLength);
8615
+ return [target];
8616
+ }
8617
+
8618
+ applyMask(data, mask, data, 0, dataLength);
8619
+ return [target, data];
8620
+ }
8621
+
8622
+ /**
8623
+ * Sends a close message to the other peer.
8624
+ *
8625
+ * @param {Number} [code] The status code component of the body
8626
+ * @param {(String|Buffer)} [data] The message component of the body
8627
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
8628
+ * @param {Function} [cb] Callback
8629
+ * @public
8630
+ */
8631
+ close(code, data, mask, cb) {
8632
+ let buf;
8633
+
8634
+ if (code === undefined) {
8635
+ buf = EMPTY_BUFFER;
8636
+ } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
8637
+ throw new TypeError('First argument must be a valid error code number');
8638
+ } else if (data === undefined || !data.length) {
8639
+ buf = Buffer.allocUnsafe(2);
8640
+ buf.writeUInt16BE(code, 0);
8641
+ } else {
8642
+ const length = Buffer.byteLength(data);
8643
+
8644
+ if (length > 123) {
8645
+ throw new RangeError('The message must not be greater than 123 bytes');
8646
+ }
8647
+
8648
+ buf = Buffer.allocUnsafe(2 + length);
8649
+ buf.writeUInt16BE(code, 0);
8650
+
8651
+ if (typeof data === 'string') {
8652
+ buf.write(data, 2);
8653
+ } else {
8654
+ buf.set(data, 2);
8655
+ }
8656
+ }
8657
+
8658
+ const options = {
8659
+ [kByteLength]: buf.length,
8660
+ fin: true,
8661
+ generateMask: this._generateMask,
8662
+ mask,
8663
+ maskBuffer: this._maskBuffer,
8664
+ opcode: 0x08,
8665
+ readOnly: false,
8666
+ rsv1: false
8667
+ };
8668
+
8669
+ if (this._state !== DEFAULT) {
8670
+ this.enqueue([this.dispatch, buf, false, options, cb]);
8671
+ } else {
8672
+ this.sendFrame(Sender.frame(buf, options), cb);
8673
+ }
8674
+ }
8675
+
8676
+ /**
8677
+ * Sends a ping message to the other peer.
8678
+ *
8679
+ * @param {*} data The message to send
8680
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
8681
+ * @param {Function} [cb] Callback
8682
+ * @public
8683
+ */
8684
+ ping(data, mask, cb) {
8685
+ let byteLength;
8686
+ let readOnly;
8687
+
8688
+ if (typeof data === 'string') {
8689
+ byteLength = Buffer.byteLength(data);
8690
+ readOnly = false;
8691
+ } else if (isBlob(data)) {
8692
+ byteLength = data.size;
8693
+ readOnly = false;
8694
+ } else {
8695
+ data = toBuffer(data);
8696
+ byteLength = data.length;
8697
+ readOnly = toBuffer.readOnly;
8698
+ }
8699
+
8700
+ if (byteLength > 125) {
8701
+ throw new RangeError('The data size must not be greater than 125 bytes');
8702
+ }
8703
+
8704
+ const options = {
8705
+ [kByteLength]: byteLength,
8706
+ fin: true,
8707
+ generateMask: this._generateMask,
8708
+ mask,
8709
+ maskBuffer: this._maskBuffer,
8710
+ opcode: 0x09,
8711
+ readOnly,
8712
+ rsv1: false
8713
+ };
8714
+
8715
+ if (isBlob(data)) {
8716
+ if (this._state !== DEFAULT) {
8717
+ this.enqueue([this.getBlobData, data, false, options, cb]);
8718
+ } else {
8719
+ this.getBlobData(data, false, options, cb);
8720
+ }
8721
+ } else if (this._state !== DEFAULT) {
8722
+ this.enqueue([this.dispatch, data, false, options, cb]);
8723
+ } else {
8724
+ this.sendFrame(Sender.frame(data, options), cb);
8725
+ }
8726
+ }
8727
+
8728
+ /**
8729
+ * Sends a pong message to the other peer.
8730
+ *
8731
+ * @param {*} data The message to send
8732
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
8733
+ * @param {Function} [cb] Callback
8734
+ * @public
8735
+ */
8736
+ pong(data, mask, cb) {
8737
+ let byteLength;
8738
+ let readOnly;
8739
+
8740
+ if (typeof data === 'string') {
8741
+ byteLength = Buffer.byteLength(data);
8742
+ readOnly = false;
8743
+ } else if (isBlob(data)) {
8744
+ byteLength = data.size;
8745
+ readOnly = false;
8746
+ } else {
8747
+ data = toBuffer(data);
8748
+ byteLength = data.length;
8749
+ readOnly = toBuffer.readOnly;
8750
+ }
8751
+
8752
+ if (byteLength > 125) {
8753
+ throw new RangeError('The data size must not be greater than 125 bytes');
8754
+ }
8755
+
8756
+ const options = {
8757
+ [kByteLength]: byteLength,
8758
+ fin: true,
8759
+ generateMask: this._generateMask,
8760
+ mask,
8761
+ maskBuffer: this._maskBuffer,
8762
+ opcode: 0x0a,
8763
+ readOnly,
8764
+ rsv1: false
8765
+ };
8766
+
8767
+ if (isBlob(data)) {
8768
+ if (this._state !== DEFAULT) {
8769
+ this.enqueue([this.getBlobData, data, false, options, cb]);
8770
+ } else {
8771
+ this.getBlobData(data, false, options, cb);
8772
+ }
8773
+ } else if (this._state !== DEFAULT) {
8774
+ this.enqueue([this.dispatch, data, false, options, cb]);
8775
+ } else {
8776
+ this.sendFrame(Sender.frame(data, options), cb);
8777
+ }
8778
+ }
8779
+
8780
+ /**
8781
+ * Sends a data message to the other peer.
8782
+ *
8783
+ * @param {*} data The message to send
8784
+ * @param {Object} options Options object
8785
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
8786
+ * or text
8787
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
8788
+ * compress `data`
8789
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
8790
+ * last one
8791
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
8792
+ * `data`
8793
+ * @param {Function} [cb] Callback
8794
+ * @public
8795
+ */
8796
+ send(data, options, cb) {
8797
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
8798
+ let opcode = options.binary ? 2 : 1;
8799
+ let rsv1 = options.compress;
8800
+
8801
+ let byteLength;
8802
+ let readOnly;
8803
+
8804
+ if (typeof data === 'string') {
8805
+ byteLength = Buffer.byteLength(data);
8806
+ readOnly = false;
8807
+ } else if (isBlob(data)) {
8808
+ byteLength = data.size;
8809
+ readOnly = false;
8810
+ } else {
8811
+ data = toBuffer(data);
8812
+ byteLength = data.length;
8813
+ readOnly = toBuffer.readOnly;
8814
+ }
8815
+
8816
+ if (this._firstFragment) {
8817
+ this._firstFragment = false;
8818
+ if (
8819
+ rsv1 &&
8820
+ perMessageDeflate &&
8821
+ perMessageDeflate.params[
8822
+ perMessageDeflate._isServer
8823
+ ? 'server_no_context_takeover'
8824
+ : 'client_no_context_takeover'
8825
+ ]
8826
+ ) {
8827
+ rsv1 = byteLength >= perMessageDeflate._threshold;
8828
+ }
8829
+ this._compress = rsv1;
8830
+ } else {
8831
+ rsv1 = false;
8832
+ opcode = 0;
8833
+ }
8834
+
8835
+ if (options.fin) this._firstFragment = true;
8836
+
8837
+ const opts = {
8838
+ [kByteLength]: byteLength,
8839
+ fin: options.fin,
8840
+ generateMask: this._generateMask,
8841
+ mask: options.mask,
8842
+ maskBuffer: this._maskBuffer,
8843
+ opcode,
8844
+ readOnly,
8845
+ rsv1
8846
+ };
8847
+
8848
+ if (isBlob(data)) {
8849
+ if (this._state !== DEFAULT) {
8850
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
8851
+ } else {
8852
+ this.getBlobData(data, this._compress, opts, cb);
8853
+ }
8854
+ } else if (this._state !== DEFAULT) {
8855
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
8856
+ } else {
8857
+ this.dispatch(data, this._compress, opts, cb);
8858
+ }
8859
+ }
8860
+
8861
+ /**
8862
+ * Gets the contents of a blob as binary data.
8863
+ *
8864
+ * @param {Blob} blob The blob
8865
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
8866
+ * the data
8867
+ * @param {Object} options Options object
8868
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
8869
+ * FIN bit
8870
+ * @param {Function} [options.generateMask] The function used to generate the
8871
+ * masking key
8872
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
8873
+ * `data`
8874
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
8875
+ * key
8876
+ * @param {Number} options.opcode The opcode
8877
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
8878
+ * modified
8879
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
8880
+ * RSV1 bit
8881
+ * @param {Function} [cb] Callback
8882
+ * @private
8883
+ */
8884
+ getBlobData(blob, compress, options, cb) {
8885
+ this._bufferedBytes += options[kByteLength];
8886
+ this._state = GET_BLOB_DATA;
8887
+
8888
+ blob
8889
+ .arrayBuffer()
8890
+ .then((arrayBuffer) => {
8891
+ if (this._socket.destroyed) {
8892
+ const err = new Error(
8893
+ 'The socket was closed while the blob was being read'
8894
+ );
8895
+
8896
+ //
8897
+ // `callCallbacks` is called in the next tick to ensure that errors
8898
+ // that might be thrown in the callbacks behave like errors thrown
8899
+ // outside the promise chain.
8900
+ //
8901
+ process.nextTick(callCallbacks, this, err, cb);
8902
+ return;
8903
+ }
8904
+
8905
+ this._bufferedBytes -= options[kByteLength];
8906
+ const data = toBuffer(arrayBuffer);
8907
+
8908
+ if (!compress) {
8909
+ this._state = DEFAULT;
8910
+ this.sendFrame(Sender.frame(data, options), cb);
8911
+ this.dequeue();
8912
+ } else {
8913
+ this.dispatch(data, compress, options, cb);
8914
+ }
8915
+ })
8916
+ .catch((err) => {
8917
+ //
8918
+ // `onError` is called in the next tick for the same reason that
8919
+ // `callCallbacks` above is.
8920
+ //
8921
+ process.nextTick(onError, this, err, cb);
8922
+ });
8923
+ }
8924
+
8925
+ /**
8926
+ * Dispatches a message.
8927
+ *
8928
+ * @param {(Buffer|String)} data The message to send
8929
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
8930
+ * `data`
8931
+ * @param {Object} options Options object
8932
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
8933
+ * FIN bit
8934
+ * @param {Function} [options.generateMask] The function used to generate the
8935
+ * masking key
8936
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
8937
+ * `data`
8938
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
8939
+ * key
8940
+ * @param {Number} options.opcode The opcode
8941
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
8942
+ * modified
8943
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
8944
+ * RSV1 bit
8945
+ * @param {Function} [cb] Callback
8946
+ * @private
8947
+ */
8948
+ dispatch(data, compress, options, cb) {
8949
+ if (!compress) {
8950
+ this.sendFrame(Sender.frame(data, options), cb);
8951
+ return;
8952
+ }
8953
+
8954
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
8955
+
8956
+ this._bufferedBytes += options[kByteLength];
8957
+ this._state = DEFLATING;
8958
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
8959
+ if (this._socket.destroyed) {
8960
+ const err = new Error(
8961
+ 'The socket was closed while data was being compressed'
8962
+ );
8963
+
8964
+ callCallbacks(this, err, cb);
8965
+ return;
8966
+ }
8967
+
8968
+ this._bufferedBytes -= options[kByteLength];
8969
+ this._state = DEFAULT;
8970
+ options.readOnly = false;
8971
+ this.sendFrame(Sender.frame(buf, options), cb);
8972
+ this.dequeue();
8973
+ });
8974
+ }
8975
+
8976
+ /**
8977
+ * Executes queued send operations.
8978
+ *
8979
+ * @private
8980
+ */
8981
+ dequeue() {
8982
+ while (this._state === DEFAULT && this._queue.length) {
8983
+ const params = this._queue.shift();
8984
+
8985
+ this._bufferedBytes -= params[3][kByteLength];
8986
+ Reflect.apply(params[0], this, params.slice(1));
8987
+ }
8988
+ }
8989
+
8990
+ /**
8991
+ * Enqueues a send operation.
8992
+ *
8993
+ * @param {Array} params Send operation parameters.
8994
+ * @private
8995
+ */
8996
+ enqueue(params) {
8997
+ this._bufferedBytes += params[3][kByteLength];
8998
+ this._queue.push(params);
8999
+ }
9000
+
9001
+ /**
9002
+ * Sends a frame.
9003
+ *
9004
+ * @param {(Buffer | String)[]} list The frame to send
9005
+ * @param {Function} [cb] Callback
9006
+ * @private
9007
+ */
9008
+ sendFrame(list, cb) {
9009
+ if (list.length === 2) {
9010
+ this._socket.cork();
9011
+ this._socket.write(list[0]);
9012
+ this._socket.write(list[1], cb);
9013
+ this._socket.uncork();
9014
+ } else {
9015
+ this._socket.write(list[0], cb);
9016
+ }
9017
+ }
9018
+ }
9019
+
9020
+ sender = Sender;
9021
+
9022
+ /**
9023
+ * Calls queued callbacks with an error.
9024
+ *
9025
+ * @param {Sender} sender The `Sender` instance
9026
+ * @param {Error} err The error to call the callbacks with
9027
+ * @param {Function} [cb] The first callback
9028
+ * @private
9029
+ */
9030
+ function callCallbacks(sender, err, cb) {
9031
+ if (typeof cb === 'function') cb(err);
9032
+
9033
+ for (let i = 0; i < sender._queue.length; i++) {
9034
+ const params = sender._queue[i];
9035
+ const callback = params[params.length - 1];
9036
+
9037
+ if (typeof callback === 'function') callback(err);
9038
+ }
9039
+ }
9040
+
9041
+ /**
9042
+ * Handles a `Sender` error.
9043
+ *
9044
+ * @param {Sender} sender The `Sender` instance
9045
+ * @param {Error} err The error
9046
+ * @param {Function} [cb] The first pending callback
9047
+ * @private
9048
+ */
9049
+ function onError(sender, err, cb) {
9050
+ callCallbacks(sender, err, cb);
9051
+ sender.onerror(err);
9052
+ }
9053
+ return sender;
9054
+ }
9055
+
9056
+ var eventTarget;
9057
+ var hasRequiredEventTarget;
9058
+
9059
+ function requireEventTarget () {
9060
+ if (hasRequiredEventTarget) return eventTarget;
9061
+ hasRequiredEventTarget = 1;
9062
+
9063
+ const { kForOnEventAttribute, kListener } = requireConstants();
9064
+
9065
+ const kCode = Symbol('kCode');
9066
+ const kData = Symbol('kData');
9067
+ const kError = Symbol('kError');
9068
+ const kMessage = Symbol('kMessage');
9069
+ const kReason = Symbol('kReason');
9070
+ const kTarget = Symbol('kTarget');
9071
+ const kType = Symbol('kType');
9072
+ const kWasClean = Symbol('kWasClean');
9073
+
9074
+ /**
9075
+ * Class representing an event.
9076
+ */
9077
+ class Event {
9078
+ /**
9079
+ * Create a new `Event`.
9080
+ *
9081
+ * @param {String} type The name of the event
9082
+ * @throws {TypeError} If the `type` argument is not specified
9083
+ */
9084
+ constructor(type) {
9085
+ this[kTarget] = null;
9086
+ this[kType] = type;
9087
+ }
9088
+
9089
+ /**
9090
+ * @type {*}
9091
+ */
9092
+ get target() {
9093
+ return this[kTarget];
9094
+ }
9095
+
9096
+ /**
9097
+ * @type {String}
9098
+ */
9099
+ get type() {
9100
+ return this[kType];
9101
+ }
9102
+ }
9103
+
9104
+ Object.defineProperty(Event.prototype, 'target', { enumerable: true });
9105
+ Object.defineProperty(Event.prototype, 'type', { enumerable: true });
9106
+
9107
+ /**
9108
+ * Class representing a close event.
9109
+ *
9110
+ * @extends Event
9111
+ */
9112
+ class CloseEvent extends Event {
9113
+ /**
9114
+ * Create a new `CloseEvent`.
9115
+ *
9116
+ * @param {String} type The name of the event
9117
+ * @param {Object} [options] A dictionary object that allows for setting
9118
+ * attributes via object members of the same name
9119
+ * @param {Number} [options.code=0] The status code explaining why the
9120
+ * connection was closed
9121
+ * @param {String} [options.reason=''] A human-readable string explaining why
9122
+ * the connection was closed
9123
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
9124
+ * connection was cleanly closed
9125
+ */
9126
+ constructor(type, options = {}) {
9127
+ super(type);
9128
+
9129
+ this[kCode] = options.code === undefined ? 0 : options.code;
9130
+ this[kReason] = options.reason === undefined ? '' : options.reason;
9131
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
9132
+ }
9133
+
9134
+ /**
9135
+ * @type {Number}
9136
+ */
9137
+ get code() {
9138
+ return this[kCode];
9139
+ }
9140
+
9141
+ /**
9142
+ * @type {String}
9143
+ */
9144
+ get reason() {
9145
+ return this[kReason];
9146
+ }
9147
+
9148
+ /**
9149
+ * @type {Boolean}
9150
+ */
9151
+ get wasClean() {
9152
+ return this[kWasClean];
9153
+ }
9154
+ }
9155
+
9156
+ Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
9157
+ Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
9158
+ Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
9159
+
9160
+ /**
9161
+ * Class representing an error event.
9162
+ *
9163
+ * @extends Event
9164
+ */
9165
+ class ErrorEvent extends Event {
9166
+ /**
9167
+ * Create a new `ErrorEvent`.
9168
+ *
9169
+ * @param {String} type The name of the event
9170
+ * @param {Object} [options] A dictionary object that allows for setting
9171
+ * attributes via object members of the same name
9172
+ * @param {*} [options.error=null] The error that generated this event
9173
+ * @param {String} [options.message=''] The error message
9174
+ */
9175
+ constructor(type, options = {}) {
9176
+ super(type);
9177
+
9178
+ this[kError] = options.error === undefined ? null : options.error;
9179
+ this[kMessage] = options.message === undefined ? '' : options.message;
9180
+ }
9181
+
9182
+ /**
9183
+ * @type {*}
9184
+ */
9185
+ get error() {
9186
+ return this[kError];
9187
+ }
9188
+
9189
+ /**
9190
+ * @type {String}
9191
+ */
9192
+ get message() {
9193
+ return this[kMessage];
9194
+ }
9195
+ }
9196
+
9197
+ Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
9198
+ Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
9199
+
9200
+ /**
9201
+ * Class representing a message event.
9202
+ *
9203
+ * @extends Event
9204
+ */
9205
+ class MessageEvent extends Event {
9206
+ /**
9207
+ * Create a new `MessageEvent`.
9208
+ *
9209
+ * @param {String} type The name of the event
9210
+ * @param {Object} [options] A dictionary object that allows for setting
9211
+ * attributes via object members of the same name
9212
+ * @param {*} [options.data=null] The message content
9213
+ */
9214
+ constructor(type, options = {}) {
9215
+ super(type);
9216
+
9217
+ this[kData] = options.data === undefined ? null : options.data;
9218
+ }
9219
+
9220
+ /**
9221
+ * @type {*}
9222
+ */
9223
+ get data() {
9224
+ return this[kData];
9225
+ }
9226
+ }
9227
+
9228
+ Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
9229
+
9230
+ /**
9231
+ * This provides methods for emulating the `EventTarget` interface. It's not
9232
+ * meant to be used directly.
9233
+ *
9234
+ * @mixin
9235
+ */
9236
+ const EventTarget = {
9237
+ /**
9238
+ * Register an event listener.
9239
+ *
9240
+ * @param {String} type A string representing the event type to listen for
9241
+ * @param {(Function|Object)} handler The listener to add
9242
+ * @param {Object} [options] An options object specifies characteristics about
9243
+ * the event listener
9244
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
9245
+ * listener should be invoked at most once after being added. If `true`,
9246
+ * the listener would be automatically removed when invoked.
9247
+ * @public
9248
+ */
9249
+ addEventListener(type, handler, options = {}) {
9250
+ for (const listener of this.listeners(type)) {
9251
+ if (
9252
+ !options[kForOnEventAttribute] &&
9253
+ listener[kListener] === handler &&
9254
+ !listener[kForOnEventAttribute]
9255
+ ) {
9256
+ return;
9257
+ }
9258
+ }
9259
+
9260
+ let wrapper;
9261
+
9262
+ if (type === 'message') {
9263
+ wrapper = function onMessage(data, isBinary) {
9264
+ const event = new MessageEvent('message', {
9265
+ data: isBinary ? data : data.toString()
9266
+ });
9267
+
9268
+ event[kTarget] = this;
9269
+ callListener(handler, this, event);
9270
+ };
9271
+ } else if (type === 'close') {
9272
+ wrapper = function onClose(code, message) {
9273
+ const event = new CloseEvent('close', {
9274
+ code,
9275
+ reason: message.toString(),
9276
+ wasClean: this._closeFrameReceived && this._closeFrameSent
9277
+ });
9278
+
9279
+ event[kTarget] = this;
9280
+ callListener(handler, this, event);
9281
+ };
9282
+ } else if (type === 'error') {
9283
+ wrapper = function onError(error) {
9284
+ const event = new ErrorEvent('error', {
9285
+ error,
9286
+ message: error.message
9287
+ });
9288
+
9289
+ event[kTarget] = this;
9290
+ callListener(handler, this, event);
9291
+ };
9292
+ } else if (type === 'open') {
9293
+ wrapper = function onOpen() {
9294
+ const event = new Event('open');
9295
+
9296
+ event[kTarget] = this;
9297
+ callListener(handler, this, event);
9298
+ };
9299
+ } else {
9300
+ return;
9301
+ }
9302
+
9303
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
9304
+ wrapper[kListener] = handler;
9305
+
9306
+ if (options.once) {
9307
+ this.once(type, wrapper);
9308
+ } else {
9309
+ this.on(type, wrapper);
9310
+ }
9311
+ },
9312
+
9313
+ /**
9314
+ * Remove an event listener.
9315
+ *
9316
+ * @param {String} type A string representing the event type to remove
9317
+ * @param {(Function|Object)} handler The listener to remove
9318
+ * @public
9319
+ */
9320
+ removeEventListener(type, handler) {
9321
+ for (const listener of this.listeners(type)) {
9322
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
9323
+ this.removeListener(type, listener);
9324
+ break;
9325
+ }
9326
+ }
9327
+ }
9328
+ };
9329
+
9330
+ eventTarget = {
9331
+ CloseEvent,
9332
+ ErrorEvent,
9333
+ Event,
9334
+ EventTarget,
9335
+ MessageEvent
9336
+ };
9337
+
9338
+ /**
9339
+ * Call an event listener
9340
+ *
9341
+ * @param {(Function|Object)} listener The listener to call
9342
+ * @param {*} thisArg The value to use as `this`` when calling the listener
9343
+ * @param {Event} event The event to pass to the listener
9344
+ * @private
9345
+ */
9346
+ function callListener(listener, thisArg, event) {
9347
+ if (typeof listener === 'object' && listener.handleEvent) {
9348
+ listener.handleEvent.call(listener, event);
9349
+ } else {
9350
+ listener.call(thisArg, event);
9351
+ }
9352
+ }
9353
+ return eventTarget;
9354
+ }
9355
+
9356
+ var extension;
9357
+ var hasRequiredExtension;
9358
+
9359
+ function requireExtension () {
9360
+ if (hasRequiredExtension) return extension;
9361
+ hasRequiredExtension = 1;
9362
+
9363
+ const { tokenChars } = requireValidation();
9364
+
9365
+ /**
9366
+ * Adds an offer to the map of extension offers or a parameter to the map of
9367
+ * parameters.
9368
+ *
9369
+ * @param {Object} dest The map of extension offers or parameters
9370
+ * @param {String} name The extension or parameter name
9371
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
9372
+ * parameter value
9373
+ * @private
9374
+ */
9375
+ function push(dest, name, elem) {
9376
+ if (dest[name] === undefined) dest[name] = [elem];
9377
+ else dest[name].push(elem);
9378
+ }
9379
+
9380
+ /**
9381
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
9382
+ *
9383
+ * @param {String} header The field value of the header
9384
+ * @return {Object} The parsed object
9385
+ * @public
9386
+ */
9387
+ function parse(header) {
9388
+ const offers = Object.create(null);
9389
+ let params = Object.create(null);
9390
+ let mustUnescape = false;
9391
+ let isEscaping = false;
9392
+ let inQuotes = false;
9393
+ let extensionName;
9394
+ let paramName;
9395
+ let start = -1;
9396
+ let code = -1;
9397
+ let end = -1;
9398
+ let i = 0;
9399
+
9400
+ for (; i < header.length; i++) {
9401
+ code = header.charCodeAt(i);
9402
+
9403
+ if (extensionName === undefined) {
9404
+ if (end === -1 && tokenChars[code] === 1) {
9405
+ if (start === -1) start = i;
9406
+ } else if (
9407
+ i !== 0 &&
9408
+ (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
9409
+ ) {
9410
+ if (end === -1 && start !== -1) end = i;
9411
+ } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
9412
+ if (start === -1) {
9413
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9414
+ }
9415
+
9416
+ if (end === -1) end = i;
9417
+ const name = header.slice(start, end);
9418
+ if (code === 0x2c) {
9419
+ push(offers, name, params);
9420
+ params = Object.create(null);
9421
+ } else {
9422
+ extensionName = name;
9423
+ }
9424
+
9425
+ start = end = -1;
9426
+ } else {
9427
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9428
+ }
9429
+ } else if (paramName === undefined) {
9430
+ if (end === -1 && tokenChars[code] === 1) {
9431
+ if (start === -1) start = i;
9432
+ } else if (code === 0x20 || code === 0x09) {
9433
+ if (end === -1 && start !== -1) end = i;
9434
+ } else if (code === 0x3b || code === 0x2c) {
9435
+ if (start === -1) {
9436
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9437
+ }
9438
+
9439
+ if (end === -1) end = i;
9440
+ push(params, header.slice(start, end), true);
9441
+ if (code === 0x2c) {
9442
+ push(offers, extensionName, params);
9443
+ params = Object.create(null);
9444
+ extensionName = undefined;
9445
+ }
9446
+
9447
+ start = end = -1;
9448
+ } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
9449
+ paramName = header.slice(start, i);
9450
+ start = end = -1;
9451
+ } else {
9452
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9453
+ }
9454
+ } else {
9455
+ //
9456
+ // The value of a quoted-string after unescaping must conform to the
9457
+ // token ABNF, so only token characters are valid.
9458
+ // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
9459
+ //
9460
+ if (isEscaping) {
9461
+ if (tokenChars[code] !== 1) {
9462
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9463
+ }
9464
+ if (start === -1) start = i;
9465
+ else if (!mustUnescape) mustUnescape = true;
9466
+ isEscaping = false;
9467
+ } else if (inQuotes) {
9468
+ if (tokenChars[code] === 1) {
9469
+ if (start === -1) start = i;
9470
+ } else if (code === 0x22 /* '"' */ && start !== -1) {
9471
+ inQuotes = false;
9472
+ end = i;
9473
+ } else if (code === 0x5c /* '\' */) {
9474
+ isEscaping = true;
9475
+ } else {
9476
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9477
+ }
9478
+ } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
9479
+ inQuotes = true;
9480
+ } else if (end === -1 && tokenChars[code] === 1) {
9481
+ if (start === -1) start = i;
9482
+ } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
9483
+ if (end === -1) end = i;
9484
+ } else if (code === 0x3b || code === 0x2c) {
9485
+ if (start === -1) {
9486
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9487
+ }
9488
+
9489
+ if (end === -1) end = i;
9490
+ let value = header.slice(start, end);
9491
+ if (mustUnescape) {
9492
+ value = value.replace(/\\/g, '');
9493
+ mustUnescape = false;
9494
+ }
9495
+ push(params, paramName, value);
9496
+ if (code === 0x2c) {
9497
+ push(offers, extensionName, params);
9498
+ params = Object.create(null);
9499
+ extensionName = undefined;
9500
+ }
9501
+
9502
+ paramName = undefined;
9503
+ start = end = -1;
9504
+ } else {
9505
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9506
+ }
9507
+ }
9508
+ }
9509
+
9510
+ if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
9511
+ throw new SyntaxError('Unexpected end of input');
9512
+ }
9513
+
9514
+ if (end === -1) end = i;
9515
+ const token = header.slice(start, end);
9516
+ if (extensionName === undefined) {
9517
+ push(offers, token, params);
9518
+ } else {
9519
+ if (paramName === undefined) {
9520
+ push(params, token, true);
9521
+ } else if (mustUnescape) {
9522
+ push(params, paramName, token.replace(/\\/g, ''));
9523
+ } else {
9524
+ push(params, paramName, token);
9525
+ }
9526
+ push(offers, extensionName, params);
9527
+ }
9528
+
9529
+ return offers;
9530
+ }
9531
+
9532
+ /**
9533
+ * Builds the `Sec-WebSocket-Extensions` header field value.
9534
+ *
9535
+ * @param {Object} extensions The map of extensions and parameters to format
9536
+ * @return {String} A string representing the given object
9537
+ * @public
9538
+ */
9539
+ function format(extensions) {
9540
+ return Object.keys(extensions)
9541
+ .map((extension) => {
9542
+ let configurations = extensions[extension];
9543
+ if (!Array.isArray(configurations)) configurations = [configurations];
9544
+ return configurations
9545
+ .map((params) => {
9546
+ return [extension]
9547
+ .concat(
9548
+ Object.keys(params).map((k) => {
9549
+ let values = params[k];
9550
+ if (!Array.isArray(values)) values = [values];
9551
+ return values
9552
+ .map((v) => (v === true ? k : `${k}=${v}`))
9553
+ .join('; ');
9554
+ })
9555
+ )
9556
+ .join('; ');
9557
+ })
9558
+ .join(', ');
9559
+ })
9560
+ .join(', ');
9561
+ }
9562
+
9563
+ extension = { format, parse };
9564
+ return extension;
9565
+ }
9566
+
9567
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
9568
+
9569
+ var websocket;
9570
+ var hasRequiredWebsocket;
9571
+
9572
+ function requireWebsocket () {
9573
+ if (hasRequiredWebsocket) return websocket;
9574
+ hasRequiredWebsocket = 1;
9575
+
9576
+ const EventEmitter = require$$0$3;
9577
+ const https$1 = https;
9578
+ const http$1 = http;
9579
+ const net = require$$3;
9580
+ const tls = require$$4;
9581
+ const { randomBytes, createHash } = require$$1;
9582
+ const { Duplex, Readable } = require$$0$2;
9583
+ const { URL } = url;
9584
+
9585
+ const PerMessageDeflate = requirePermessageDeflate();
9586
+ const Receiver = requireReceiver();
9587
+ const Sender = requireSender();
9588
+ const { isBlob } = requireValidation();
9589
+
9590
+ const {
9591
+ BINARY_TYPES,
9592
+ EMPTY_BUFFER,
9593
+ GUID,
9594
+ kForOnEventAttribute,
9595
+ kListener,
9596
+ kStatusCode,
9597
+ kWebSocket,
9598
+ NOOP
9599
+ } = requireConstants();
9600
+ const {
9601
+ EventTarget: { addEventListener, removeEventListener }
9602
+ } = requireEventTarget();
9603
+ const { format, parse } = requireExtension();
9604
+ const { toBuffer } = requireBufferUtil();
9605
+
9606
+ const closeTimeout = 30 * 1000;
9607
+ const kAborted = Symbol('kAborted');
9608
+ const protocolVersions = [8, 13];
9609
+ const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
9610
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
9611
+
9612
+ /**
9613
+ * Class representing a WebSocket.
9614
+ *
9615
+ * @extends EventEmitter
9616
+ */
9617
+ class WebSocket extends EventEmitter {
9618
+ /**
9619
+ * Create a new `WebSocket`.
9620
+ *
9621
+ * @param {(String|URL)} address The URL to which to connect
9622
+ * @param {(String|String[])} [protocols] The subprotocols
9623
+ * @param {Object} [options] Connection options
9624
+ */
9625
+ constructor(address, protocols, options) {
9626
+ super();
9627
+
9628
+ this._binaryType = BINARY_TYPES[0];
9629
+ this._closeCode = 1006;
9630
+ this._closeFrameReceived = false;
9631
+ this._closeFrameSent = false;
9632
+ this._closeMessage = EMPTY_BUFFER;
9633
+ this._closeTimer = null;
9634
+ this._errorEmitted = false;
9635
+ this._extensions = {};
9636
+ this._paused = false;
9637
+ this._protocol = '';
9638
+ this._readyState = WebSocket.CONNECTING;
9639
+ this._receiver = null;
9640
+ this._sender = null;
9641
+ this._socket = null;
9642
+
9643
+ if (address !== null) {
9644
+ this._bufferedAmount = 0;
9645
+ this._isServer = false;
9646
+ this._redirects = 0;
9647
+
9648
+ if (protocols === undefined) {
9649
+ protocols = [];
9650
+ } else if (!Array.isArray(protocols)) {
9651
+ if (typeof protocols === 'object' && protocols !== null) {
9652
+ options = protocols;
9653
+ protocols = [];
9654
+ } else {
9655
+ protocols = [protocols];
9656
+ }
9657
+ }
9658
+
9659
+ initAsClient(this, address, protocols, options);
9660
+ } else {
9661
+ this._autoPong = options.autoPong;
9662
+ this._isServer = true;
9663
+ }
9664
+ }
9665
+
9666
+ /**
9667
+ * For historical reasons, the custom "nodebuffer" type is used by the default
9668
+ * instead of "blob".
9669
+ *
9670
+ * @type {String}
9671
+ */
9672
+ get binaryType() {
9673
+ return this._binaryType;
9674
+ }
9675
+
9676
+ set binaryType(type) {
9677
+ if (!BINARY_TYPES.includes(type)) return;
9678
+
9679
+ this._binaryType = type;
9680
+
9681
+ //
9682
+ // Allow to change `binaryType` on the fly.
9683
+ //
9684
+ if (this._receiver) this._receiver._binaryType = type;
9685
+ }
9686
+
9687
+ /**
9688
+ * @type {Number}
9689
+ */
9690
+ get bufferedAmount() {
9691
+ if (!this._socket) return this._bufferedAmount;
9692
+
9693
+ return this._socket._writableState.length + this._sender._bufferedBytes;
9694
+ }
9695
+
9696
+ /**
9697
+ * @type {String}
9698
+ */
9699
+ get extensions() {
9700
+ return Object.keys(this._extensions).join();
9701
+ }
9702
+
9703
+ /**
9704
+ * @type {Boolean}
9705
+ */
9706
+ get isPaused() {
9707
+ return this._paused;
9708
+ }
9709
+
9710
+ /**
9711
+ * @type {Function}
9712
+ */
9713
+ /* istanbul ignore next */
9714
+ get onclose() {
9715
+ return null;
9716
+ }
9717
+
9718
+ /**
9719
+ * @type {Function}
9720
+ */
9721
+ /* istanbul ignore next */
9722
+ get onerror() {
9723
+ return null;
9724
+ }
9725
+
9726
+ /**
9727
+ * @type {Function}
9728
+ */
9729
+ /* istanbul ignore next */
9730
+ get onopen() {
9731
+ return null;
9732
+ }
9733
+
9734
+ /**
9735
+ * @type {Function}
9736
+ */
9737
+ /* istanbul ignore next */
9738
+ get onmessage() {
9739
+ return null;
9740
+ }
9741
+
9742
+ /**
9743
+ * @type {String}
9744
+ */
9745
+ get protocol() {
9746
+ return this._protocol;
9747
+ }
9748
+
9749
+ /**
9750
+ * @type {Number}
9751
+ */
9752
+ get readyState() {
9753
+ return this._readyState;
9754
+ }
9755
+
9756
+ /**
9757
+ * @type {String}
9758
+ */
9759
+ get url() {
9760
+ return this._url;
9761
+ }
9762
+
9763
+ /**
9764
+ * Set up the socket and the internal resources.
9765
+ *
9766
+ * @param {Duplex} socket The network socket between the server and client
9767
+ * @param {Buffer} head The first packet of the upgraded stream
9768
+ * @param {Object} options Options object
9769
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
9770
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
9771
+ * multiple times in the same tick
9772
+ * @param {Function} [options.generateMask] The function used to generate the
9773
+ * masking key
9774
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
9775
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
9776
+ * not to skip UTF-8 validation for text and close messages
9777
+ * @private
9778
+ */
9779
+ setSocket(socket, head, options) {
9780
+ const receiver = new Receiver({
9781
+ allowSynchronousEvents: options.allowSynchronousEvents,
9782
+ binaryType: this.binaryType,
9783
+ extensions: this._extensions,
9784
+ isServer: this._isServer,
9785
+ maxPayload: options.maxPayload,
9786
+ skipUTF8Validation: options.skipUTF8Validation
9787
+ });
9788
+
9789
+ const sender = new Sender(socket, this._extensions, options.generateMask);
9790
+
9791
+ this._receiver = receiver;
9792
+ this._sender = sender;
9793
+ this._socket = socket;
9794
+
9795
+ receiver[kWebSocket] = this;
9796
+ sender[kWebSocket] = this;
9797
+ socket[kWebSocket] = this;
9798
+
9799
+ receiver.on('conclude', receiverOnConclude);
9800
+ receiver.on('drain', receiverOnDrain);
9801
+ receiver.on('error', receiverOnError);
9802
+ receiver.on('message', receiverOnMessage);
9803
+ receiver.on('ping', receiverOnPing);
9804
+ receiver.on('pong', receiverOnPong);
9805
+
9806
+ sender.onerror = senderOnError;
9807
+
9808
+ //
9809
+ // These methods may not be available if `socket` is just a `Duplex`.
9810
+ //
9811
+ if (socket.setTimeout) socket.setTimeout(0);
9812
+ if (socket.setNoDelay) socket.setNoDelay();
9813
+
9814
+ if (head.length > 0) socket.unshift(head);
9815
+
9816
+ socket.on('close', socketOnClose);
9817
+ socket.on('data', socketOnData);
9818
+ socket.on('end', socketOnEnd);
9819
+ socket.on('error', socketOnError);
9820
+
9821
+ this._readyState = WebSocket.OPEN;
9822
+ this.emit('open');
9823
+ }
9824
+
9825
+ /**
9826
+ * Emit the `'close'` event.
9827
+ *
9828
+ * @private
9829
+ */
9830
+ emitClose() {
9831
+ if (!this._socket) {
9832
+ this._readyState = WebSocket.CLOSED;
9833
+ this.emit('close', this._closeCode, this._closeMessage);
9834
+ return;
9835
+ }
9836
+
9837
+ if (this._extensions[PerMessageDeflate.extensionName]) {
9838
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
9839
+ }
9840
+
9841
+ this._receiver.removeAllListeners();
9842
+ this._readyState = WebSocket.CLOSED;
9843
+ this.emit('close', this._closeCode, this._closeMessage);
9844
+ }
9845
+
9846
+ /**
9847
+ * Start a closing handshake.
9848
+ *
9849
+ * +----------+ +-----------+ +----------+
9850
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
9851
+ * | +----------+ +-----------+ +----------+ |
9852
+ * +----------+ +-----------+ |
9853
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
9854
+ * +----------+ +-----------+ |
9855
+ * | | | +---+ |
9856
+ * +------------------------+-->|fin| - - - -
9857
+ * | +---+ | +---+
9858
+ * - - - - -|fin|<---------------------+
9859
+ * +---+
9860
+ *
9861
+ * @param {Number} [code] Status code explaining why the connection is closing
9862
+ * @param {(String|Buffer)} [data] The reason why the connection is
9863
+ * closing
9864
+ * @public
9865
+ */
9866
+ close(code, data) {
9867
+ if (this.readyState === WebSocket.CLOSED) return;
9868
+ if (this.readyState === WebSocket.CONNECTING) {
9869
+ const msg = 'WebSocket was closed before the connection was established';
9870
+ abortHandshake(this, this._req, msg);
9871
+ return;
9872
+ }
9873
+
9874
+ if (this.readyState === WebSocket.CLOSING) {
9875
+ if (
9876
+ this._closeFrameSent &&
9877
+ (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
9878
+ ) {
9879
+ this._socket.end();
9880
+ }
9881
+
9882
+ return;
9883
+ }
9884
+
9885
+ this._readyState = WebSocket.CLOSING;
9886
+ this._sender.close(code, data, !this._isServer, (err) => {
9887
+ //
9888
+ // This error is handled by the `'error'` listener on the socket. We only
9889
+ // want to know if the close frame has been sent here.
9890
+ //
9891
+ if (err) return;
9892
+
9893
+ this._closeFrameSent = true;
9894
+
9895
+ if (
9896
+ this._closeFrameReceived ||
9897
+ this._receiver._writableState.errorEmitted
9898
+ ) {
9899
+ this._socket.end();
9900
+ }
9901
+ });
9902
+
9903
+ setCloseTimer(this);
9904
+ }
9905
+
9906
+ /**
9907
+ * Pause the socket.
9908
+ *
9909
+ * @public
9910
+ */
9911
+ pause() {
9912
+ if (
9913
+ this.readyState === WebSocket.CONNECTING ||
9914
+ this.readyState === WebSocket.CLOSED
9915
+ ) {
9916
+ return;
9917
+ }
9918
+
9919
+ this._paused = true;
9920
+ this._socket.pause();
9921
+ }
9922
+
9923
+ /**
9924
+ * Send a ping.
9925
+ *
9926
+ * @param {*} [data] The data to send
9927
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
9928
+ * @param {Function} [cb] Callback which is executed when the ping is sent
9929
+ * @public
9930
+ */
9931
+ ping(data, mask, cb) {
9932
+ if (this.readyState === WebSocket.CONNECTING) {
9933
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
9934
+ }
9935
+
9936
+ if (typeof data === 'function') {
9937
+ cb = data;
9938
+ data = mask = undefined;
9939
+ } else if (typeof mask === 'function') {
9940
+ cb = mask;
9941
+ mask = undefined;
9942
+ }
9943
+
9944
+ if (typeof data === 'number') data = data.toString();
9945
+
9946
+ if (this.readyState !== WebSocket.OPEN) {
9947
+ sendAfterClose(this, data, cb);
9948
+ return;
9949
+ }
9950
+
9951
+ if (mask === undefined) mask = !this._isServer;
9952
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
9953
+ }
9954
+
9955
+ /**
9956
+ * Send a pong.
9957
+ *
9958
+ * @param {*} [data] The data to send
9959
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
9960
+ * @param {Function} [cb] Callback which is executed when the pong is sent
9961
+ * @public
9962
+ */
9963
+ pong(data, mask, cb) {
9964
+ if (this.readyState === WebSocket.CONNECTING) {
9965
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
9966
+ }
9967
+
9968
+ if (typeof data === 'function') {
9969
+ cb = data;
9970
+ data = mask = undefined;
9971
+ } else if (typeof mask === 'function') {
9972
+ cb = mask;
9973
+ mask = undefined;
9974
+ }
9975
+
9976
+ if (typeof data === 'number') data = data.toString();
9977
+
9978
+ if (this.readyState !== WebSocket.OPEN) {
9979
+ sendAfterClose(this, data, cb);
9980
+ return;
9981
+ }
9982
+
9983
+ if (mask === undefined) mask = !this._isServer;
9984
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
9985
+ }
9986
+
9987
+ /**
9988
+ * Resume the socket.
9989
+ *
9990
+ * @public
9991
+ */
9992
+ resume() {
9993
+ if (
9994
+ this.readyState === WebSocket.CONNECTING ||
9995
+ this.readyState === WebSocket.CLOSED
9996
+ ) {
9997
+ return;
9998
+ }
9999
+
10000
+ this._paused = false;
10001
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
10002
+ }
10003
+
10004
+ /**
10005
+ * Send a data message.
10006
+ *
10007
+ * @param {*} data The message to send
10008
+ * @param {Object} [options] Options object
10009
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
10010
+ * text
10011
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
10012
+ * `data`
10013
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
10014
+ * last one
10015
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
10016
+ * @param {Function} [cb] Callback which is executed when data is written out
10017
+ * @public
10018
+ */
10019
+ send(data, options, cb) {
10020
+ if (this.readyState === WebSocket.CONNECTING) {
10021
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
10022
+ }
10023
+
10024
+ if (typeof options === 'function') {
10025
+ cb = options;
10026
+ options = {};
10027
+ }
10028
+
10029
+ if (typeof data === 'number') data = data.toString();
10030
+
10031
+ if (this.readyState !== WebSocket.OPEN) {
10032
+ sendAfterClose(this, data, cb);
10033
+ return;
10034
+ }
10035
+
10036
+ const opts = {
10037
+ binary: typeof data !== 'string',
10038
+ mask: !this._isServer,
10039
+ compress: true,
10040
+ fin: true,
10041
+ ...options
10042
+ };
10043
+
10044
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
10045
+ opts.compress = false;
10046
+ }
10047
+
10048
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
10049
+ }
10050
+
10051
+ /**
10052
+ * Forcibly close the connection.
10053
+ *
10054
+ * @public
10055
+ */
10056
+ terminate() {
10057
+ if (this.readyState === WebSocket.CLOSED) return;
10058
+ if (this.readyState === WebSocket.CONNECTING) {
10059
+ const msg = 'WebSocket was closed before the connection was established';
10060
+ abortHandshake(this, this._req, msg);
10061
+ return;
10062
+ }
10063
+
10064
+ if (this._socket) {
10065
+ this._readyState = WebSocket.CLOSING;
10066
+ this._socket.destroy();
10067
+ }
10068
+ }
10069
+ }
10070
+
10071
+ /**
10072
+ * @constant {Number} CONNECTING
10073
+ * @memberof WebSocket
10074
+ */
10075
+ Object.defineProperty(WebSocket, 'CONNECTING', {
10076
+ enumerable: true,
10077
+ value: readyStates.indexOf('CONNECTING')
10078
+ });
10079
+
10080
+ /**
10081
+ * @constant {Number} CONNECTING
10082
+ * @memberof WebSocket.prototype
10083
+ */
10084
+ Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
10085
+ enumerable: true,
10086
+ value: readyStates.indexOf('CONNECTING')
10087
+ });
10088
+
10089
+ /**
10090
+ * @constant {Number} OPEN
10091
+ * @memberof WebSocket
10092
+ */
10093
+ Object.defineProperty(WebSocket, 'OPEN', {
10094
+ enumerable: true,
10095
+ value: readyStates.indexOf('OPEN')
10096
+ });
10097
+
10098
+ /**
10099
+ * @constant {Number} OPEN
10100
+ * @memberof WebSocket.prototype
10101
+ */
10102
+ Object.defineProperty(WebSocket.prototype, 'OPEN', {
10103
+ enumerable: true,
10104
+ value: readyStates.indexOf('OPEN')
10105
+ });
10106
+
10107
+ /**
10108
+ * @constant {Number} CLOSING
10109
+ * @memberof WebSocket
10110
+ */
10111
+ Object.defineProperty(WebSocket, 'CLOSING', {
10112
+ enumerable: true,
10113
+ value: readyStates.indexOf('CLOSING')
10114
+ });
10115
+
10116
+ /**
10117
+ * @constant {Number} CLOSING
10118
+ * @memberof WebSocket.prototype
10119
+ */
10120
+ Object.defineProperty(WebSocket.prototype, 'CLOSING', {
10121
+ enumerable: true,
10122
+ value: readyStates.indexOf('CLOSING')
10123
+ });
10124
+
10125
+ /**
10126
+ * @constant {Number} CLOSED
10127
+ * @memberof WebSocket
10128
+ */
10129
+ Object.defineProperty(WebSocket, 'CLOSED', {
10130
+ enumerable: true,
10131
+ value: readyStates.indexOf('CLOSED')
10132
+ });
10133
+
10134
+ /**
10135
+ * @constant {Number} CLOSED
10136
+ * @memberof WebSocket.prototype
10137
+ */
10138
+ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
10139
+ enumerable: true,
10140
+ value: readyStates.indexOf('CLOSED')
10141
+ });
10142
+
10143
+ [
10144
+ 'binaryType',
10145
+ 'bufferedAmount',
10146
+ 'extensions',
10147
+ 'isPaused',
10148
+ 'protocol',
10149
+ 'readyState',
10150
+ 'url'
10151
+ ].forEach((property) => {
10152
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
10153
+ });
10154
+
10155
+ //
10156
+ // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
10157
+ // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
10158
+ //
10159
+ ['open', 'error', 'close', 'message'].forEach((method) => {
10160
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
10161
+ enumerable: true,
10162
+ get() {
10163
+ for (const listener of this.listeners(method)) {
10164
+ if (listener[kForOnEventAttribute]) return listener[kListener];
10165
+ }
10166
+
10167
+ return null;
10168
+ },
10169
+ set(handler) {
10170
+ for (const listener of this.listeners(method)) {
10171
+ if (listener[kForOnEventAttribute]) {
10172
+ this.removeListener(method, listener);
10173
+ break;
10174
+ }
10175
+ }
10176
+
10177
+ if (typeof handler !== 'function') return;
10178
+
10179
+ this.addEventListener(method, handler, {
10180
+ [kForOnEventAttribute]: true
10181
+ });
10182
+ }
10183
+ });
10184
+ });
10185
+
10186
+ WebSocket.prototype.addEventListener = addEventListener;
10187
+ WebSocket.prototype.removeEventListener = removeEventListener;
10188
+
10189
+ websocket = WebSocket;
10190
+
10191
+ /**
10192
+ * Initialize a WebSocket client.
10193
+ *
10194
+ * @param {WebSocket} websocket The client to initialize
10195
+ * @param {(String|URL)} address The URL to which to connect
10196
+ * @param {Array} protocols The subprotocols
10197
+ * @param {Object} [options] Connection options
10198
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
10199
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
10200
+ * times in the same tick
10201
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
10202
+ * automatically send a pong in response to a ping
10203
+ * @param {Function} [options.finishRequest] A function which can be used to
10204
+ * customize the headers of each http request before it is sent
10205
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
10206
+ * redirects
10207
+ * @param {Function} [options.generateMask] The function used to generate the
10208
+ * masking key
10209
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
10210
+ * handshake request
10211
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
10212
+ * size
10213
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
10214
+ * allowed
10215
+ * @param {String} [options.origin] Value of the `Origin` or
10216
+ * `Sec-WebSocket-Origin` header
10217
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
10218
+ * permessage-deflate
10219
+ * @param {Number} [options.protocolVersion=13] Value of the
10220
+ * `Sec-WebSocket-Version` header
10221
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
10222
+ * not to skip UTF-8 validation for text and close messages
10223
+ * @private
10224
+ */
10225
+ function initAsClient(websocket, address, protocols, options) {
10226
+ const opts = {
10227
+ allowSynchronousEvents: true,
10228
+ autoPong: true,
10229
+ protocolVersion: protocolVersions[1],
10230
+ maxPayload: 100 * 1024 * 1024,
10231
+ skipUTF8Validation: false,
10232
+ perMessageDeflate: true,
10233
+ followRedirects: false,
10234
+ maxRedirects: 10,
10235
+ ...options,
10236
+ socketPath: undefined,
10237
+ hostname: undefined,
10238
+ protocol: undefined,
10239
+ timeout: undefined,
10240
+ method: 'GET',
10241
+ host: undefined,
10242
+ path: undefined,
10243
+ port: undefined
10244
+ };
10245
+
10246
+ websocket._autoPong = opts.autoPong;
10247
+
10248
+ if (!protocolVersions.includes(opts.protocolVersion)) {
10249
+ throw new RangeError(
10250
+ `Unsupported protocol version: ${opts.protocolVersion} ` +
10251
+ `(supported versions: ${protocolVersions.join(', ')})`
10252
+ );
10253
+ }
10254
+
10255
+ let parsedUrl;
10256
+
10257
+ if (address instanceof URL) {
10258
+ parsedUrl = address;
10259
+ } else {
10260
+ try {
10261
+ parsedUrl = new URL(address);
10262
+ } catch (e) {
10263
+ throw new SyntaxError(`Invalid URL: ${address}`);
10264
+ }
10265
+ }
10266
+
10267
+ if (parsedUrl.protocol === 'http:') {
10268
+ parsedUrl.protocol = 'ws:';
10269
+ } else if (parsedUrl.protocol === 'https:') {
10270
+ parsedUrl.protocol = 'wss:';
10271
+ }
10272
+
10273
+ websocket._url = parsedUrl.href;
10274
+
10275
+ const isSecure = parsedUrl.protocol === 'wss:';
10276
+ const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
10277
+ let invalidUrlMessage;
10278
+
10279
+ if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
10280
+ invalidUrlMessage =
10281
+ 'The URL\'s protocol must be one of "ws:", "wss:", ' +
10282
+ '"http:", "https:", or "ws+unix:"';
10283
+ } else if (isIpcUrl && !parsedUrl.pathname) {
10284
+ invalidUrlMessage = "The URL's pathname is empty";
10285
+ } else if (parsedUrl.hash) {
10286
+ invalidUrlMessage = 'The URL contains a fragment identifier';
10287
+ }
10288
+
10289
+ if (invalidUrlMessage) {
10290
+ const err = new SyntaxError(invalidUrlMessage);
10291
+
10292
+ if (websocket._redirects === 0) {
10293
+ throw err;
10294
+ } else {
10295
+ emitErrorAndClose(websocket, err);
10296
+ return;
10297
+ }
10298
+ }
10299
+
10300
+ const defaultPort = isSecure ? 443 : 80;
10301
+ const key = randomBytes(16).toString('base64');
10302
+ const request = isSecure ? https$1.request : http$1.request;
10303
+ const protocolSet = new Set();
10304
+ let perMessageDeflate;
10305
+
10306
+ opts.createConnection =
10307
+ opts.createConnection || (isSecure ? tlsConnect : netConnect);
10308
+ opts.defaultPort = opts.defaultPort || defaultPort;
10309
+ opts.port = parsedUrl.port || defaultPort;
10310
+ opts.host = parsedUrl.hostname.startsWith('[')
10311
+ ? parsedUrl.hostname.slice(1, -1)
10312
+ : parsedUrl.hostname;
10313
+ opts.headers = {
10314
+ ...opts.headers,
10315
+ 'Sec-WebSocket-Version': opts.protocolVersion,
10316
+ 'Sec-WebSocket-Key': key,
10317
+ Connection: 'Upgrade',
10318
+ Upgrade: 'websocket'
10319
+ };
10320
+ opts.path = parsedUrl.pathname + parsedUrl.search;
10321
+ opts.timeout = opts.handshakeTimeout;
10322
+
10323
+ if (opts.perMessageDeflate) {
10324
+ perMessageDeflate = new PerMessageDeflate(
10325
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
10326
+ false,
10327
+ opts.maxPayload
10328
+ );
10329
+ opts.headers['Sec-WebSocket-Extensions'] = format({
10330
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
10331
+ });
10332
+ }
10333
+ if (protocols.length) {
10334
+ for (const protocol of protocols) {
10335
+ if (
10336
+ typeof protocol !== 'string' ||
10337
+ !subprotocolRegex.test(protocol) ||
10338
+ protocolSet.has(protocol)
10339
+ ) {
10340
+ throw new SyntaxError(
10341
+ 'An invalid or duplicated subprotocol was specified'
10342
+ );
10343
+ }
10344
+
10345
+ protocolSet.add(protocol);
10346
+ }
10347
+
10348
+ opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
10349
+ }
10350
+ if (opts.origin) {
10351
+ if (opts.protocolVersion < 13) {
10352
+ opts.headers['Sec-WebSocket-Origin'] = opts.origin;
10353
+ } else {
10354
+ opts.headers.Origin = opts.origin;
10355
+ }
10356
+ }
10357
+ if (parsedUrl.username || parsedUrl.password) {
10358
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
10359
+ }
10360
+
10361
+ if (isIpcUrl) {
10362
+ const parts = opts.path.split(':');
10363
+
10364
+ opts.socketPath = parts[0];
10365
+ opts.path = parts[1];
10366
+ }
10367
+
10368
+ let req;
10369
+
10370
+ if (opts.followRedirects) {
10371
+ if (websocket._redirects === 0) {
10372
+ websocket._originalIpc = isIpcUrl;
10373
+ websocket._originalSecure = isSecure;
10374
+ websocket._originalHostOrSocketPath = isIpcUrl
10375
+ ? opts.socketPath
10376
+ : parsedUrl.host;
10377
+
10378
+ const headers = options && options.headers;
10379
+
10380
+ //
10381
+ // Shallow copy the user provided options so that headers can be changed
10382
+ // without mutating the original object.
10383
+ //
10384
+ options = { ...options, headers: {} };
10385
+
10386
+ if (headers) {
10387
+ for (const [key, value] of Object.entries(headers)) {
10388
+ options.headers[key.toLowerCase()] = value;
10389
+ }
10390
+ }
10391
+ } else if (websocket.listenerCount('redirect') === 0) {
10392
+ const isSameHost = isIpcUrl
10393
+ ? websocket._originalIpc
10394
+ ? opts.socketPath === websocket._originalHostOrSocketPath
10395
+ : false
10396
+ : websocket._originalIpc
10397
+ ? false
10398
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
10399
+
10400
+ if (!isSameHost || (websocket._originalSecure && !isSecure)) {
10401
+ //
10402
+ // Match curl 7.77.0 behavior and drop the following headers. These
10403
+ // headers are also dropped when following a redirect to a subdomain.
10404
+ //
10405
+ delete opts.headers.authorization;
10406
+ delete opts.headers.cookie;
10407
+
10408
+ if (!isSameHost) delete opts.headers.host;
10409
+
10410
+ opts.auth = undefined;
10411
+ }
10412
+ }
10413
+
10414
+ //
10415
+ // Match curl 7.77.0 behavior and make the first `Authorization` header win.
10416
+ // If the `Authorization` header is set, then there is nothing to do as it
10417
+ // will take precedence.
10418
+ //
10419
+ if (opts.auth && !options.headers.authorization) {
10420
+ options.headers.authorization =
10421
+ 'Basic ' + Buffer.from(opts.auth).toString('base64');
10422
+ }
10423
+
10424
+ req = websocket._req = request(opts);
10425
+
10426
+ if (websocket._redirects) {
10427
+ //
10428
+ // Unlike what is done for the `'upgrade'` event, no early exit is
10429
+ // triggered here if the user calls `websocket.close()` or
10430
+ // `websocket.terminate()` from a listener of the `'redirect'` event. This
10431
+ // is because the user can also call `request.destroy()` with an error
10432
+ // before calling `websocket.close()` or `websocket.terminate()` and this
10433
+ // would result in an error being emitted on the `request` object with no
10434
+ // `'error'` event listeners attached.
10435
+ //
10436
+ websocket.emit('redirect', websocket.url, req);
10437
+ }
10438
+ } else {
10439
+ req = websocket._req = request(opts);
10440
+ }
10441
+
10442
+ if (opts.timeout) {
10443
+ req.on('timeout', () => {
10444
+ abortHandshake(websocket, req, 'Opening handshake has timed out');
10445
+ });
10446
+ }
10447
+
10448
+ req.on('error', (err) => {
10449
+ if (req === null || req[kAborted]) return;
10450
+
10451
+ req = websocket._req = null;
10452
+ emitErrorAndClose(websocket, err);
10453
+ });
10454
+
10455
+ req.on('response', (res) => {
10456
+ const location = res.headers.location;
10457
+ const statusCode = res.statusCode;
10458
+
10459
+ if (
10460
+ location &&
10461
+ opts.followRedirects &&
10462
+ statusCode >= 300 &&
10463
+ statusCode < 400
10464
+ ) {
10465
+ if (++websocket._redirects > opts.maxRedirects) {
10466
+ abortHandshake(websocket, req, 'Maximum redirects exceeded');
10467
+ return;
10468
+ }
10469
+
10470
+ req.abort();
10471
+
10472
+ let addr;
10473
+
10474
+ try {
10475
+ addr = new URL(location, address);
10476
+ } catch (e) {
10477
+ const err = new SyntaxError(`Invalid URL: ${location}`);
10478
+ emitErrorAndClose(websocket, err);
10479
+ return;
10480
+ }
10481
+
10482
+ initAsClient(websocket, addr, protocols, options);
10483
+ } else if (!websocket.emit('unexpected-response', req, res)) {
10484
+ abortHandshake(
10485
+ websocket,
10486
+ req,
10487
+ `Unexpected server response: ${res.statusCode}`
10488
+ );
10489
+ }
10490
+ });
10491
+
10492
+ req.on('upgrade', (res, socket, head) => {
10493
+ websocket.emit('upgrade', res);
10494
+
10495
+ //
10496
+ // The user may have closed the connection from a listener of the
10497
+ // `'upgrade'` event.
10498
+ //
10499
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
10500
+
10501
+ req = websocket._req = null;
10502
+
10503
+ const upgrade = res.headers.upgrade;
10504
+
10505
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
10506
+ abortHandshake(websocket, socket, 'Invalid Upgrade header');
10507
+ return;
10508
+ }
10509
+
10510
+ const digest = createHash('sha1')
10511
+ .update(key + GUID)
10512
+ .digest('base64');
10513
+
10514
+ if (res.headers['sec-websocket-accept'] !== digest) {
10515
+ abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
10516
+ return;
10517
+ }
10518
+
10519
+ const serverProt = res.headers['sec-websocket-protocol'];
10520
+ let protError;
10521
+
10522
+ if (serverProt !== undefined) {
10523
+ if (!protocolSet.size) {
10524
+ protError = 'Server sent a subprotocol but none was requested';
10525
+ } else if (!protocolSet.has(serverProt)) {
10526
+ protError = 'Server sent an invalid subprotocol';
10527
+ }
10528
+ } else if (protocolSet.size) {
10529
+ protError = 'Server sent no subprotocol';
10530
+ }
10531
+
10532
+ if (protError) {
10533
+ abortHandshake(websocket, socket, protError);
10534
+ return;
10535
+ }
10536
+
10537
+ if (serverProt) websocket._protocol = serverProt;
10538
+
10539
+ const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
10540
+
10541
+ if (secWebSocketExtensions !== undefined) {
10542
+ if (!perMessageDeflate) {
10543
+ const message =
10544
+ 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
10545
+ 'was requested';
10546
+ abortHandshake(websocket, socket, message);
10547
+ return;
10548
+ }
10549
+
10550
+ let extensions;
10551
+
10552
+ try {
10553
+ extensions = parse(secWebSocketExtensions);
10554
+ } catch (err) {
10555
+ const message = 'Invalid Sec-WebSocket-Extensions header';
10556
+ abortHandshake(websocket, socket, message);
10557
+ return;
10558
+ }
10559
+
10560
+ const extensionNames = Object.keys(extensions);
10561
+
10562
+ if (
10563
+ extensionNames.length !== 1 ||
10564
+ extensionNames[0] !== PerMessageDeflate.extensionName
10565
+ ) {
10566
+ const message = 'Server indicated an extension that was not requested';
10567
+ abortHandshake(websocket, socket, message);
10568
+ return;
10569
+ }
10570
+
10571
+ try {
10572
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
10573
+ } catch (err) {
10574
+ const message = 'Invalid Sec-WebSocket-Extensions header';
10575
+ abortHandshake(websocket, socket, message);
10576
+ return;
10577
+ }
10578
+
10579
+ websocket._extensions[PerMessageDeflate.extensionName] =
10580
+ perMessageDeflate;
10581
+ }
10582
+
10583
+ websocket.setSocket(socket, head, {
10584
+ allowSynchronousEvents: opts.allowSynchronousEvents,
10585
+ generateMask: opts.generateMask,
10586
+ maxPayload: opts.maxPayload,
10587
+ skipUTF8Validation: opts.skipUTF8Validation
10588
+ });
10589
+ });
10590
+
10591
+ if (opts.finishRequest) {
10592
+ opts.finishRequest(req, websocket);
10593
+ } else {
10594
+ req.end();
10595
+ }
10596
+ }
10597
+
10598
+ /**
10599
+ * Emit the `'error'` and `'close'` events.
10600
+ *
10601
+ * @param {WebSocket} websocket The WebSocket instance
10602
+ * @param {Error} The error to emit
10603
+ * @private
10604
+ */
10605
+ function emitErrorAndClose(websocket, err) {
10606
+ websocket._readyState = WebSocket.CLOSING;
10607
+ //
10608
+ // The following assignment is practically useless and is done only for
10609
+ // consistency.
10610
+ //
10611
+ websocket._errorEmitted = true;
10612
+ websocket.emit('error', err);
10613
+ websocket.emitClose();
10614
+ }
10615
+
10616
+ /**
10617
+ * Create a `net.Socket` and initiate a connection.
10618
+ *
10619
+ * @param {Object} options Connection options
10620
+ * @return {net.Socket} The newly created socket used to start the connection
10621
+ * @private
10622
+ */
10623
+ function netConnect(options) {
10624
+ options.path = options.socketPath;
10625
+ return net.connect(options);
10626
+ }
10627
+
10628
+ /**
10629
+ * Create a `tls.TLSSocket` and initiate a connection.
10630
+ *
10631
+ * @param {Object} options Connection options
10632
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
10633
+ * @private
10634
+ */
10635
+ function tlsConnect(options) {
10636
+ options.path = undefined;
10637
+
10638
+ if (!options.servername && options.servername !== '') {
10639
+ options.servername = net.isIP(options.host) ? '' : options.host;
10640
+ }
10641
+
10642
+ return tls.connect(options);
10643
+ }
10644
+
10645
+ /**
10646
+ * Abort the handshake and emit an error.
10647
+ *
10648
+ * @param {WebSocket} websocket The WebSocket instance
10649
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
10650
+ * abort or the socket to destroy
10651
+ * @param {String} message The error message
10652
+ * @private
10653
+ */
10654
+ function abortHandshake(websocket, stream, message) {
10655
+ websocket._readyState = WebSocket.CLOSING;
10656
+
10657
+ const err = new Error(message);
10658
+ Error.captureStackTrace(err, abortHandshake);
10659
+
10660
+ if (stream.setHeader) {
10661
+ stream[kAborted] = true;
10662
+ stream.abort();
10663
+
10664
+ if (stream.socket && !stream.socket.destroyed) {
10665
+ //
10666
+ // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
10667
+ // called after the request completed. See
10668
+ // https://github.com/websockets/ws/issues/1869.
10669
+ //
10670
+ stream.socket.destroy();
10671
+ }
10672
+
10673
+ process.nextTick(emitErrorAndClose, websocket, err);
10674
+ } else {
10675
+ stream.destroy(err);
10676
+ stream.once('error', websocket.emit.bind(websocket, 'error'));
10677
+ stream.once('close', websocket.emitClose.bind(websocket));
10678
+ }
10679
+ }
10680
+
10681
+ /**
10682
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
10683
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
10684
+ *
10685
+ * @param {WebSocket} websocket The WebSocket instance
10686
+ * @param {*} [data] The data to send
10687
+ * @param {Function} [cb] Callback
10688
+ * @private
10689
+ */
10690
+ function sendAfterClose(websocket, data, cb) {
10691
+ if (data) {
10692
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
10693
+
10694
+ //
10695
+ // The `_bufferedAmount` property is used only when the peer is a client and
10696
+ // the opening handshake fails. Under these circumstances, in fact, the
10697
+ // `setSocket()` method is not called, so the `_socket` and `_sender`
10698
+ // properties are set to `null`.
10699
+ //
10700
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
10701
+ else websocket._bufferedAmount += length;
10702
+ }
10703
+
10704
+ if (cb) {
10705
+ const err = new Error(
10706
+ `WebSocket is not open: readyState ${websocket.readyState} ` +
10707
+ `(${readyStates[websocket.readyState]})`
10708
+ );
10709
+ process.nextTick(cb, err);
10710
+ }
10711
+ }
10712
+
10713
+ /**
10714
+ * The listener of the `Receiver` `'conclude'` event.
10715
+ *
10716
+ * @param {Number} code The status code
10717
+ * @param {Buffer} reason The reason for closing
10718
+ * @private
10719
+ */
10720
+ function receiverOnConclude(code, reason) {
10721
+ const websocket = this[kWebSocket];
10722
+
10723
+ websocket._closeFrameReceived = true;
10724
+ websocket._closeMessage = reason;
10725
+ websocket._closeCode = code;
10726
+
10727
+ if (websocket._socket[kWebSocket] === undefined) return;
10728
+
10729
+ websocket._socket.removeListener('data', socketOnData);
10730
+ process.nextTick(resume, websocket._socket);
10731
+
10732
+ if (code === 1005) websocket.close();
10733
+ else websocket.close(code, reason);
10734
+ }
10735
+
10736
+ /**
10737
+ * The listener of the `Receiver` `'drain'` event.
10738
+ *
10739
+ * @private
10740
+ */
10741
+ function receiverOnDrain() {
10742
+ const websocket = this[kWebSocket];
10743
+
10744
+ if (!websocket.isPaused) websocket._socket.resume();
10745
+ }
10746
+
10747
+ /**
10748
+ * The listener of the `Receiver` `'error'` event.
10749
+ *
10750
+ * @param {(RangeError|Error)} err The emitted error
10751
+ * @private
10752
+ */
10753
+ function receiverOnError(err) {
10754
+ const websocket = this[kWebSocket];
10755
+
10756
+ if (websocket._socket[kWebSocket] !== undefined) {
10757
+ websocket._socket.removeListener('data', socketOnData);
10758
+
10759
+ //
10760
+ // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
10761
+ // https://github.com/websockets/ws/issues/1940.
10762
+ //
10763
+ process.nextTick(resume, websocket._socket);
10764
+
10765
+ websocket.close(err[kStatusCode]);
10766
+ }
10767
+
10768
+ if (!websocket._errorEmitted) {
10769
+ websocket._errorEmitted = true;
10770
+ websocket.emit('error', err);
10771
+ }
10772
+ }
10773
+
10774
+ /**
10775
+ * The listener of the `Receiver` `'finish'` event.
10776
+ *
10777
+ * @private
10778
+ */
10779
+ function receiverOnFinish() {
10780
+ this[kWebSocket].emitClose();
10781
+ }
10782
+
10783
+ /**
10784
+ * The listener of the `Receiver` `'message'` event.
10785
+ *
10786
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
10787
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
10788
+ * @private
10789
+ */
10790
+ function receiverOnMessage(data, isBinary) {
10791
+ this[kWebSocket].emit('message', data, isBinary);
10792
+ }
10793
+
10794
+ /**
10795
+ * The listener of the `Receiver` `'ping'` event.
10796
+ *
10797
+ * @param {Buffer} data The data included in the ping frame
10798
+ * @private
10799
+ */
10800
+ function receiverOnPing(data) {
10801
+ const websocket = this[kWebSocket];
10802
+
10803
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
10804
+ websocket.emit('ping', data);
10805
+ }
10806
+
10807
+ /**
10808
+ * The listener of the `Receiver` `'pong'` event.
10809
+ *
10810
+ * @param {Buffer} data The data included in the pong frame
10811
+ * @private
10812
+ */
10813
+ function receiverOnPong(data) {
10814
+ this[kWebSocket].emit('pong', data);
10815
+ }
10816
+
10817
+ /**
10818
+ * Resume a readable stream
10819
+ *
10820
+ * @param {Readable} stream The readable stream
10821
+ * @private
10822
+ */
10823
+ function resume(stream) {
10824
+ stream.resume();
10825
+ }
10826
+
10827
+ /**
10828
+ * The `Sender` error event handler.
10829
+ *
10830
+ * @param {Error} The error
10831
+ * @private
10832
+ */
10833
+ function senderOnError(err) {
10834
+ const websocket = this[kWebSocket];
10835
+
10836
+ if (websocket.readyState === WebSocket.CLOSED) return;
10837
+ if (websocket.readyState === WebSocket.OPEN) {
10838
+ websocket._readyState = WebSocket.CLOSING;
10839
+ setCloseTimer(websocket);
10840
+ }
10841
+
10842
+ //
10843
+ // `socket.end()` is used instead of `socket.destroy()` to allow the other
10844
+ // peer to finish sending queued data. There is no need to set a timer here
10845
+ // because `CLOSING` means that it is already set or not needed.
10846
+ //
10847
+ this._socket.end();
10848
+
10849
+ if (!websocket._errorEmitted) {
10850
+ websocket._errorEmitted = true;
10851
+ websocket.emit('error', err);
10852
+ }
10853
+ }
10854
+
10855
+ /**
10856
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
10857
+ *
10858
+ * @param {WebSocket} websocket The WebSocket instance
10859
+ * @private
10860
+ */
10861
+ function setCloseTimer(websocket) {
10862
+ websocket._closeTimer = setTimeout(
10863
+ websocket._socket.destroy.bind(websocket._socket),
10864
+ closeTimeout
10865
+ );
10866
+ }
10867
+
10868
+ /**
10869
+ * The listener of the socket `'close'` event.
10870
+ *
10871
+ * @private
10872
+ */
10873
+ function socketOnClose() {
10874
+ const websocket = this[kWebSocket];
10875
+
10876
+ this.removeListener('close', socketOnClose);
10877
+ this.removeListener('data', socketOnData);
10878
+ this.removeListener('end', socketOnEnd);
10879
+
10880
+ websocket._readyState = WebSocket.CLOSING;
10881
+
10882
+ let chunk;
10883
+
10884
+ //
10885
+ // The close frame might not have been received or the `'end'` event emitted,
10886
+ // for example, if the socket was destroyed due to an error. Ensure that the
10887
+ // `receiver` stream is closed after writing any remaining buffered data to
10888
+ // it. If the readable side of the socket is in flowing mode then there is no
10889
+ // buffered data as everything has been already written and `readable.read()`
10890
+ // will return `null`. If instead, the socket is paused, any possible buffered
10891
+ // data will be read as a single chunk.
10892
+ //
10893
+ if (
10894
+ !this._readableState.endEmitted &&
10895
+ !websocket._closeFrameReceived &&
10896
+ !websocket._receiver._writableState.errorEmitted &&
10897
+ (chunk = websocket._socket.read()) !== null
10898
+ ) {
10899
+ websocket._receiver.write(chunk);
10900
+ }
10901
+
10902
+ websocket._receiver.end();
10903
+
10904
+ this[kWebSocket] = undefined;
10905
+
10906
+ clearTimeout(websocket._closeTimer);
10907
+
10908
+ if (
10909
+ websocket._receiver._writableState.finished ||
10910
+ websocket._receiver._writableState.errorEmitted
10911
+ ) {
10912
+ websocket.emitClose();
10913
+ } else {
10914
+ websocket._receiver.on('error', receiverOnFinish);
10915
+ websocket._receiver.on('finish', receiverOnFinish);
10916
+ }
10917
+ }
10918
+
10919
+ /**
10920
+ * The listener of the socket `'data'` event.
10921
+ *
10922
+ * @param {Buffer} chunk A chunk of data
10923
+ * @private
10924
+ */
10925
+ function socketOnData(chunk) {
10926
+ if (!this[kWebSocket]._receiver.write(chunk)) {
10927
+ this.pause();
10928
+ }
10929
+ }
10930
+
10931
+ /**
10932
+ * The listener of the socket `'end'` event.
10933
+ *
10934
+ * @private
10935
+ */
10936
+ function socketOnEnd() {
10937
+ const websocket = this[kWebSocket];
10938
+
10939
+ websocket._readyState = WebSocket.CLOSING;
10940
+ websocket._receiver.end();
10941
+ this.end();
10942
+ }
10943
+
10944
+ /**
10945
+ * The listener of the socket `'error'` event.
10946
+ *
10947
+ * @private
10948
+ */
10949
+ function socketOnError() {
10950
+ const websocket = this[kWebSocket];
10951
+
10952
+ this.removeListener('error', socketOnError);
10953
+ this.on('error', NOOP);
10954
+
10955
+ if (websocket) {
10956
+ websocket._readyState = WebSocket.CLOSING;
10957
+ this.destroy();
10958
+ }
10959
+ }
10960
+ return websocket;
10961
+ }
10962
+
10963
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */
10964
+
10965
+ var stream;
10966
+ var hasRequiredStream;
10967
+
10968
+ function requireStream () {
10969
+ if (hasRequiredStream) return stream;
10970
+ hasRequiredStream = 1;
10971
+
10972
+ requireWebsocket();
10973
+ const { Duplex } = require$$0$2;
10974
+
10975
+ /**
10976
+ * Emits the `'close'` event on a stream.
10977
+ *
10978
+ * @param {Duplex} stream The stream.
10979
+ * @private
10980
+ */
10981
+ function emitClose(stream) {
10982
+ stream.emit('close');
10983
+ }
10984
+
10985
+ /**
10986
+ * The listener of the `'end'` event.
10987
+ *
10988
+ * @private
10989
+ */
10990
+ function duplexOnEnd() {
10991
+ if (!this.destroyed && this._writableState.finished) {
10992
+ this.destroy();
10993
+ }
10994
+ }
10995
+
10996
+ /**
10997
+ * The listener of the `'error'` event.
10998
+ *
10999
+ * @param {Error} err The error
11000
+ * @private
11001
+ */
11002
+ function duplexOnError(err) {
11003
+ this.removeListener('error', duplexOnError);
11004
+ this.destroy();
11005
+ if (this.listenerCount('error') === 0) {
11006
+ // Do not suppress the throwing behavior.
11007
+ this.emit('error', err);
11008
+ }
11009
+ }
11010
+
11011
+ /**
11012
+ * Wraps a `WebSocket` in a duplex stream.
11013
+ *
11014
+ * @param {WebSocket} ws The `WebSocket` to wrap
11015
+ * @param {Object} [options] The options for the `Duplex` constructor
11016
+ * @return {Duplex} The duplex stream
11017
+ * @public
11018
+ */
11019
+ function createWebSocketStream(ws, options) {
11020
+ let terminateOnDestroy = true;
11021
+
11022
+ const duplex = new Duplex({
11023
+ ...options,
11024
+ autoDestroy: false,
11025
+ emitClose: false,
11026
+ objectMode: false,
11027
+ writableObjectMode: false
11028
+ });
11029
+
11030
+ ws.on('message', function message(msg, isBinary) {
11031
+ const data =
11032
+ !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
11033
+
11034
+ if (!duplex.push(data)) ws.pause();
11035
+ });
11036
+
11037
+ ws.once('error', function error(err) {
11038
+ if (duplex.destroyed) return;
11039
+
11040
+ // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
11041
+ //
11042
+ // - If the `'error'` event is emitted before the `'open'` event, then
11043
+ // `ws.terminate()` is a noop as no socket is assigned.
11044
+ // - Otherwise, the error is re-emitted by the listener of the `'error'`
11045
+ // event of the `Receiver` object. The listener already closes the
11046
+ // connection by calling `ws.close()`. This allows a close frame to be
11047
+ // sent to the other peer. If `ws.terminate()` is called right after this,
11048
+ // then the close frame might not be sent.
11049
+ terminateOnDestroy = false;
11050
+ duplex.destroy(err);
11051
+ });
11052
+
11053
+ ws.once('close', function close() {
11054
+ if (duplex.destroyed) return;
11055
+
11056
+ duplex.push(null);
11057
+ });
11058
+
11059
+ duplex._destroy = function (err, callback) {
11060
+ if (ws.readyState === ws.CLOSED) {
11061
+ callback(err);
11062
+ process.nextTick(emitClose, duplex);
11063
+ return;
11064
+ }
11065
+
11066
+ let called = false;
11067
+
11068
+ ws.once('error', function error(err) {
11069
+ called = true;
11070
+ callback(err);
11071
+ });
11072
+
11073
+ ws.once('close', function close() {
11074
+ if (!called) callback(err);
11075
+ process.nextTick(emitClose, duplex);
11076
+ });
11077
+
11078
+ if (terminateOnDestroy) ws.terminate();
11079
+ };
11080
+
11081
+ duplex._final = function (callback) {
11082
+ if (ws.readyState === ws.CONNECTING) {
11083
+ ws.once('open', function open() {
11084
+ duplex._final(callback);
11085
+ });
11086
+ return;
11087
+ }
11088
+
11089
+ // If the value of the `_socket` property is `null` it means that `ws` is a
11090
+ // client websocket and the handshake failed. In fact, when this happens, a
11091
+ // socket is never assigned to the websocket. Wait for the `'error'` event
11092
+ // that will be emitted by the websocket.
11093
+ if (ws._socket === null) return;
11094
+
11095
+ if (ws._socket._writableState.finished) {
11096
+ callback();
11097
+ if (duplex._readableState.endEmitted) duplex.destroy();
11098
+ } else {
11099
+ ws._socket.once('finish', function finish() {
11100
+ // `duplex` is not destroyed here because the `'end'` event will be
11101
+ // emitted on `duplex` after this `'finish'` event. The EOF signaling
11102
+ // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
11103
+ callback();
11104
+ });
11105
+ ws.close();
11106
+ }
11107
+ };
11108
+
11109
+ duplex._read = function () {
11110
+ if (ws.isPaused) ws.resume();
11111
+ };
11112
+
11113
+ duplex._write = function (chunk, encoding, callback) {
11114
+ if (ws.readyState === ws.CONNECTING) {
11115
+ ws.once('open', function open() {
11116
+ duplex._write(chunk, encoding, callback);
11117
+ });
11118
+ return;
11119
+ }
11120
+
11121
+ ws.send(chunk, callback);
11122
+ };
11123
+
11124
+ duplex.on('end', duplexOnEnd);
11125
+ duplex.on('error', duplexOnError);
11126
+ return duplex;
11127
+ }
11128
+
11129
+ stream = createWebSocketStream;
11130
+ return stream;
11131
+ }
11132
+
11133
+ requireStream();
11134
+
11135
+ requireReceiver();
11136
+
11137
+ requireSender();
11138
+
11139
+ requireWebsocket();
11140
+
11141
+ var subprotocol;
11142
+ var hasRequiredSubprotocol;
11143
+
11144
+ function requireSubprotocol () {
11145
+ if (hasRequiredSubprotocol) return subprotocol;
11146
+ hasRequiredSubprotocol = 1;
11147
+
11148
+ const { tokenChars } = requireValidation();
11149
+
11150
+ /**
11151
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
11152
+ *
11153
+ * @param {String} header The field value of the header
11154
+ * @return {Set} The subprotocol names
11155
+ * @public
11156
+ */
11157
+ function parse(header) {
11158
+ const protocols = new Set();
11159
+ let start = -1;
11160
+ let end = -1;
11161
+ let i = 0;
11162
+
11163
+ for (i; i < header.length; i++) {
11164
+ const code = header.charCodeAt(i);
11165
+
11166
+ if (end === -1 && tokenChars[code] === 1) {
11167
+ if (start === -1) start = i;
11168
+ } else if (
11169
+ i !== 0 &&
11170
+ (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
11171
+ ) {
11172
+ if (end === -1 && start !== -1) end = i;
11173
+ } else if (code === 0x2c /* ',' */) {
11174
+ if (start === -1) {
11175
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11176
+ }
11177
+
11178
+ if (end === -1) end = i;
11179
+
11180
+ const protocol = header.slice(start, end);
11181
+
11182
+ if (protocols.has(protocol)) {
11183
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
11184
+ }
11185
+
11186
+ protocols.add(protocol);
11187
+ start = end = -1;
11188
+ } else {
11189
+ throw new SyntaxError(`Unexpected character at index ${i}`);
11190
+ }
11191
+ }
11192
+
11193
+ if (start === -1 || end !== -1) {
11194
+ throw new SyntaxError('Unexpected end of input');
11195
+ }
11196
+
11197
+ const protocol = header.slice(start, i);
11198
+
11199
+ if (protocols.has(protocol)) {
11200
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
11201
+ }
11202
+
11203
+ protocols.add(protocol);
11204
+ return protocols;
11205
+ }
11206
+
11207
+ subprotocol = { parse };
11208
+ return subprotocol;
11209
+ }
11210
+
11211
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
11212
+
11213
+ var websocketServer;
11214
+ var hasRequiredWebsocketServer;
11215
+
11216
+ function requireWebsocketServer () {
11217
+ if (hasRequiredWebsocketServer) return websocketServer;
11218
+ hasRequiredWebsocketServer = 1;
11219
+
11220
+ const EventEmitter = require$$0$3;
11221
+ const http$1 = http;
11222
+ const { Duplex } = require$$0$2;
11223
+ const { createHash } = require$$1;
11224
+
11225
+ const extension = requireExtension();
11226
+ const PerMessageDeflate = requirePermessageDeflate();
11227
+ const subprotocol = requireSubprotocol();
11228
+ const WebSocket = requireWebsocket();
11229
+ const { GUID, kWebSocket } = requireConstants();
11230
+
11231
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
11232
+
11233
+ const RUNNING = 0;
11234
+ const CLOSING = 1;
11235
+ const CLOSED = 2;
11236
+
11237
+ /**
11238
+ * Class representing a WebSocket server.
11239
+ *
11240
+ * @extends EventEmitter
11241
+ */
11242
+ class WebSocketServer extends EventEmitter {
11243
+ /**
11244
+ * Create a `WebSocketServer` instance.
11245
+ *
11246
+ * @param {Object} options Configuration options
11247
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
11248
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
11249
+ * multiple times in the same tick
11250
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
11251
+ * automatically send a pong in response to a ping
11252
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
11253
+ * pending connections
11254
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
11255
+ * track clients
11256
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
11257
+ * @param {String} [options.host] The hostname where to bind the server
11258
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
11259
+ * size
11260
+ * @param {Boolean} [options.noServer=false] Enable no server mode
11261
+ * @param {String} [options.path] Accept only connections matching this path
11262
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
11263
+ * permessage-deflate
11264
+ * @param {Number} [options.port] The port where to bind the server
11265
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
11266
+ * server to use
11267
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
11268
+ * not to skip UTF-8 validation for text and close messages
11269
+ * @param {Function} [options.verifyClient] A hook to reject connections
11270
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
11271
+ * class to use. It must be the `WebSocket` class or class that extends it
11272
+ * @param {Function} [callback] A listener for the `listening` event
11273
+ */
11274
+ constructor(options, callback) {
11275
+ super();
11276
+
11277
+ options = {
11278
+ allowSynchronousEvents: true,
11279
+ autoPong: true,
11280
+ maxPayload: 100 * 1024 * 1024,
11281
+ skipUTF8Validation: false,
11282
+ perMessageDeflate: false,
11283
+ handleProtocols: null,
11284
+ clientTracking: true,
11285
+ verifyClient: null,
11286
+ noServer: false,
11287
+ backlog: null, // use default (511 as implemented in net.js)
11288
+ server: null,
11289
+ host: null,
11290
+ path: null,
11291
+ port: null,
11292
+ WebSocket,
11293
+ ...options
11294
+ };
11295
+
11296
+ if (
11297
+ (options.port == null && !options.server && !options.noServer) ||
11298
+ (options.port != null && (options.server || options.noServer)) ||
11299
+ (options.server && options.noServer)
11300
+ ) {
11301
+ throw new TypeError(
11302
+ 'One and only one of the "port", "server", or "noServer" options ' +
11303
+ 'must be specified'
11304
+ );
11305
+ }
11306
+
11307
+ if (options.port != null) {
11308
+ this._server = http$1.createServer((req, res) => {
11309
+ const body = http$1.STATUS_CODES[426];
11310
+
11311
+ res.writeHead(426, {
11312
+ 'Content-Length': body.length,
11313
+ 'Content-Type': 'text/plain'
11314
+ });
11315
+ res.end(body);
11316
+ });
11317
+ this._server.listen(
11318
+ options.port,
11319
+ options.host,
11320
+ options.backlog,
11321
+ callback
11322
+ );
11323
+ } else if (options.server) {
11324
+ this._server = options.server;
11325
+ }
11326
+
11327
+ if (this._server) {
11328
+ const emitConnection = this.emit.bind(this, 'connection');
11329
+
11330
+ this._removeListeners = addListeners(this._server, {
11331
+ listening: this.emit.bind(this, 'listening'),
11332
+ error: this.emit.bind(this, 'error'),
11333
+ upgrade: (req, socket, head) => {
11334
+ this.handleUpgrade(req, socket, head, emitConnection);
11335
+ }
11336
+ });
11337
+ }
11338
+
11339
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
11340
+ if (options.clientTracking) {
11341
+ this.clients = new Set();
11342
+ this._shouldEmitClose = false;
11343
+ }
11344
+
11345
+ this.options = options;
11346
+ this._state = RUNNING;
11347
+ }
11348
+
11349
+ /**
11350
+ * Returns the bound address, the address family name, and port of the server
11351
+ * as reported by the operating system if listening on an IP socket.
11352
+ * If the server is listening on a pipe or UNIX domain socket, the name is
11353
+ * returned as a string.
11354
+ *
11355
+ * @return {(Object|String|null)} The address of the server
11356
+ * @public
11357
+ */
11358
+ address() {
11359
+ if (this.options.noServer) {
11360
+ throw new Error('The server is operating in "noServer" mode');
11361
+ }
11362
+
11363
+ if (!this._server) return null;
11364
+ return this._server.address();
11365
+ }
11366
+
11367
+ /**
11368
+ * Stop the server from accepting new connections and emit the `'close'` event
11369
+ * when all existing connections are closed.
11370
+ *
11371
+ * @param {Function} [cb] A one-time listener for the `'close'` event
11372
+ * @public
11373
+ */
11374
+ close(cb) {
11375
+ if (this._state === CLOSED) {
11376
+ if (cb) {
11377
+ this.once('close', () => {
11378
+ cb(new Error('The server is not running'));
11379
+ });
11380
+ }
11381
+
11382
+ process.nextTick(emitClose, this);
11383
+ return;
11384
+ }
11385
+
11386
+ if (cb) this.once('close', cb);
11387
+
11388
+ if (this._state === CLOSING) return;
11389
+ this._state = CLOSING;
11390
+
11391
+ if (this.options.noServer || this.options.server) {
11392
+ if (this._server) {
11393
+ this._removeListeners();
11394
+ this._removeListeners = this._server = null;
11395
+ }
11396
+
11397
+ if (this.clients) {
11398
+ if (!this.clients.size) {
11399
+ process.nextTick(emitClose, this);
11400
+ } else {
11401
+ this._shouldEmitClose = true;
11402
+ }
11403
+ } else {
11404
+ process.nextTick(emitClose, this);
11405
+ }
11406
+ } else {
11407
+ const server = this._server;
11408
+
11409
+ this._removeListeners();
11410
+ this._removeListeners = this._server = null;
11411
+
11412
+ //
11413
+ // The HTTP/S server was created internally. Close it, and rely on its
11414
+ // `'close'` event.
11415
+ //
11416
+ server.close(() => {
11417
+ emitClose(this);
11418
+ });
11419
+ }
11420
+ }
11421
+
11422
+ /**
11423
+ * See if a given request should be handled by this server instance.
11424
+ *
11425
+ * @param {http.IncomingMessage} req Request object to inspect
11426
+ * @return {Boolean} `true` if the request is valid, else `false`
11427
+ * @public
11428
+ */
11429
+ shouldHandle(req) {
11430
+ if (this.options.path) {
11431
+ const index = req.url.indexOf('?');
11432
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
11433
+
11434
+ if (pathname !== this.options.path) return false;
11435
+ }
11436
+
11437
+ return true;
11438
+ }
11439
+
11440
+ /**
11441
+ * Handle a HTTP Upgrade request.
11442
+ *
11443
+ * @param {http.IncomingMessage} req The request object
11444
+ * @param {Duplex} socket The network socket between the server and client
11445
+ * @param {Buffer} head The first packet of the upgraded stream
11446
+ * @param {Function} cb Callback
11447
+ * @public
11448
+ */
11449
+ handleUpgrade(req, socket, head, cb) {
11450
+ socket.on('error', socketOnError);
11451
+
11452
+ const key = req.headers['sec-websocket-key'];
11453
+ const upgrade = req.headers.upgrade;
11454
+ const version = +req.headers['sec-websocket-version'];
11455
+
11456
+ if (req.method !== 'GET') {
11457
+ const message = 'Invalid HTTP method';
11458
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
11459
+ return;
11460
+ }
11461
+
11462
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
11463
+ const message = 'Invalid Upgrade header';
11464
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
11465
+ return;
11466
+ }
11467
+
11468
+ if (key === undefined || !keyRegex.test(key)) {
11469
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
11470
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
11471
+ return;
11472
+ }
11473
+
11474
+ if (version !== 8 && version !== 13) {
11475
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
11476
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
11477
+ return;
11478
+ }
11479
+
11480
+ if (!this.shouldHandle(req)) {
11481
+ abortHandshake(socket, 400);
11482
+ return;
11483
+ }
11484
+
11485
+ const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
11486
+ let protocols = new Set();
11487
+
11488
+ if (secWebSocketProtocol !== undefined) {
11489
+ try {
11490
+ protocols = subprotocol.parse(secWebSocketProtocol);
11491
+ } catch (err) {
11492
+ const message = 'Invalid Sec-WebSocket-Protocol header';
11493
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
11494
+ return;
11495
+ }
11496
+ }
11497
+
11498
+ const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
11499
+ const extensions = {};
11500
+
11501
+ if (
11502
+ this.options.perMessageDeflate &&
11503
+ secWebSocketExtensions !== undefined
11504
+ ) {
11505
+ const perMessageDeflate = new PerMessageDeflate(
11506
+ this.options.perMessageDeflate,
11507
+ true,
11508
+ this.options.maxPayload
11509
+ );
11510
+
11511
+ try {
11512
+ const offers = extension.parse(secWebSocketExtensions);
11513
+
11514
+ if (offers[PerMessageDeflate.extensionName]) {
11515
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
11516
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
11517
+ }
11518
+ } catch (err) {
11519
+ const message =
11520
+ 'Invalid or unacceptable Sec-WebSocket-Extensions header';
11521
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
11522
+ return;
11523
+ }
11524
+ }
11525
+
11526
+ //
11527
+ // Optionally call external client verification handler.
11528
+ //
11529
+ if (this.options.verifyClient) {
11530
+ const info = {
11531
+ origin:
11532
+ req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
11533
+ secure: !!(req.socket.authorized || req.socket.encrypted),
11534
+ req
11535
+ };
11536
+
11537
+ if (this.options.verifyClient.length === 2) {
11538
+ this.options.verifyClient(info, (verified, code, message, headers) => {
11539
+ if (!verified) {
11540
+ return abortHandshake(socket, code || 401, message, headers);
11541
+ }
11542
+
11543
+ this.completeUpgrade(
11544
+ extensions,
11545
+ key,
11546
+ protocols,
11547
+ req,
11548
+ socket,
11549
+ head,
11550
+ cb
11551
+ );
11552
+ });
11553
+ return;
11554
+ }
11555
+
11556
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
11557
+ }
11558
+
11559
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
11560
+ }
11561
+
11562
+ /**
11563
+ * Upgrade the connection to WebSocket.
11564
+ *
11565
+ * @param {Object} extensions The accepted extensions
11566
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
11567
+ * @param {Set} protocols The subprotocols
11568
+ * @param {http.IncomingMessage} req The request object
11569
+ * @param {Duplex} socket The network socket between the server and client
11570
+ * @param {Buffer} head The first packet of the upgraded stream
11571
+ * @param {Function} cb Callback
11572
+ * @throws {Error} If called more than once with the same socket
11573
+ * @private
11574
+ */
11575
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
11576
+ //
11577
+ // Destroy the socket if the client has already sent a FIN packet.
11578
+ //
11579
+ if (!socket.readable || !socket.writable) return socket.destroy();
11580
+
11581
+ if (socket[kWebSocket]) {
11582
+ throw new Error(
11583
+ 'server.handleUpgrade() was called more than once with the same ' +
11584
+ 'socket, possibly due to a misconfiguration'
11585
+ );
11586
+ }
11587
+
11588
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
11589
+
11590
+ const digest = createHash('sha1')
11591
+ .update(key + GUID)
11592
+ .digest('base64');
11593
+
11594
+ const headers = [
11595
+ 'HTTP/1.1 101 Switching Protocols',
11596
+ 'Upgrade: websocket',
11597
+ 'Connection: Upgrade',
11598
+ `Sec-WebSocket-Accept: ${digest}`
11599
+ ];
11600
+
11601
+ const ws = new this.options.WebSocket(null, undefined, this.options);
11602
+
11603
+ if (protocols.size) {
11604
+ //
11605
+ // Optionally call external protocol selection handler.
11606
+ //
11607
+ const protocol = this.options.handleProtocols
11608
+ ? this.options.handleProtocols(protocols, req)
11609
+ : protocols.values().next().value;
11610
+
11611
+ if (protocol) {
11612
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
11613
+ ws._protocol = protocol;
11614
+ }
11615
+ }
11616
+
11617
+ if (extensions[PerMessageDeflate.extensionName]) {
11618
+ const params = extensions[PerMessageDeflate.extensionName].params;
11619
+ const value = extension.format({
11620
+ [PerMessageDeflate.extensionName]: [params]
11621
+ });
11622
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
11623
+ ws._extensions = extensions;
11624
+ }
11625
+
11626
+ //
11627
+ // Allow external modification/inspection of handshake headers.
11628
+ //
11629
+ this.emit('headers', headers, req);
11630
+
11631
+ socket.write(headers.concat('\r\n').join('\r\n'));
11632
+ socket.removeListener('error', socketOnError);
11633
+
11634
+ ws.setSocket(socket, head, {
11635
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
11636
+ maxPayload: this.options.maxPayload,
11637
+ skipUTF8Validation: this.options.skipUTF8Validation
11638
+ });
11639
+
11640
+ if (this.clients) {
11641
+ this.clients.add(ws);
11642
+ ws.on('close', () => {
11643
+ this.clients.delete(ws);
11644
+
11645
+ if (this._shouldEmitClose && !this.clients.size) {
11646
+ process.nextTick(emitClose, this);
11647
+ }
11648
+ });
11649
+ }
11650
+
11651
+ cb(ws, req);
11652
+ }
11653
+ }
11654
+
11655
+ websocketServer = WebSocketServer;
11656
+
11657
+ /**
11658
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
11659
+ * pairs.
11660
+ *
11661
+ * @param {EventEmitter} server The event emitter
11662
+ * @param {Object.<String, Function>} map The listeners to add
11663
+ * @return {Function} A function that will remove the added listeners when
11664
+ * called
11665
+ * @private
11666
+ */
11667
+ function addListeners(server, map) {
11668
+ for (const event of Object.keys(map)) server.on(event, map[event]);
11669
+
11670
+ return function removeListeners() {
11671
+ for (const event of Object.keys(map)) {
11672
+ server.removeListener(event, map[event]);
11673
+ }
11674
+ };
11675
+ }
11676
+
11677
+ /**
11678
+ * Emit a `'close'` event on an `EventEmitter`.
11679
+ *
11680
+ * @param {EventEmitter} server The event emitter
11681
+ * @private
11682
+ */
11683
+ function emitClose(server) {
11684
+ server._state = CLOSED;
11685
+ server.emit('close');
11686
+ }
11687
+
11688
+ /**
11689
+ * Handle socket errors.
11690
+ *
11691
+ * @private
11692
+ */
11693
+ function socketOnError() {
11694
+ this.destroy();
11695
+ }
11696
+
11697
+ /**
11698
+ * Close the connection when preconditions are not fulfilled.
11699
+ *
11700
+ * @param {Duplex} socket The socket of the upgrade request
11701
+ * @param {Number} code The HTTP response status code
11702
+ * @param {String} [message] The HTTP response body
11703
+ * @param {Object} [headers] Additional HTTP response headers
11704
+ * @private
11705
+ */
11706
+ function abortHandshake(socket, code, message, headers) {
11707
+ //
11708
+ // The socket is writable unless the user destroyed or ended it before calling
11709
+ // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
11710
+ // error. Handling this does not make much sense as the worst that can happen
11711
+ // is that some of the data written by the user might be discarded due to the
11712
+ // call to `socket.end()` below, which triggers an `'error'` event that in
11713
+ // turn causes the socket to be destroyed.
11714
+ //
11715
+ message = message || http$1.STATUS_CODES[code];
11716
+ headers = {
11717
+ Connection: 'close',
11718
+ 'Content-Type': 'text/html',
11719
+ 'Content-Length': Buffer.byteLength(message),
11720
+ ...headers
11721
+ };
11722
+
11723
+ socket.once('finish', socket.destroy);
11724
+
11725
+ socket.end(
11726
+ `HTTP/1.1 ${code} ${http$1.STATUS_CODES[code]}\r\n` +
11727
+ Object.keys(headers)
11728
+ .map((h) => `${h}: ${headers[h]}`)
11729
+ .join('\r\n') +
11730
+ '\r\n\r\n' +
11731
+ message
11732
+ );
11733
+ }
11734
+
11735
+ /**
11736
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
11737
+ * one listener for it, otherwise call `abortHandshake()`.
11738
+ *
11739
+ * @param {WebSocketServer} server The WebSocket server
11740
+ * @param {http.IncomingMessage} req The request object
11741
+ * @param {Duplex} socket The socket of the upgrade request
11742
+ * @param {Number} code The HTTP response status code
11743
+ * @param {String} message The HTTP response body
11744
+ * @private
11745
+ */
11746
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
11747
+ if (server.listenerCount('wsClientError')) {
11748
+ const err = new Error(message);
11749
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
11750
+
11751
+ server.emit('wsClientError', err, socket, req);
11752
+ } else {
11753
+ abortHandshake(socket, code, message);
11754
+ }
11755
+ }
11756
+ return websocketServer;
6838
11757
  }
6839
11758
 
6840
- var browserExports = requireBrowser();
11759
+ var websocketServerExports = requireWebsocketServer();
11760
+ var WebSocketServer = /*@__PURE__*/getDefaultExportFromCjs(websocketServerExports);
6841
11761
 
6842
11762
  const parseIfJson = (input) => {
6843
11763
  try {
@@ -6941,7 +11861,7 @@ class WsServerBase {
6941
11861
  class WsServer extends WsServerBase {
6942
11862
  server;
6943
11863
  constructor(server, opts) {
6944
- const wss = new browserExports.WebSocketServer({ noServer: true });
11864
+ const wss = new WebSocketServer({ noServer: true });
6945
11865
  const path = server.path;
6946
11866
  super({ wss });
6947
11867
  this.server = server;