@naeemo/capnp 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
9
10
  var __copyProps = (to, from, except, desc) => {
10
11
  if (from && typeof from === "object" || typeof from === "function") {
11
12
  for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
@@ -29,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
30
  const require_rpc_connection = require('./rpc-connection-_eHtWsk2.js');
30
31
  let node_net = require("node:net");
31
32
  node_net = __toESM(node_net);
33
+ let node_events = require("node:events");
32
34
 
33
35
  //#region src/core/pointer.ts
34
36
  /**
@@ -6215,11 +6217,3763 @@ var SchemaCapabilityClient = class {
6215
6217
  }
6216
6218
  };
6217
6219
 
6220
+ //#endregion
6221
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/constants.js
6222
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6223
+ const BINARY_TYPES = [
6224
+ "nodebuffer",
6225
+ "arraybuffer",
6226
+ "fragments"
6227
+ ];
6228
+ const hasBlob = typeof Blob !== "undefined";
6229
+ if (hasBlob) BINARY_TYPES.push("blob");
6230
+ module.exports = {
6231
+ BINARY_TYPES,
6232
+ CLOSE_TIMEOUT: 3e4,
6233
+ EMPTY_BUFFER: Buffer.alloc(0),
6234
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
6235
+ hasBlob,
6236
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
6237
+ kListener: Symbol("kListener"),
6238
+ kStatusCode: Symbol("status-code"),
6239
+ kWebSocket: Symbol("websocket"),
6240
+ NOOP: () => {}
6241
+ };
6242
+ }));
6243
+
6244
+ //#endregion
6245
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/buffer-util.js
6246
+ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6247
+ const { EMPTY_BUFFER } = require_constants();
6248
+ const FastBuffer = Buffer[Symbol.species];
6249
+ /**
6250
+ * Merges an array of buffers into a new buffer.
6251
+ *
6252
+ * @param {Buffer[]} list The array of buffers to concat
6253
+ * @param {Number} totalLength The total length of buffers in the list
6254
+ * @return {Buffer} The resulting buffer
6255
+ * @public
6256
+ */
6257
+ function concat(list, totalLength) {
6258
+ if (list.length === 0) return EMPTY_BUFFER;
6259
+ if (list.length === 1) return list[0];
6260
+ const target = Buffer.allocUnsafe(totalLength);
6261
+ let offset = 0;
6262
+ for (let i = 0; i < list.length; i++) {
6263
+ const buf = list[i];
6264
+ target.set(buf, offset);
6265
+ offset += buf.length;
6266
+ }
6267
+ if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
6268
+ return target;
6269
+ }
6270
+ /**
6271
+ * Masks a buffer using the given mask.
6272
+ *
6273
+ * @param {Buffer} source The buffer to mask
6274
+ * @param {Buffer} mask The mask to use
6275
+ * @param {Buffer} output The buffer where to store the result
6276
+ * @param {Number} offset The offset at which to start writing
6277
+ * @param {Number} length The number of bytes to mask.
6278
+ * @public
6279
+ */
6280
+ function _mask(source, mask, output, offset, length) {
6281
+ for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
6282
+ }
6283
+ /**
6284
+ * Unmasks a buffer using the given mask.
6285
+ *
6286
+ * @param {Buffer} buffer The buffer to unmask
6287
+ * @param {Buffer} mask The mask to use
6288
+ * @public
6289
+ */
6290
+ function _unmask(buffer, mask) {
6291
+ for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
6292
+ }
6293
+ /**
6294
+ * Converts a buffer to an `ArrayBuffer`.
6295
+ *
6296
+ * @param {Buffer} buf The buffer to convert
6297
+ * @return {ArrayBuffer} Converted buffer
6298
+ * @public
6299
+ */
6300
+ function toArrayBuffer(buf) {
6301
+ if (buf.length === buf.buffer.byteLength) return buf.buffer;
6302
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
6303
+ }
6304
+ /**
6305
+ * Converts `data` to a `Buffer`.
6306
+ *
6307
+ * @param {*} data The data to convert
6308
+ * @return {Buffer} The buffer
6309
+ * @throws {TypeError}
6310
+ * @public
6311
+ */
6312
+ function toBuffer(data) {
6313
+ toBuffer.readOnly = true;
6314
+ if (Buffer.isBuffer(data)) return data;
6315
+ let buf;
6316
+ if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
6317
+ else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
6318
+ else {
6319
+ buf = Buffer.from(data);
6320
+ toBuffer.readOnly = false;
6321
+ }
6322
+ return buf;
6323
+ }
6324
+ module.exports = {
6325
+ concat,
6326
+ mask: _mask,
6327
+ toArrayBuffer,
6328
+ toBuffer,
6329
+ unmask: _unmask
6330
+ };
6331
+ /* istanbul ignore else */
6332
+ if (!process.env.WS_NO_BUFFER_UTIL) try {
6333
+ const bufferUtil = require("bufferutil");
6334
+ module.exports.mask = function(source, mask, output, offset, length) {
6335
+ if (length < 48) _mask(source, mask, output, offset, length);
6336
+ else bufferUtil.mask(source, mask, output, offset, length);
6337
+ };
6338
+ module.exports.unmask = function(buffer, mask) {
6339
+ if (buffer.length < 32) _unmask(buffer, mask);
6340
+ else bufferUtil.unmask(buffer, mask);
6341
+ };
6342
+ } catch (e) {}
6343
+ }));
6344
+
6345
+ //#endregion
6346
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/limiter.js
6347
+ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6348
+ const kDone = Symbol("kDone");
6349
+ const kRun = Symbol("kRun");
6350
+ /**
6351
+ * A very simple job queue with adjustable concurrency. Adapted from
6352
+ * https://github.com/STRML/async-limiter
6353
+ */
6354
+ var Limiter = class {
6355
+ /**
6356
+ * Creates a new `Limiter`.
6357
+ *
6358
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
6359
+ * to run concurrently
6360
+ */
6361
+ constructor(concurrency) {
6362
+ this[kDone] = () => {
6363
+ this.pending--;
6364
+ this[kRun]();
6365
+ };
6366
+ this.concurrency = concurrency || Infinity;
6367
+ this.jobs = [];
6368
+ this.pending = 0;
6369
+ }
6370
+ /**
6371
+ * Adds a job to the queue.
6372
+ *
6373
+ * @param {Function} job The job to run
6374
+ * @public
6375
+ */
6376
+ add(job) {
6377
+ this.jobs.push(job);
6378
+ this[kRun]();
6379
+ }
6380
+ /**
6381
+ * Removes a job from the queue and runs it if possible.
6382
+ *
6383
+ * @private
6384
+ */
6385
+ [kRun]() {
6386
+ if (this.pending === this.concurrency) return;
6387
+ if (this.jobs.length) {
6388
+ const job = this.jobs.shift();
6389
+ this.pending++;
6390
+ job(this[kDone]);
6391
+ }
6392
+ }
6393
+ };
6394
+ module.exports = Limiter;
6395
+ }));
6396
+
6397
+ //#endregion
6398
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/permessage-deflate.js
6399
+ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6400
+ const zlib = require("zlib");
6401
+ const bufferUtil = require_buffer_util();
6402
+ const Limiter = require_limiter();
6403
+ const { kStatusCode } = require_constants();
6404
+ const FastBuffer = Buffer[Symbol.species];
6405
+ const TRAILER = Buffer.from([
6406
+ 0,
6407
+ 0,
6408
+ 255,
6409
+ 255
6410
+ ]);
6411
+ const kPerMessageDeflate = Symbol("permessage-deflate");
6412
+ const kTotalLength = Symbol("total-length");
6413
+ const kCallback = Symbol("callback");
6414
+ const kBuffers = Symbol("buffers");
6415
+ const kError = Symbol("error");
6416
+ let zlibLimiter;
6417
+ /**
6418
+ * permessage-deflate implementation.
6419
+ */
6420
+ var PerMessageDeflate = class {
6421
+ /**
6422
+ * Creates a PerMessageDeflate instance.
6423
+ *
6424
+ * @param {Object} [options] Configuration options
6425
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
6426
+ * for, or request, a custom client window size
6427
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
6428
+ * acknowledge disabling of client context takeover
6429
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
6430
+ * calls to zlib
6431
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
6432
+ * use of a custom server window size
6433
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
6434
+ * disabling of server context takeover
6435
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
6436
+ * messages should not be compressed if context takeover is disabled
6437
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
6438
+ * deflate
6439
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
6440
+ * inflate
6441
+ * @param {Boolean} [isServer=false] Create the instance in either server or
6442
+ * client mode
6443
+ * @param {Number} [maxPayload=0] The maximum allowed message length
6444
+ */
6445
+ constructor(options, isServer, maxPayload) {
6446
+ this._maxPayload = maxPayload | 0;
6447
+ this._options = options || {};
6448
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
6449
+ this._isServer = !!isServer;
6450
+ this._deflate = null;
6451
+ this._inflate = null;
6452
+ this.params = null;
6453
+ if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
6454
+ }
6455
+ /**
6456
+ * @type {String}
6457
+ */
6458
+ static get extensionName() {
6459
+ return "permessage-deflate";
6460
+ }
6461
+ /**
6462
+ * Create an extension negotiation offer.
6463
+ *
6464
+ * @return {Object} Extension parameters
6465
+ * @public
6466
+ */
6467
+ offer() {
6468
+ const params = {};
6469
+ if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
6470
+ if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
6471
+ if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
6472
+ if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
6473
+ else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
6474
+ return params;
6475
+ }
6476
+ /**
6477
+ * Accept an extension negotiation offer/response.
6478
+ *
6479
+ * @param {Array} configurations The extension negotiation offers/reponse
6480
+ * @return {Object} Accepted configuration
6481
+ * @public
6482
+ */
6483
+ accept(configurations) {
6484
+ configurations = this.normalizeParams(configurations);
6485
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
6486
+ return this.params;
6487
+ }
6488
+ /**
6489
+ * Releases all resources used by the extension.
6490
+ *
6491
+ * @public
6492
+ */
6493
+ cleanup() {
6494
+ if (this._inflate) {
6495
+ this._inflate.close();
6496
+ this._inflate = null;
6497
+ }
6498
+ if (this._deflate) {
6499
+ const callback = this._deflate[kCallback];
6500
+ this._deflate.close();
6501
+ this._deflate = null;
6502
+ if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
6503
+ }
6504
+ }
6505
+ /**
6506
+ * Accept an extension negotiation offer.
6507
+ *
6508
+ * @param {Array} offers The extension negotiation offers
6509
+ * @return {Object} Accepted configuration
6510
+ * @private
6511
+ */
6512
+ acceptAsServer(offers) {
6513
+ const opts = this._options;
6514
+ const accepted = offers.find((params) => {
6515
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
6516
+ return true;
6517
+ });
6518
+ if (!accepted) throw new Error("None of the extension offers can be accepted");
6519
+ if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
6520
+ if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
6521
+ if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
6522
+ if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
6523
+ else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
6524
+ return accepted;
6525
+ }
6526
+ /**
6527
+ * Accept the extension negotiation response.
6528
+ *
6529
+ * @param {Array} response The extension negotiation response
6530
+ * @return {Object} Accepted configuration
6531
+ * @private
6532
+ */
6533
+ acceptAsClient(response) {
6534
+ const params = response[0];
6535
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
6536
+ if (!params.client_max_window_bits) {
6537
+ if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
6538
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
6539
+ return params;
6540
+ }
6541
+ /**
6542
+ * Normalize parameters.
6543
+ *
6544
+ * @param {Array} configurations The extension negotiation offers/reponse
6545
+ * @return {Array} The offers/response with normalized parameters
6546
+ * @private
6547
+ */
6548
+ normalizeParams(configurations) {
6549
+ configurations.forEach((params) => {
6550
+ Object.keys(params).forEach((key) => {
6551
+ let value = params[key];
6552
+ if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
6553
+ value = value[0];
6554
+ if (key === "client_max_window_bits") {
6555
+ if (value !== true) {
6556
+ const num = +value;
6557
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6558
+ value = num;
6559
+ } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6560
+ } else if (key === "server_max_window_bits") {
6561
+ const num = +value;
6562
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6563
+ value = num;
6564
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
6565
+ if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6566
+ } else throw new Error(`Unknown parameter "${key}"`);
6567
+ params[key] = value;
6568
+ });
6569
+ });
6570
+ return configurations;
6571
+ }
6572
+ /**
6573
+ * Decompress data. Concurrency limited.
6574
+ *
6575
+ * @param {Buffer} data Compressed data
6576
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6577
+ * @param {Function} callback Callback
6578
+ * @public
6579
+ */
6580
+ decompress(data, fin, callback) {
6581
+ zlibLimiter.add((done) => {
6582
+ this._decompress(data, fin, (err, result) => {
6583
+ done();
6584
+ callback(err, result);
6585
+ });
6586
+ });
6587
+ }
6588
+ /**
6589
+ * Compress data. Concurrency limited.
6590
+ *
6591
+ * @param {(Buffer|String)} data Data to compress
6592
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6593
+ * @param {Function} callback Callback
6594
+ * @public
6595
+ */
6596
+ compress(data, fin, callback) {
6597
+ zlibLimiter.add((done) => {
6598
+ this._compress(data, fin, (err, result) => {
6599
+ done();
6600
+ callback(err, result);
6601
+ });
6602
+ });
6603
+ }
6604
+ /**
6605
+ * Decompress data.
6606
+ *
6607
+ * @param {Buffer} data Compressed data
6608
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6609
+ * @param {Function} callback Callback
6610
+ * @private
6611
+ */
6612
+ _decompress(data, fin, callback) {
6613
+ const endpoint = this._isServer ? "client" : "server";
6614
+ if (!this._inflate) {
6615
+ const key = `${endpoint}_max_window_bits`;
6616
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6617
+ this._inflate = zlib.createInflateRaw({
6618
+ ...this._options.zlibInflateOptions,
6619
+ windowBits
6620
+ });
6621
+ this._inflate[kPerMessageDeflate] = this;
6622
+ this._inflate[kTotalLength] = 0;
6623
+ this._inflate[kBuffers] = [];
6624
+ this._inflate.on("error", inflateOnError);
6625
+ this._inflate.on("data", inflateOnData);
6626
+ }
6627
+ this._inflate[kCallback] = callback;
6628
+ this._inflate.write(data);
6629
+ if (fin) this._inflate.write(TRAILER);
6630
+ this._inflate.flush(() => {
6631
+ const err = this._inflate[kError];
6632
+ if (err) {
6633
+ this._inflate.close();
6634
+ this._inflate = null;
6635
+ callback(err);
6636
+ return;
6637
+ }
6638
+ const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
6639
+ if (this._inflate._readableState.endEmitted) {
6640
+ this._inflate.close();
6641
+ this._inflate = null;
6642
+ } else {
6643
+ this._inflate[kTotalLength] = 0;
6644
+ this._inflate[kBuffers] = [];
6645
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
6646
+ }
6647
+ callback(null, data);
6648
+ });
6649
+ }
6650
+ /**
6651
+ * Compress data.
6652
+ *
6653
+ * @param {(Buffer|String)} data Data to compress
6654
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6655
+ * @param {Function} callback Callback
6656
+ * @private
6657
+ */
6658
+ _compress(data, fin, callback) {
6659
+ const endpoint = this._isServer ? "server" : "client";
6660
+ if (!this._deflate) {
6661
+ const key = `${endpoint}_max_window_bits`;
6662
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6663
+ this._deflate = zlib.createDeflateRaw({
6664
+ ...this._options.zlibDeflateOptions,
6665
+ windowBits
6666
+ });
6667
+ this._deflate[kTotalLength] = 0;
6668
+ this._deflate[kBuffers] = [];
6669
+ this._deflate.on("data", deflateOnData);
6670
+ }
6671
+ this._deflate[kCallback] = callback;
6672
+ this._deflate.write(data);
6673
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
6674
+ if (!this._deflate) return;
6675
+ let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
6676
+ if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
6677
+ this._deflate[kCallback] = null;
6678
+ this._deflate[kTotalLength] = 0;
6679
+ this._deflate[kBuffers] = [];
6680
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
6681
+ callback(null, data);
6682
+ });
6683
+ }
6684
+ };
6685
+ module.exports = PerMessageDeflate;
6686
+ /**
6687
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
6688
+ *
6689
+ * @param {Buffer} chunk A chunk of data
6690
+ * @private
6691
+ */
6692
+ function deflateOnData(chunk) {
6693
+ this[kBuffers].push(chunk);
6694
+ this[kTotalLength] += chunk.length;
6695
+ }
6696
+ /**
6697
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
6698
+ *
6699
+ * @param {Buffer} chunk A chunk of data
6700
+ * @private
6701
+ */
6702
+ function inflateOnData(chunk) {
6703
+ this[kTotalLength] += chunk.length;
6704
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
6705
+ this[kBuffers].push(chunk);
6706
+ return;
6707
+ }
6708
+ this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
6709
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
6710
+ this[kError][kStatusCode] = 1009;
6711
+ this.removeListener("data", inflateOnData);
6712
+ this.reset();
6713
+ }
6714
+ /**
6715
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
6716
+ *
6717
+ * @param {Error} err The emitted error
6718
+ * @private
6719
+ */
6720
+ function inflateOnError(err) {
6721
+ this[kPerMessageDeflate]._inflate = null;
6722
+ if (this[kError]) {
6723
+ this[kCallback](this[kError]);
6724
+ return;
6725
+ }
6726
+ err[kStatusCode] = 1007;
6727
+ this[kCallback](err);
6728
+ }
6729
+ }));
6730
+
6731
+ //#endregion
6732
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/validation.js
6733
+ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6734
+ const { isUtf8 } = require("buffer");
6735
+ const { hasBlob } = require_constants();
6736
+ const tokenChars = [
6737
+ 0,
6738
+ 0,
6739
+ 0,
6740
+ 0,
6741
+ 0,
6742
+ 0,
6743
+ 0,
6744
+ 0,
6745
+ 0,
6746
+ 0,
6747
+ 0,
6748
+ 0,
6749
+ 0,
6750
+ 0,
6751
+ 0,
6752
+ 0,
6753
+ 0,
6754
+ 0,
6755
+ 0,
6756
+ 0,
6757
+ 0,
6758
+ 0,
6759
+ 0,
6760
+ 0,
6761
+ 0,
6762
+ 0,
6763
+ 0,
6764
+ 0,
6765
+ 0,
6766
+ 0,
6767
+ 0,
6768
+ 0,
6769
+ 0,
6770
+ 1,
6771
+ 0,
6772
+ 1,
6773
+ 1,
6774
+ 1,
6775
+ 1,
6776
+ 1,
6777
+ 0,
6778
+ 0,
6779
+ 1,
6780
+ 1,
6781
+ 0,
6782
+ 1,
6783
+ 1,
6784
+ 0,
6785
+ 1,
6786
+ 1,
6787
+ 1,
6788
+ 1,
6789
+ 1,
6790
+ 1,
6791
+ 1,
6792
+ 1,
6793
+ 1,
6794
+ 1,
6795
+ 0,
6796
+ 0,
6797
+ 0,
6798
+ 0,
6799
+ 0,
6800
+ 0,
6801
+ 0,
6802
+ 1,
6803
+ 1,
6804
+ 1,
6805
+ 1,
6806
+ 1,
6807
+ 1,
6808
+ 1,
6809
+ 1,
6810
+ 1,
6811
+ 1,
6812
+ 1,
6813
+ 1,
6814
+ 1,
6815
+ 1,
6816
+ 1,
6817
+ 1,
6818
+ 1,
6819
+ 1,
6820
+ 1,
6821
+ 1,
6822
+ 1,
6823
+ 1,
6824
+ 1,
6825
+ 1,
6826
+ 1,
6827
+ 1,
6828
+ 0,
6829
+ 0,
6830
+ 0,
6831
+ 1,
6832
+ 1,
6833
+ 1,
6834
+ 1,
6835
+ 1,
6836
+ 1,
6837
+ 1,
6838
+ 1,
6839
+ 1,
6840
+ 1,
6841
+ 1,
6842
+ 1,
6843
+ 1,
6844
+ 1,
6845
+ 1,
6846
+ 1,
6847
+ 1,
6848
+ 1,
6849
+ 1,
6850
+ 1,
6851
+ 1,
6852
+ 1,
6853
+ 1,
6854
+ 1,
6855
+ 1,
6856
+ 1,
6857
+ 1,
6858
+ 1,
6859
+ 1,
6860
+ 0,
6861
+ 1,
6862
+ 0,
6863
+ 1,
6864
+ 0
6865
+ ];
6866
+ /**
6867
+ * Checks if a status code is allowed in a close frame.
6868
+ *
6869
+ * @param {Number} code The status code
6870
+ * @return {Boolean} `true` if the status code is valid, else `false`
6871
+ * @public
6872
+ */
6873
+ function isValidStatusCode(code) {
6874
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
6875
+ }
6876
+ /**
6877
+ * Checks if a given buffer contains only correct UTF-8.
6878
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
6879
+ * Markus Kuhn.
6880
+ *
6881
+ * @param {Buffer} buf The buffer to check
6882
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
6883
+ * @public
6884
+ */
6885
+ function _isValidUTF8(buf) {
6886
+ const len = buf.length;
6887
+ let i = 0;
6888
+ while (i < len) if ((buf[i] & 128) === 0) i++;
6889
+ else if ((buf[i] & 224) === 192) {
6890
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
6891
+ i += 2;
6892
+ } else if ((buf[i] & 240) === 224) {
6893
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
6894
+ i += 3;
6895
+ } else if ((buf[i] & 248) === 240) {
6896
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
6897
+ i += 4;
6898
+ } else return false;
6899
+ return true;
6900
+ }
6901
+ /**
6902
+ * Determines whether a value is a `Blob`.
6903
+ *
6904
+ * @param {*} value The value to be tested
6905
+ * @return {Boolean} `true` if `value` is a `Blob`, else `false`
6906
+ * @private
6907
+ */
6908
+ function isBlob(value) {
6909
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
6910
+ }
6911
+ module.exports = {
6912
+ isBlob,
6913
+ isValidStatusCode,
6914
+ isValidUTF8: _isValidUTF8,
6915
+ tokenChars
6916
+ };
6917
+ if (isUtf8) module.exports.isValidUTF8 = function(buf) {
6918
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
6919
+ };
6920
+ else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
6921
+ const isValidUTF8 = require("utf-8-validate");
6922
+ module.exports.isValidUTF8 = function(buf) {
6923
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
6924
+ };
6925
+ } catch (e) {}
6926
+ }));
6927
+
6928
+ //#endregion
6929
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/receiver.js
6930
+ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6931
+ const { Writable } = require("stream");
6932
+ const PerMessageDeflate = require_permessage_deflate();
6933
+ const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
6934
+ const { concat, toArrayBuffer, unmask } = require_buffer_util();
6935
+ const { isValidStatusCode, isValidUTF8 } = require_validation();
6936
+ const FastBuffer = Buffer[Symbol.species];
6937
+ const GET_INFO = 0;
6938
+ const GET_PAYLOAD_LENGTH_16 = 1;
6939
+ const GET_PAYLOAD_LENGTH_64 = 2;
6940
+ const GET_MASK = 3;
6941
+ const GET_DATA = 4;
6942
+ const INFLATING = 5;
6943
+ const DEFER_EVENT = 6;
6944
+ /**
6945
+ * HyBi Receiver implementation.
6946
+ *
6947
+ * @extends Writable
6948
+ */
6949
+ var Receiver = class extends Writable {
6950
+ /**
6951
+ * Creates a Receiver instance.
6952
+ *
6953
+ * @param {Object} [options] Options object
6954
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
6955
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
6956
+ * multiple times in the same tick
6957
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
6958
+ * @param {Object} [options.extensions] An object containing the negotiated
6959
+ * extensions
6960
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
6961
+ * client or server mode
6962
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
6963
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
6964
+ * not to skip UTF-8 validation for text and close messages
6965
+ */
6966
+ constructor(options = {}) {
6967
+ super();
6968
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
6969
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
6970
+ this._extensions = options.extensions || {};
6971
+ this._isServer = !!options.isServer;
6972
+ this._maxPayload = options.maxPayload | 0;
6973
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
6974
+ this[kWebSocket] = void 0;
6975
+ this._bufferedBytes = 0;
6976
+ this._buffers = [];
6977
+ this._compressed = false;
6978
+ this._payloadLength = 0;
6979
+ this._mask = void 0;
6980
+ this._fragmented = 0;
6981
+ this._masked = false;
6982
+ this._fin = false;
6983
+ this._opcode = 0;
6984
+ this._totalPayloadLength = 0;
6985
+ this._messageLength = 0;
6986
+ this._fragments = [];
6987
+ this._errored = false;
6988
+ this._loop = false;
6989
+ this._state = GET_INFO;
6990
+ }
6991
+ /**
6992
+ * Implements `Writable.prototype._write()`.
6993
+ *
6994
+ * @param {Buffer} chunk The chunk of data to write
6995
+ * @param {String} encoding The character encoding of `chunk`
6996
+ * @param {Function} cb Callback
6997
+ * @private
6998
+ */
6999
+ _write(chunk, encoding, cb) {
7000
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
7001
+ this._bufferedBytes += chunk.length;
7002
+ this._buffers.push(chunk);
7003
+ this.startLoop(cb);
7004
+ }
7005
+ /**
7006
+ * Consumes `n` bytes from the buffered data.
7007
+ *
7008
+ * @param {Number} n The number of bytes to consume
7009
+ * @return {Buffer} The consumed bytes
7010
+ * @private
7011
+ */
7012
+ consume(n) {
7013
+ this._bufferedBytes -= n;
7014
+ if (n === this._buffers[0].length) return this._buffers.shift();
7015
+ if (n < this._buffers[0].length) {
7016
+ const buf = this._buffers[0];
7017
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7018
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
7019
+ }
7020
+ const dst = Buffer.allocUnsafe(n);
7021
+ do {
7022
+ const buf = this._buffers[0];
7023
+ const offset = dst.length - n;
7024
+ if (n >= buf.length) dst.set(this._buffers.shift(), offset);
7025
+ else {
7026
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
7027
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7028
+ }
7029
+ n -= buf.length;
7030
+ } while (n > 0);
7031
+ return dst;
7032
+ }
7033
+ /**
7034
+ * Starts the parsing loop.
7035
+ *
7036
+ * @param {Function} cb Callback
7037
+ * @private
7038
+ */
7039
+ startLoop(cb) {
7040
+ this._loop = true;
7041
+ do
7042
+ switch (this._state) {
7043
+ case GET_INFO:
7044
+ this.getInfo(cb);
7045
+ break;
7046
+ case GET_PAYLOAD_LENGTH_16:
7047
+ this.getPayloadLength16(cb);
7048
+ break;
7049
+ case GET_PAYLOAD_LENGTH_64:
7050
+ this.getPayloadLength64(cb);
7051
+ break;
7052
+ case GET_MASK:
7053
+ this.getMask();
7054
+ break;
7055
+ case GET_DATA:
7056
+ this.getData(cb);
7057
+ break;
7058
+ case INFLATING:
7059
+ case DEFER_EVENT:
7060
+ this._loop = false;
7061
+ return;
7062
+ }
7063
+ while (this._loop);
7064
+ if (!this._errored) cb();
7065
+ }
7066
+ /**
7067
+ * Reads the first two bytes of a frame.
7068
+ *
7069
+ * @param {Function} cb Callback
7070
+ * @private
7071
+ */
7072
+ getInfo(cb) {
7073
+ if (this._bufferedBytes < 2) {
7074
+ this._loop = false;
7075
+ return;
7076
+ }
7077
+ const buf = this.consume(2);
7078
+ if ((buf[0] & 48) !== 0) {
7079
+ cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
7080
+ return;
7081
+ }
7082
+ const compressed = (buf[0] & 64) === 64;
7083
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
7084
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7085
+ return;
7086
+ }
7087
+ this._fin = (buf[0] & 128) === 128;
7088
+ this._opcode = buf[0] & 15;
7089
+ this._payloadLength = buf[1] & 127;
7090
+ if (this._opcode === 0) {
7091
+ if (compressed) {
7092
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7093
+ return;
7094
+ }
7095
+ if (!this._fragmented) {
7096
+ cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
7097
+ return;
7098
+ }
7099
+ this._opcode = this._fragmented;
7100
+ } else if (this._opcode === 1 || this._opcode === 2) {
7101
+ if (this._fragmented) {
7102
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
7103
+ return;
7104
+ }
7105
+ this._compressed = compressed;
7106
+ } else if (this._opcode > 7 && this._opcode < 11) {
7107
+ if (!this._fin) {
7108
+ cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
7109
+ return;
7110
+ }
7111
+ if (compressed) {
7112
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7113
+ return;
7114
+ }
7115
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
7116
+ cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
7117
+ return;
7118
+ }
7119
+ } else {
7120
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
7121
+ return;
7122
+ }
7123
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
7124
+ this._masked = (buf[1] & 128) === 128;
7125
+ if (this._isServer) {
7126
+ if (!this._masked) {
7127
+ cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
7128
+ return;
7129
+ }
7130
+ } else if (this._masked) {
7131
+ cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
7132
+ return;
7133
+ }
7134
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
7135
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
7136
+ else this.haveLength(cb);
7137
+ }
7138
+ /**
7139
+ * Gets extended payload length (7+16).
7140
+ *
7141
+ * @param {Function} cb Callback
7142
+ * @private
7143
+ */
7144
+ getPayloadLength16(cb) {
7145
+ if (this._bufferedBytes < 2) {
7146
+ this._loop = false;
7147
+ return;
7148
+ }
7149
+ this._payloadLength = this.consume(2).readUInt16BE(0);
7150
+ this.haveLength(cb);
7151
+ }
7152
+ /**
7153
+ * Gets extended payload length (7+64).
7154
+ *
7155
+ * @param {Function} cb Callback
7156
+ * @private
7157
+ */
7158
+ getPayloadLength64(cb) {
7159
+ if (this._bufferedBytes < 8) {
7160
+ this._loop = false;
7161
+ return;
7162
+ }
7163
+ const buf = this.consume(8);
7164
+ const num = buf.readUInt32BE(0);
7165
+ if (num > Math.pow(2, 21) - 1) {
7166
+ cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
7167
+ return;
7168
+ }
7169
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
7170
+ this.haveLength(cb);
7171
+ }
7172
+ /**
7173
+ * Payload length has been read.
7174
+ *
7175
+ * @param {Function} cb Callback
7176
+ * @private
7177
+ */
7178
+ haveLength(cb) {
7179
+ if (this._payloadLength && this._opcode < 8) {
7180
+ this._totalPayloadLength += this._payloadLength;
7181
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
7182
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
7183
+ return;
7184
+ }
7185
+ }
7186
+ if (this._masked) this._state = GET_MASK;
7187
+ else this._state = GET_DATA;
7188
+ }
7189
+ /**
7190
+ * Reads mask bytes.
7191
+ *
7192
+ * @private
7193
+ */
7194
+ getMask() {
7195
+ if (this._bufferedBytes < 4) {
7196
+ this._loop = false;
7197
+ return;
7198
+ }
7199
+ this._mask = this.consume(4);
7200
+ this._state = GET_DATA;
7201
+ }
7202
+ /**
7203
+ * Reads data bytes.
7204
+ *
7205
+ * @param {Function} cb Callback
7206
+ * @private
7207
+ */
7208
+ getData(cb) {
7209
+ let data = EMPTY_BUFFER;
7210
+ if (this._payloadLength) {
7211
+ if (this._bufferedBytes < this._payloadLength) {
7212
+ this._loop = false;
7213
+ return;
7214
+ }
7215
+ data = this.consume(this._payloadLength);
7216
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
7217
+ }
7218
+ if (this._opcode > 7) {
7219
+ this.controlMessage(data, cb);
7220
+ return;
7221
+ }
7222
+ if (this._compressed) {
7223
+ this._state = INFLATING;
7224
+ this.decompress(data, cb);
7225
+ return;
7226
+ }
7227
+ if (data.length) {
7228
+ this._messageLength = this._totalPayloadLength;
7229
+ this._fragments.push(data);
7230
+ }
7231
+ this.dataMessage(cb);
7232
+ }
7233
+ /**
7234
+ * Decompresses data.
7235
+ *
7236
+ * @param {Buffer} data Compressed data
7237
+ * @param {Function} cb Callback
7238
+ * @private
7239
+ */
7240
+ decompress(data, cb) {
7241
+ this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
7242
+ if (err) return cb(err);
7243
+ if (buf.length) {
7244
+ this._messageLength += buf.length;
7245
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
7246
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
7247
+ return;
7248
+ }
7249
+ this._fragments.push(buf);
7250
+ }
7251
+ this.dataMessage(cb);
7252
+ if (this._state === GET_INFO) this.startLoop(cb);
7253
+ });
7254
+ }
7255
+ /**
7256
+ * Handles a data message.
7257
+ *
7258
+ * @param {Function} cb Callback
7259
+ * @private
7260
+ */
7261
+ dataMessage(cb) {
7262
+ if (!this._fin) {
7263
+ this._state = GET_INFO;
7264
+ return;
7265
+ }
7266
+ const messageLength = this._messageLength;
7267
+ const fragments = this._fragments;
7268
+ this._totalPayloadLength = 0;
7269
+ this._messageLength = 0;
7270
+ this._fragmented = 0;
7271
+ this._fragments = [];
7272
+ if (this._opcode === 2) {
7273
+ let data;
7274
+ if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
7275
+ else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
7276
+ else if (this._binaryType === "blob") data = new Blob(fragments);
7277
+ else data = fragments;
7278
+ if (this._allowSynchronousEvents) {
7279
+ this.emit("message", data, true);
7280
+ this._state = GET_INFO;
7281
+ } else {
7282
+ this._state = DEFER_EVENT;
7283
+ setImmediate(() => {
7284
+ this.emit("message", data, true);
7285
+ this._state = GET_INFO;
7286
+ this.startLoop(cb);
7287
+ });
7288
+ }
7289
+ } else {
7290
+ const buf = concat(fragments, messageLength);
7291
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7292
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
7293
+ return;
7294
+ }
7295
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
7296
+ this.emit("message", buf, false);
7297
+ this._state = GET_INFO;
7298
+ } else {
7299
+ this._state = DEFER_EVENT;
7300
+ setImmediate(() => {
7301
+ this.emit("message", buf, false);
7302
+ this._state = GET_INFO;
7303
+ this.startLoop(cb);
7304
+ });
7305
+ }
7306
+ }
7307
+ }
7308
+ /**
7309
+ * Handles a control message.
7310
+ *
7311
+ * @param {Buffer} data Data to handle
7312
+ * @return {(Error|RangeError|undefined)} A possible error
7313
+ * @private
7314
+ */
7315
+ controlMessage(data, cb) {
7316
+ if (this._opcode === 8) {
7317
+ if (data.length === 0) {
7318
+ this._loop = false;
7319
+ this.emit("conclude", 1005, EMPTY_BUFFER);
7320
+ this.end();
7321
+ } else {
7322
+ const code = data.readUInt16BE(0);
7323
+ if (!isValidStatusCode(code)) {
7324
+ cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
7325
+ return;
7326
+ }
7327
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
7328
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7329
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
7330
+ return;
7331
+ }
7332
+ this._loop = false;
7333
+ this.emit("conclude", code, buf);
7334
+ this.end();
7335
+ }
7336
+ this._state = GET_INFO;
7337
+ return;
7338
+ }
7339
+ if (this._allowSynchronousEvents) {
7340
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7341
+ this._state = GET_INFO;
7342
+ } else {
7343
+ this._state = DEFER_EVENT;
7344
+ setImmediate(() => {
7345
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7346
+ this._state = GET_INFO;
7347
+ this.startLoop(cb);
7348
+ });
7349
+ }
7350
+ }
7351
+ /**
7352
+ * Builds an error object.
7353
+ *
7354
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
7355
+ * @param {String} message The error message
7356
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
7357
+ * `message`
7358
+ * @param {Number} statusCode The status code
7359
+ * @param {String} errorCode The exposed error code
7360
+ * @return {(Error|RangeError)} The error
7361
+ * @private
7362
+ */
7363
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
7364
+ this._loop = false;
7365
+ this._errored = true;
7366
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
7367
+ Error.captureStackTrace(err, this.createError);
7368
+ err.code = errorCode;
7369
+ err[kStatusCode] = statusCode;
7370
+ return err;
7371
+ }
7372
+ };
7373
+ module.exports = Receiver;
7374
+ }));
7375
+
7376
+ //#endregion
7377
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/sender.js
7378
+ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7379
+ const { Duplex: Duplex$3 } = require("stream");
7380
+ const { randomFillSync } = require("crypto");
7381
+ const PerMessageDeflate = require_permessage_deflate();
7382
+ const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
7383
+ const { isBlob, isValidStatusCode } = require_validation();
7384
+ const { mask: applyMask, toBuffer } = require_buffer_util();
7385
+ const kByteLength = Symbol("kByteLength");
7386
+ const maskBuffer = Buffer.alloc(4);
7387
+ const RANDOM_POOL_SIZE = 8 * 1024;
7388
+ let randomPool;
7389
+ let randomPoolPointer = RANDOM_POOL_SIZE;
7390
+ const DEFAULT = 0;
7391
+ const DEFLATING = 1;
7392
+ const GET_BLOB_DATA = 2;
7393
+ /**
7394
+ * HyBi Sender implementation.
7395
+ */
7396
+ var Sender = class Sender {
7397
+ /**
7398
+ * Creates a Sender instance.
7399
+ *
7400
+ * @param {Duplex} socket The connection socket
7401
+ * @param {Object} [extensions] An object containing the negotiated extensions
7402
+ * @param {Function} [generateMask] The function used to generate the masking
7403
+ * key
7404
+ */
7405
+ constructor(socket, extensions, generateMask) {
7406
+ this._extensions = extensions || {};
7407
+ if (generateMask) {
7408
+ this._generateMask = generateMask;
7409
+ this._maskBuffer = Buffer.alloc(4);
7410
+ }
7411
+ this._socket = socket;
7412
+ this._firstFragment = true;
7413
+ this._compress = false;
7414
+ this._bufferedBytes = 0;
7415
+ this._queue = [];
7416
+ this._state = DEFAULT;
7417
+ this.onerror = NOOP;
7418
+ this[kWebSocket] = void 0;
7419
+ }
7420
+ /**
7421
+ * Frames a piece of data according to the HyBi WebSocket protocol.
7422
+ *
7423
+ * @param {(Buffer|String)} data The data to frame
7424
+ * @param {Object} options Options object
7425
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7426
+ * FIN bit
7427
+ * @param {Function} [options.generateMask] The function used to generate the
7428
+ * masking key
7429
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7430
+ * `data`
7431
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7432
+ * key
7433
+ * @param {Number} options.opcode The opcode
7434
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7435
+ * modified
7436
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7437
+ * RSV1 bit
7438
+ * @return {(Buffer|String)[]} The framed data
7439
+ * @public
7440
+ */
7441
+ static frame(data, options) {
7442
+ let mask;
7443
+ let merge = false;
7444
+ let offset = 2;
7445
+ let skipMasking = false;
7446
+ if (options.mask) {
7447
+ mask = options.maskBuffer || maskBuffer;
7448
+ if (options.generateMask) options.generateMask(mask);
7449
+ else {
7450
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
7451
+ /* istanbul ignore else */
7452
+ if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
7453
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
7454
+ randomPoolPointer = 0;
7455
+ }
7456
+ mask[0] = randomPool[randomPoolPointer++];
7457
+ mask[1] = randomPool[randomPoolPointer++];
7458
+ mask[2] = randomPool[randomPoolPointer++];
7459
+ mask[3] = randomPool[randomPoolPointer++];
7460
+ }
7461
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
7462
+ offset = 6;
7463
+ }
7464
+ let dataLength;
7465
+ if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
7466
+ else {
7467
+ data = Buffer.from(data);
7468
+ dataLength = data.length;
7469
+ }
7470
+ else {
7471
+ dataLength = data.length;
7472
+ merge = options.mask && options.readOnly && !skipMasking;
7473
+ }
7474
+ let payloadLength = dataLength;
7475
+ if (dataLength >= 65536) {
7476
+ offset += 8;
7477
+ payloadLength = 127;
7478
+ } else if (dataLength > 125) {
7479
+ offset += 2;
7480
+ payloadLength = 126;
7481
+ }
7482
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
7483
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
7484
+ if (options.rsv1) target[0] |= 64;
7485
+ target[1] = payloadLength;
7486
+ if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
7487
+ else if (payloadLength === 127) {
7488
+ target[2] = target[3] = 0;
7489
+ target.writeUIntBE(dataLength, 4, 6);
7490
+ }
7491
+ if (!options.mask) return [target, data];
7492
+ target[1] |= 128;
7493
+ target[offset - 4] = mask[0];
7494
+ target[offset - 3] = mask[1];
7495
+ target[offset - 2] = mask[2];
7496
+ target[offset - 1] = mask[3];
7497
+ if (skipMasking) return [target, data];
7498
+ if (merge) {
7499
+ applyMask(data, mask, target, offset, dataLength);
7500
+ return [target];
7501
+ }
7502
+ applyMask(data, mask, data, 0, dataLength);
7503
+ return [target, data];
7504
+ }
7505
+ /**
7506
+ * Sends a close message to the other peer.
7507
+ *
7508
+ * @param {Number} [code] The status code component of the body
7509
+ * @param {(String|Buffer)} [data] The message component of the body
7510
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
7511
+ * @param {Function} [cb] Callback
7512
+ * @public
7513
+ */
7514
+ close(code, data, mask, cb) {
7515
+ let buf;
7516
+ if (code === void 0) buf = EMPTY_BUFFER;
7517
+ else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
7518
+ else if (data === void 0 || !data.length) {
7519
+ buf = Buffer.allocUnsafe(2);
7520
+ buf.writeUInt16BE(code, 0);
7521
+ } else {
7522
+ const length = Buffer.byteLength(data);
7523
+ if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
7524
+ buf = Buffer.allocUnsafe(2 + length);
7525
+ buf.writeUInt16BE(code, 0);
7526
+ if (typeof data === "string") buf.write(data, 2);
7527
+ else buf.set(data, 2);
7528
+ }
7529
+ const options = {
7530
+ [kByteLength]: buf.length,
7531
+ fin: true,
7532
+ generateMask: this._generateMask,
7533
+ mask,
7534
+ maskBuffer: this._maskBuffer,
7535
+ opcode: 8,
7536
+ readOnly: false,
7537
+ rsv1: false
7538
+ };
7539
+ if (this._state !== DEFAULT) this.enqueue([
7540
+ this.dispatch,
7541
+ buf,
7542
+ false,
7543
+ options,
7544
+ cb
7545
+ ]);
7546
+ else this.sendFrame(Sender.frame(buf, options), cb);
7547
+ }
7548
+ /**
7549
+ * Sends a ping message to the other peer.
7550
+ *
7551
+ * @param {*} data The message to send
7552
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
7553
+ * @param {Function} [cb] Callback
7554
+ * @public
7555
+ */
7556
+ ping(data, mask, cb) {
7557
+ let byteLength;
7558
+ let readOnly;
7559
+ if (typeof data === "string") {
7560
+ byteLength = Buffer.byteLength(data);
7561
+ readOnly = false;
7562
+ } else if (isBlob(data)) {
7563
+ byteLength = data.size;
7564
+ readOnly = false;
7565
+ } else {
7566
+ data = toBuffer(data);
7567
+ byteLength = data.length;
7568
+ readOnly = toBuffer.readOnly;
7569
+ }
7570
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
7571
+ const options = {
7572
+ [kByteLength]: byteLength,
7573
+ fin: true,
7574
+ generateMask: this._generateMask,
7575
+ mask,
7576
+ maskBuffer: this._maskBuffer,
7577
+ opcode: 9,
7578
+ readOnly,
7579
+ rsv1: false
7580
+ };
7581
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7582
+ this.getBlobData,
7583
+ data,
7584
+ false,
7585
+ options,
7586
+ cb
7587
+ ]);
7588
+ else this.getBlobData(data, false, options, cb);
7589
+ else if (this._state !== DEFAULT) this.enqueue([
7590
+ this.dispatch,
7591
+ data,
7592
+ false,
7593
+ options,
7594
+ cb
7595
+ ]);
7596
+ else this.sendFrame(Sender.frame(data, options), cb);
7597
+ }
7598
+ /**
7599
+ * Sends a pong message to the other peer.
7600
+ *
7601
+ * @param {*} data The message to send
7602
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
7603
+ * @param {Function} [cb] Callback
7604
+ * @public
7605
+ */
7606
+ pong(data, mask, cb) {
7607
+ let byteLength;
7608
+ let readOnly;
7609
+ if (typeof data === "string") {
7610
+ byteLength = Buffer.byteLength(data);
7611
+ readOnly = false;
7612
+ } else if (isBlob(data)) {
7613
+ byteLength = data.size;
7614
+ readOnly = false;
7615
+ } else {
7616
+ data = toBuffer(data);
7617
+ byteLength = data.length;
7618
+ readOnly = toBuffer.readOnly;
7619
+ }
7620
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
7621
+ const options = {
7622
+ [kByteLength]: byteLength,
7623
+ fin: true,
7624
+ generateMask: this._generateMask,
7625
+ mask,
7626
+ maskBuffer: this._maskBuffer,
7627
+ opcode: 10,
7628
+ readOnly,
7629
+ rsv1: false
7630
+ };
7631
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7632
+ this.getBlobData,
7633
+ data,
7634
+ false,
7635
+ options,
7636
+ cb
7637
+ ]);
7638
+ else this.getBlobData(data, false, options, cb);
7639
+ else if (this._state !== DEFAULT) this.enqueue([
7640
+ this.dispatch,
7641
+ data,
7642
+ false,
7643
+ options,
7644
+ cb
7645
+ ]);
7646
+ else this.sendFrame(Sender.frame(data, options), cb);
7647
+ }
7648
+ /**
7649
+ * Sends a data message to the other peer.
7650
+ *
7651
+ * @param {*} data The message to send
7652
+ * @param {Object} options Options object
7653
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
7654
+ * or text
7655
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
7656
+ * compress `data`
7657
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
7658
+ * last one
7659
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7660
+ * `data`
7661
+ * @param {Function} [cb] Callback
7662
+ * @public
7663
+ */
7664
+ send(data, options, cb) {
7665
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7666
+ let opcode = options.binary ? 2 : 1;
7667
+ let rsv1 = options.compress;
7668
+ let byteLength;
7669
+ let readOnly;
7670
+ if (typeof data === "string") {
7671
+ byteLength = Buffer.byteLength(data);
7672
+ readOnly = false;
7673
+ } else if (isBlob(data)) {
7674
+ byteLength = data.size;
7675
+ readOnly = false;
7676
+ } else {
7677
+ data = toBuffer(data);
7678
+ byteLength = data.length;
7679
+ readOnly = toBuffer.readOnly;
7680
+ }
7681
+ if (this._firstFragment) {
7682
+ this._firstFragment = false;
7683
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
7684
+ this._compress = rsv1;
7685
+ } else {
7686
+ rsv1 = false;
7687
+ opcode = 0;
7688
+ }
7689
+ if (options.fin) this._firstFragment = true;
7690
+ const opts = {
7691
+ [kByteLength]: byteLength,
7692
+ fin: options.fin,
7693
+ generateMask: this._generateMask,
7694
+ mask: options.mask,
7695
+ maskBuffer: this._maskBuffer,
7696
+ opcode,
7697
+ readOnly,
7698
+ rsv1
7699
+ };
7700
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7701
+ this.getBlobData,
7702
+ data,
7703
+ this._compress,
7704
+ opts,
7705
+ cb
7706
+ ]);
7707
+ else this.getBlobData(data, this._compress, opts, cb);
7708
+ else if (this._state !== DEFAULT) this.enqueue([
7709
+ this.dispatch,
7710
+ data,
7711
+ this._compress,
7712
+ opts,
7713
+ cb
7714
+ ]);
7715
+ else this.dispatch(data, this._compress, opts, cb);
7716
+ }
7717
+ /**
7718
+ * Gets the contents of a blob as binary data.
7719
+ *
7720
+ * @param {Blob} blob The blob
7721
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
7722
+ * the data
7723
+ * @param {Object} options Options object
7724
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7725
+ * FIN bit
7726
+ * @param {Function} [options.generateMask] The function used to generate the
7727
+ * masking key
7728
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7729
+ * `data`
7730
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7731
+ * key
7732
+ * @param {Number} options.opcode The opcode
7733
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7734
+ * modified
7735
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7736
+ * RSV1 bit
7737
+ * @param {Function} [cb] Callback
7738
+ * @private
7739
+ */
7740
+ getBlobData(blob, compress, options, cb) {
7741
+ this._bufferedBytes += options[kByteLength];
7742
+ this._state = GET_BLOB_DATA;
7743
+ blob.arrayBuffer().then((arrayBuffer) => {
7744
+ if (this._socket.destroyed) {
7745
+ const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
7746
+ process.nextTick(callCallbacks, this, err, cb);
7747
+ return;
7748
+ }
7749
+ this._bufferedBytes -= options[kByteLength];
7750
+ const data = toBuffer(arrayBuffer);
7751
+ if (!compress) {
7752
+ this._state = DEFAULT;
7753
+ this.sendFrame(Sender.frame(data, options), cb);
7754
+ this.dequeue();
7755
+ } else this.dispatch(data, compress, options, cb);
7756
+ }).catch((err) => {
7757
+ process.nextTick(onError, this, err, cb);
7758
+ });
7759
+ }
7760
+ /**
7761
+ * Dispatches a message.
7762
+ *
7763
+ * @param {(Buffer|String)} data The message to send
7764
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
7765
+ * `data`
7766
+ * @param {Object} options Options object
7767
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7768
+ * FIN bit
7769
+ * @param {Function} [options.generateMask] The function used to generate the
7770
+ * masking key
7771
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7772
+ * `data`
7773
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7774
+ * key
7775
+ * @param {Number} options.opcode The opcode
7776
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7777
+ * modified
7778
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7779
+ * RSV1 bit
7780
+ * @param {Function} [cb] Callback
7781
+ * @private
7782
+ */
7783
+ dispatch(data, compress, options, cb) {
7784
+ if (!compress) {
7785
+ this.sendFrame(Sender.frame(data, options), cb);
7786
+ return;
7787
+ }
7788
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7789
+ this._bufferedBytes += options[kByteLength];
7790
+ this._state = DEFLATING;
7791
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
7792
+ if (this._socket.destroyed) {
7793
+ callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
7794
+ return;
7795
+ }
7796
+ this._bufferedBytes -= options[kByteLength];
7797
+ this._state = DEFAULT;
7798
+ options.readOnly = false;
7799
+ this.sendFrame(Sender.frame(buf, options), cb);
7800
+ this.dequeue();
7801
+ });
7802
+ }
7803
+ /**
7804
+ * Executes queued send operations.
7805
+ *
7806
+ * @private
7807
+ */
7808
+ dequeue() {
7809
+ while (this._state === DEFAULT && this._queue.length) {
7810
+ const params = this._queue.shift();
7811
+ this._bufferedBytes -= params[3][kByteLength];
7812
+ Reflect.apply(params[0], this, params.slice(1));
7813
+ }
7814
+ }
7815
+ /**
7816
+ * Enqueues a send operation.
7817
+ *
7818
+ * @param {Array} params Send operation parameters.
7819
+ * @private
7820
+ */
7821
+ enqueue(params) {
7822
+ this._bufferedBytes += params[3][kByteLength];
7823
+ this._queue.push(params);
7824
+ }
7825
+ /**
7826
+ * Sends a frame.
7827
+ *
7828
+ * @param {(Buffer | String)[]} list The frame to send
7829
+ * @param {Function} [cb] Callback
7830
+ * @private
7831
+ */
7832
+ sendFrame(list, cb) {
7833
+ if (list.length === 2) {
7834
+ this._socket.cork();
7835
+ this._socket.write(list[0]);
7836
+ this._socket.write(list[1], cb);
7837
+ this._socket.uncork();
7838
+ } else this._socket.write(list[0], cb);
7839
+ }
7840
+ };
7841
+ module.exports = Sender;
7842
+ /**
7843
+ * Calls queued callbacks with an error.
7844
+ *
7845
+ * @param {Sender} sender The `Sender` instance
7846
+ * @param {Error} err The error to call the callbacks with
7847
+ * @param {Function} [cb] The first callback
7848
+ * @private
7849
+ */
7850
+ function callCallbacks(sender, err, cb) {
7851
+ if (typeof cb === "function") cb(err);
7852
+ for (let i = 0; i < sender._queue.length; i++) {
7853
+ const params = sender._queue[i];
7854
+ const callback = params[params.length - 1];
7855
+ if (typeof callback === "function") callback(err);
7856
+ }
7857
+ }
7858
+ /**
7859
+ * Handles a `Sender` error.
7860
+ *
7861
+ * @param {Sender} sender The `Sender` instance
7862
+ * @param {Error} err The error
7863
+ * @param {Function} [cb] The first pending callback
7864
+ * @private
7865
+ */
7866
+ function onError(sender, err, cb) {
7867
+ callCallbacks(sender, err, cb);
7868
+ sender.onerror(err);
7869
+ }
7870
+ }));
7871
+
7872
+ //#endregion
7873
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/event-target.js
7874
+ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7875
+ const { kForOnEventAttribute, kListener } = require_constants();
7876
+ const kCode = Symbol("kCode");
7877
+ const kData = Symbol("kData");
7878
+ const kError = Symbol("kError");
7879
+ const kMessage = Symbol("kMessage");
7880
+ const kReason = Symbol("kReason");
7881
+ const kTarget = Symbol("kTarget");
7882
+ const kType = Symbol("kType");
7883
+ const kWasClean = Symbol("kWasClean");
7884
+ /**
7885
+ * Class representing an event.
7886
+ */
7887
+ var Event = class {
7888
+ /**
7889
+ * Create a new `Event`.
7890
+ *
7891
+ * @param {String} type The name of the event
7892
+ * @throws {TypeError} If the `type` argument is not specified
7893
+ */
7894
+ constructor(type) {
7895
+ this[kTarget] = null;
7896
+ this[kType] = type;
7897
+ }
7898
+ /**
7899
+ * @type {*}
7900
+ */
7901
+ get target() {
7902
+ return this[kTarget];
7903
+ }
7904
+ /**
7905
+ * @type {String}
7906
+ */
7907
+ get type() {
7908
+ return this[kType];
7909
+ }
7910
+ };
7911
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
7912
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
7913
+ /**
7914
+ * Class representing a close event.
7915
+ *
7916
+ * @extends Event
7917
+ */
7918
+ var CloseEvent = class extends Event {
7919
+ /**
7920
+ * Create a new `CloseEvent`.
7921
+ *
7922
+ * @param {String} type The name of the event
7923
+ * @param {Object} [options] A dictionary object that allows for setting
7924
+ * attributes via object members of the same name
7925
+ * @param {Number} [options.code=0] The status code explaining why the
7926
+ * connection was closed
7927
+ * @param {String} [options.reason=''] A human-readable string explaining why
7928
+ * the connection was closed
7929
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
7930
+ * connection was cleanly closed
7931
+ */
7932
+ constructor(type, options = {}) {
7933
+ super(type);
7934
+ this[kCode] = options.code === void 0 ? 0 : options.code;
7935
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
7936
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
7937
+ }
7938
+ /**
7939
+ * @type {Number}
7940
+ */
7941
+ get code() {
7942
+ return this[kCode];
7943
+ }
7944
+ /**
7945
+ * @type {String}
7946
+ */
7947
+ get reason() {
7948
+ return this[kReason];
7949
+ }
7950
+ /**
7951
+ * @type {Boolean}
7952
+ */
7953
+ get wasClean() {
7954
+ return this[kWasClean];
7955
+ }
7956
+ };
7957
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
7958
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
7959
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
7960
+ /**
7961
+ * Class representing an error event.
7962
+ *
7963
+ * @extends Event
7964
+ */
7965
+ var ErrorEvent = class extends Event {
7966
+ /**
7967
+ * Create a new `ErrorEvent`.
7968
+ *
7969
+ * @param {String} type The name of the event
7970
+ * @param {Object} [options] A dictionary object that allows for setting
7971
+ * attributes via object members of the same name
7972
+ * @param {*} [options.error=null] The error that generated this event
7973
+ * @param {String} [options.message=''] The error message
7974
+ */
7975
+ constructor(type, options = {}) {
7976
+ super(type);
7977
+ this[kError] = options.error === void 0 ? null : options.error;
7978
+ this[kMessage] = options.message === void 0 ? "" : options.message;
7979
+ }
7980
+ /**
7981
+ * @type {*}
7982
+ */
7983
+ get error() {
7984
+ return this[kError];
7985
+ }
7986
+ /**
7987
+ * @type {String}
7988
+ */
7989
+ get message() {
7990
+ return this[kMessage];
7991
+ }
7992
+ };
7993
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
7994
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
7995
+ /**
7996
+ * Class representing a message event.
7997
+ *
7998
+ * @extends Event
7999
+ */
8000
+ var MessageEvent = class extends Event {
8001
+ /**
8002
+ * Create a new `MessageEvent`.
8003
+ *
8004
+ * @param {String} type The name of the event
8005
+ * @param {Object} [options] A dictionary object that allows for setting
8006
+ * attributes via object members of the same name
8007
+ * @param {*} [options.data=null] The message content
8008
+ */
8009
+ constructor(type, options = {}) {
8010
+ super(type);
8011
+ this[kData] = options.data === void 0 ? null : options.data;
8012
+ }
8013
+ /**
8014
+ * @type {*}
8015
+ */
8016
+ get data() {
8017
+ return this[kData];
8018
+ }
8019
+ };
8020
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
8021
+ /**
8022
+ * This provides methods for emulating the `EventTarget` interface. It's not
8023
+ * meant to be used directly.
8024
+ *
8025
+ * @mixin
8026
+ */
8027
+ const EventTarget = {
8028
+ addEventListener(type, handler, options = {}) {
8029
+ for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
8030
+ let wrapper;
8031
+ if (type === "message") wrapper = function onMessage(data, isBinary) {
8032
+ const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
8033
+ event[kTarget] = this;
8034
+ callListener(handler, this, event);
8035
+ };
8036
+ else if (type === "close") wrapper = function onClose(code, message) {
8037
+ const event = new CloseEvent("close", {
8038
+ code,
8039
+ reason: message.toString(),
8040
+ wasClean: this._closeFrameReceived && this._closeFrameSent
8041
+ });
8042
+ event[kTarget] = this;
8043
+ callListener(handler, this, event);
8044
+ };
8045
+ else if (type === "error") wrapper = function onError(error) {
8046
+ const event = new ErrorEvent("error", {
8047
+ error,
8048
+ message: error.message
8049
+ });
8050
+ event[kTarget] = this;
8051
+ callListener(handler, this, event);
8052
+ };
8053
+ else if (type === "open") wrapper = function onOpen() {
8054
+ const event = new Event("open");
8055
+ event[kTarget] = this;
8056
+ callListener(handler, this, event);
8057
+ };
8058
+ else return;
8059
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
8060
+ wrapper[kListener] = handler;
8061
+ if (options.once) this.once(type, wrapper);
8062
+ else this.on(type, wrapper);
8063
+ },
8064
+ removeEventListener(type, handler) {
8065
+ for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
8066
+ this.removeListener(type, listener);
8067
+ break;
8068
+ }
8069
+ }
8070
+ };
8071
+ module.exports = {
8072
+ CloseEvent,
8073
+ ErrorEvent,
8074
+ Event,
8075
+ EventTarget,
8076
+ MessageEvent
8077
+ };
8078
+ /**
8079
+ * Call an event listener
8080
+ *
8081
+ * @param {(Function|Object)} listener The listener to call
8082
+ * @param {*} thisArg The value to use as `this`` when calling the listener
8083
+ * @param {Event} event The event to pass to the listener
8084
+ * @private
8085
+ */
8086
+ function callListener(listener, thisArg, event) {
8087
+ if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
8088
+ else listener.call(thisArg, event);
8089
+ }
8090
+ }));
8091
+
8092
+ //#endregion
8093
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/extension.js
8094
+ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8095
+ const { tokenChars } = require_validation();
8096
+ /**
8097
+ * Adds an offer to the map of extension offers or a parameter to the map of
8098
+ * parameters.
8099
+ *
8100
+ * @param {Object} dest The map of extension offers or parameters
8101
+ * @param {String} name The extension or parameter name
8102
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
8103
+ * parameter value
8104
+ * @private
8105
+ */
8106
+ function push(dest, name, elem) {
8107
+ if (dest[name] === void 0) dest[name] = [elem];
8108
+ else dest[name].push(elem);
8109
+ }
8110
+ /**
8111
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
8112
+ *
8113
+ * @param {String} header The field value of the header
8114
+ * @return {Object} The parsed object
8115
+ * @public
8116
+ */
8117
+ function parse(header) {
8118
+ const offers = Object.create(null);
8119
+ let params = Object.create(null);
8120
+ let mustUnescape = false;
8121
+ let isEscaping = false;
8122
+ let inQuotes = false;
8123
+ let extensionName;
8124
+ let paramName;
8125
+ let start = -1;
8126
+ let code = -1;
8127
+ let end = -1;
8128
+ let i = 0;
8129
+ for (; i < header.length; i++) {
8130
+ code = header.charCodeAt(i);
8131
+ if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
8132
+ if (start === -1) start = i;
8133
+ } else if (i !== 0 && (code === 32 || code === 9)) {
8134
+ if (end === -1 && start !== -1) end = i;
8135
+ } else if (code === 59 || code === 44) {
8136
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8137
+ if (end === -1) end = i;
8138
+ const name = header.slice(start, end);
8139
+ if (code === 44) {
8140
+ push(offers, name, params);
8141
+ params = Object.create(null);
8142
+ } else extensionName = name;
8143
+ start = end = -1;
8144
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8145
+ else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
8146
+ if (start === -1) start = i;
8147
+ } else if (code === 32 || code === 9) {
8148
+ if (end === -1 && start !== -1) end = i;
8149
+ } else if (code === 59 || code === 44) {
8150
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8151
+ if (end === -1) end = i;
8152
+ push(params, header.slice(start, end), true);
8153
+ if (code === 44) {
8154
+ push(offers, extensionName, params);
8155
+ params = Object.create(null);
8156
+ extensionName = void 0;
8157
+ }
8158
+ start = end = -1;
8159
+ } else if (code === 61 && start !== -1 && end === -1) {
8160
+ paramName = header.slice(start, i);
8161
+ start = end = -1;
8162
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8163
+ else if (isEscaping) {
8164
+ if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
8165
+ if (start === -1) start = i;
8166
+ else if (!mustUnescape) mustUnescape = true;
8167
+ isEscaping = false;
8168
+ } else if (inQuotes) if (tokenChars[code] === 1) {
8169
+ if (start === -1) start = i;
8170
+ } else if (code === 34 && start !== -1) {
8171
+ inQuotes = false;
8172
+ end = i;
8173
+ } else if (code === 92) isEscaping = true;
8174
+ else throw new SyntaxError(`Unexpected character at index ${i}`);
8175
+ else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
8176
+ else if (end === -1 && tokenChars[code] === 1) {
8177
+ if (start === -1) start = i;
8178
+ } else if (start !== -1 && (code === 32 || code === 9)) {
8179
+ if (end === -1) end = i;
8180
+ } else if (code === 59 || code === 44) {
8181
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8182
+ if (end === -1) end = i;
8183
+ let value = header.slice(start, end);
8184
+ if (mustUnescape) {
8185
+ value = value.replace(/\\/g, "");
8186
+ mustUnescape = false;
8187
+ }
8188
+ push(params, paramName, value);
8189
+ if (code === 44) {
8190
+ push(offers, extensionName, params);
8191
+ params = Object.create(null);
8192
+ extensionName = void 0;
8193
+ }
8194
+ paramName = void 0;
8195
+ start = end = -1;
8196
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8197
+ }
8198
+ if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
8199
+ if (end === -1) end = i;
8200
+ const token = header.slice(start, end);
8201
+ if (extensionName === void 0) push(offers, token, params);
8202
+ else {
8203
+ if (paramName === void 0) push(params, token, true);
8204
+ else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
8205
+ else push(params, paramName, token);
8206
+ push(offers, extensionName, params);
8207
+ }
8208
+ return offers;
8209
+ }
8210
+ /**
8211
+ * Builds the `Sec-WebSocket-Extensions` header field value.
8212
+ *
8213
+ * @param {Object} extensions The map of extensions and parameters to format
8214
+ * @return {String} A string representing the given object
8215
+ * @public
8216
+ */
8217
+ function format(extensions) {
8218
+ return Object.keys(extensions).map((extension) => {
8219
+ let configurations = extensions[extension];
8220
+ if (!Array.isArray(configurations)) configurations = [configurations];
8221
+ return configurations.map((params) => {
8222
+ return [extension].concat(Object.keys(params).map((k) => {
8223
+ let values = params[k];
8224
+ if (!Array.isArray(values)) values = [values];
8225
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
8226
+ })).join("; ");
8227
+ }).join(", ");
8228
+ }).join(", ");
8229
+ }
8230
+ module.exports = {
8231
+ format,
8232
+ parse
8233
+ };
8234
+ }));
8235
+
8236
+ //#endregion
8237
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js
8238
+ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8239
+ const EventEmitter$2 = require("events");
8240
+ const https = require("https");
8241
+ const http$1 = require("http");
8242
+ const net = require("net");
8243
+ const tls = require("tls");
8244
+ const { randomBytes, createHash: createHash$1 } = require("crypto");
8245
+ const { Duplex: Duplex$2, Readable } = require("stream");
8246
+ const { URL } = require("url");
8247
+ const PerMessageDeflate = require_permessage_deflate();
8248
+ const Receiver = require_receiver();
8249
+ const Sender = require_sender();
8250
+ const { isBlob } = require_validation();
8251
+ const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
8252
+ const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
8253
+ const { format, parse } = require_extension();
8254
+ const { toBuffer } = require_buffer_util();
8255
+ const kAborted = Symbol("kAborted");
8256
+ const protocolVersions = [8, 13];
8257
+ const readyStates = [
8258
+ "CONNECTING",
8259
+ "OPEN",
8260
+ "CLOSING",
8261
+ "CLOSED"
8262
+ ];
8263
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
8264
+ /**
8265
+ * Class representing a WebSocket.
8266
+ *
8267
+ * @extends EventEmitter
8268
+ */
8269
+ var WebSocket = class WebSocket extends EventEmitter$2 {
8270
+ /**
8271
+ * Create a new `WebSocket`.
8272
+ *
8273
+ * @param {(String|URL)} address The URL to which to connect
8274
+ * @param {(String|String[])} [protocols] The subprotocols
8275
+ * @param {Object} [options] Connection options
8276
+ */
8277
+ constructor(address, protocols, options) {
8278
+ super();
8279
+ this._binaryType = BINARY_TYPES[0];
8280
+ this._closeCode = 1006;
8281
+ this._closeFrameReceived = false;
8282
+ this._closeFrameSent = false;
8283
+ this._closeMessage = EMPTY_BUFFER;
8284
+ this._closeTimer = null;
8285
+ this._errorEmitted = false;
8286
+ this._extensions = {};
8287
+ this._paused = false;
8288
+ this._protocol = "";
8289
+ this._readyState = WebSocket.CONNECTING;
8290
+ this._receiver = null;
8291
+ this._sender = null;
8292
+ this._socket = null;
8293
+ if (address !== null) {
8294
+ this._bufferedAmount = 0;
8295
+ this._isServer = false;
8296
+ this._redirects = 0;
8297
+ if (protocols === void 0) protocols = [];
8298
+ else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
8299
+ options = protocols;
8300
+ protocols = [];
8301
+ } else protocols = [protocols];
8302
+ initAsClient(this, address, protocols, options);
8303
+ } else {
8304
+ this._autoPong = options.autoPong;
8305
+ this._closeTimeout = options.closeTimeout;
8306
+ this._isServer = true;
8307
+ }
8308
+ }
8309
+ /**
8310
+ * For historical reasons, the custom "nodebuffer" type is used by the default
8311
+ * instead of "blob".
8312
+ *
8313
+ * @type {String}
8314
+ */
8315
+ get binaryType() {
8316
+ return this._binaryType;
8317
+ }
8318
+ set binaryType(type) {
8319
+ if (!BINARY_TYPES.includes(type)) return;
8320
+ this._binaryType = type;
8321
+ if (this._receiver) this._receiver._binaryType = type;
8322
+ }
8323
+ /**
8324
+ * @type {Number}
8325
+ */
8326
+ get bufferedAmount() {
8327
+ if (!this._socket) return this._bufferedAmount;
8328
+ return this._socket._writableState.length + this._sender._bufferedBytes;
8329
+ }
8330
+ /**
8331
+ * @type {String}
8332
+ */
8333
+ get extensions() {
8334
+ return Object.keys(this._extensions).join();
8335
+ }
8336
+ /**
8337
+ * @type {Boolean}
8338
+ */
8339
+ get isPaused() {
8340
+ return this._paused;
8341
+ }
8342
+ /**
8343
+ * @type {Function}
8344
+ */
8345
+ /* istanbul ignore next */
8346
+ get onclose() {
8347
+ return null;
8348
+ }
8349
+ /**
8350
+ * @type {Function}
8351
+ */
8352
+ /* istanbul ignore next */
8353
+ get onerror() {
8354
+ return null;
8355
+ }
8356
+ /**
8357
+ * @type {Function}
8358
+ */
8359
+ /* istanbul ignore next */
8360
+ get onopen() {
8361
+ return null;
8362
+ }
8363
+ /**
8364
+ * @type {Function}
8365
+ */
8366
+ /* istanbul ignore next */
8367
+ get onmessage() {
8368
+ return null;
8369
+ }
8370
+ /**
8371
+ * @type {String}
8372
+ */
8373
+ get protocol() {
8374
+ return this._protocol;
8375
+ }
8376
+ /**
8377
+ * @type {Number}
8378
+ */
8379
+ get readyState() {
8380
+ return this._readyState;
8381
+ }
8382
+ /**
8383
+ * @type {String}
8384
+ */
8385
+ get url() {
8386
+ return this._url;
8387
+ }
8388
+ /**
8389
+ * Set up the socket and the internal resources.
8390
+ *
8391
+ * @param {Duplex} socket The network socket between the server and client
8392
+ * @param {Buffer} head The first packet of the upgraded stream
8393
+ * @param {Object} options Options object
8394
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
8395
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
8396
+ * multiple times in the same tick
8397
+ * @param {Function} [options.generateMask] The function used to generate the
8398
+ * masking key
8399
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
8400
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
8401
+ * not to skip UTF-8 validation for text and close messages
8402
+ * @private
8403
+ */
8404
+ setSocket(socket, head, options) {
8405
+ const receiver = new Receiver({
8406
+ allowSynchronousEvents: options.allowSynchronousEvents,
8407
+ binaryType: this.binaryType,
8408
+ extensions: this._extensions,
8409
+ isServer: this._isServer,
8410
+ maxPayload: options.maxPayload,
8411
+ skipUTF8Validation: options.skipUTF8Validation
8412
+ });
8413
+ const sender = new Sender(socket, this._extensions, options.generateMask);
8414
+ this._receiver = receiver;
8415
+ this._sender = sender;
8416
+ this._socket = socket;
8417
+ receiver[kWebSocket] = this;
8418
+ sender[kWebSocket] = this;
8419
+ socket[kWebSocket] = this;
8420
+ receiver.on("conclude", receiverOnConclude);
8421
+ receiver.on("drain", receiverOnDrain);
8422
+ receiver.on("error", receiverOnError);
8423
+ receiver.on("message", receiverOnMessage);
8424
+ receiver.on("ping", receiverOnPing);
8425
+ receiver.on("pong", receiverOnPong);
8426
+ sender.onerror = senderOnError;
8427
+ if (socket.setTimeout) socket.setTimeout(0);
8428
+ if (socket.setNoDelay) socket.setNoDelay();
8429
+ if (head.length > 0) socket.unshift(head);
8430
+ socket.on("close", socketOnClose);
8431
+ socket.on("data", socketOnData);
8432
+ socket.on("end", socketOnEnd);
8433
+ socket.on("error", socketOnError);
8434
+ this._readyState = WebSocket.OPEN;
8435
+ this.emit("open");
8436
+ }
8437
+ /**
8438
+ * Emit the `'close'` event.
8439
+ *
8440
+ * @private
8441
+ */
8442
+ emitClose() {
8443
+ if (!this._socket) {
8444
+ this._readyState = WebSocket.CLOSED;
8445
+ this.emit("close", this._closeCode, this._closeMessage);
8446
+ return;
8447
+ }
8448
+ if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
8449
+ this._receiver.removeAllListeners();
8450
+ this._readyState = WebSocket.CLOSED;
8451
+ this.emit("close", this._closeCode, this._closeMessage);
8452
+ }
8453
+ /**
8454
+ * Start a closing handshake.
8455
+ *
8456
+ * +----------+ +-----------+ +----------+
8457
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
8458
+ * | +----------+ +-----------+ +----------+ |
8459
+ * +----------+ +-----------+ |
8460
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
8461
+ * +----------+ +-----------+ |
8462
+ * | | | +---+ |
8463
+ * +------------------------+-->|fin| - - - -
8464
+ * | +---+ | +---+
8465
+ * - - - - -|fin|<---------------------+
8466
+ * +---+
8467
+ *
8468
+ * @param {Number} [code] Status code explaining why the connection is closing
8469
+ * @param {(String|Buffer)} [data] The reason why the connection is
8470
+ * closing
8471
+ * @public
8472
+ */
8473
+ close(code, data) {
8474
+ if (this.readyState === WebSocket.CLOSED) return;
8475
+ if (this.readyState === WebSocket.CONNECTING) {
8476
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
8477
+ return;
8478
+ }
8479
+ if (this.readyState === WebSocket.CLOSING) {
8480
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
8481
+ return;
8482
+ }
8483
+ this._readyState = WebSocket.CLOSING;
8484
+ this._sender.close(code, data, !this._isServer, (err) => {
8485
+ if (err) return;
8486
+ this._closeFrameSent = true;
8487
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
8488
+ });
8489
+ setCloseTimer(this);
8490
+ }
8491
+ /**
8492
+ * Pause the socket.
8493
+ *
8494
+ * @public
8495
+ */
8496
+ pause() {
8497
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
8498
+ this._paused = true;
8499
+ this._socket.pause();
8500
+ }
8501
+ /**
8502
+ * Send a ping.
8503
+ *
8504
+ * @param {*} [data] The data to send
8505
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
8506
+ * @param {Function} [cb] Callback which is executed when the ping is sent
8507
+ * @public
8508
+ */
8509
+ ping(data, mask, cb) {
8510
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8511
+ if (typeof data === "function") {
8512
+ cb = data;
8513
+ data = mask = void 0;
8514
+ } else if (typeof mask === "function") {
8515
+ cb = mask;
8516
+ mask = void 0;
8517
+ }
8518
+ if (typeof data === "number") data = data.toString();
8519
+ if (this.readyState !== WebSocket.OPEN) {
8520
+ sendAfterClose(this, data, cb);
8521
+ return;
8522
+ }
8523
+ if (mask === void 0) mask = !this._isServer;
8524
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
8525
+ }
8526
+ /**
8527
+ * Send a pong.
8528
+ *
8529
+ * @param {*} [data] The data to send
8530
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
8531
+ * @param {Function} [cb] Callback which is executed when the pong is sent
8532
+ * @public
8533
+ */
8534
+ pong(data, mask, cb) {
8535
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8536
+ if (typeof data === "function") {
8537
+ cb = data;
8538
+ data = mask = void 0;
8539
+ } else if (typeof mask === "function") {
8540
+ cb = mask;
8541
+ mask = void 0;
8542
+ }
8543
+ if (typeof data === "number") data = data.toString();
8544
+ if (this.readyState !== WebSocket.OPEN) {
8545
+ sendAfterClose(this, data, cb);
8546
+ return;
8547
+ }
8548
+ if (mask === void 0) mask = !this._isServer;
8549
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
8550
+ }
8551
+ /**
8552
+ * Resume the socket.
8553
+ *
8554
+ * @public
8555
+ */
8556
+ resume() {
8557
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
8558
+ this._paused = false;
8559
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
8560
+ }
8561
+ /**
8562
+ * Send a data message.
8563
+ *
8564
+ * @param {*} data The message to send
8565
+ * @param {Object} [options] Options object
8566
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
8567
+ * text
8568
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
8569
+ * `data`
8570
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
8571
+ * last one
8572
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
8573
+ * @param {Function} [cb] Callback which is executed when data is written out
8574
+ * @public
8575
+ */
8576
+ send(data, options, cb) {
8577
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8578
+ if (typeof options === "function") {
8579
+ cb = options;
8580
+ options = {};
8581
+ }
8582
+ if (typeof data === "number") data = data.toString();
8583
+ if (this.readyState !== WebSocket.OPEN) {
8584
+ sendAfterClose(this, data, cb);
8585
+ return;
8586
+ }
8587
+ const opts = {
8588
+ binary: typeof data !== "string",
8589
+ mask: !this._isServer,
8590
+ compress: true,
8591
+ fin: true,
8592
+ ...options
8593
+ };
8594
+ if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
8595
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
8596
+ }
8597
+ /**
8598
+ * Forcibly close the connection.
8599
+ *
8600
+ * @public
8601
+ */
8602
+ terminate() {
8603
+ if (this.readyState === WebSocket.CLOSED) return;
8604
+ if (this.readyState === WebSocket.CONNECTING) {
8605
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
8606
+ return;
8607
+ }
8608
+ if (this._socket) {
8609
+ this._readyState = WebSocket.CLOSING;
8610
+ this._socket.destroy();
8611
+ }
8612
+ }
8613
+ };
8614
+ /**
8615
+ * @constant {Number} CONNECTING
8616
+ * @memberof WebSocket
8617
+ */
8618
+ Object.defineProperty(WebSocket, "CONNECTING", {
8619
+ enumerable: true,
8620
+ value: readyStates.indexOf("CONNECTING")
8621
+ });
8622
+ /**
8623
+ * @constant {Number} CONNECTING
8624
+ * @memberof WebSocket.prototype
8625
+ */
8626
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
8627
+ enumerable: true,
8628
+ value: readyStates.indexOf("CONNECTING")
8629
+ });
8630
+ /**
8631
+ * @constant {Number} OPEN
8632
+ * @memberof WebSocket
8633
+ */
8634
+ Object.defineProperty(WebSocket, "OPEN", {
8635
+ enumerable: true,
8636
+ value: readyStates.indexOf("OPEN")
8637
+ });
8638
+ /**
8639
+ * @constant {Number} OPEN
8640
+ * @memberof WebSocket.prototype
8641
+ */
8642
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
8643
+ enumerable: true,
8644
+ value: readyStates.indexOf("OPEN")
8645
+ });
8646
+ /**
8647
+ * @constant {Number} CLOSING
8648
+ * @memberof WebSocket
8649
+ */
8650
+ Object.defineProperty(WebSocket, "CLOSING", {
8651
+ enumerable: true,
8652
+ value: readyStates.indexOf("CLOSING")
8653
+ });
8654
+ /**
8655
+ * @constant {Number} CLOSING
8656
+ * @memberof WebSocket.prototype
8657
+ */
8658
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
8659
+ enumerable: true,
8660
+ value: readyStates.indexOf("CLOSING")
8661
+ });
8662
+ /**
8663
+ * @constant {Number} CLOSED
8664
+ * @memberof WebSocket
8665
+ */
8666
+ Object.defineProperty(WebSocket, "CLOSED", {
8667
+ enumerable: true,
8668
+ value: readyStates.indexOf("CLOSED")
8669
+ });
8670
+ /**
8671
+ * @constant {Number} CLOSED
8672
+ * @memberof WebSocket.prototype
8673
+ */
8674
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
8675
+ enumerable: true,
8676
+ value: readyStates.indexOf("CLOSED")
8677
+ });
8678
+ [
8679
+ "binaryType",
8680
+ "bufferedAmount",
8681
+ "extensions",
8682
+ "isPaused",
8683
+ "protocol",
8684
+ "readyState",
8685
+ "url"
8686
+ ].forEach((property) => {
8687
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
8688
+ });
8689
+ [
8690
+ "open",
8691
+ "error",
8692
+ "close",
8693
+ "message"
8694
+ ].forEach((method) => {
8695
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
8696
+ enumerable: true,
8697
+ get() {
8698
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
8699
+ return null;
8700
+ },
8701
+ set(handler) {
8702
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
8703
+ this.removeListener(method, listener);
8704
+ break;
8705
+ }
8706
+ if (typeof handler !== "function") return;
8707
+ this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
8708
+ }
8709
+ });
8710
+ });
8711
+ WebSocket.prototype.addEventListener = addEventListener;
8712
+ WebSocket.prototype.removeEventListener = removeEventListener;
8713
+ module.exports = WebSocket;
8714
+ /**
8715
+ * Initialize a WebSocket client.
8716
+ *
8717
+ * @param {WebSocket} websocket The client to initialize
8718
+ * @param {(String|URL)} address The URL to which to connect
8719
+ * @param {Array} protocols The subprotocols
8720
+ * @param {Object} [options] Connection options
8721
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
8722
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
8723
+ * times in the same tick
8724
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
8725
+ * automatically send a pong in response to a ping
8726
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
8727
+ * for the closing handshake to finish after `websocket.close()` is called
8728
+ * @param {Function} [options.finishRequest] A function which can be used to
8729
+ * customize the headers of each http request before it is sent
8730
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
8731
+ * redirects
8732
+ * @param {Function} [options.generateMask] The function used to generate the
8733
+ * masking key
8734
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
8735
+ * handshake request
8736
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
8737
+ * size
8738
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
8739
+ * allowed
8740
+ * @param {String} [options.origin] Value of the `Origin` or
8741
+ * `Sec-WebSocket-Origin` header
8742
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
8743
+ * permessage-deflate
8744
+ * @param {Number} [options.protocolVersion=13] Value of the
8745
+ * `Sec-WebSocket-Version` header
8746
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
8747
+ * not to skip UTF-8 validation for text and close messages
8748
+ * @private
8749
+ */
8750
+ function initAsClient(websocket, address, protocols, options) {
8751
+ const opts = {
8752
+ allowSynchronousEvents: true,
8753
+ autoPong: true,
8754
+ closeTimeout: CLOSE_TIMEOUT,
8755
+ protocolVersion: protocolVersions[1],
8756
+ maxPayload: 100 * 1024 * 1024,
8757
+ skipUTF8Validation: false,
8758
+ perMessageDeflate: true,
8759
+ followRedirects: false,
8760
+ maxRedirects: 10,
8761
+ ...options,
8762
+ socketPath: void 0,
8763
+ hostname: void 0,
8764
+ protocol: void 0,
8765
+ timeout: void 0,
8766
+ method: "GET",
8767
+ host: void 0,
8768
+ path: void 0,
8769
+ port: void 0
8770
+ };
8771
+ websocket._autoPong = opts.autoPong;
8772
+ websocket._closeTimeout = opts.closeTimeout;
8773
+ if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
8774
+ let parsedUrl;
8775
+ if (address instanceof URL) parsedUrl = address;
8776
+ else try {
8777
+ parsedUrl = new URL(address);
8778
+ } catch (e) {
8779
+ throw new SyntaxError(`Invalid URL: ${address}`);
8780
+ }
8781
+ if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
8782
+ else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
8783
+ websocket._url = parsedUrl.href;
8784
+ const isSecure = parsedUrl.protocol === "wss:";
8785
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
8786
+ let invalidUrlMessage;
8787
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
8788
+ else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
8789
+ else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
8790
+ if (invalidUrlMessage) {
8791
+ const err = new SyntaxError(invalidUrlMessage);
8792
+ if (websocket._redirects === 0) throw err;
8793
+ else {
8794
+ emitErrorAndClose(websocket, err);
8795
+ return;
8796
+ }
8797
+ }
8798
+ const defaultPort = isSecure ? 443 : 80;
8799
+ const key = randomBytes(16).toString("base64");
8800
+ const request = isSecure ? https.request : http$1.request;
8801
+ const protocolSet = /* @__PURE__ */ new Set();
8802
+ let perMessageDeflate;
8803
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
8804
+ opts.defaultPort = opts.defaultPort || defaultPort;
8805
+ opts.port = parsedUrl.port || defaultPort;
8806
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
8807
+ opts.headers = {
8808
+ ...opts.headers,
8809
+ "Sec-WebSocket-Version": opts.protocolVersion,
8810
+ "Sec-WebSocket-Key": key,
8811
+ Connection: "Upgrade",
8812
+ Upgrade: "websocket"
8813
+ };
8814
+ opts.path = parsedUrl.pathname + parsedUrl.search;
8815
+ opts.timeout = opts.handshakeTimeout;
8816
+ if (opts.perMessageDeflate) {
8817
+ perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
8818
+ opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
8819
+ }
8820
+ if (protocols.length) {
8821
+ for (const protocol of protocols) {
8822
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
8823
+ protocolSet.add(protocol);
8824
+ }
8825
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
8826
+ }
8827
+ if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
8828
+ else opts.headers.Origin = opts.origin;
8829
+ if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
8830
+ if (isIpcUrl) {
8831
+ const parts = opts.path.split(":");
8832
+ opts.socketPath = parts[0];
8833
+ opts.path = parts[1];
8834
+ }
8835
+ let req;
8836
+ if (opts.followRedirects) {
8837
+ if (websocket._redirects === 0) {
8838
+ websocket._originalIpc = isIpcUrl;
8839
+ websocket._originalSecure = isSecure;
8840
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
8841
+ const headers = options && options.headers;
8842
+ options = {
8843
+ ...options,
8844
+ headers: {}
8845
+ };
8846
+ if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
8847
+ } else if (websocket.listenerCount("redirect") === 0) {
8848
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
8849
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
8850
+ delete opts.headers.authorization;
8851
+ delete opts.headers.cookie;
8852
+ if (!isSameHost) delete opts.headers.host;
8853
+ opts.auth = void 0;
8854
+ }
8855
+ }
8856
+ if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
8857
+ req = websocket._req = request(opts);
8858
+ if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
8859
+ } else req = websocket._req = request(opts);
8860
+ if (opts.timeout) req.on("timeout", () => {
8861
+ abortHandshake(websocket, req, "Opening handshake has timed out");
8862
+ });
8863
+ req.on("error", (err) => {
8864
+ if (req === null || req[kAborted]) return;
8865
+ req = websocket._req = null;
8866
+ emitErrorAndClose(websocket, err);
8867
+ });
8868
+ req.on("response", (res) => {
8869
+ const location = res.headers.location;
8870
+ const statusCode = res.statusCode;
8871
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
8872
+ if (++websocket._redirects > opts.maxRedirects) {
8873
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
8874
+ return;
8875
+ }
8876
+ req.abort();
8877
+ let addr;
8878
+ try {
8879
+ addr = new URL(location, address);
8880
+ } catch (e) {
8881
+ emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
8882
+ return;
8883
+ }
8884
+ initAsClient(websocket, addr, protocols, options);
8885
+ } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
8886
+ });
8887
+ req.on("upgrade", (res, socket, head) => {
8888
+ websocket.emit("upgrade", res);
8889
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
8890
+ req = websocket._req = null;
8891
+ const upgrade = res.headers.upgrade;
8892
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
8893
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
8894
+ return;
8895
+ }
8896
+ const digest = createHash$1("sha1").update(key + GUID).digest("base64");
8897
+ if (res.headers["sec-websocket-accept"] !== digest) {
8898
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
8899
+ return;
8900
+ }
8901
+ const serverProt = res.headers["sec-websocket-protocol"];
8902
+ let protError;
8903
+ if (serverProt !== void 0) {
8904
+ if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
8905
+ else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
8906
+ } else if (protocolSet.size) protError = "Server sent no subprotocol";
8907
+ if (protError) {
8908
+ abortHandshake(websocket, socket, protError);
8909
+ return;
8910
+ }
8911
+ if (serverProt) websocket._protocol = serverProt;
8912
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
8913
+ if (secWebSocketExtensions !== void 0) {
8914
+ if (!perMessageDeflate) {
8915
+ abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
8916
+ return;
8917
+ }
8918
+ let extensions;
8919
+ try {
8920
+ extensions = parse(secWebSocketExtensions);
8921
+ } catch (err) {
8922
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
8923
+ return;
8924
+ }
8925
+ const extensionNames = Object.keys(extensions);
8926
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
8927
+ abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
8928
+ return;
8929
+ }
8930
+ try {
8931
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
8932
+ } catch (err) {
8933
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
8934
+ return;
8935
+ }
8936
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
8937
+ }
8938
+ websocket.setSocket(socket, head, {
8939
+ allowSynchronousEvents: opts.allowSynchronousEvents,
8940
+ generateMask: opts.generateMask,
8941
+ maxPayload: opts.maxPayload,
8942
+ skipUTF8Validation: opts.skipUTF8Validation
8943
+ });
8944
+ });
8945
+ if (opts.finishRequest) opts.finishRequest(req, websocket);
8946
+ else req.end();
8947
+ }
8948
+ /**
8949
+ * Emit the `'error'` and `'close'` events.
8950
+ *
8951
+ * @param {WebSocket} websocket The WebSocket instance
8952
+ * @param {Error} The error to emit
8953
+ * @private
8954
+ */
8955
+ function emitErrorAndClose(websocket, err) {
8956
+ websocket._readyState = WebSocket.CLOSING;
8957
+ websocket._errorEmitted = true;
8958
+ websocket.emit("error", err);
8959
+ websocket.emitClose();
8960
+ }
8961
+ /**
8962
+ * Create a `net.Socket` and initiate a connection.
8963
+ *
8964
+ * @param {Object} options Connection options
8965
+ * @return {net.Socket} The newly created socket used to start the connection
8966
+ * @private
8967
+ */
8968
+ function netConnect(options) {
8969
+ options.path = options.socketPath;
8970
+ return net.connect(options);
8971
+ }
8972
+ /**
8973
+ * Create a `tls.TLSSocket` and initiate a connection.
8974
+ *
8975
+ * @param {Object} options Connection options
8976
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
8977
+ * @private
8978
+ */
8979
+ function tlsConnect(options) {
8980
+ options.path = void 0;
8981
+ if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
8982
+ return tls.connect(options);
8983
+ }
8984
+ /**
8985
+ * Abort the handshake and emit an error.
8986
+ *
8987
+ * @param {WebSocket} websocket The WebSocket instance
8988
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
8989
+ * abort or the socket to destroy
8990
+ * @param {String} message The error message
8991
+ * @private
8992
+ */
8993
+ function abortHandshake(websocket, stream, message) {
8994
+ websocket._readyState = WebSocket.CLOSING;
8995
+ const err = new Error(message);
8996
+ Error.captureStackTrace(err, abortHandshake);
8997
+ if (stream.setHeader) {
8998
+ stream[kAborted] = true;
8999
+ stream.abort();
9000
+ if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
9001
+ process.nextTick(emitErrorAndClose, websocket, err);
9002
+ } else {
9003
+ stream.destroy(err);
9004
+ stream.once("error", websocket.emit.bind(websocket, "error"));
9005
+ stream.once("close", websocket.emitClose.bind(websocket));
9006
+ }
9007
+ }
9008
+ /**
9009
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
9010
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
9011
+ *
9012
+ * @param {WebSocket} websocket The WebSocket instance
9013
+ * @param {*} [data] The data to send
9014
+ * @param {Function} [cb] Callback
9015
+ * @private
9016
+ */
9017
+ function sendAfterClose(websocket, data, cb) {
9018
+ if (data) {
9019
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
9020
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
9021
+ else websocket._bufferedAmount += length;
9022
+ }
9023
+ if (cb) {
9024
+ const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
9025
+ process.nextTick(cb, err);
9026
+ }
9027
+ }
9028
+ /**
9029
+ * The listener of the `Receiver` `'conclude'` event.
9030
+ *
9031
+ * @param {Number} code The status code
9032
+ * @param {Buffer} reason The reason for closing
9033
+ * @private
9034
+ */
9035
+ function receiverOnConclude(code, reason) {
9036
+ const websocket = this[kWebSocket];
9037
+ websocket._closeFrameReceived = true;
9038
+ websocket._closeMessage = reason;
9039
+ websocket._closeCode = code;
9040
+ if (websocket._socket[kWebSocket] === void 0) return;
9041
+ websocket._socket.removeListener("data", socketOnData);
9042
+ process.nextTick(resume, websocket._socket);
9043
+ if (code === 1005) websocket.close();
9044
+ else websocket.close(code, reason);
9045
+ }
9046
+ /**
9047
+ * The listener of the `Receiver` `'drain'` event.
9048
+ *
9049
+ * @private
9050
+ */
9051
+ function receiverOnDrain() {
9052
+ const websocket = this[kWebSocket];
9053
+ if (!websocket.isPaused) websocket._socket.resume();
9054
+ }
9055
+ /**
9056
+ * The listener of the `Receiver` `'error'` event.
9057
+ *
9058
+ * @param {(RangeError|Error)} err The emitted error
9059
+ * @private
9060
+ */
9061
+ function receiverOnError(err) {
9062
+ const websocket = this[kWebSocket];
9063
+ if (websocket._socket[kWebSocket] !== void 0) {
9064
+ websocket._socket.removeListener("data", socketOnData);
9065
+ process.nextTick(resume, websocket._socket);
9066
+ websocket.close(err[kStatusCode]);
9067
+ }
9068
+ if (!websocket._errorEmitted) {
9069
+ websocket._errorEmitted = true;
9070
+ websocket.emit("error", err);
9071
+ }
9072
+ }
9073
+ /**
9074
+ * The listener of the `Receiver` `'finish'` event.
9075
+ *
9076
+ * @private
9077
+ */
9078
+ function receiverOnFinish() {
9079
+ this[kWebSocket].emitClose();
9080
+ }
9081
+ /**
9082
+ * The listener of the `Receiver` `'message'` event.
9083
+ *
9084
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
9085
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
9086
+ * @private
9087
+ */
9088
+ function receiverOnMessage(data, isBinary) {
9089
+ this[kWebSocket].emit("message", data, isBinary);
9090
+ }
9091
+ /**
9092
+ * The listener of the `Receiver` `'ping'` event.
9093
+ *
9094
+ * @param {Buffer} data The data included in the ping frame
9095
+ * @private
9096
+ */
9097
+ function receiverOnPing(data) {
9098
+ const websocket = this[kWebSocket];
9099
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
9100
+ websocket.emit("ping", data);
9101
+ }
9102
+ /**
9103
+ * The listener of the `Receiver` `'pong'` event.
9104
+ *
9105
+ * @param {Buffer} data The data included in the pong frame
9106
+ * @private
9107
+ */
9108
+ function receiverOnPong(data) {
9109
+ this[kWebSocket].emit("pong", data);
9110
+ }
9111
+ /**
9112
+ * Resume a readable stream
9113
+ *
9114
+ * @param {Readable} stream The readable stream
9115
+ * @private
9116
+ */
9117
+ function resume(stream) {
9118
+ stream.resume();
9119
+ }
9120
+ /**
9121
+ * The `Sender` error event handler.
9122
+ *
9123
+ * @param {Error} The error
9124
+ * @private
9125
+ */
9126
+ function senderOnError(err) {
9127
+ const websocket = this[kWebSocket];
9128
+ if (websocket.readyState === WebSocket.CLOSED) return;
9129
+ if (websocket.readyState === WebSocket.OPEN) {
9130
+ websocket._readyState = WebSocket.CLOSING;
9131
+ setCloseTimer(websocket);
9132
+ }
9133
+ this._socket.end();
9134
+ if (!websocket._errorEmitted) {
9135
+ websocket._errorEmitted = true;
9136
+ websocket.emit("error", err);
9137
+ }
9138
+ }
9139
+ /**
9140
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
9141
+ *
9142
+ * @param {WebSocket} websocket The WebSocket instance
9143
+ * @private
9144
+ */
9145
+ function setCloseTimer(websocket) {
9146
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
9147
+ }
9148
+ /**
9149
+ * The listener of the socket `'close'` event.
9150
+ *
9151
+ * @private
9152
+ */
9153
+ function socketOnClose() {
9154
+ const websocket = this[kWebSocket];
9155
+ this.removeListener("close", socketOnClose);
9156
+ this.removeListener("data", socketOnData);
9157
+ this.removeListener("end", socketOnEnd);
9158
+ websocket._readyState = WebSocket.CLOSING;
9159
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
9160
+ const chunk = this.read(this._readableState.length);
9161
+ websocket._receiver.write(chunk);
9162
+ }
9163
+ websocket._receiver.end();
9164
+ this[kWebSocket] = void 0;
9165
+ clearTimeout(websocket._closeTimer);
9166
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
9167
+ else {
9168
+ websocket._receiver.on("error", receiverOnFinish);
9169
+ websocket._receiver.on("finish", receiverOnFinish);
9170
+ }
9171
+ }
9172
+ /**
9173
+ * The listener of the socket `'data'` event.
9174
+ *
9175
+ * @param {Buffer} chunk A chunk of data
9176
+ * @private
9177
+ */
9178
+ function socketOnData(chunk) {
9179
+ if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
9180
+ }
9181
+ /**
9182
+ * The listener of the socket `'end'` event.
9183
+ *
9184
+ * @private
9185
+ */
9186
+ function socketOnEnd() {
9187
+ const websocket = this[kWebSocket];
9188
+ websocket._readyState = WebSocket.CLOSING;
9189
+ websocket._receiver.end();
9190
+ this.end();
9191
+ }
9192
+ /**
9193
+ * The listener of the socket `'error'` event.
9194
+ *
9195
+ * @private
9196
+ */
9197
+ function socketOnError() {
9198
+ const websocket = this[kWebSocket];
9199
+ this.removeListener("error", socketOnError);
9200
+ this.on("error", NOOP);
9201
+ if (websocket) {
9202
+ websocket._readyState = WebSocket.CLOSING;
9203
+ this.destroy();
9204
+ }
9205
+ }
9206
+ }));
9207
+
9208
+ //#endregion
9209
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/stream.js
9210
+ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9211
+ require_websocket();
9212
+ const { Duplex: Duplex$1 } = require("stream");
9213
+ /**
9214
+ * Emits the `'close'` event on a stream.
9215
+ *
9216
+ * @param {Duplex} stream The stream.
9217
+ * @private
9218
+ */
9219
+ function emitClose(stream) {
9220
+ stream.emit("close");
9221
+ }
9222
+ /**
9223
+ * The listener of the `'end'` event.
9224
+ *
9225
+ * @private
9226
+ */
9227
+ function duplexOnEnd() {
9228
+ if (!this.destroyed && this._writableState.finished) this.destroy();
9229
+ }
9230
+ /**
9231
+ * The listener of the `'error'` event.
9232
+ *
9233
+ * @param {Error} err The error
9234
+ * @private
9235
+ */
9236
+ function duplexOnError(err) {
9237
+ this.removeListener("error", duplexOnError);
9238
+ this.destroy();
9239
+ if (this.listenerCount("error") === 0) this.emit("error", err);
9240
+ }
9241
+ /**
9242
+ * Wraps a `WebSocket` in a duplex stream.
9243
+ *
9244
+ * @param {WebSocket} ws The `WebSocket` to wrap
9245
+ * @param {Object} [options] The options for the `Duplex` constructor
9246
+ * @return {Duplex} The duplex stream
9247
+ * @public
9248
+ */
9249
+ function createWebSocketStream(ws, options) {
9250
+ let terminateOnDestroy = true;
9251
+ const duplex = new Duplex$1({
9252
+ ...options,
9253
+ autoDestroy: false,
9254
+ emitClose: false,
9255
+ objectMode: false,
9256
+ writableObjectMode: false
9257
+ });
9258
+ ws.on("message", function message(msg, isBinary) {
9259
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
9260
+ if (!duplex.push(data)) ws.pause();
9261
+ });
9262
+ ws.once("error", function error(err) {
9263
+ if (duplex.destroyed) return;
9264
+ terminateOnDestroy = false;
9265
+ duplex.destroy(err);
9266
+ });
9267
+ ws.once("close", function close() {
9268
+ if (duplex.destroyed) return;
9269
+ duplex.push(null);
9270
+ });
9271
+ duplex._destroy = function(err, callback) {
9272
+ if (ws.readyState === ws.CLOSED) {
9273
+ callback(err);
9274
+ process.nextTick(emitClose, duplex);
9275
+ return;
9276
+ }
9277
+ let called = false;
9278
+ ws.once("error", function error(err) {
9279
+ called = true;
9280
+ callback(err);
9281
+ });
9282
+ ws.once("close", function close() {
9283
+ if (!called) callback(err);
9284
+ process.nextTick(emitClose, duplex);
9285
+ });
9286
+ if (terminateOnDestroy) ws.terminate();
9287
+ };
9288
+ duplex._final = function(callback) {
9289
+ if (ws.readyState === ws.CONNECTING) {
9290
+ ws.once("open", function open() {
9291
+ duplex._final(callback);
9292
+ });
9293
+ return;
9294
+ }
9295
+ if (ws._socket === null) return;
9296
+ if (ws._socket._writableState.finished) {
9297
+ callback();
9298
+ if (duplex._readableState.endEmitted) duplex.destroy();
9299
+ } else {
9300
+ ws._socket.once("finish", function finish() {
9301
+ callback();
9302
+ });
9303
+ ws.close();
9304
+ }
9305
+ };
9306
+ duplex._read = function() {
9307
+ if (ws.isPaused) ws.resume();
9308
+ };
9309
+ duplex._write = function(chunk, encoding, callback) {
9310
+ if (ws.readyState === ws.CONNECTING) {
9311
+ ws.once("open", function open() {
9312
+ duplex._write(chunk, encoding, callback);
9313
+ });
9314
+ return;
9315
+ }
9316
+ ws.send(chunk, callback);
9317
+ };
9318
+ duplex.on("end", duplexOnEnd);
9319
+ duplex.on("error", duplexOnError);
9320
+ return duplex;
9321
+ }
9322
+ module.exports = createWebSocketStream;
9323
+ }));
9324
+
9325
+ //#endregion
9326
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/subprotocol.js
9327
+ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9328
+ const { tokenChars } = require_validation();
9329
+ /**
9330
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
9331
+ *
9332
+ * @param {String} header The field value of the header
9333
+ * @return {Set} The subprotocol names
9334
+ * @public
9335
+ */
9336
+ function parse(header) {
9337
+ const protocols = /* @__PURE__ */ new Set();
9338
+ let start = -1;
9339
+ let end = -1;
9340
+ let i = 0;
9341
+ for (; i < header.length; i++) {
9342
+ const code = header.charCodeAt(i);
9343
+ if (end === -1 && tokenChars[code] === 1) {
9344
+ if (start === -1) start = i;
9345
+ } else if (i !== 0 && (code === 32 || code === 9)) {
9346
+ if (end === -1 && start !== -1) end = i;
9347
+ } else if (code === 44) {
9348
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
9349
+ if (end === -1) end = i;
9350
+ const protocol = header.slice(start, end);
9351
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
9352
+ protocols.add(protocol);
9353
+ start = end = -1;
9354
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
9355
+ }
9356
+ if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
9357
+ const protocol = header.slice(start, i);
9358
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
9359
+ protocols.add(protocol);
9360
+ return protocols;
9361
+ }
9362
+ module.exports = { parse };
9363
+ }));
9364
+
9365
+ //#endregion
9366
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js
9367
+ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9368
+ const EventEmitter$1 = require("events");
9369
+ const http = require("http");
9370
+ const { Duplex } = require("stream");
9371
+ const { createHash } = require("crypto");
9372
+ const extension = require_extension();
9373
+ const PerMessageDeflate = require_permessage_deflate();
9374
+ const subprotocol = require_subprotocol();
9375
+ const WebSocket = require_websocket();
9376
+ const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
9377
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
9378
+ const RUNNING = 0;
9379
+ const CLOSING = 1;
9380
+ const CLOSED = 2;
9381
+ /**
9382
+ * Class representing a WebSocket server.
9383
+ *
9384
+ * @extends EventEmitter
9385
+ */
9386
+ var WebSocketServer = class extends EventEmitter$1 {
9387
+ /**
9388
+ * Create a `WebSocketServer` instance.
9389
+ *
9390
+ * @param {Object} options Configuration options
9391
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
9392
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
9393
+ * multiple times in the same tick
9394
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
9395
+ * automatically send a pong in response to a ping
9396
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
9397
+ * pending connections
9398
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
9399
+ * track clients
9400
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
9401
+ * wait for the closing handshake to finish after `websocket.close()` is
9402
+ * called
9403
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
9404
+ * @param {String} [options.host] The hostname where to bind the server
9405
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
9406
+ * size
9407
+ * @param {Boolean} [options.noServer=false] Enable no server mode
9408
+ * @param {String} [options.path] Accept only connections matching this path
9409
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
9410
+ * permessage-deflate
9411
+ * @param {Number} [options.port] The port where to bind the server
9412
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
9413
+ * server to use
9414
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
9415
+ * not to skip UTF-8 validation for text and close messages
9416
+ * @param {Function} [options.verifyClient] A hook to reject connections
9417
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
9418
+ * class to use. It must be the `WebSocket` class or class that extends it
9419
+ * @param {Function} [callback] A listener for the `listening` event
9420
+ */
9421
+ constructor(options, callback) {
9422
+ super();
9423
+ options = {
9424
+ allowSynchronousEvents: true,
9425
+ autoPong: true,
9426
+ maxPayload: 100 * 1024 * 1024,
9427
+ skipUTF8Validation: false,
9428
+ perMessageDeflate: false,
9429
+ handleProtocols: null,
9430
+ clientTracking: true,
9431
+ closeTimeout: CLOSE_TIMEOUT,
9432
+ verifyClient: null,
9433
+ noServer: false,
9434
+ backlog: null,
9435
+ server: null,
9436
+ host: null,
9437
+ path: null,
9438
+ port: null,
9439
+ WebSocket,
9440
+ ...options
9441
+ };
9442
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
9443
+ if (options.port != null) {
9444
+ this._server = http.createServer((req, res) => {
9445
+ const body = http.STATUS_CODES[426];
9446
+ res.writeHead(426, {
9447
+ "Content-Length": body.length,
9448
+ "Content-Type": "text/plain"
9449
+ });
9450
+ res.end(body);
9451
+ });
9452
+ this._server.listen(options.port, options.host, options.backlog, callback);
9453
+ } else if (options.server) this._server = options.server;
9454
+ if (this._server) {
9455
+ const emitConnection = this.emit.bind(this, "connection");
9456
+ this._removeListeners = addListeners(this._server, {
9457
+ listening: this.emit.bind(this, "listening"),
9458
+ error: this.emit.bind(this, "error"),
9459
+ upgrade: (req, socket, head) => {
9460
+ this.handleUpgrade(req, socket, head, emitConnection);
9461
+ }
9462
+ });
9463
+ }
9464
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
9465
+ if (options.clientTracking) {
9466
+ this.clients = /* @__PURE__ */ new Set();
9467
+ this._shouldEmitClose = false;
9468
+ }
9469
+ this.options = options;
9470
+ this._state = RUNNING;
9471
+ }
9472
+ /**
9473
+ * Returns the bound address, the address family name, and port of the server
9474
+ * as reported by the operating system if listening on an IP socket.
9475
+ * If the server is listening on a pipe or UNIX domain socket, the name is
9476
+ * returned as a string.
9477
+ *
9478
+ * @return {(Object|String|null)} The address of the server
9479
+ * @public
9480
+ */
9481
+ address() {
9482
+ if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
9483
+ if (!this._server) return null;
9484
+ return this._server.address();
9485
+ }
9486
+ /**
9487
+ * Stop the server from accepting new connections and emit the `'close'` event
9488
+ * when all existing connections are closed.
9489
+ *
9490
+ * @param {Function} [cb] A one-time listener for the `'close'` event
9491
+ * @public
9492
+ */
9493
+ close(cb) {
9494
+ if (this._state === CLOSED) {
9495
+ if (cb) this.once("close", () => {
9496
+ cb(/* @__PURE__ */ new Error("The server is not running"));
9497
+ });
9498
+ process.nextTick(emitClose, this);
9499
+ return;
9500
+ }
9501
+ if (cb) this.once("close", cb);
9502
+ if (this._state === CLOSING) return;
9503
+ this._state = CLOSING;
9504
+ if (this.options.noServer || this.options.server) {
9505
+ if (this._server) {
9506
+ this._removeListeners();
9507
+ this._removeListeners = this._server = null;
9508
+ }
9509
+ if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
9510
+ else this._shouldEmitClose = true;
9511
+ else process.nextTick(emitClose, this);
9512
+ } else {
9513
+ const server = this._server;
9514
+ this._removeListeners();
9515
+ this._removeListeners = this._server = null;
9516
+ server.close(() => {
9517
+ emitClose(this);
9518
+ });
9519
+ }
9520
+ }
9521
+ /**
9522
+ * See if a given request should be handled by this server instance.
9523
+ *
9524
+ * @param {http.IncomingMessage} req Request object to inspect
9525
+ * @return {Boolean} `true` if the request is valid, else `false`
9526
+ * @public
9527
+ */
9528
+ shouldHandle(req) {
9529
+ if (this.options.path) {
9530
+ const index = req.url.indexOf("?");
9531
+ if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
9532
+ }
9533
+ return true;
9534
+ }
9535
+ /**
9536
+ * Handle a HTTP Upgrade request.
9537
+ *
9538
+ * @param {http.IncomingMessage} req The request object
9539
+ * @param {Duplex} socket The network socket between the server and client
9540
+ * @param {Buffer} head The first packet of the upgraded stream
9541
+ * @param {Function} cb Callback
9542
+ * @public
9543
+ */
9544
+ handleUpgrade(req, socket, head, cb) {
9545
+ socket.on("error", socketOnError);
9546
+ const key = req.headers["sec-websocket-key"];
9547
+ const upgrade = req.headers.upgrade;
9548
+ const version = +req.headers["sec-websocket-version"];
9549
+ if (req.method !== "GET") {
9550
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
9551
+ return;
9552
+ }
9553
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
9554
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
9555
+ return;
9556
+ }
9557
+ if (key === void 0 || !keyRegex.test(key)) {
9558
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
9559
+ return;
9560
+ }
9561
+ if (version !== 13 && version !== 8) {
9562
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
9563
+ return;
9564
+ }
9565
+ if (!this.shouldHandle(req)) {
9566
+ abortHandshake(socket, 400);
9567
+ return;
9568
+ }
9569
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
9570
+ let protocols = /* @__PURE__ */ new Set();
9571
+ if (secWebSocketProtocol !== void 0) try {
9572
+ protocols = subprotocol.parse(secWebSocketProtocol);
9573
+ } catch (err) {
9574
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
9575
+ return;
9576
+ }
9577
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
9578
+ const extensions = {};
9579
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
9580
+ const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
9581
+ try {
9582
+ const offers = extension.parse(secWebSocketExtensions);
9583
+ if (offers[PerMessageDeflate.extensionName]) {
9584
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
9585
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
9586
+ }
9587
+ } catch (err) {
9588
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
9589
+ return;
9590
+ }
9591
+ }
9592
+ if (this.options.verifyClient) {
9593
+ const info = {
9594
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
9595
+ secure: !!(req.socket.authorized || req.socket.encrypted),
9596
+ req
9597
+ };
9598
+ if (this.options.verifyClient.length === 2) {
9599
+ this.options.verifyClient(info, (verified, code, message, headers) => {
9600
+ if (!verified) return abortHandshake(socket, code || 401, message, headers);
9601
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9602
+ });
9603
+ return;
9604
+ }
9605
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
9606
+ }
9607
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9608
+ }
9609
+ /**
9610
+ * Upgrade the connection to WebSocket.
9611
+ *
9612
+ * @param {Object} extensions The accepted extensions
9613
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
9614
+ * @param {Set} protocols The subprotocols
9615
+ * @param {http.IncomingMessage} req The request object
9616
+ * @param {Duplex} socket The network socket between the server and client
9617
+ * @param {Buffer} head The first packet of the upgraded stream
9618
+ * @param {Function} cb Callback
9619
+ * @throws {Error} If called more than once with the same socket
9620
+ * @private
9621
+ */
9622
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
9623
+ if (!socket.readable || !socket.writable) return socket.destroy();
9624
+ if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
9625
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
9626
+ const headers = [
9627
+ "HTTP/1.1 101 Switching Protocols",
9628
+ "Upgrade: websocket",
9629
+ "Connection: Upgrade",
9630
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
9631
+ ];
9632
+ const ws = new this.options.WebSocket(null, void 0, this.options);
9633
+ if (protocols.size) {
9634
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
9635
+ if (protocol) {
9636
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
9637
+ ws._protocol = protocol;
9638
+ }
9639
+ }
9640
+ if (extensions[PerMessageDeflate.extensionName]) {
9641
+ const params = extensions[PerMessageDeflate.extensionName].params;
9642
+ const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
9643
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
9644
+ ws._extensions = extensions;
9645
+ }
9646
+ this.emit("headers", headers, req);
9647
+ socket.write(headers.concat("\r\n").join("\r\n"));
9648
+ socket.removeListener("error", socketOnError);
9649
+ ws.setSocket(socket, head, {
9650
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
9651
+ maxPayload: this.options.maxPayload,
9652
+ skipUTF8Validation: this.options.skipUTF8Validation
9653
+ });
9654
+ if (this.clients) {
9655
+ this.clients.add(ws);
9656
+ ws.on("close", () => {
9657
+ this.clients.delete(ws);
9658
+ if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
9659
+ });
9660
+ }
9661
+ cb(ws, req);
9662
+ }
9663
+ };
9664
+ module.exports = WebSocketServer;
9665
+ /**
9666
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
9667
+ * pairs.
9668
+ *
9669
+ * @param {EventEmitter} server The event emitter
9670
+ * @param {Object.<String, Function>} map The listeners to add
9671
+ * @return {Function} A function that will remove the added listeners when
9672
+ * called
9673
+ * @private
9674
+ */
9675
+ function addListeners(server, map) {
9676
+ for (const event of Object.keys(map)) server.on(event, map[event]);
9677
+ return function removeListeners() {
9678
+ for (const event of Object.keys(map)) server.removeListener(event, map[event]);
9679
+ };
9680
+ }
9681
+ /**
9682
+ * Emit a `'close'` event on an `EventEmitter`.
9683
+ *
9684
+ * @param {EventEmitter} server The event emitter
9685
+ * @private
9686
+ */
9687
+ function emitClose(server) {
9688
+ server._state = CLOSED;
9689
+ server.emit("close");
9690
+ }
9691
+ /**
9692
+ * Handle socket errors.
9693
+ *
9694
+ * @private
9695
+ */
9696
+ function socketOnError() {
9697
+ this.destroy();
9698
+ }
9699
+ /**
9700
+ * Close the connection when preconditions are not fulfilled.
9701
+ *
9702
+ * @param {Duplex} socket The socket of the upgrade request
9703
+ * @param {Number} code The HTTP response status code
9704
+ * @param {String} [message] The HTTP response body
9705
+ * @param {Object} [headers] Additional HTTP response headers
9706
+ * @private
9707
+ */
9708
+ function abortHandshake(socket, code, message, headers) {
9709
+ message = message || http.STATUS_CODES[code];
9710
+ headers = {
9711
+ Connection: "close",
9712
+ "Content-Type": "text/html",
9713
+ "Content-Length": Buffer.byteLength(message),
9714
+ ...headers
9715
+ };
9716
+ socket.once("finish", socket.destroy);
9717
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
9718
+ }
9719
+ /**
9720
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
9721
+ * one listener for it, otherwise call `abortHandshake()`.
9722
+ *
9723
+ * @param {WebSocketServer} server The WebSocket server
9724
+ * @param {http.IncomingMessage} req The request object
9725
+ * @param {Duplex} socket The socket of the upgrade request
9726
+ * @param {Number} code The HTTP response status code
9727
+ * @param {String} message The HTTP response body
9728
+ * @param {Object} [headers] The HTTP response headers
9729
+ * @private
9730
+ */
9731
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
9732
+ if (server.listenerCount("wsClientError")) {
9733
+ const err = new Error(message);
9734
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
9735
+ server.emit("wsClientError", err, socket, req);
9736
+ } else abortHandshake(socket, code, message, headers);
9737
+ }
9738
+ }));
9739
+
9740
+ //#endregion
9741
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
9742
+ var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
9743
+ var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
9744
+ var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
9745
+ var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
9746
+ var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
9747
+
9748
+ //#endregion
9749
+ //#region src/proxy/websocket-proxy.ts
9750
+ /**
9751
+ * WebSocket-to-TCP Proxy for Cap'n Proto
9752
+ *
9753
+ * Allows browsers to connect to native Cap'n Proto services (C++, etc.)
9754
+ * via WebSocket. Handles the protocol bridging between WebSocket (browser)
9755
+ * and raw TCP (Cap'n Proto services).
9756
+ */
9757
+ var ProxyConnection = class extends node_events.EventEmitter {
9758
+ ws;
9759
+ tcpSocket = null;
9760
+ stats;
9761
+ options;
9762
+ closed = false;
9763
+ constructor(ws, options) {
9764
+ super();
9765
+ this.ws = ws;
9766
+ this.options = options;
9767
+ this.stats = {
9768
+ wsMessagesIn: 0,
9769
+ wsMessagesOut: 0,
9770
+ tcpBytesIn: 0,
9771
+ tcpBytesOut: 0,
9772
+ connectedAt: /* @__PURE__ */ new Date()
9773
+ };
9774
+ this.setupWebSocket();
9775
+ }
9776
+ setupWebSocket() {
9777
+ this.ws.on("message", (data) => {
9778
+ this.handleWebSocketMessage(data);
9779
+ });
9780
+ this.ws.on("close", () => {
9781
+ this.log("WebSocket closed");
9782
+ this.close();
9783
+ });
9784
+ this.ws.on("error", (err) => {
9785
+ this.log("WebSocket error:", err);
9786
+ this.emit("error", err);
9787
+ this.close();
9788
+ });
9789
+ this.connectToTarget();
9790
+ }
9791
+ connectToTarget() {
9792
+ const timeout = this.options.connectionTimeout ?? 3e4;
9793
+ this.tcpSocket = (0, node_net.createConnection)({
9794
+ host: this.options.targetHost,
9795
+ port: this.options.targetPort,
9796
+ timeout
9797
+ });
9798
+ this.tcpSocket.on("connect", () => {
9799
+ this.log("Connected to target TCP service");
9800
+ this.emit("connected");
9801
+ });
9802
+ this.tcpSocket.on("data", (data) => {
9803
+ this.handleTcpData(data);
9804
+ });
9805
+ this.tcpSocket.on("close", () => {
9806
+ this.log("TCP connection closed");
9807
+ this.close();
9808
+ });
9809
+ this.tcpSocket.on("error", (err) => {
9810
+ this.log("TCP error:", err);
9811
+ this.emit("error", err);
9812
+ this.close();
9813
+ });
9814
+ this.tcpSocket.on("timeout", () => {
9815
+ this.log("TCP connection timeout");
9816
+ this.close();
9817
+ });
9818
+ }
9819
+ handleWebSocketMessage(data) {
9820
+ if (this.closed) return;
9821
+ const buffer = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
9822
+ const maxSize = this.options.maxMessageSize ?? 16 * 1024 * 1024;
9823
+ if (buffer.length > maxSize) {
9824
+ this.log(`Message too large: ${buffer.length} bytes`);
9825
+ this.close();
9826
+ return;
9827
+ }
9828
+ this.stats.wsMessagesIn++;
9829
+ this.stats.tcpBytesOut += buffer.length;
9830
+ if (this.tcpSocket?.writable) {
9831
+ this.tcpSocket.write(buffer);
9832
+ this.log(`Forwarded ${buffer.length} bytes to TCP`);
9833
+ }
9834
+ }
9835
+ handleTcpData(data) {
9836
+ if (this.closed) return;
9837
+ this.stats.tcpBytesIn += data.length;
9838
+ this.stats.wsMessagesOut++;
9839
+ if (this.ws.readyState === import_websocket.default.OPEN) {
9840
+ this.ws.send(data);
9841
+ this.log(`Forwarded ${data.length} bytes to WebSocket`);
9842
+ }
9843
+ }
9844
+ log(...args) {
9845
+ if (this.options.debug) console.log("[ProxyConnection]", ...args);
9846
+ }
9847
+ getStats() {
9848
+ return { ...this.stats };
9849
+ }
9850
+ close() {
9851
+ if (this.closed) return;
9852
+ this.closed = true;
9853
+ this.ws.close();
9854
+ this.tcpSocket?.destroy();
9855
+ this.emit("closed");
9856
+ }
9857
+ };
9858
+ var CapnpWebSocketProxy = class extends node_events.EventEmitter {
9859
+ wss;
9860
+ connections = /* @__PURE__ */ new Map();
9861
+ options;
9862
+ constructor(options) {
9863
+ super();
9864
+ this.options = options;
9865
+ this.wss = new import_websocket_server.default({ port: options.wsPort });
9866
+ this.setupServer();
9867
+ }
9868
+ setupServer() {
9869
+ this.wss.on("connection", (ws, req) => {
9870
+ const clientIp = req.socket.remoteAddress;
9871
+ this.log(`New WebSocket connection from ${clientIp}`);
9872
+ const connection = new ProxyConnection(ws, this.options);
9873
+ this.connections.set(ws, connection);
9874
+ connection.on("connected", () => {
9875
+ this.emit("connection", connection);
9876
+ });
9877
+ connection.on("error", (err) => {
9878
+ this.emit("error", err, connection);
9879
+ });
9880
+ connection.on("closed", () => {
9881
+ this.connections.delete(ws);
9882
+ this.emit("disconnection", connection);
9883
+ });
9884
+ });
9885
+ this.wss.on("error", (err) => {
9886
+ this.emit("error", err);
9887
+ });
9888
+ }
9889
+ log(...args) {
9890
+ if (this.options.debug) console.log("[CapnpWebSocketProxy]", ...args);
9891
+ }
9892
+ getConnectionCount() {
9893
+ return this.connections.size;
9894
+ }
9895
+ getAllStats() {
9896
+ return Array.from(this.connections.values()).map((c) => c.getStats());
9897
+ }
9898
+ close() {
9899
+ return new Promise((resolve) => {
9900
+ for (const connection of this.connections.values()) connection.close();
9901
+ this.connections.clear();
9902
+ this.wss.close(() => {
9903
+ this.emit("closed");
9904
+ resolve();
9905
+ });
9906
+ });
9907
+ }
9908
+ };
9909
+ if (require("url").pathToFileURL(__filename).href === `file://${process.argv[1]}`) {
9910
+ const args = process.argv.slice(2);
9911
+ let wsPort = 8080;
9912
+ let targetHost = "localhost";
9913
+ let targetPort = 8081;
9914
+ let debug = false;
9915
+ for (let i = 0; i < args.length; i++) switch (args[i]) {
9916
+ case "--ws-port":
9917
+ case "-p":
9918
+ wsPort = Number.parseInt(args[++i], 10);
9919
+ break;
9920
+ case "--target":
9921
+ case "-t": {
9922
+ const [host, port] = args[++i].split(":");
9923
+ targetHost = host;
9924
+ targetPort = Number.parseInt(port, 10);
9925
+ break;
9926
+ }
9927
+ case "--debug":
9928
+ case "-d":
9929
+ debug = true;
9930
+ break;
9931
+ case "--help":
9932
+ case "-h":
9933
+ console.log(`
9934
+ Cap'n Proto WebSocket-to-TCP Proxy
9935
+
9936
+ Usage: npx @naeemo/capnp proxy [options]
9937
+
9938
+ Options:
9939
+ -p, --ws-port <port> WebSocket server port (default: 8080)
9940
+ -t, --target <host:port> Target TCP service (default: localhost:8081)
9941
+ -d, --debug Enable debug logging
9942
+ -h, --help Show this help
9943
+
9944
+ Example:
9945
+ npx @naeemo/capnp proxy -p 9000 -t 192.168.1.100:7000
9946
+ `);
9947
+ process.exit(0);
9948
+ }
9949
+ const proxy = new CapnpWebSocketProxy({
9950
+ wsPort,
9951
+ targetHost,
9952
+ targetPort,
9953
+ debug
9954
+ });
9955
+ console.log("WebSocket-to-TCP Proxy started");
9956
+ console.log(` WebSocket: ws://localhost:${wsPort}`);
9957
+ console.log(` Target: ${targetHost}:${targetPort}`);
9958
+ proxy.on("connection", () => {
9959
+ console.log(`Active connections: ${proxy.getConnectionCount()}`);
9960
+ });
9961
+ proxy.on("disconnection", () => {
9962
+ console.log(`Active connections: ${proxy.getConnectionCount()}`);
9963
+ });
9964
+ process.on("SIGINT", async () => {
9965
+ console.log("\nShutting down...");
9966
+ await proxy.close();
9967
+ process.exit(0);
9968
+ });
9969
+ }
9970
+
6218
9971
  //#endregion
6219
9972
  exports.AnswerTable = require_rpc_connection.AnswerTable;
6220
9973
  exports.BaseCapabilityClient = BaseCapabilityClient;
6221
9974
  exports.BulkTransfer = BulkTransfer;
6222
9975
  exports.BulkTransferManager = BulkTransferManager;
9976
+ exports.CapnpWebSocketProxy = CapnpWebSocketProxy;
6223
9977
  exports.ConnectionManager = ConnectionManager;
6224
9978
  exports.DEFAULT_BULK_CONFIG = DEFAULT_BULK_CONFIG;
6225
9979
  exports.DEFAULT_ESCROW_CONFIG = DEFAULT_ESCROW_CONFIG;