@kevisual/router 0.0.11 → 0.0.13

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