hocai-connect 0.13.0 → 0.14.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.
Files changed (2) hide show
  1. package/dist/cli.js +3938 -48
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -12986,11 +12986,3681 @@ var require_content_type = __commonJS({
12986
12986
  }
12987
12987
  });
12988
12988
 
12989
+ // node_modules/ws/lib/constants.js
12990
+ var require_constants = __commonJS({
12991
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
12992
+ "use strict";
12993
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
12994
+ var hasBlob = typeof Blob !== "undefined";
12995
+ if (hasBlob) BINARY_TYPES.push("blob");
12996
+ module2.exports = {
12997
+ BINARY_TYPES,
12998
+ CLOSE_TIMEOUT: 3e4,
12999
+ EMPTY_BUFFER: Buffer.alloc(0),
13000
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
13001
+ hasBlob,
13002
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
13003
+ kListener: /* @__PURE__ */ Symbol("kListener"),
13004
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
13005
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
13006
+ NOOP: () => {
13007
+ }
13008
+ };
13009
+ }
13010
+ });
13011
+
13012
+ // node_modules/ws/lib/buffer-util.js
13013
+ var require_buffer_util = __commonJS({
13014
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
13015
+ "use strict";
13016
+ var { EMPTY_BUFFER } = require_constants();
13017
+ var FastBuffer = Buffer[Symbol.species];
13018
+ function concat(list, totalLength) {
13019
+ if (list.length === 0) return EMPTY_BUFFER;
13020
+ if (list.length === 1) return list[0];
13021
+ const target = Buffer.allocUnsafe(totalLength);
13022
+ let offset = 0;
13023
+ for (let i = 0; i < list.length; i++) {
13024
+ const buf = list[i];
13025
+ target.set(buf, offset);
13026
+ offset += buf.length;
13027
+ }
13028
+ if (offset < totalLength) {
13029
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
13030
+ }
13031
+ return target;
13032
+ }
13033
+ function _mask(source, mask, output, offset, length) {
13034
+ for (let i = 0; i < length; i++) {
13035
+ output[offset + i] = source[i] ^ mask[i & 3];
13036
+ }
13037
+ }
13038
+ function _unmask(buffer, mask) {
13039
+ for (let i = 0; i < buffer.length; i++) {
13040
+ buffer[i] ^= mask[i & 3];
13041
+ }
13042
+ }
13043
+ function toArrayBuffer2(buf) {
13044
+ if (buf.length === buf.buffer.byteLength) {
13045
+ return buf.buffer;
13046
+ }
13047
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
13048
+ }
13049
+ function toBuffer(data) {
13050
+ toBuffer.readOnly = true;
13051
+ if (Buffer.isBuffer(data)) return data;
13052
+ let buf;
13053
+ if (data instanceof ArrayBuffer) {
13054
+ buf = new FastBuffer(data);
13055
+ } else if (ArrayBuffer.isView(data)) {
13056
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
13057
+ } else {
13058
+ buf = Buffer.from(data);
13059
+ toBuffer.readOnly = false;
13060
+ }
13061
+ return buf;
13062
+ }
13063
+ module2.exports = {
13064
+ concat,
13065
+ mask: _mask,
13066
+ toArrayBuffer: toArrayBuffer2,
13067
+ toBuffer,
13068
+ unmask: _unmask
13069
+ };
13070
+ if (!process.env.WS_NO_BUFFER_UTIL) {
13071
+ try {
13072
+ const bufferUtil = require("bufferutil");
13073
+ module2.exports.mask = function(source, mask, output, offset, length) {
13074
+ if (length < 48) _mask(source, mask, output, offset, length);
13075
+ else bufferUtil.mask(source, mask, output, offset, length);
13076
+ };
13077
+ module2.exports.unmask = function(buffer, mask) {
13078
+ if (buffer.length < 32) _unmask(buffer, mask);
13079
+ else bufferUtil.unmask(buffer, mask);
13080
+ };
13081
+ } catch (e) {
13082
+ }
13083
+ }
13084
+ }
13085
+ });
13086
+
13087
+ // node_modules/ws/lib/limiter.js
13088
+ var require_limiter = __commonJS({
13089
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
13090
+ "use strict";
13091
+ var kDone = /* @__PURE__ */ Symbol("kDone");
13092
+ var kRun = /* @__PURE__ */ Symbol("kRun");
13093
+ var Limiter = class {
13094
+ /**
13095
+ * Creates a new `Limiter`.
13096
+ *
13097
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
13098
+ * to run concurrently
13099
+ */
13100
+ constructor(concurrency) {
13101
+ this[kDone] = () => {
13102
+ this.pending--;
13103
+ this[kRun]();
13104
+ };
13105
+ this.concurrency = concurrency || Infinity;
13106
+ this.jobs = [];
13107
+ this.pending = 0;
13108
+ }
13109
+ /**
13110
+ * Adds a job to the queue.
13111
+ *
13112
+ * @param {Function} job The job to run
13113
+ * @public
13114
+ */
13115
+ add(job) {
13116
+ this.jobs.push(job);
13117
+ this[kRun]();
13118
+ }
13119
+ /**
13120
+ * Removes a job from the queue and runs it if possible.
13121
+ *
13122
+ * @private
13123
+ */
13124
+ [kRun]() {
13125
+ if (this.pending === this.concurrency) return;
13126
+ if (this.jobs.length) {
13127
+ const job = this.jobs.shift();
13128
+ this.pending++;
13129
+ job(this[kDone]);
13130
+ }
13131
+ }
13132
+ };
13133
+ module2.exports = Limiter;
13134
+ }
13135
+ });
13136
+
13137
+ // node_modules/ws/lib/permessage-deflate.js
13138
+ var require_permessage_deflate = __commonJS({
13139
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
13140
+ "use strict";
13141
+ var zlib = require("zlib");
13142
+ var bufferUtil = require_buffer_util();
13143
+ var Limiter = require_limiter();
13144
+ var { kStatusCode } = require_constants();
13145
+ var FastBuffer = Buffer[Symbol.species];
13146
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
13147
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
13148
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
13149
+ var kCallback = /* @__PURE__ */ Symbol("callback");
13150
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
13151
+ var kError = /* @__PURE__ */ Symbol("error");
13152
+ var zlibLimiter;
13153
+ var PerMessageDeflate2 = class {
13154
+ /**
13155
+ * Creates a PerMessageDeflate instance.
13156
+ *
13157
+ * @param {Object} [options] Configuration options
13158
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
13159
+ * for, or request, a custom client window size
13160
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
13161
+ * acknowledge disabling of client context takeover
13162
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
13163
+ * calls to zlib
13164
+ * @param {Boolean} [options.isServer=false] Create the instance in either
13165
+ * server or client mode
13166
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
13167
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
13168
+ * use of a custom server window size
13169
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
13170
+ * disabling of server context takeover
13171
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
13172
+ * messages should not be compressed if context takeover is disabled
13173
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
13174
+ * deflate
13175
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
13176
+ * inflate
13177
+ */
13178
+ constructor(options) {
13179
+ this._options = options || {};
13180
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
13181
+ this._maxPayload = this._options.maxPayload | 0;
13182
+ this._isServer = !!this._options.isServer;
13183
+ this._deflate = null;
13184
+ this._inflate = null;
13185
+ this.params = null;
13186
+ if (!zlibLimiter) {
13187
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
13188
+ zlibLimiter = new Limiter(concurrency);
13189
+ }
13190
+ }
13191
+ /**
13192
+ * @type {String}
13193
+ */
13194
+ static get extensionName() {
13195
+ return "permessage-deflate";
13196
+ }
13197
+ /**
13198
+ * Create an extension negotiation offer.
13199
+ *
13200
+ * @return {Object} Extension parameters
13201
+ * @public
13202
+ */
13203
+ offer() {
13204
+ const params = {};
13205
+ if (this._options.serverNoContextTakeover) {
13206
+ params.server_no_context_takeover = true;
13207
+ }
13208
+ if (this._options.clientNoContextTakeover) {
13209
+ params.client_no_context_takeover = true;
13210
+ }
13211
+ if (this._options.serverMaxWindowBits) {
13212
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
13213
+ }
13214
+ if (this._options.clientMaxWindowBits) {
13215
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
13216
+ } else if (this._options.clientMaxWindowBits == null) {
13217
+ params.client_max_window_bits = true;
13218
+ }
13219
+ return params;
13220
+ }
13221
+ /**
13222
+ * Accept an extension negotiation offer/response.
13223
+ *
13224
+ * @param {Array} configurations The extension negotiation offers/reponse
13225
+ * @return {Object} Accepted configuration
13226
+ * @public
13227
+ */
13228
+ accept(configurations) {
13229
+ configurations = this.normalizeParams(configurations);
13230
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
13231
+ return this.params;
13232
+ }
13233
+ /**
13234
+ * Releases all resources used by the extension.
13235
+ *
13236
+ * @public
13237
+ */
13238
+ cleanup() {
13239
+ if (this._inflate) {
13240
+ this._inflate.close();
13241
+ this._inflate = null;
13242
+ }
13243
+ if (this._deflate) {
13244
+ const callback = this._deflate[kCallback];
13245
+ this._deflate.close();
13246
+ this._deflate = null;
13247
+ if (callback) {
13248
+ callback(
13249
+ new Error(
13250
+ "The deflate stream was closed while data was being processed"
13251
+ )
13252
+ );
13253
+ }
13254
+ }
13255
+ }
13256
+ /**
13257
+ * Accept an extension negotiation offer.
13258
+ *
13259
+ * @param {Array} offers The extension negotiation offers
13260
+ * @return {Object} Accepted configuration
13261
+ * @private
13262
+ */
13263
+ acceptAsServer(offers) {
13264
+ const opts = this._options;
13265
+ const accepted = offers.find((params) => {
13266
+ 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" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
13267
+ return false;
13268
+ }
13269
+ return true;
13270
+ });
13271
+ if (!accepted) {
13272
+ throw new Error("None of the extension offers can be accepted");
13273
+ }
13274
+ if (opts.serverNoContextTakeover) {
13275
+ accepted.server_no_context_takeover = true;
13276
+ }
13277
+ if (opts.clientNoContextTakeover) {
13278
+ accepted.client_no_context_takeover = true;
13279
+ }
13280
+ if (typeof opts.serverMaxWindowBits === "number") {
13281
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
13282
+ }
13283
+ if (typeof opts.clientMaxWindowBits === "number") {
13284
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
13285
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
13286
+ delete accepted.client_max_window_bits;
13287
+ }
13288
+ return accepted;
13289
+ }
13290
+ /**
13291
+ * Accept the extension negotiation response.
13292
+ *
13293
+ * @param {Array} response The extension negotiation response
13294
+ * @return {Object} Accepted configuration
13295
+ * @private
13296
+ */
13297
+ acceptAsClient(response) {
13298
+ const params = response[0];
13299
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
13300
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
13301
+ }
13302
+ if (!params.client_max_window_bits) {
13303
+ if (typeof this._options.clientMaxWindowBits === "number") {
13304
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
13305
+ }
13306
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
13307
+ throw new Error(
13308
+ 'Unexpected or invalid parameter "client_max_window_bits"'
13309
+ );
13310
+ }
13311
+ return params;
13312
+ }
13313
+ /**
13314
+ * Normalize parameters.
13315
+ *
13316
+ * @param {Array} configurations The extension negotiation offers/reponse
13317
+ * @return {Array} The offers/response with normalized parameters
13318
+ * @private
13319
+ */
13320
+ normalizeParams(configurations) {
13321
+ configurations.forEach((params) => {
13322
+ Object.keys(params).forEach((key) => {
13323
+ let value = params[key];
13324
+ if (value.length > 1) {
13325
+ throw new Error(`Parameter "${key}" must have only a single value`);
13326
+ }
13327
+ value = value[0];
13328
+ if (key === "client_max_window_bits") {
13329
+ if (value !== true) {
13330
+ const num = +value;
13331
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
13332
+ throw new TypeError(
13333
+ `Invalid value for parameter "${key}": ${value}`
13334
+ );
13335
+ }
13336
+ value = num;
13337
+ } else if (!this._isServer) {
13338
+ throw new TypeError(
13339
+ `Invalid value for parameter "${key}": ${value}`
13340
+ );
13341
+ }
13342
+ } else if (key === "server_max_window_bits") {
13343
+ const num = +value;
13344
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
13345
+ throw new TypeError(
13346
+ `Invalid value for parameter "${key}": ${value}`
13347
+ );
13348
+ }
13349
+ value = num;
13350
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
13351
+ if (value !== true) {
13352
+ throw new TypeError(
13353
+ `Invalid value for parameter "${key}": ${value}`
13354
+ );
13355
+ }
13356
+ } else {
13357
+ throw new Error(`Unknown parameter "${key}"`);
13358
+ }
13359
+ params[key] = value;
13360
+ });
13361
+ });
13362
+ return configurations;
13363
+ }
13364
+ /**
13365
+ * Decompress data. Concurrency limited.
13366
+ *
13367
+ * @param {Buffer} data Compressed data
13368
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
13369
+ * @param {Function} callback Callback
13370
+ * @public
13371
+ */
13372
+ decompress(data, fin, callback) {
13373
+ zlibLimiter.add((done) => {
13374
+ this._decompress(data, fin, (err, result) => {
13375
+ done();
13376
+ callback(err, result);
13377
+ });
13378
+ });
13379
+ }
13380
+ /**
13381
+ * Compress data. Concurrency limited.
13382
+ *
13383
+ * @param {(Buffer|String)} data Data to compress
13384
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
13385
+ * @param {Function} callback Callback
13386
+ * @public
13387
+ */
13388
+ compress(data, fin, callback) {
13389
+ zlibLimiter.add((done) => {
13390
+ this._compress(data, fin, (err, result) => {
13391
+ done();
13392
+ callback(err, result);
13393
+ });
13394
+ });
13395
+ }
13396
+ /**
13397
+ * Decompress data.
13398
+ *
13399
+ * @param {Buffer} data Compressed data
13400
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
13401
+ * @param {Function} callback Callback
13402
+ * @private
13403
+ */
13404
+ _decompress(data, fin, callback) {
13405
+ const endpoint = this._isServer ? "client" : "server";
13406
+ if (!this._inflate) {
13407
+ const key = `${endpoint}_max_window_bits`;
13408
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
13409
+ this._inflate = zlib.createInflateRaw({
13410
+ ...this._options.zlibInflateOptions,
13411
+ windowBits
13412
+ });
13413
+ this._inflate[kPerMessageDeflate] = this;
13414
+ this._inflate[kTotalLength] = 0;
13415
+ this._inflate[kBuffers] = [];
13416
+ this._inflate.on("error", inflateOnError);
13417
+ this._inflate.on("data", inflateOnData);
13418
+ }
13419
+ this._inflate[kCallback] = callback;
13420
+ this._inflate.write(data);
13421
+ if (fin) this._inflate.write(TRAILER);
13422
+ this._inflate.flush(() => {
13423
+ const err = this._inflate[kError];
13424
+ if (err) {
13425
+ this._inflate.close();
13426
+ this._inflate = null;
13427
+ callback(err);
13428
+ return;
13429
+ }
13430
+ const data2 = bufferUtil.concat(
13431
+ this._inflate[kBuffers],
13432
+ this._inflate[kTotalLength]
13433
+ );
13434
+ if (this._inflate._readableState.endEmitted) {
13435
+ this._inflate.close();
13436
+ this._inflate = null;
13437
+ } else {
13438
+ this._inflate[kTotalLength] = 0;
13439
+ this._inflate[kBuffers] = [];
13440
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
13441
+ this._inflate.reset();
13442
+ }
13443
+ }
13444
+ callback(null, data2);
13445
+ });
13446
+ }
13447
+ /**
13448
+ * Compress data.
13449
+ *
13450
+ * @param {(Buffer|String)} data Data to compress
13451
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
13452
+ * @param {Function} callback Callback
13453
+ * @private
13454
+ */
13455
+ _compress(data, fin, callback) {
13456
+ const endpoint = this._isServer ? "server" : "client";
13457
+ if (!this._deflate) {
13458
+ const key = `${endpoint}_max_window_bits`;
13459
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
13460
+ this._deflate = zlib.createDeflateRaw({
13461
+ ...this._options.zlibDeflateOptions,
13462
+ windowBits
13463
+ });
13464
+ this._deflate[kTotalLength] = 0;
13465
+ this._deflate[kBuffers] = [];
13466
+ this._deflate.on("data", deflateOnData);
13467
+ }
13468
+ this._deflate[kCallback] = callback;
13469
+ this._deflate.write(data);
13470
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
13471
+ if (!this._deflate) {
13472
+ return;
13473
+ }
13474
+ let data2 = bufferUtil.concat(
13475
+ this._deflate[kBuffers],
13476
+ this._deflate[kTotalLength]
13477
+ );
13478
+ if (fin) {
13479
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
13480
+ }
13481
+ this._deflate[kCallback] = null;
13482
+ this._deflate[kTotalLength] = 0;
13483
+ this._deflate[kBuffers] = [];
13484
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
13485
+ this._deflate.reset();
13486
+ }
13487
+ callback(null, data2);
13488
+ });
13489
+ }
13490
+ };
13491
+ module2.exports = PerMessageDeflate2;
13492
+ function deflateOnData(chunk) {
13493
+ this[kBuffers].push(chunk);
13494
+ this[kTotalLength] += chunk.length;
13495
+ }
13496
+ function inflateOnData(chunk) {
13497
+ this[kTotalLength] += chunk.length;
13498
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
13499
+ this[kBuffers].push(chunk);
13500
+ return;
13501
+ }
13502
+ this[kError] = new RangeError("Max payload size exceeded");
13503
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
13504
+ this[kError][kStatusCode] = 1009;
13505
+ this.removeListener("data", inflateOnData);
13506
+ this.reset();
13507
+ }
13508
+ function inflateOnError(err) {
13509
+ this[kPerMessageDeflate]._inflate = null;
13510
+ if (this[kError]) {
13511
+ this[kCallback](this[kError]);
13512
+ return;
13513
+ }
13514
+ err[kStatusCode] = 1007;
13515
+ this[kCallback](err);
13516
+ }
13517
+ }
13518
+ });
13519
+
13520
+ // node_modules/ws/lib/validation.js
13521
+ var require_validation3 = __commonJS({
13522
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
13523
+ "use strict";
13524
+ var { isUtf8 } = require("buffer");
13525
+ var { hasBlob } = require_constants();
13526
+ var tokenChars = [
13527
+ 0,
13528
+ 0,
13529
+ 0,
13530
+ 0,
13531
+ 0,
13532
+ 0,
13533
+ 0,
13534
+ 0,
13535
+ 0,
13536
+ 0,
13537
+ 0,
13538
+ 0,
13539
+ 0,
13540
+ 0,
13541
+ 0,
13542
+ 0,
13543
+ // 0 - 15
13544
+ 0,
13545
+ 0,
13546
+ 0,
13547
+ 0,
13548
+ 0,
13549
+ 0,
13550
+ 0,
13551
+ 0,
13552
+ 0,
13553
+ 0,
13554
+ 0,
13555
+ 0,
13556
+ 0,
13557
+ 0,
13558
+ 0,
13559
+ 0,
13560
+ // 16 - 31
13561
+ 0,
13562
+ 1,
13563
+ 0,
13564
+ 1,
13565
+ 1,
13566
+ 1,
13567
+ 1,
13568
+ 1,
13569
+ 0,
13570
+ 0,
13571
+ 1,
13572
+ 1,
13573
+ 0,
13574
+ 1,
13575
+ 1,
13576
+ 0,
13577
+ // 32 - 47
13578
+ 1,
13579
+ 1,
13580
+ 1,
13581
+ 1,
13582
+ 1,
13583
+ 1,
13584
+ 1,
13585
+ 1,
13586
+ 1,
13587
+ 1,
13588
+ 0,
13589
+ 0,
13590
+ 0,
13591
+ 0,
13592
+ 0,
13593
+ 0,
13594
+ // 48 - 63
13595
+ 0,
13596
+ 1,
13597
+ 1,
13598
+ 1,
13599
+ 1,
13600
+ 1,
13601
+ 1,
13602
+ 1,
13603
+ 1,
13604
+ 1,
13605
+ 1,
13606
+ 1,
13607
+ 1,
13608
+ 1,
13609
+ 1,
13610
+ 1,
13611
+ // 64 - 79
13612
+ 1,
13613
+ 1,
13614
+ 1,
13615
+ 1,
13616
+ 1,
13617
+ 1,
13618
+ 1,
13619
+ 1,
13620
+ 1,
13621
+ 1,
13622
+ 1,
13623
+ 0,
13624
+ 0,
13625
+ 0,
13626
+ 1,
13627
+ 1,
13628
+ // 80 - 95
13629
+ 1,
13630
+ 1,
13631
+ 1,
13632
+ 1,
13633
+ 1,
13634
+ 1,
13635
+ 1,
13636
+ 1,
13637
+ 1,
13638
+ 1,
13639
+ 1,
13640
+ 1,
13641
+ 1,
13642
+ 1,
13643
+ 1,
13644
+ 1,
13645
+ // 96 - 111
13646
+ 1,
13647
+ 1,
13648
+ 1,
13649
+ 1,
13650
+ 1,
13651
+ 1,
13652
+ 1,
13653
+ 1,
13654
+ 1,
13655
+ 1,
13656
+ 1,
13657
+ 0,
13658
+ 1,
13659
+ 0,
13660
+ 1,
13661
+ 0
13662
+ // 112 - 127
13663
+ ];
13664
+ function isValidStatusCode(code) {
13665
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
13666
+ }
13667
+ function _isValidUTF8(buf) {
13668
+ const len = buf.length;
13669
+ let i = 0;
13670
+ while (i < len) {
13671
+ if ((buf[i] & 128) === 0) {
13672
+ i++;
13673
+ } else if ((buf[i] & 224) === 192) {
13674
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
13675
+ return false;
13676
+ }
13677
+ i += 2;
13678
+ } else if ((buf[i] & 240) === 224) {
13679
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
13680
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
13681
+ return false;
13682
+ }
13683
+ i += 3;
13684
+ } else if ((buf[i] & 248) === 240) {
13685
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
13686
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
13687
+ return false;
13688
+ }
13689
+ i += 4;
13690
+ } else {
13691
+ return false;
13692
+ }
13693
+ }
13694
+ return true;
13695
+ }
13696
+ function isBlob(value) {
13697
+ 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");
13698
+ }
13699
+ module2.exports = {
13700
+ isBlob,
13701
+ isValidStatusCode,
13702
+ isValidUTF8: _isValidUTF8,
13703
+ tokenChars
13704
+ };
13705
+ if (isUtf8) {
13706
+ module2.exports.isValidUTF8 = function(buf) {
13707
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
13708
+ };
13709
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
13710
+ try {
13711
+ const isValidUTF8 = require("utf-8-validate");
13712
+ module2.exports.isValidUTF8 = function(buf) {
13713
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
13714
+ };
13715
+ } catch (e) {
13716
+ }
13717
+ }
13718
+ }
13719
+ });
13720
+
13721
+ // node_modules/ws/lib/receiver.js
13722
+ var require_receiver = __commonJS({
13723
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
13724
+ "use strict";
13725
+ var { Writable } = require("stream");
13726
+ var PerMessageDeflate2 = require_permessage_deflate();
13727
+ var {
13728
+ BINARY_TYPES,
13729
+ EMPTY_BUFFER,
13730
+ kStatusCode,
13731
+ kWebSocket
13732
+ } = require_constants();
13733
+ var { concat, toArrayBuffer: toArrayBuffer2, unmask } = require_buffer_util();
13734
+ var { isValidStatusCode, isValidUTF8 } = require_validation3();
13735
+ var FastBuffer = Buffer[Symbol.species];
13736
+ var GET_INFO = 0;
13737
+ var GET_PAYLOAD_LENGTH_16 = 1;
13738
+ var GET_PAYLOAD_LENGTH_64 = 2;
13739
+ var GET_MASK = 3;
13740
+ var GET_DATA = 4;
13741
+ var INFLATING = 5;
13742
+ var DEFER_EVENT = 6;
13743
+ var Receiver2 = class extends Writable {
13744
+ /**
13745
+ * Creates a Receiver instance.
13746
+ *
13747
+ * @param {Object} [options] Options object
13748
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
13749
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
13750
+ * multiple times in the same tick
13751
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
13752
+ * @param {Object} [options.extensions] An object containing the negotiated
13753
+ * extensions
13754
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
13755
+ * client or server mode
13756
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
13757
+ * buffered data chunks
13758
+ * @param {Number} [options.maxFragments=0] The maximum number of message
13759
+ * fragments
13760
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
13761
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
13762
+ * not to skip UTF-8 validation for text and close messages
13763
+ */
13764
+ constructor(options = {}) {
13765
+ super();
13766
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
13767
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
13768
+ this._extensions = options.extensions || {};
13769
+ this._isServer = !!options.isServer;
13770
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
13771
+ this._maxFragments = options.maxFragments | 0;
13772
+ this._maxPayload = options.maxPayload | 0;
13773
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
13774
+ this[kWebSocket] = void 0;
13775
+ this._bufferedBytes = 0;
13776
+ this._buffers = [];
13777
+ this._compressed = false;
13778
+ this._payloadLength = 0;
13779
+ this._mask = void 0;
13780
+ this._fragmented = 0;
13781
+ this._masked = false;
13782
+ this._fin = false;
13783
+ this._opcode = 0;
13784
+ this._totalPayloadLength = 0;
13785
+ this._messageLength = 0;
13786
+ this._numFragments = 0;
13787
+ this._fragments = [];
13788
+ this._errored = false;
13789
+ this._loop = false;
13790
+ this._state = GET_INFO;
13791
+ }
13792
+ /**
13793
+ * Implements `Writable.prototype._write()`.
13794
+ *
13795
+ * @param {Buffer} chunk The chunk of data to write
13796
+ * @param {String} encoding The character encoding of `chunk`
13797
+ * @param {Function} cb Callback
13798
+ * @private
13799
+ */
13800
+ _write(chunk, encoding, cb) {
13801
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
13802
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
13803
+ cb(
13804
+ this.createError(
13805
+ RangeError,
13806
+ "Too many buffered chunks",
13807
+ false,
13808
+ 1008,
13809
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
13810
+ )
13811
+ );
13812
+ return;
13813
+ }
13814
+ this._bufferedBytes += chunk.length;
13815
+ this._buffers.push(chunk);
13816
+ this.startLoop(cb);
13817
+ }
13818
+ /**
13819
+ * Consumes `n` bytes from the buffered data.
13820
+ *
13821
+ * @param {Number} n The number of bytes to consume
13822
+ * @return {Buffer} The consumed bytes
13823
+ * @private
13824
+ */
13825
+ consume(n) {
13826
+ this._bufferedBytes -= n;
13827
+ if (n === this._buffers[0].length) return this._buffers.shift();
13828
+ if (n < this._buffers[0].length) {
13829
+ const buf = this._buffers[0];
13830
+ this._buffers[0] = new FastBuffer(
13831
+ buf.buffer,
13832
+ buf.byteOffset + n,
13833
+ buf.length - n
13834
+ );
13835
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
13836
+ }
13837
+ const dst = Buffer.allocUnsafe(n);
13838
+ do {
13839
+ const buf = this._buffers[0];
13840
+ const offset = dst.length - n;
13841
+ if (n >= buf.length) {
13842
+ dst.set(this._buffers.shift(), offset);
13843
+ } else {
13844
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
13845
+ this._buffers[0] = new FastBuffer(
13846
+ buf.buffer,
13847
+ buf.byteOffset + n,
13848
+ buf.length - n
13849
+ );
13850
+ }
13851
+ n -= buf.length;
13852
+ } while (n > 0);
13853
+ return dst;
13854
+ }
13855
+ /**
13856
+ * Starts the parsing loop.
13857
+ *
13858
+ * @param {Function} cb Callback
13859
+ * @private
13860
+ */
13861
+ startLoop(cb) {
13862
+ this._loop = true;
13863
+ do {
13864
+ switch (this._state) {
13865
+ case GET_INFO:
13866
+ this.getInfo(cb);
13867
+ break;
13868
+ case GET_PAYLOAD_LENGTH_16:
13869
+ this.getPayloadLength16(cb);
13870
+ break;
13871
+ case GET_PAYLOAD_LENGTH_64:
13872
+ this.getPayloadLength64(cb);
13873
+ break;
13874
+ case GET_MASK:
13875
+ this.getMask();
13876
+ break;
13877
+ case GET_DATA:
13878
+ this.getData(cb);
13879
+ break;
13880
+ case INFLATING:
13881
+ case DEFER_EVENT:
13882
+ this._loop = false;
13883
+ return;
13884
+ }
13885
+ } while (this._loop);
13886
+ if (!this._errored) cb();
13887
+ }
13888
+ /**
13889
+ * Reads the first two bytes of a frame.
13890
+ *
13891
+ * @param {Function} cb Callback
13892
+ * @private
13893
+ */
13894
+ getInfo(cb) {
13895
+ if (this._bufferedBytes < 2) {
13896
+ this._loop = false;
13897
+ return;
13898
+ }
13899
+ const buf = this.consume(2);
13900
+ if ((buf[0] & 48) !== 0) {
13901
+ const error51 = this.createError(
13902
+ RangeError,
13903
+ "RSV2 and RSV3 must be clear",
13904
+ true,
13905
+ 1002,
13906
+ "WS_ERR_UNEXPECTED_RSV_2_3"
13907
+ );
13908
+ cb(error51);
13909
+ return;
13910
+ }
13911
+ const compressed = (buf[0] & 64) === 64;
13912
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
13913
+ const error51 = this.createError(
13914
+ RangeError,
13915
+ "RSV1 must be clear",
13916
+ true,
13917
+ 1002,
13918
+ "WS_ERR_UNEXPECTED_RSV_1"
13919
+ );
13920
+ cb(error51);
13921
+ return;
13922
+ }
13923
+ this._fin = (buf[0] & 128) === 128;
13924
+ this._opcode = buf[0] & 15;
13925
+ this._payloadLength = buf[1] & 127;
13926
+ if (this._opcode === 0) {
13927
+ if (compressed) {
13928
+ const error51 = this.createError(
13929
+ RangeError,
13930
+ "RSV1 must be clear",
13931
+ true,
13932
+ 1002,
13933
+ "WS_ERR_UNEXPECTED_RSV_1"
13934
+ );
13935
+ cb(error51);
13936
+ return;
13937
+ }
13938
+ if (!this._fragmented) {
13939
+ const error51 = this.createError(
13940
+ RangeError,
13941
+ "invalid opcode 0",
13942
+ true,
13943
+ 1002,
13944
+ "WS_ERR_INVALID_OPCODE"
13945
+ );
13946
+ cb(error51);
13947
+ return;
13948
+ }
13949
+ this._opcode = this._fragmented;
13950
+ } else if (this._opcode === 1 || this._opcode === 2) {
13951
+ if (this._fragmented) {
13952
+ const error51 = this.createError(
13953
+ RangeError,
13954
+ `invalid opcode ${this._opcode}`,
13955
+ true,
13956
+ 1002,
13957
+ "WS_ERR_INVALID_OPCODE"
13958
+ );
13959
+ cb(error51);
13960
+ return;
13961
+ }
13962
+ this._compressed = compressed;
13963
+ } else if (this._opcode > 7 && this._opcode < 11) {
13964
+ if (!this._fin) {
13965
+ const error51 = this.createError(
13966
+ RangeError,
13967
+ "FIN must be set",
13968
+ true,
13969
+ 1002,
13970
+ "WS_ERR_EXPECTED_FIN"
13971
+ );
13972
+ cb(error51);
13973
+ return;
13974
+ }
13975
+ if (compressed) {
13976
+ const error51 = this.createError(
13977
+ RangeError,
13978
+ "RSV1 must be clear",
13979
+ true,
13980
+ 1002,
13981
+ "WS_ERR_UNEXPECTED_RSV_1"
13982
+ );
13983
+ cb(error51);
13984
+ return;
13985
+ }
13986
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
13987
+ const error51 = this.createError(
13988
+ RangeError,
13989
+ `invalid payload length ${this._payloadLength}`,
13990
+ true,
13991
+ 1002,
13992
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
13993
+ );
13994
+ cb(error51);
13995
+ return;
13996
+ }
13997
+ } else {
13998
+ const error51 = this.createError(
13999
+ RangeError,
14000
+ `invalid opcode ${this._opcode}`,
14001
+ true,
14002
+ 1002,
14003
+ "WS_ERR_INVALID_OPCODE"
14004
+ );
14005
+ cb(error51);
14006
+ return;
14007
+ }
14008
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
14009
+ this._masked = (buf[1] & 128) === 128;
14010
+ if (this._isServer) {
14011
+ if (!this._masked) {
14012
+ const error51 = this.createError(
14013
+ RangeError,
14014
+ "MASK must be set",
14015
+ true,
14016
+ 1002,
14017
+ "WS_ERR_EXPECTED_MASK"
14018
+ );
14019
+ cb(error51);
14020
+ return;
14021
+ }
14022
+ } else if (this._masked) {
14023
+ const error51 = this.createError(
14024
+ RangeError,
14025
+ "MASK must be clear",
14026
+ true,
14027
+ 1002,
14028
+ "WS_ERR_UNEXPECTED_MASK"
14029
+ );
14030
+ cb(error51);
14031
+ return;
14032
+ }
14033
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
14034
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
14035
+ else this.haveLength(cb);
14036
+ }
14037
+ /**
14038
+ * Gets extended payload length (7+16).
14039
+ *
14040
+ * @param {Function} cb Callback
14041
+ * @private
14042
+ */
14043
+ getPayloadLength16(cb) {
14044
+ if (this._bufferedBytes < 2) {
14045
+ this._loop = false;
14046
+ return;
14047
+ }
14048
+ this._payloadLength = this.consume(2).readUInt16BE(0);
14049
+ this.haveLength(cb);
14050
+ }
14051
+ /**
14052
+ * Gets extended payload length (7+64).
14053
+ *
14054
+ * @param {Function} cb Callback
14055
+ * @private
14056
+ */
14057
+ getPayloadLength64(cb) {
14058
+ if (this._bufferedBytes < 8) {
14059
+ this._loop = false;
14060
+ return;
14061
+ }
14062
+ const buf = this.consume(8);
14063
+ const num = buf.readUInt32BE(0);
14064
+ if (num > Math.pow(2, 53 - 32) - 1) {
14065
+ const error51 = this.createError(
14066
+ RangeError,
14067
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
14068
+ false,
14069
+ 1009,
14070
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
14071
+ );
14072
+ cb(error51);
14073
+ return;
14074
+ }
14075
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
14076
+ this.haveLength(cb);
14077
+ }
14078
+ /**
14079
+ * Payload length has been read.
14080
+ *
14081
+ * @param {Function} cb Callback
14082
+ * @private
14083
+ */
14084
+ haveLength(cb) {
14085
+ if (this._payloadLength && this._opcode < 8) {
14086
+ this._totalPayloadLength += this._payloadLength;
14087
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
14088
+ const error51 = this.createError(
14089
+ RangeError,
14090
+ "Max payload size exceeded",
14091
+ false,
14092
+ 1009,
14093
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
14094
+ );
14095
+ cb(error51);
14096
+ return;
14097
+ }
14098
+ }
14099
+ if (this._masked) this._state = GET_MASK;
14100
+ else this._state = GET_DATA;
14101
+ }
14102
+ /**
14103
+ * Reads mask bytes.
14104
+ *
14105
+ * @private
14106
+ */
14107
+ getMask() {
14108
+ if (this._bufferedBytes < 4) {
14109
+ this._loop = false;
14110
+ return;
14111
+ }
14112
+ this._mask = this.consume(4);
14113
+ this._state = GET_DATA;
14114
+ }
14115
+ /**
14116
+ * Reads data bytes.
14117
+ *
14118
+ * @param {Function} cb Callback
14119
+ * @private
14120
+ */
14121
+ getData(cb) {
14122
+ let data = EMPTY_BUFFER;
14123
+ if (this._payloadLength) {
14124
+ if (this._bufferedBytes < this._payloadLength) {
14125
+ this._loop = false;
14126
+ return;
14127
+ }
14128
+ data = this.consume(this._payloadLength);
14129
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
14130
+ unmask(data, this._mask);
14131
+ }
14132
+ }
14133
+ if (this._opcode > 7) {
14134
+ this.controlMessage(data, cb);
14135
+ return;
14136
+ }
14137
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
14138
+ const error51 = this.createError(
14139
+ RangeError,
14140
+ "Too many message fragments",
14141
+ false,
14142
+ 1008,
14143
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
14144
+ );
14145
+ cb(error51);
14146
+ return;
14147
+ }
14148
+ if (this._compressed) {
14149
+ this._state = INFLATING;
14150
+ this.decompress(data, cb);
14151
+ return;
14152
+ }
14153
+ if (data.length) {
14154
+ this._messageLength = this._totalPayloadLength;
14155
+ this._fragments.push(data);
14156
+ }
14157
+ this.dataMessage(cb);
14158
+ }
14159
+ /**
14160
+ * Decompresses data.
14161
+ *
14162
+ * @param {Buffer} data Compressed data
14163
+ * @param {Function} cb Callback
14164
+ * @private
14165
+ */
14166
+ decompress(data, cb) {
14167
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
14168
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
14169
+ if (err) return cb(err);
14170
+ if (buf.length) {
14171
+ this._messageLength += buf.length;
14172
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
14173
+ const error51 = this.createError(
14174
+ RangeError,
14175
+ "Max payload size exceeded",
14176
+ false,
14177
+ 1009,
14178
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
14179
+ );
14180
+ cb(error51);
14181
+ return;
14182
+ }
14183
+ this._fragments.push(buf);
14184
+ }
14185
+ this.dataMessage(cb);
14186
+ if (this._state === GET_INFO) this.startLoop(cb);
14187
+ });
14188
+ }
14189
+ /**
14190
+ * Handles a data message.
14191
+ *
14192
+ * @param {Function} cb Callback
14193
+ * @private
14194
+ */
14195
+ dataMessage(cb) {
14196
+ if (!this._fin) {
14197
+ this._state = GET_INFO;
14198
+ return;
14199
+ }
14200
+ const messageLength = this._messageLength;
14201
+ const fragments = this._fragments;
14202
+ this._totalPayloadLength = 0;
14203
+ this._messageLength = 0;
14204
+ this._fragmented = 0;
14205
+ this._numFragments = 0;
14206
+ this._fragments = [];
14207
+ if (this._opcode === 2) {
14208
+ let data;
14209
+ if (this._binaryType === "nodebuffer") {
14210
+ data = concat(fragments, messageLength);
14211
+ } else if (this._binaryType === "arraybuffer") {
14212
+ data = toArrayBuffer2(concat(fragments, messageLength));
14213
+ } else if (this._binaryType === "blob") {
14214
+ data = new Blob(fragments);
14215
+ } else {
14216
+ data = fragments;
14217
+ }
14218
+ if (this._allowSynchronousEvents) {
14219
+ this.emit("message", data, true);
14220
+ this._state = GET_INFO;
14221
+ } else {
14222
+ this._state = DEFER_EVENT;
14223
+ setImmediate(() => {
14224
+ this.emit("message", data, true);
14225
+ this._state = GET_INFO;
14226
+ this.startLoop(cb);
14227
+ });
14228
+ }
14229
+ } else {
14230
+ const buf = concat(fragments, messageLength);
14231
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
14232
+ const error51 = this.createError(
14233
+ Error,
14234
+ "invalid UTF-8 sequence",
14235
+ true,
14236
+ 1007,
14237
+ "WS_ERR_INVALID_UTF8"
14238
+ );
14239
+ cb(error51);
14240
+ return;
14241
+ }
14242
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
14243
+ this.emit("message", buf, false);
14244
+ this._state = GET_INFO;
14245
+ } else {
14246
+ this._state = DEFER_EVENT;
14247
+ setImmediate(() => {
14248
+ this.emit("message", buf, false);
14249
+ this._state = GET_INFO;
14250
+ this.startLoop(cb);
14251
+ });
14252
+ }
14253
+ }
14254
+ }
14255
+ /**
14256
+ * Handles a control message.
14257
+ *
14258
+ * @param {Buffer} data Data to handle
14259
+ * @return {(Error|RangeError|undefined)} A possible error
14260
+ * @private
14261
+ */
14262
+ controlMessage(data, cb) {
14263
+ if (this._opcode === 8) {
14264
+ if (data.length === 0) {
14265
+ this._loop = false;
14266
+ this.emit("conclude", 1005, EMPTY_BUFFER);
14267
+ this.end();
14268
+ } else {
14269
+ const code = data.readUInt16BE(0);
14270
+ if (!isValidStatusCode(code)) {
14271
+ const error51 = this.createError(
14272
+ RangeError,
14273
+ `invalid status code ${code}`,
14274
+ true,
14275
+ 1002,
14276
+ "WS_ERR_INVALID_CLOSE_CODE"
14277
+ );
14278
+ cb(error51);
14279
+ return;
14280
+ }
14281
+ const buf = new FastBuffer(
14282
+ data.buffer,
14283
+ data.byteOffset + 2,
14284
+ data.length - 2
14285
+ );
14286
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
14287
+ const error51 = this.createError(
14288
+ Error,
14289
+ "invalid UTF-8 sequence",
14290
+ true,
14291
+ 1007,
14292
+ "WS_ERR_INVALID_UTF8"
14293
+ );
14294
+ cb(error51);
14295
+ return;
14296
+ }
14297
+ this._loop = false;
14298
+ this.emit("conclude", code, buf);
14299
+ this.end();
14300
+ }
14301
+ this._state = GET_INFO;
14302
+ return;
14303
+ }
14304
+ if (this._allowSynchronousEvents) {
14305
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
14306
+ this._state = GET_INFO;
14307
+ } else {
14308
+ this._state = DEFER_EVENT;
14309
+ setImmediate(() => {
14310
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
14311
+ this._state = GET_INFO;
14312
+ this.startLoop(cb);
14313
+ });
14314
+ }
14315
+ }
14316
+ /**
14317
+ * Builds an error object.
14318
+ *
14319
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
14320
+ * @param {String} message The error message
14321
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
14322
+ * `message`
14323
+ * @param {Number} statusCode The status code
14324
+ * @param {String} errorCode The exposed error code
14325
+ * @return {(Error|RangeError)} The error
14326
+ * @private
14327
+ */
14328
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
14329
+ this._loop = false;
14330
+ this._errored = true;
14331
+ const err = new ErrorCtor(
14332
+ prefix ? `Invalid WebSocket frame: ${message}` : message
14333
+ );
14334
+ Error.captureStackTrace(err, this.createError);
14335
+ err.code = errorCode;
14336
+ err[kStatusCode] = statusCode;
14337
+ return err;
14338
+ }
14339
+ };
14340
+ module2.exports = Receiver2;
14341
+ }
14342
+ });
14343
+
14344
+ // node_modules/ws/lib/sender.js
14345
+ var require_sender = __commonJS({
14346
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
14347
+ "use strict";
14348
+ var { Duplex } = require("stream");
14349
+ var { randomFillSync } = require("crypto");
14350
+ var {
14351
+ types: { isUint8Array }
14352
+ } = require("util");
14353
+ var PerMessageDeflate2 = require_permessage_deflate();
14354
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
14355
+ var { isBlob, isValidStatusCode } = require_validation3();
14356
+ var { mask: applyMask, toBuffer } = require_buffer_util();
14357
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
14358
+ var maskBuffer = Buffer.alloc(4);
14359
+ var RANDOM_POOL_SIZE = 8 * 1024;
14360
+ var randomPool;
14361
+ var randomPoolPointer = RANDOM_POOL_SIZE;
14362
+ var DEFAULT = 0;
14363
+ var DEFLATING = 1;
14364
+ var GET_BLOB_DATA = 2;
14365
+ var Sender2 = class _Sender {
14366
+ /**
14367
+ * Creates a Sender instance.
14368
+ *
14369
+ * @param {Duplex} socket The connection socket
14370
+ * @param {Object} [extensions] An object containing the negotiated extensions
14371
+ * @param {Function} [generateMask] The function used to generate the masking
14372
+ * key
14373
+ */
14374
+ constructor(socket, extensions, generateMask) {
14375
+ this._extensions = extensions || {};
14376
+ if (generateMask) {
14377
+ this._generateMask = generateMask;
14378
+ this._maskBuffer = Buffer.alloc(4);
14379
+ }
14380
+ this._socket = socket;
14381
+ this._firstFragment = true;
14382
+ this._compress = false;
14383
+ this._bufferedBytes = 0;
14384
+ this._queue = [];
14385
+ this._state = DEFAULT;
14386
+ this.onerror = NOOP;
14387
+ this[kWebSocket] = void 0;
14388
+ }
14389
+ /**
14390
+ * Frames a piece of data according to the HyBi WebSocket protocol.
14391
+ *
14392
+ * @param {(Buffer|String)} data The data to frame
14393
+ * @param {Object} options Options object
14394
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
14395
+ * FIN bit
14396
+ * @param {Function} [options.generateMask] The function used to generate the
14397
+ * masking key
14398
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
14399
+ * `data`
14400
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
14401
+ * key
14402
+ * @param {Number} options.opcode The opcode
14403
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
14404
+ * modified
14405
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
14406
+ * RSV1 bit
14407
+ * @return {(Buffer|String)[]} The framed data
14408
+ * @public
14409
+ */
14410
+ static frame(data, options) {
14411
+ let mask;
14412
+ let merge2 = false;
14413
+ let offset = 2;
14414
+ let skipMasking = false;
14415
+ if (options.mask) {
14416
+ mask = options.maskBuffer || maskBuffer;
14417
+ if (options.generateMask) {
14418
+ options.generateMask(mask);
14419
+ } else {
14420
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
14421
+ if (randomPool === void 0) {
14422
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
14423
+ }
14424
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
14425
+ randomPoolPointer = 0;
14426
+ }
14427
+ mask[0] = randomPool[randomPoolPointer++];
14428
+ mask[1] = randomPool[randomPoolPointer++];
14429
+ mask[2] = randomPool[randomPoolPointer++];
14430
+ mask[3] = randomPool[randomPoolPointer++];
14431
+ }
14432
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
14433
+ offset = 6;
14434
+ }
14435
+ let dataLength;
14436
+ if (typeof data === "string") {
14437
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
14438
+ dataLength = options[kByteLength];
14439
+ } else {
14440
+ data = Buffer.from(data);
14441
+ dataLength = data.length;
14442
+ }
14443
+ } else {
14444
+ dataLength = data.length;
14445
+ merge2 = options.mask && options.readOnly && !skipMasking;
14446
+ }
14447
+ let payloadLength = dataLength;
14448
+ if (dataLength >= 65536) {
14449
+ offset += 8;
14450
+ payloadLength = 127;
14451
+ } else if (dataLength > 125) {
14452
+ offset += 2;
14453
+ payloadLength = 126;
14454
+ }
14455
+ const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset);
14456
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
14457
+ if (options.rsv1) target[0] |= 64;
14458
+ target[1] = payloadLength;
14459
+ if (payloadLength === 126) {
14460
+ target.writeUInt16BE(dataLength, 2);
14461
+ } else if (payloadLength === 127) {
14462
+ target[2] = target[3] = 0;
14463
+ target.writeUIntBE(dataLength, 4, 6);
14464
+ }
14465
+ if (!options.mask) return [target, data];
14466
+ target[1] |= 128;
14467
+ target[offset - 4] = mask[0];
14468
+ target[offset - 3] = mask[1];
14469
+ target[offset - 2] = mask[2];
14470
+ target[offset - 1] = mask[3];
14471
+ if (skipMasking) return [target, data];
14472
+ if (merge2) {
14473
+ applyMask(data, mask, target, offset, dataLength);
14474
+ return [target];
14475
+ }
14476
+ applyMask(data, mask, data, 0, dataLength);
14477
+ return [target, data];
14478
+ }
14479
+ /**
14480
+ * Sends a close message to the other peer.
14481
+ *
14482
+ * @param {Number} [code] The status code component of the body
14483
+ * @param {(String|Buffer)} [data] The message component of the body
14484
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
14485
+ * @param {Function} [cb] Callback
14486
+ * @public
14487
+ */
14488
+ close(code, data, mask, cb) {
14489
+ let buf;
14490
+ if (code === void 0) {
14491
+ buf = EMPTY_BUFFER;
14492
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
14493
+ throw new TypeError("First argument must be a valid error code number");
14494
+ } else if (data === void 0 || !data.length) {
14495
+ buf = Buffer.allocUnsafe(2);
14496
+ buf.writeUInt16BE(code, 0);
14497
+ } else {
14498
+ const length = Buffer.byteLength(data);
14499
+ if (length > 123) {
14500
+ throw new RangeError("The message must not be greater than 123 bytes");
14501
+ }
14502
+ buf = Buffer.allocUnsafe(2 + length);
14503
+ buf.writeUInt16BE(code, 0);
14504
+ if (typeof data === "string") {
14505
+ buf.write(data, 2);
14506
+ } else if (isUint8Array(data)) {
14507
+ buf.set(data, 2);
14508
+ } else {
14509
+ throw new TypeError("Second argument must be a string or a Uint8Array");
14510
+ }
14511
+ }
14512
+ const options = {
14513
+ [kByteLength]: buf.length,
14514
+ fin: true,
14515
+ generateMask: this._generateMask,
14516
+ mask,
14517
+ maskBuffer: this._maskBuffer,
14518
+ opcode: 8,
14519
+ readOnly: false,
14520
+ rsv1: false
14521
+ };
14522
+ if (this._state !== DEFAULT) {
14523
+ this.enqueue([this.dispatch, buf, false, options, cb]);
14524
+ } else {
14525
+ this.sendFrame(_Sender.frame(buf, options), cb);
14526
+ }
14527
+ }
14528
+ /**
14529
+ * Sends a ping message to the other peer.
14530
+ *
14531
+ * @param {*} data The message to send
14532
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
14533
+ * @param {Function} [cb] Callback
14534
+ * @public
14535
+ */
14536
+ ping(data, mask, cb) {
14537
+ let byteLength;
14538
+ let readOnly;
14539
+ if (typeof data === "string") {
14540
+ byteLength = Buffer.byteLength(data);
14541
+ readOnly = false;
14542
+ } else if (isBlob(data)) {
14543
+ byteLength = data.size;
14544
+ readOnly = false;
14545
+ } else {
14546
+ data = toBuffer(data);
14547
+ byteLength = data.length;
14548
+ readOnly = toBuffer.readOnly;
14549
+ }
14550
+ if (byteLength > 125) {
14551
+ throw new RangeError("The data size must not be greater than 125 bytes");
14552
+ }
14553
+ const options = {
14554
+ [kByteLength]: byteLength,
14555
+ fin: true,
14556
+ generateMask: this._generateMask,
14557
+ mask,
14558
+ maskBuffer: this._maskBuffer,
14559
+ opcode: 9,
14560
+ readOnly,
14561
+ rsv1: false
14562
+ };
14563
+ if (isBlob(data)) {
14564
+ if (this._state !== DEFAULT) {
14565
+ this.enqueue([this.getBlobData, data, false, options, cb]);
14566
+ } else {
14567
+ this.getBlobData(data, false, options, cb);
14568
+ }
14569
+ } else if (this._state !== DEFAULT) {
14570
+ this.enqueue([this.dispatch, data, false, options, cb]);
14571
+ } else {
14572
+ this.sendFrame(_Sender.frame(data, options), cb);
14573
+ }
14574
+ }
14575
+ /**
14576
+ * Sends a pong message to the other peer.
14577
+ *
14578
+ * @param {*} data The message to send
14579
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
14580
+ * @param {Function} [cb] Callback
14581
+ * @public
14582
+ */
14583
+ pong(data, mask, cb) {
14584
+ let byteLength;
14585
+ let readOnly;
14586
+ if (typeof data === "string") {
14587
+ byteLength = Buffer.byteLength(data);
14588
+ readOnly = false;
14589
+ } else if (isBlob(data)) {
14590
+ byteLength = data.size;
14591
+ readOnly = false;
14592
+ } else {
14593
+ data = toBuffer(data);
14594
+ byteLength = data.length;
14595
+ readOnly = toBuffer.readOnly;
14596
+ }
14597
+ if (byteLength > 125) {
14598
+ throw new RangeError("The data size must not be greater than 125 bytes");
14599
+ }
14600
+ const options = {
14601
+ [kByteLength]: byteLength,
14602
+ fin: true,
14603
+ generateMask: this._generateMask,
14604
+ mask,
14605
+ maskBuffer: this._maskBuffer,
14606
+ opcode: 10,
14607
+ readOnly,
14608
+ rsv1: false
14609
+ };
14610
+ if (isBlob(data)) {
14611
+ if (this._state !== DEFAULT) {
14612
+ this.enqueue([this.getBlobData, data, false, options, cb]);
14613
+ } else {
14614
+ this.getBlobData(data, false, options, cb);
14615
+ }
14616
+ } else if (this._state !== DEFAULT) {
14617
+ this.enqueue([this.dispatch, data, false, options, cb]);
14618
+ } else {
14619
+ this.sendFrame(_Sender.frame(data, options), cb);
14620
+ }
14621
+ }
14622
+ /**
14623
+ * Sends a data message to the other peer.
14624
+ *
14625
+ * @param {*} data The message to send
14626
+ * @param {Object} options Options object
14627
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
14628
+ * or text
14629
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
14630
+ * compress `data`
14631
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
14632
+ * last one
14633
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
14634
+ * `data`
14635
+ * @param {Function} [cb] Callback
14636
+ * @public
14637
+ */
14638
+ send(data, options, cb) {
14639
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
14640
+ let opcode = options.binary ? 2 : 1;
14641
+ let rsv1 = options.compress;
14642
+ let byteLength;
14643
+ let readOnly;
14644
+ if (typeof data === "string") {
14645
+ byteLength = Buffer.byteLength(data);
14646
+ readOnly = false;
14647
+ } else if (isBlob(data)) {
14648
+ byteLength = data.size;
14649
+ readOnly = false;
14650
+ } else {
14651
+ data = toBuffer(data);
14652
+ byteLength = data.length;
14653
+ readOnly = toBuffer.readOnly;
14654
+ }
14655
+ if (this._firstFragment) {
14656
+ this._firstFragment = false;
14657
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
14658
+ rsv1 = byteLength >= perMessageDeflate._threshold;
14659
+ }
14660
+ this._compress = rsv1;
14661
+ } else {
14662
+ rsv1 = false;
14663
+ opcode = 0;
14664
+ }
14665
+ if (options.fin) this._firstFragment = true;
14666
+ const opts = {
14667
+ [kByteLength]: byteLength,
14668
+ fin: options.fin,
14669
+ generateMask: this._generateMask,
14670
+ mask: options.mask,
14671
+ maskBuffer: this._maskBuffer,
14672
+ opcode,
14673
+ readOnly,
14674
+ rsv1
14675
+ };
14676
+ if (isBlob(data)) {
14677
+ if (this._state !== DEFAULT) {
14678
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
14679
+ } else {
14680
+ this.getBlobData(data, this._compress, opts, cb);
14681
+ }
14682
+ } else if (this._state !== DEFAULT) {
14683
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
14684
+ } else {
14685
+ this.dispatch(data, this._compress, opts, cb);
14686
+ }
14687
+ }
14688
+ /**
14689
+ * Gets the contents of a blob as binary data.
14690
+ *
14691
+ * @param {Blob} blob The blob
14692
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
14693
+ * the data
14694
+ * @param {Object} options Options object
14695
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
14696
+ * FIN bit
14697
+ * @param {Function} [options.generateMask] The function used to generate the
14698
+ * masking key
14699
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
14700
+ * `data`
14701
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
14702
+ * key
14703
+ * @param {Number} options.opcode The opcode
14704
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
14705
+ * modified
14706
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
14707
+ * RSV1 bit
14708
+ * @param {Function} [cb] Callback
14709
+ * @private
14710
+ */
14711
+ getBlobData(blob, compress, options, cb) {
14712
+ this._bufferedBytes += options[kByteLength];
14713
+ this._state = GET_BLOB_DATA;
14714
+ blob.arrayBuffer().then((arrayBuffer) => {
14715
+ if (this._socket.destroyed) {
14716
+ const err = new Error(
14717
+ "The socket was closed while the blob was being read"
14718
+ );
14719
+ process.nextTick(callCallbacks, this, err, cb);
14720
+ return;
14721
+ }
14722
+ this._bufferedBytes -= options[kByteLength];
14723
+ const data = toBuffer(arrayBuffer);
14724
+ if (!compress) {
14725
+ this._state = DEFAULT;
14726
+ this.sendFrame(_Sender.frame(data, options), cb);
14727
+ this.dequeue();
14728
+ } else {
14729
+ this.dispatch(data, compress, options, cb);
14730
+ }
14731
+ }).catch((err) => {
14732
+ process.nextTick(onError, this, err, cb);
14733
+ });
14734
+ }
14735
+ /**
14736
+ * Dispatches a message.
14737
+ *
14738
+ * @param {(Buffer|String)} data The message to send
14739
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
14740
+ * `data`
14741
+ * @param {Object} options Options object
14742
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
14743
+ * FIN bit
14744
+ * @param {Function} [options.generateMask] The function used to generate the
14745
+ * masking key
14746
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
14747
+ * `data`
14748
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
14749
+ * key
14750
+ * @param {Number} options.opcode The opcode
14751
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
14752
+ * modified
14753
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
14754
+ * RSV1 bit
14755
+ * @param {Function} [cb] Callback
14756
+ * @private
14757
+ */
14758
+ dispatch(data, compress, options, cb) {
14759
+ if (!compress) {
14760
+ this.sendFrame(_Sender.frame(data, options), cb);
14761
+ return;
14762
+ }
14763
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
14764
+ this._bufferedBytes += options[kByteLength];
14765
+ this._state = DEFLATING;
14766
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
14767
+ if (this._socket.destroyed) {
14768
+ const err = new Error(
14769
+ "The socket was closed while data was being compressed"
14770
+ );
14771
+ callCallbacks(this, err, cb);
14772
+ return;
14773
+ }
14774
+ this._bufferedBytes -= options[kByteLength];
14775
+ this._state = DEFAULT;
14776
+ options.readOnly = false;
14777
+ this.sendFrame(_Sender.frame(buf, options), cb);
14778
+ this.dequeue();
14779
+ });
14780
+ }
14781
+ /**
14782
+ * Executes queued send operations.
14783
+ *
14784
+ * @private
14785
+ */
14786
+ dequeue() {
14787
+ while (this._state === DEFAULT && this._queue.length) {
14788
+ const params = this._queue.shift();
14789
+ this._bufferedBytes -= params[3][kByteLength];
14790
+ Reflect.apply(params[0], this, params.slice(1));
14791
+ }
14792
+ }
14793
+ /**
14794
+ * Enqueues a send operation.
14795
+ *
14796
+ * @param {Array} params Send operation parameters.
14797
+ * @private
14798
+ */
14799
+ enqueue(params) {
14800
+ this._bufferedBytes += params[3][kByteLength];
14801
+ this._queue.push(params);
14802
+ }
14803
+ /**
14804
+ * Sends a frame.
14805
+ *
14806
+ * @param {(Buffer | String)[]} list The frame to send
14807
+ * @param {Function} [cb] Callback
14808
+ * @private
14809
+ */
14810
+ sendFrame(list, cb) {
14811
+ if (list.length === 2) {
14812
+ this._socket.cork();
14813
+ this._socket.write(list[0]);
14814
+ this._socket.write(list[1], cb);
14815
+ this._socket.uncork();
14816
+ } else {
14817
+ this._socket.write(list[0], cb);
14818
+ }
14819
+ }
14820
+ };
14821
+ module2.exports = Sender2;
14822
+ function callCallbacks(sender, err, cb) {
14823
+ if (typeof cb === "function") cb(err);
14824
+ for (let i = 0; i < sender._queue.length; i++) {
14825
+ const params = sender._queue[i];
14826
+ const callback = params[params.length - 1];
14827
+ if (typeof callback === "function") callback(err);
14828
+ }
14829
+ }
14830
+ function onError(sender, err, cb) {
14831
+ callCallbacks(sender, err, cb);
14832
+ sender.onerror(err);
14833
+ }
14834
+ }
14835
+ });
14836
+
14837
+ // node_modules/ws/lib/event-target.js
14838
+ var require_event_target = __commonJS({
14839
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
14840
+ "use strict";
14841
+ var { kForOnEventAttribute, kListener } = require_constants();
14842
+ var kCode = /* @__PURE__ */ Symbol("kCode");
14843
+ var kData = /* @__PURE__ */ Symbol("kData");
14844
+ var kError = /* @__PURE__ */ Symbol("kError");
14845
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
14846
+ var kReason = /* @__PURE__ */ Symbol("kReason");
14847
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
14848
+ var kType = /* @__PURE__ */ Symbol("kType");
14849
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
14850
+ var Event2 = class {
14851
+ /**
14852
+ * Create a new `Event`.
14853
+ *
14854
+ * @param {String} type The name of the event
14855
+ * @throws {TypeError} If the `type` argument is not specified
14856
+ */
14857
+ constructor(type) {
14858
+ this[kTarget] = null;
14859
+ this[kType] = type;
14860
+ }
14861
+ /**
14862
+ * @type {*}
14863
+ */
14864
+ get target() {
14865
+ return this[kTarget];
14866
+ }
14867
+ /**
14868
+ * @type {String}
14869
+ */
14870
+ get type() {
14871
+ return this[kType];
14872
+ }
14873
+ };
14874
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
14875
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
14876
+ var CloseEvent2 = class extends Event2 {
14877
+ /**
14878
+ * Create a new `CloseEvent`.
14879
+ *
14880
+ * @param {String} type The name of the event
14881
+ * @param {Object} [options] A dictionary object that allows for setting
14882
+ * attributes via object members of the same name
14883
+ * @param {Number} [options.code=0] The status code explaining why the
14884
+ * connection was closed
14885
+ * @param {String} [options.reason=''] A human-readable string explaining why
14886
+ * the connection was closed
14887
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
14888
+ * connection was cleanly closed
14889
+ */
14890
+ constructor(type, options = {}) {
14891
+ super(type);
14892
+ this[kCode] = options.code === void 0 ? 0 : options.code;
14893
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
14894
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
14895
+ }
14896
+ /**
14897
+ * @type {Number}
14898
+ */
14899
+ get code() {
14900
+ return this[kCode];
14901
+ }
14902
+ /**
14903
+ * @type {String}
14904
+ */
14905
+ get reason() {
14906
+ return this[kReason];
14907
+ }
14908
+ /**
14909
+ * @type {Boolean}
14910
+ */
14911
+ get wasClean() {
14912
+ return this[kWasClean];
14913
+ }
14914
+ };
14915
+ Object.defineProperty(CloseEvent2.prototype, "code", { enumerable: true });
14916
+ Object.defineProperty(CloseEvent2.prototype, "reason", { enumerable: true });
14917
+ Object.defineProperty(CloseEvent2.prototype, "wasClean", { enumerable: true });
14918
+ var ErrorEvent2 = class extends Event2 {
14919
+ /**
14920
+ * Create a new `ErrorEvent`.
14921
+ *
14922
+ * @param {String} type The name of the event
14923
+ * @param {Object} [options] A dictionary object that allows for setting
14924
+ * attributes via object members of the same name
14925
+ * @param {*} [options.error=null] The error that generated this event
14926
+ * @param {String} [options.message=''] The error message
14927
+ */
14928
+ constructor(type, options = {}) {
14929
+ super(type);
14930
+ this[kError] = options.error === void 0 ? null : options.error;
14931
+ this[kMessage] = options.message === void 0 ? "" : options.message;
14932
+ }
14933
+ /**
14934
+ * @type {*}
14935
+ */
14936
+ get error() {
14937
+ return this[kError];
14938
+ }
14939
+ /**
14940
+ * @type {String}
14941
+ */
14942
+ get message() {
14943
+ return this[kMessage];
14944
+ }
14945
+ };
14946
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
14947
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
14948
+ var MessageEvent2 = class extends Event2 {
14949
+ /**
14950
+ * Create a new `MessageEvent`.
14951
+ *
14952
+ * @param {String} type The name of the event
14953
+ * @param {Object} [options] A dictionary object that allows for setting
14954
+ * attributes via object members of the same name
14955
+ * @param {*} [options.data=null] The message content
14956
+ */
14957
+ constructor(type, options = {}) {
14958
+ super(type);
14959
+ this[kData] = options.data === void 0 ? null : options.data;
14960
+ }
14961
+ /**
14962
+ * @type {*}
14963
+ */
14964
+ get data() {
14965
+ return this[kData];
14966
+ }
14967
+ };
14968
+ Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true });
14969
+ var EventTarget = {
14970
+ /**
14971
+ * Register an event listener.
14972
+ *
14973
+ * @param {String} type A string representing the event type to listen for
14974
+ * @param {(Function|Object)} handler The listener to add
14975
+ * @param {Object} [options] An options object specifies characteristics about
14976
+ * the event listener
14977
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
14978
+ * listener should be invoked at most once after being added. If `true`,
14979
+ * the listener would be automatically removed when invoked.
14980
+ * @public
14981
+ */
14982
+ addEventListener(type, handler, options = {}) {
14983
+ for (const listener of this.listeners(type)) {
14984
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
14985
+ return;
14986
+ }
14987
+ }
14988
+ let wrapper;
14989
+ if (type === "message") {
14990
+ wrapper = function onMessage(data, isBinary) {
14991
+ const event = new MessageEvent2("message", {
14992
+ data: isBinary ? data : data.toString()
14993
+ });
14994
+ event[kTarget] = this;
14995
+ callListener(handler, this, event);
14996
+ };
14997
+ } else if (type === "close") {
14998
+ wrapper = function onClose(code, message) {
14999
+ const event = new CloseEvent2("close", {
15000
+ code,
15001
+ reason: message.toString(),
15002
+ wasClean: this._closeFrameReceived && this._closeFrameSent
15003
+ });
15004
+ event[kTarget] = this;
15005
+ callListener(handler, this, event);
15006
+ };
15007
+ } else if (type === "error") {
15008
+ wrapper = function onError(error51) {
15009
+ const event = new ErrorEvent2("error", {
15010
+ error: error51,
15011
+ message: error51.message
15012
+ });
15013
+ event[kTarget] = this;
15014
+ callListener(handler, this, event);
15015
+ };
15016
+ } else if (type === "open") {
15017
+ wrapper = function onOpen() {
15018
+ const event = new Event2("open");
15019
+ event[kTarget] = this;
15020
+ callListener(handler, this, event);
15021
+ };
15022
+ } else {
15023
+ return;
15024
+ }
15025
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
15026
+ wrapper[kListener] = handler;
15027
+ if (options.once) {
15028
+ this.once(type, wrapper);
15029
+ } else {
15030
+ this.on(type, wrapper);
15031
+ }
15032
+ },
15033
+ /**
15034
+ * Remove an event listener.
15035
+ *
15036
+ * @param {String} type A string representing the event type to remove
15037
+ * @param {(Function|Object)} handler The listener to remove
15038
+ * @public
15039
+ */
15040
+ removeEventListener(type, handler) {
15041
+ for (const listener of this.listeners(type)) {
15042
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
15043
+ this.removeListener(type, listener);
15044
+ break;
15045
+ }
15046
+ }
15047
+ }
15048
+ };
15049
+ module2.exports = {
15050
+ CloseEvent: CloseEvent2,
15051
+ ErrorEvent: ErrorEvent2,
15052
+ Event: Event2,
15053
+ EventTarget,
15054
+ MessageEvent: MessageEvent2
15055
+ };
15056
+ function callListener(listener, thisArg, event) {
15057
+ if (typeof listener === "object" && listener.handleEvent) {
15058
+ listener.handleEvent.call(listener, event);
15059
+ } else {
15060
+ listener.call(thisArg, event);
15061
+ }
15062
+ }
15063
+ }
15064
+ });
15065
+
15066
+ // node_modules/ws/lib/extension.js
15067
+ var require_extension = __commonJS({
15068
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
15069
+ "use strict";
15070
+ var { tokenChars } = require_validation3();
15071
+ function push(dest, name, elem) {
15072
+ if (dest[name] === void 0) dest[name] = [elem];
15073
+ else dest[name].push(elem);
15074
+ }
15075
+ function parse3(header) {
15076
+ const offers = /* @__PURE__ */ Object.create(null);
15077
+ let params = /* @__PURE__ */ Object.create(null);
15078
+ let mustUnescape = false;
15079
+ let isEscaping = false;
15080
+ let inQuotes = false;
15081
+ let extensionName;
15082
+ let paramName;
15083
+ let start = -1;
15084
+ let code = -1;
15085
+ let end = -1;
15086
+ let i = 0;
15087
+ for (; i < header.length; i++) {
15088
+ code = header.charCodeAt(i);
15089
+ if (extensionName === void 0) {
15090
+ if (end === -1 && tokenChars[code] === 1) {
15091
+ if (start === -1) start = i;
15092
+ } else if (i !== 0 && (code === 32 || code === 9)) {
15093
+ if (end === -1 && start !== -1) end = i;
15094
+ } else if (code === 59 || code === 44) {
15095
+ if (start === -1) {
15096
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15097
+ }
15098
+ if (end === -1) end = i;
15099
+ const name = header.slice(start, end);
15100
+ if (code === 44) {
15101
+ push(offers, name, params);
15102
+ params = /* @__PURE__ */ Object.create(null);
15103
+ } else {
15104
+ extensionName = name;
15105
+ }
15106
+ start = end = -1;
15107
+ } else {
15108
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15109
+ }
15110
+ } else if (paramName === void 0) {
15111
+ if (end === -1 && tokenChars[code] === 1) {
15112
+ if (start === -1) start = i;
15113
+ } else if (code === 32 || code === 9) {
15114
+ if (end === -1 && start !== -1) end = i;
15115
+ } else if (code === 59 || code === 44) {
15116
+ if (start === -1) {
15117
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15118
+ }
15119
+ if (end === -1) end = i;
15120
+ push(params, header.slice(start, end), true);
15121
+ if (code === 44) {
15122
+ push(offers, extensionName, params);
15123
+ params = /* @__PURE__ */ Object.create(null);
15124
+ extensionName = void 0;
15125
+ }
15126
+ start = end = -1;
15127
+ } else if (code === 61 && start !== -1 && end === -1) {
15128
+ paramName = header.slice(start, i);
15129
+ start = end = -1;
15130
+ } else {
15131
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15132
+ }
15133
+ } else {
15134
+ if (isEscaping) {
15135
+ if (tokenChars[code] !== 1) {
15136
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15137
+ }
15138
+ if (start === -1) start = i;
15139
+ else if (!mustUnescape) mustUnescape = true;
15140
+ isEscaping = false;
15141
+ } else if (inQuotes) {
15142
+ if (tokenChars[code] === 1) {
15143
+ if (start === -1) start = i;
15144
+ } else if (code === 34 && start !== -1) {
15145
+ inQuotes = false;
15146
+ end = i;
15147
+ } else if (code === 92) {
15148
+ isEscaping = true;
15149
+ } else {
15150
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15151
+ }
15152
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
15153
+ inQuotes = true;
15154
+ } else if (end === -1 && tokenChars[code] === 1) {
15155
+ if (start === -1) start = i;
15156
+ } else if (start !== -1 && (code === 32 || code === 9)) {
15157
+ if (end === -1) end = i;
15158
+ } else if (code === 59 || code === 44) {
15159
+ if (start === -1) {
15160
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15161
+ }
15162
+ if (end === -1) end = i;
15163
+ let value = header.slice(start, end);
15164
+ if (mustUnescape) {
15165
+ value = value.replace(/\\/g, "");
15166
+ mustUnescape = false;
15167
+ }
15168
+ push(params, paramName, value);
15169
+ if (code === 44) {
15170
+ push(offers, extensionName, params);
15171
+ params = /* @__PURE__ */ Object.create(null);
15172
+ extensionName = void 0;
15173
+ }
15174
+ paramName = void 0;
15175
+ start = end = -1;
15176
+ } else {
15177
+ throw new SyntaxError(`Unexpected character at index ${i}`);
15178
+ }
15179
+ }
15180
+ }
15181
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
15182
+ throw new SyntaxError("Unexpected end of input");
15183
+ }
15184
+ if (end === -1) end = i;
15185
+ const token = header.slice(start, end);
15186
+ if (extensionName === void 0) {
15187
+ push(offers, token, params);
15188
+ } else {
15189
+ if (paramName === void 0) {
15190
+ push(params, token, true);
15191
+ } else if (mustUnescape) {
15192
+ push(params, paramName, token.replace(/\\/g, ""));
15193
+ } else {
15194
+ push(params, paramName, token);
15195
+ }
15196
+ push(offers, extensionName, params);
15197
+ }
15198
+ return offers;
15199
+ }
15200
+ function format(extensions) {
15201
+ return Object.keys(extensions).map((extension2) => {
15202
+ let configurations = extensions[extension2];
15203
+ if (!Array.isArray(configurations)) configurations = [configurations];
15204
+ return configurations.map((params) => {
15205
+ return [extension2].concat(
15206
+ Object.keys(params).map((k) => {
15207
+ let values = params[k];
15208
+ if (!Array.isArray(values)) values = [values];
15209
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
15210
+ })
15211
+ ).join("; ");
15212
+ }).join(", ");
15213
+ }).join(", ");
15214
+ }
15215
+ module2.exports = { format, parse: parse3 };
15216
+ }
15217
+ });
15218
+
15219
+ // node_modules/ws/lib/websocket.js
15220
+ var require_websocket = __commonJS({
15221
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
15222
+ "use strict";
15223
+ var EventEmitter = require("events");
15224
+ var https = require("https");
15225
+ var http2 = require("http");
15226
+ var net = require("net");
15227
+ var tls = require("tls");
15228
+ var { randomBytes: randomBytes2, createHash } = require("crypto");
15229
+ var { Duplex, Readable: Readable2 } = require("stream");
15230
+ var { URL: URL2 } = require("url");
15231
+ var PerMessageDeflate2 = require_permessage_deflate();
15232
+ var Receiver2 = require_receiver();
15233
+ var Sender2 = require_sender();
15234
+ var { isBlob } = require_validation3();
15235
+ var {
15236
+ BINARY_TYPES,
15237
+ CLOSE_TIMEOUT,
15238
+ EMPTY_BUFFER,
15239
+ GUID,
15240
+ kForOnEventAttribute,
15241
+ kListener,
15242
+ kStatusCode,
15243
+ kWebSocket,
15244
+ NOOP
15245
+ } = require_constants();
15246
+ var {
15247
+ EventTarget: { addEventListener, removeEventListener }
15248
+ } = require_event_target();
15249
+ var { format, parse: parse3 } = require_extension();
15250
+ var { toBuffer } = require_buffer_util();
15251
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
15252
+ var protocolVersions = [8, 13];
15253
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
15254
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
15255
+ var WebSocket2 = class _WebSocket extends EventEmitter {
15256
+ /**
15257
+ * Create a new `WebSocket`.
15258
+ *
15259
+ * @param {(String|URL)} address The URL to which to connect
15260
+ * @param {(String|String[])} [protocols] The subprotocols
15261
+ * @param {Object} [options] Connection options
15262
+ */
15263
+ constructor(address, protocols, options) {
15264
+ super();
15265
+ this._binaryType = BINARY_TYPES[0];
15266
+ this._closeCode = 1006;
15267
+ this._closeFrameReceived = false;
15268
+ this._closeFrameSent = false;
15269
+ this._closeMessage = EMPTY_BUFFER;
15270
+ this._closeTimer = null;
15271
+ this._errorEmitted = false;
15272
+ this._extensions = {};
15273
+ this._paused = false;
15274
+ this._protocol = "";
15275
+ this._readyState = _WebSocket.CONNECTING;
15276
+ this._receiver = null;
15277
+ this._sender = null;
15278
+ this._socket = null;
15279
+ if (address !== null) {
15280
+ this._bufferedAmount = 0;
15281
+ this._isServer = false;
15282
+ this._redirects = 0;
15283
+ if (protocols === void 0) {
15284
+ protocols = [];
15285
+ } else if (!Array.isArray(protocols)) {
15286
+ if (typeof protocols === "object" && protocols !== null) {
15287
+ options = protocols;
15288
+ protocols = [];
15289
+ } else {
15290
+ protocols = [protocols];
15291
+ }
15292
+ }
15293
+ initAsClient(this, address, protocols, options);
15294
+ } else {
15295
+ this._autoPong = options.autoPong;
15296
+ this._closeTimeout = options.closeTimeout;
15297
+ this._isServer = true;
15298
+ }
15299
+ }
15300
+ /**
15301
+ * For historical reasons, the custom "nodebuffer" type is used by the default
15302
+ * instead of "blob".
15303
+ *
15304
+ * @type {String}
15305
+ */
15306
+ get binaryType() {
15307
+ return this._binaryType;
15308
+ }
15309
+ set binaryType(type) {
15310
+ if (!BINARY_TYPES.includes(type)) return;
15311
+ this._binaryType = type;
15312
+ if (this._receiver) this._receiver._binaryType = type;
15313
+ }
15314
+ /**
15315
+ * @type {Number}
15316
+ */
15317
+ get bufferedAmount() {
15318
+ if (!this._socket) return this._bufferedAmount;
15319
+ return this._socket._writableState.length + this._sender._bufferedBytes;
15320
+ }
15321
+ /**
15322
+ * @type {String}
15323
+ */
15324
+ get extensions() {
15325
+ return Object.keys(this._extensions).join();
15326
+ }
15327
+ /**
15328
+ * @type {Boolean}
15329
+ */
15330
+ get isPaused() {
15331
+ return this._paused;
15332
+ }
15333
+ /**
15334
+ * @type {Function}
15335
+ */
15336
+ /* istanbul ignore next */
15337
+ get onclose() {
15338
+ return null;
15339
+ }
15340
+ /**
15341
+ * @type {Function}
15342
+ */
15343
+ /* istanbul ignore next */
15344
+ get onerror() {
15345
+ return null;
15346
+ }
15347
+ /**
15348
+ * @type {Function}
15349
+ */
15350
+ /* istanbul ignore next */
15351
+ get onopen() {
15352
+ return null;
15353
+ }
15354
+ /**
15355
+ * @type {Function}
15356
+ */
15357
+ /* istanbul ignore next */
15358
+ get onmessage() {
15359
+ return null;
15360
+ }
15361
+ /**
15362
+ * @type {String}
15363
+ */
15364
+ get protocol() {
15365
+ return this._protocol;
15366
+ }
15367
+ /**
15368
+ * @type {Number}
15369
+ */
15370
+ get readyState() {
15371
+ return this._readyState;
15372
+ }
15373
+ /**
15374
+ * @type {String}
15375
+ */
15376
+ get url() {
15377
+ return this._url;
15378
+ }
15379
+ /**
15380
+ * Set up the socket and the internal resources.
15381
+ *
15382
+ * @param {Duplex} socket The network socket between the server and client
15383
+ * @param {Buffer} head The first packet of the upgraded stream
15384
+ * @param {Object} options Options object
15385
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
15386
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
15387
+ * multiple times in the same tick
15388
+ * @param {Function} [options.generateMask] The function used to generate the
15389
+ * masking key
15390
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
15391
+ * buffered data chunks
15392
+ * @param {Number} [options.maxFragments=0] The maximum number of message
15393
+ * fragments
15394
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
15395
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
15396
+ * not to skip UTF-8 validation for text and close messages
15397
+ * @private
15398
+ */
15399
+ setSocket(socket, head, options) {
15400
+ const receiver = new Receiver2({
15401
+ allowSynchronousEvents: options.allowSynchronousEvents,
15402
+ binaryType: this.binaryType,
15403
+ extensions: this._extensions,
15404
+ isServer: this._isServer,
15405
+ maxBufferedChunks: options.maxBufferedChunks,
15406
+ maxFragments: options.maxFragments,
15407
+ maxPayload: options.maxPayload,
15408
+ skipUTF8Validation: options.skipUTF8Validation
15409
+ });
15410
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
15411
+ this._receiver = receiver;
15412
+ this._sender = sender;
15413
+ this._socket = socket;
15414
+ receiver[kWebSocket] = this;
15415
+ sender[kWebSocket] = this;
15416
+ socket[kWebSocket] = this;
15417
+ receiver.on("conclude", receiverOnConclude);
15418
+ receiver.on("drain", receiverOnDrain);
15419
+ receiver.on("error", receiverOnError);
15420
+ receiver.on("message", receiverOnMessage);
15421
+ receiver.on("ping", receiverOnPing);
15422
+ receiver.on("pong", receiverOnPong);
15423
+ sender.onerror = senderOnError;
15424
+ if (socket.setTimeout) socket.setTimeout(0);
15425
+ if (socket.setNoDelay) socket.setNoDelay();
15426
+ if (head.length > 0) socket.unshift(head);
15427
+ socket.on("close", socketOnClose);
15428
+ socket.on("data", socketOnData);
15429
+ socket.on("end", socketOnEnd);
15430
+ socket.on("error", socketOnError);
15431
+ this._readyState = _WebSocket.OPEN;
15432
+ this.emit("open");
15433
+ }
15434
+ /**
15435
+ * Emit the `'close'` event.
15436
+ *
15437
+ * @private
15438
+ */
15439
+ emitClose() {
15440
+ if (!this._socket) {
15441
+ this._readyState = _WebSocket.CLOSED;
15442
+ this.emit("close", this._closeCode, this._closeMessage);
15443
+ return;
15444
+ }
15445
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
15446
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
15447
+ }
15448
+ this._receiver.removeAllListeners();
15449
+ this._readyState = _WebSocket.CLOSED;
15450
+ this.emit("close", this._closeCode, this._closeMessage);
15451
+ }
15452
+ /**
15453
+ * Start a closing handshake.
15454
+ *
15455
+ * +----------+ +-----------+ +----------+
15456
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
15457
+ * | +----------+ +-----------+ +----------+ |
15458
+ * +----------+ +-----------+ |
15459
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
15460
+ * +----------+ +-----------+ |
15461
+ * | | | +---+ |
15462
+ * +------------------------+-->|fin| - - - -
15463
+ * | +---+ | +---+
15464
+ * - - - - -|fin|<---------------------+
15465
+ * +---+
15466
+ *
15467
+ * @param {Number} [code] Status code explaining why the connection is closing
15468
+ * @param {(String|Buffer)} [data] The reason why the connection is
15469
+ * closing
15470
+ * @public
15471
+ */
15472
+ close(code, data) {
15473
+ if (this.readyState === _WebSocket.CLOSED) return;
15474
+ if (this.readyState === _WebSocket.CONNECTING) {
15475
+ const msg = "WebSocket was closed before the connection was established";
15476
+ abortHandshake(this, this._req, msg);
15477
+ return;
15478
+ }
15479
+ if (this.readyState === _WebSocket.CLOSING) {
15480
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
15481
+ this._socket.end();
15482
+ }
15483
+ return;
15484
+ }
15485
+ this._readyState = _WebSocket.CLOSING;
15486
+ this._sender.close(code, data, !this._isServer, (err) => {
15487
+ if (err) return;
15488
+ this._closeFrameSent = true;
15489
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
15490
+ this._socket.end();
15491
+ }
15492
+ });
15493
+ setCloseTimer(this);
15494
+ }
15495
+ /**
15496
+ * Pause the socket.
15497
+ *
15498
+ * @public
15499
+ */
15500
+ pause() {
15501
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
15502
+ return;
15503
+ }
15504
+ this._paused = true;
15505
+ this._socket.pause();
15506
+ }
15507
+ /**
15508
+ * Send a ping.
15509
+ *
15510
+ * @param {*} [data] The data to send
15511
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
15512
+ * @param {Function} [cb] Callback which is executed when the ping is sent
15513
+ * @public
15514
+ */
15515
+ ping(data, mask, cb) {
15516
+ if (this.readyState === _WebSocket.CONNECTING) {
15517
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
15518
+ }
15519
+ if (typeof data === "function") {
15520
+ cb = data;
15521
+ data = mask = void 0;
15522
+ } else if (typeof mask === "function") {
15523
+ cb = mask;
15524
+ mask = void 0;
15525
+ }
15526
+ if (typeof data === "number") data = data.toString();
15527
+ if (this.readyState !== _WebSocket.OPEN) {
15528
+ sendAfterClose(this, data, cb);
15529
+ return;
15530
+ }
15531
+ if (mask === void 0) mask = !this._isServer;
15532
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
15533
+ }
15534
+ /**
15535
+ * Send a pong.
15536
+ *
15537
+ * @param {*} [data] The data to send
15538
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
15539
+ * @param {Function} [cb] Callback which is executed when the pong is sent
15540
+ * @public
15541
+ */
15542
+ pong(data, mask, cb) {
15543
+ if (this.readyState === _WebSocket.CONNECTING) {
15544
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
15545
+ }
15546
+ if (typeof data === "function") {
15547
+ cb = data;
15548
+ data = mask = void 0;
15549
+ } else if (typeof mask === "function") {
15550
+ cb = mask;
15551
+ mask = void 0;
15552
+ }
15553
+ if (typeof data === "number") data = data.toString();
15554
+ if (this.readyState !== _WebSocket.OPEN) {
15555
+ sendAfterClose(this, data, cb);
15556
+ return;
15557
+ }
15558
+ if (mask === void 0) mask = !this._isServer;
15559
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
15560
+ }
15561
+ /**
15562
+ * Resume the socket.
15563
+ *
15564
+ * @public
15565
+ */
15566
+ resume() {
15567
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
15568
+ return;
15569
+ }
15570
+ this._paused = false;
15571
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
15572
+ }
15573
+ /**
15574
+ * Send a data message.
15575
+ *
15576
+ * @param {*} data The message to send
15577
+ * @param {Object} [options] Options object
15578
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
15579
+ * text
15580
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
15581
+ * `data`
15582
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
15583
+ * last one
15584
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
15585
+ * @param {Function} [cb] Callback which is executed when data is written out
15586
+ * @public
15587
+ */
15588
+ send(data, options, cb) {
15589
+ if (this.readyState === _WebSocket.CONNECTING) {
15590
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
15591
+ }
15592
+ if (typeof options === "function") {
15593
+ cb = options;
15594
+ options = {};
15595
+ }
15596
+ if (typeof data === "number") data = data.toString();
15597
+ if (this.readyState !== _WebSocket.OPEN) {
15598
+ sendAfterClose(this, data, cb);
15599
+ return;
15600
+ }
15601
+ const opts = {
15602
+ binary: typeof data !== "string",
15603
+ mask: !this._isServer,
15604
+ compress: true,
15605
+ fin: true,
15606
+ ...options
15607
+ };
15608
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
15609
+ opts.compress = false;
15610
+ }
15611
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
15612
+ }
15613
+ /**
15614
+ * Forcibly close the connection.
15615
+ *
15616
+ * @public
15617
+ */
15618
+ terminate() {
15619
+ if (this.readyState === _WebSocket.CLOSED) return;
15620
+ if (this.readyState === _WebSocket.CONNECTING) {
15621
+ const msg = "WebSocket was closed before the connection was established";
15622
+ abortHandshake(this, this._req, msg);
15623
+ return;
15624
+ }
15625
+ if (this._socket) {
15626
+ this._readyState = _WebSocket.CLOSING;
15627
+ this._socket.destroy();
15628
+ }
15629
+ }
15630
+ };
15631
+ Object.defineProperty(WebSocket2, "CONNECTING", {
15632
+ enumerable: true,
15633
+ value: readyStates.indexOf("CONNECTING")
15634
+ });
15635
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
15636
+ enumerable: true,
15637
+ value: readyStates.indexOf("CONNECTING")
15638
+ });
15639
+ Object.defineProperty(WebSocket2, "OPEN", {
15640
+ enumerable: true,
15641
+ value: readyStates.indexOf("OPEN")
15642
+ });
15643
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
15644
+ enumerable: true,
15645
+ value: readyStates.indexOf("OPEN")
15646
+ });
15647
+ Object.defineProperty(WebSocket2, "CLOSING", {
15648
+ enumerable: true,
15649
+ value: readyStates.indexOf("CLOSING")
15650
+ });
15651
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
15652
+ enumerable: true,
15653
+ value: readyStates.indexOf("CLOSING")
15654
+ });
15655
+ Object.defineProperty(WebSocket2, "CLOSED", {
15656
+ enumerable: true,
15657
+ value: readyStates.indexOf("CLOSED")
15658
+ });
15659
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
15660
+ enumerable: true,
15661
+ value: readyStates.indexOf("CLOSED")
15662
+ });
15663
+ [
15664
+ "binaryType",
15665
+ "bufferedAmount",
15666
+ "extensions",
15667
+ "isPaused",
15668
+ "protocol",
15669
+ "readyState",
15670
+ "url"
15671
+ ].forEach((property) => {
15672
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
15673
+ });
15674
+ ["open", "error", "close", "message"].forEach((method) => {
15675
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
15676
+ enumerable: true,
15677
+ get() {
15678
+ for (const listener of this.listeners(method)) {
15679
+ if (listener[kForOnEventAttribute]) return listener[kListener];
15680
+ }
15681
+ return null;
15682
+ },
15683
+ set(handler) {
15684
+ for (const listener of this.listeners(method)) {
15685
+ if (listener[kForOnEventAttribute]) {
15686
+ this.removeListener(method, listener);
15687
+ break;
15688
+ }
15689
+ }
15690
+ if (typeof handler !== "function") return;
15691
+ this.addEventListener(method, handler, {
15692
+ [kForOnEventAttribute]: true
15693
+ });
15694
+ }
15695
+ });
15696
+ });
15697
+ WebSocket2.prototype.addEventListener = addEventListener;
15698
+ WebSocket2.prototype.removeEventListener = removeEventListener;
15699
+ module2.exports = WebSocket2;
15700
+ function initAsClient(websocket, address, protocols, options) {
15701
+ const opts = {
15702
+ allowSynchronousEvents: true,
15703
+ autoPong: true,
15704
+ closeTimeout: CLOSE_TIMEOUT,
15705
+ protocolVersion: protocolVersions[1],
15706
+ maxBufferedChunks: 256 * 1024,
15707
+ maxFragments: 16 * 1024,
15708
+ maxPayload: 100 * 1024 * 1024,
15709
+ skipUTF8Validation: false,
15710
+ perMessageDeflate: true,
15711
+ followRedirects: false,
15712
+ maxRedirects: 10,
15713
+ ...options,
15714
+ socketPath: void 0,
15715
+ hostname: void 0,
15716
+ protocol: void 0,
15717
+ timeout: void 0,
15718
+ method: "GET",
15719
+ host: void 0,
15720
+ path: void 0,
15721
+ port: void 0
15722
+ };
15723
+ websocket._autoPong = opts.autoPong;
15724
+ websocket._closeTimeout = opts.closeTimeout;
15725
+ if (!protocolVersions.includes(opts.protocolVersion)) {
15726
+ throw new RangeError(
15727
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
15728
+ );
15729
+ }
15730
+ let parsedUrl;
15731
+ if (address instanceof URL2) {
15732
+ parsedUrl = address;
15733
+ } else {
15734
+ try {
15735
+ parsedUrl = new URL2(address);
15736
+ } catch {
15737
+ throw new SyntaxError(`Invalid URL: ${address}`);
15738
+ }
15739
+ }
15740
+ if (parsedUrl.protocol === "http:") {
15741
+ parsedUrl.protocol = "ws:";
15742
+ } else if (parsedUrl.protocol === "https:") {
15743
+ parsedUrl.protocol = "wss:";
15744
+ }
15745
+ websocket._url = parsedUrl.href;
15746
+ const isSecure = parsedUrl.protocol === "wss:";
15747
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
15748
+ let invalidUrlMessage;
15749
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
15750
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
15751
+ } else if (isIpcUrl && !parsedUrl.pathname) {
15752
+ invalidUrlMessage = "The URL's pathname is empty";
15753
+ } else if (parsedUrl.hash) {
15754
+ invalidUrlMessage = "The URL contains a fragment identifier";
15755
+ }
15756
+ if (invalidUrlMessage) {
15757
+ const err = new SyntaxError(invalidUrlMessage);
15758
+ if (websocket._redirects === 0) {
15759
+ throw err;
15760
+ } else {
15761
+ emitErrorAndClose(websocket, err);
15762
+ return;
15763
+ }
15764
+ }
15765
+ const defaultPort = isSecure ? 443 : 80;
15766
+ const key = randomBytes2(16).toString("base64");
15767
+ const request = isSecure ? https.request : http2.request;
15768
+ const protocolSet = /* @__PURE__ */ new Set();
15769
+ let perMessageDeflate;
15770
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
15771
+ opts.defaultPort = opts.defaultPort || defaultPort;
15772
+ opts.port = parsedUrl.port || defaultPort;
15773
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
15774
+ opts.headers = {
15775
+ ...opts.headers,
15776
+ "Sec-WebSocket-Version": opts.protocolVersion,
15777
+ "Sec-WebSocket-Key": key,
15778
+ Connection: "Upgrade",
15779
+ Upgrade: "websocket"
15780
+ };
15781
+ opts.path = parsedUrl.pathname + parsedUrl.search;
15782
+ opts.timeout = opts.handshakeTimeout;
15783
+ if (opts.perMessageDeflate) {
15784
+ perMessageDeflate = new PerMessageDeflate2({
15785
+ ...opts.perMessageDeflate,
15786
+ isServer: false,
15787
+ maxPayload: opts.maxPayload
15788
+ });
15789
+ opts.headers["Sec-WebSocket-Extensions"] = format({
15790
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
15791
+ });
15792
+ }
15793
+ if (protocols.length) {
15794
+ for (const protocol of protocols) {
15795
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
15796
+ throw new SyntaxError(
15797
+ "An invalid or duplicated subprotocol was specified"
15798
+ );
15799
+ }
15800
+ protocolSet.add(protocol);
15801
+ }
15802
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
15803
+ }
15804
+ if (opts.origin) {
15805
+ if (opts.protocolVersion < 13) {
15806
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
15807
+ } else {
15808
+ opts.headers.Origin = opts.origin;
15809
+ }
15810
+ }
15811
+ if (parsedUrl.username || parsedUrl.password) {
15812
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
15813
+ }
15814
+ if (isIpcUrl) {
15815
+ const parts = opts.path.split(":");
15816
+ opts.socketPath = parts[0];
15817
+ opts.path = parts[1];
15818
+ }
15819
+ let req;
15820
+ if (opts.followRedirects) {
15821
+ if (websocket._redirects === 0) {
15822
+ websocket._originalIpc = isIpcUrl;
15823
+ websocket._originalSecure = isSecure;
15824
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
15825
+ const headers = options && options.headers;
15826
+ options = { ...options, headers: {} };
15827
+ if (headers) {
15828
+ for (const [key2, value] of Object.entries(headers)) {
15829
+ options.headers[key2.toLowerCase()] = value;
15830
+ }
15831
+ }
15832
+ } else if (websocket.listenerCount("redirect") === 0) {
15833
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
15834
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
15835
+ delete opts.headers.authorization;
15836
+ delete opts.headers.cookie;
15837
+ if (!isSameHost) delete opts.headers.host;
15838
+ opts.auth = void 0;
15839
+ }
15840
+ }
15841
+ if (opts.auth && !options.headers.authorization) {
15842
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
15843
+ }
15844
+ req = websocket._req = request(opts);
15845
+ if (websocket._redirects) {
15846
+ websocket.emit("redirect", websocket.url, req);
15847
+ }
15848
+ } else {
15849
+ req = websocket._req = request(opts);
15850
+ }
15851
+ if (opts.timeout) {
15852
+ req.on("timeout", () => {
15853
+ abortHandshake(websocket, req, "Opening handshake has timed out");
15854
+ });
15855
+ }
15856
+ req.on("error", (err) => {
15857
+ if (req === null || req[kAborted]) return;
15858
+ req = websocket._req = null;
15859
+ emitErrorAndClose(websocket, err);
15860
+ });
15861
+ req.on("response", (res) => {
15862
+ const location = res.headers.location;
15863
+ const statusCode = res.statusCode;
15864
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
15865
+ if (++websocket._redirects > opts.maxRedirects) {
15866
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
15867
+ return;
15868
+ }
15869
+ req.abort();
15870
+ let addr;
15871
+ try {
15872
+ addr = new URL2(location, address);
15873
+ } catch (e) {
15874
+ const err = new SyntaxError(`Invalid URL: ${location}`);
15875
+ emitErrorAndClose(websocket, err);
15876
+ return;
15877
+ }
15878
+ initAsClient(websocket, addr, protocols, options);
15879
+ } else if (!websocket.emit("unexpected-response", req, res)) {
15880
+ abortHandshake(
15881
+ websocket,
15882
+ req,
15883
+ `Unexpected server response: ${res.statusCode}`
15884
+ );
15885
+ }
15886
+ });
15887
+ req.on("upgrade", (res, socket, head) => {
15888
+ websocket.emit("upgrade", res);
15889
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
15890
+ req = websocket._req = null;
15891
+ const upgrade = res.headers.upgrade;
15892
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
15893
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
15894
+ return;
15895
+ }
15896
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
15897
+ if (res.headers["sec-websocket-accept"] !== digest) {
15898
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
15899
+ return;
15900
+ }
15901
+ const serverProt = res.headers["sec-websocket-protocol"];
15902
+ let protError;
15903
+ if (serverProt !== void 0) {
15904
+ if (!protocolSet.size) {
15905
+ protError = "Server sent a subprotocol but none was requested";
15906
+ } else if (!protocolSet.has(serverProt)) {
15907
+ protError = "Server sent an invalid subprotocol";
15908
+ }
15909
+ } else if (protocolSet.size) {
15910
+ protError = "Server sent no subprotocol";
15911
+ }
15912
+ if (protError) {
15913
+ abortHandshake(websocket, socket, protError);
15914
+ return;
15915
+ }
15916
+ if (serverProt) websocket._protocol = serverProt;
15917
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
15918
+ if (secWebSocketExtensions !== void 0) {
15919
+ if (!perMessageDeflate) {
15920
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
15921
+ abortHandshake(websocket, socket, message);
15922
+ return;
15923
+ }
15924
+ let extensions;
15925
+ try {
15926
+ extensions = parse3(secWebSocketExtensions);
15927
+ } catch (err) {
15928
+ const message = "Invalid Sec-WebSocket-Extensions header";
15929
+ abortHandshake(websocket, socket, message);
15930
+ return;
15931
+ }
15932
+ const extensionNames = Object.keys(extensions);
15933
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
15934
+ const message = "Server indicated an extension that was not requested";
15935
+ abortHandshake(websocket, socket, message);
15936
+ return;
15937
+ }
15938
+ try {
15939
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
15940
+ } catch (err) {
15941
+ const message = "Invalid Sec-WebSocket-Extensions header";
15942
+ abortHandshake(websocket, socket, message);
15943
+ return;
15944
+ }
15945
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
15946
+ }
15947
+ websocket.setSocket(socket, head, {
15948
+ allowSynchronousEvents: opts.allowSynchronousEvents,
15949
+ generateMask: opts.generateMask,
15950
+ maxBufferedChunks: opts.maxBufferedChunks,
15951
+ maxFragments: opts.maxFragments,
15952
+ maxPayload: opts.maxPayload,
15953
+ skipUTF8Validation: opts.skipUTF8Validation
15954
+ });
15955
+ });
15956
+ if (opts.finishRequest) {
15957
+ opts.finishRequest(req, websocket);
15958
+ } else {
15959
+ req.end();
15960
+ }
15961
+ }
15962
+ function emitErrorAndClose(websocket, err) {
15963
+ websocket._readyState = WebSocket2.CLOSING;
15964
+ websocket._errorEmitted = true;
15965
+ websocket.emit("error", err);
15966
+ websocket.emitClose();
15967
+ }
15968
+ function netConnect(options) {
15969
+ options.path = options.socketPath;
15970
+ return net.connect(options);
15971
+ }
15972
+ function tlsConnect(options) {
15973
+ options.path = void 0;
15974
+ if (!options.servername && options.servername !== "") {
15975
+ options.servername = net.isIP(options.host) ? "" : options.host;
15976
+ }
15977
+ return tls.connect(options);
15978
+ }
15979
+ function abortHandshake(websocket, stream, message) {
15980
+ websocket._readyState = WebSocket2.CLOSING;
15981
+ const err = new Error(message);
15982
+ Error.captureStackTrace(err, abortHandshake);
15983
+ if (stream.setHeader) {
15984
+ stream[kAborted] = true;
15985
+ stream.abort();
15986
+ if (stream.socket && !stream.socket.destroyed) {
15987
+ stream.socket.destroy();
15988
+ }
15989
+ process.nextTick(emitErrorAndClose, websocket, err);
15990
+ } else {
15991
+ stream.destroy(err);
15992
+ stream.once("error", websocket.emit.bind(websocket, "error"));
15993
+ stream.once("close", websocket.emitClose.bind(websocket));
15994
+ }
15995
+ }
15996
+ function sendAfterClose(websocket, data, cb) {
15997
+ if (data) {
15998
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
15999
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
16000
+ else websocket._bufferedAmount += length;
16001
+ }
16002
+ if (cb) {
16003
+ const err = new Error(
16004
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
16005
+ );
16006
+ process.nextTick(cb, err);
16007
+ }
16008
+ }
16009
+ function receiverOnConclude(code, reason) {
16010
+ const websocket = this[kWebSocket];
16011
+ websocket._closeFrameReceived = true;
16012
+ websocket._closeMessage = reason;
16013
+ websocket._closeCode = code;
16014
+ if (websocket._socket[kWebSocket] === void 0) return;
16015
+ websocket._socket.removeListener("data", socketOnData);
16016
+ process.nextTick(resume, websocket._socket);
16017
+ if (code === 1005) websocket.close();
16018
+ else websocket.close(code, reason);
16019
+ }
16020
+ function receiverOnDrain() {
16021
+ const websocket = this[kWebSocket];
16022
+ if (!websocket.isPaused) websocket._socket.resume();
16023
+ }
16024
+ function receiverOnError(err) {
16025
+ const websocket = this[kWebSocket];
16026
+ if (websocket._socket[kWebSocket] !== void 0) {
16027
+ websocket._socket.removeListener("data", socketOnData);
16028
+ process.nextTick(resume, websocket._socket);
16029
+ websocket.close(err[kStatusCode]);
16030
+ }
16031
+ if (!websocket._errorEmitted) {
16032
+ websocket._errorEmitted = true;
16033
+ websocket.emit("error", err);
16034
+ }
16035
+ }
16036
+ function receiverOnFinish() {
16037
+ this[kWebSocket].emitClose();
16038
+ }
16039
+ function receiverOnMessage(data, isBinary) {
16040
+ this[kWebSocket].emit("message", data, isBinary);
16041
+ }
16042
+ function receiverOnPing(data) {
16043
+ const websocket = this[kWebSocket];
16044
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
16045
+ websocket.emit("ping", data);
16046
+ }
16047
+ function receiverOnPong(data) {
16048
+ this[kWebSocket].emit("pong", data);
16049
+ }
16050
+ function resume(stream) {
16051
+ stream.resume();
16052
+ }
16053
+ function senderOnError(err) {
16054
+ const websocket = this[kWebSocket];
16055
+ if (websocket.readyState === WebSocket2.CLOSED) return;
16056
+ if (websocket.readyState === WebSocket2.OPEN) {
16057
+ websocket._readyState = WebSocket2.CLOSING;
16058
+ setCloseTimer(websocket);
16059
+ }
16060
+ this._socket.end();
16061
+ if (!websocket._errorEmitted) {
16062
+ websocket._errorEmitted = true;
16063
+ websocket.emit("error", err);
16064
+ }
16065
+ }
16066
+ function setCloseTimer(websocket) {
16067
+ websocket._closeTimer = setTimeout(
16068
+ websocket._socket.destroy.bind(websocket._socket),
16069
+ websocket._closeTimeout
16070
+ );
16071
+ }
16072
+ function socketOnClose() {
16073
+ const websocket = this[kWebSocket];
16074
+ this.removeListener("close", socketOnClose);
16075
+ this.removeListener("data", socketOnData);
16076
+ this.removeListener("end", socketOnEnd);
16077
+ websocket._readyState = WebSocket2.CLOSING;
16078
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
16079
+ const chunk = this.read(this._readableState.length);
16080
+ websocket._receiver.write(chunk);
16081
+ }
16082
+ websocket._receiver.end();
16083
+ this[kWebSocket] = void 0;
16084
+ clearTimeout(websocket._closeTimer);
16085
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
16086
+ websocket.emitClose();
16087
+ } else {
16088
+ websocket._receiver.on("error", receiverOnFinish);
16089
+ websocket._receiver.on("finish", receiverOnFinish);
16090
+ }
16091
+ }
16092
+ function socketOnData(chunk) {
16093
+ if (!this[kWebSocket]._receiver.write(chunk)) {
16094
+ this.pause();
16095
+ }
16096
+ }
16097
+ function socketOnEnd() {
16098
+ const websocket = this[kWebSocket];
16099
+ websocket._readyState = WebSocket2.CLOSING;
16100
+ websocket._receiver.end();
16101
+ this.end();
16102
+ }
16103
+ function socketOnError() {
16104
+ const websocket = this[kWebSocket];
16105
+ this.removeListener("error", socketOnError);
16106
+ this.on("error", NOOP);
16107
+ if (websocket) {
16108
+ websocket._readyState = WebSocket2.CLOSING;
16109
+ this.destroy();
16110
+ }
16111
+ }
16112
+ }
16113
+ });
16114
+
16115
+ // node_modules/ws/lib/stream.js
16116
+ var require_stream = __commonJS({
16117
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
16118
+ "use strict";
16119
+ var WebSocket2 = require_websocket();
16120
+ var { Duplex } = require("stream");
16121
+ function emitClose(stream) {
16122
+ stream.emit("close");
16123
+ }
16124
+ function duplexOnEnd() {
16125
+ if (!this.destroyed && this._writableState.finished) {
16126
+ this.destroy();
16127
+ }
16128
+ }
16129
+ function duplexOnError(err) {
16130
+ this.removeListener("error", duplexOnError);
16131
+ this.destroy();
16132
+ if (this.listenerCount("error") === 0) {
16133
+ this.emit("error", err);
16134
+ }
16135
+ }
16136
+ function createWebSocketStream2(ws, options) {
16137
+ let terminateOnDestroy = true;
16138
+ const duplex = new Duplex({
16139
+ ...options,
16140
+ autoDestroy: false,
16141
+ emitClose: false,
16142
+ objectMode: false,
16143
+ writableObjectMode: false
16144
+ });
16145
+ ws.on("message", function message(msg, isBinary) {
16146
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
16147
+ if (!duplex.push(data)) ws.pause();
16148
+ });
16149
+ ws.once("error", function error51(err) {
16150
+ if (duplex.destroyed) return;
16151
+ terminateOnDestroy = false;
16152
+ duplex.destroy(err);
16153
+ });
16154
+ ws.once("close", function close() {
16155
+ if (duplex.destroyed) return;
16156
+ duplex.push(null);
16157
+ });
16158
+ duplex._destroy = function(err, callback) {
16159
+ if (ws.readyState === ws.CLOSED) {
16160
+ callback(err);
16161
+ process.nextTick(emitClose, duplex);
16162
+ return;
16163
+ }
16164
+ let called = false;
16165
+ ws.once("error", function error51(err2) {
16166
+ called = true;
16167
+ callback(err2);
16168
+ });
16169
+ ws.once("close", function close() {
16170
+ if (!called) callback(err);
16171
+ process.nextTick(emitClose, duplex);
16172
+ });
16173
+ if (terminateOnDestroy) ws.terminate();
16174
+ };
16175
+ duplex._final = function(callback) {
16176
+ if (ws.readyState === ws.CONNECTING) {
16177
+ ws.once("open", function open() {
16178
+ duplex._final(callback);
16179
+ });
16180
+ return;
16181
+ }
16182
+ if (ws._socket === null) return;
16183
+ if (ws._socket._writableState.finished) {
16184
+ callback();
16185
+ if (duplex._readableState.endEmitted) duplex.destroy();
16186
+ } else {
16187
+ ws._socket.once("finish", function finish() {
16188
+ callback();
16189
+ });
16190
+ ws.close();
16191
+ }
16192
+ };
16193
+ duplex._read = function() {
16194
+ if (ws.isPaused) ws.resume();
16195
+ };
16196
+ duplex._write = function(chunk, encoding, callback) {
16197
+ if (ws.readyState === ws.CONNECTING) {
16198
+ ws.once("open", function open() {
16199
+ duplex._write(chunk, encoding, callback);
16200
+ });
16201
+ return;
16202
+ }
16203
+ ws.send(chunk, callback);
16204
+ };
16205
+ duplex.on("end", duplexOnEnd);
16206
+ duplex.on("error", duplexOnError);
16207
+ return duplex;
16208
+ }
16209
+ module2.exports = createWebSocketStream2;
16210
+ }
16211
+ });
16212
+
16213
+ // node_modules/ws/lib/subprotocol.js
16214
+ var require_subprotocol = __commonJS({
16215
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
16216
+ "use strict";
16217
+ var { tokenChars } = require_validation3();
16218
+ function parse3(header) {
16219
+ const protocols = /* @__PURE__ */ new Set();
16220
+ let start = -1;
16221
+ let end = -1;
16222
+ let i = 0;
16223
+ for (i; i < header.length; i++) {
16224
+ const code = header.charCodeAt(i);
16225
+ if (end === -1 && tokenChars[code] === 1) {
16226
+ if (start === -1) start = i;
16227
+ } else if (i !== 0 && (code === 32 || code === 9)) {
16228
+ if (end === -1 && start !== -1) end = i;
16229
+ } else if (code === 44) {
16230
+ if (start === -1) {
16231
+ throw new SyntaxError(`Unexpected character at index ${i}`);
16232
+ }
16233
+ if (end === -1) end = i;
16234
+ const protocol2 = header.slice(start, end);
16235
+ if (protocols.has(protocol2)) {
16236
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
16237
+ }
16238
+ protocols.add(protocol2);
16239
+ start = end = -1;
16240
+ } else {
16241
+ throw new SyntaxError(`Unexpected character at index ${i}`);
16242
+ }
16243
+ }
16244
+ if (start === -1 || end !== -1) {
16245
+ throw new SyntaxError("Unexpected end of input");
16246
+ }
16247
+ const protocol = header.slice(start, i);
16248
+ if (protocols.has(protocol)) {
16249
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
16250
+ }
16251
+ protocols.add(protocol);
16252
+ return protocols;
16253
+ }
16254
+ module2.exports = { parse: parse3 };
16255
+ }
16256
+ });
16257
+
16258
+ // node_modules/ws/lib/websocket-server.js
16259
+ var require_websocket_server = __commonJS({
16260
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
16261
+ "use strict";
16262
+ var EventEmitter = require("events");
16263
+ var http2 = require("http");
16264
+ var { Duplex } = require("stream");
16265
+ var { createHash } = require("crypto");
16266
+ var extension2 = require_extension();
16267
+ var PerMessageDeflate2 = require_permessage_deflate();
16268
+ var subprotocol2 = require_subprotocol();
16269
+ var WebSocket2 = require_websocket();
16270
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
16271
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
16272
+ var RUNNING = 0;
16273
+ var CLOSING = 1;
16274
+ var CLOSED = 2;
16275
+ var WebSocketServer2 = class extends EventEmitter {
16276
+ /**
16277
+ * Create a `WebSocketServer` instance.
16278
+ *
16279
+ * @param {Object} options Configuration options
16280
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
16281
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
16282
+ * multiple times in the same tick
16283
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
16284
+ * automatically send a pong in response to a ping
16285
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
16286
+ * pending connections
16287
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
16288
+ * track clients
16289
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
16290
+ * wait for the closing handshake to finish after `websocket.close()` is
16291
+ * called
16292
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
16293
+ * @param {String} [options.host] The hostname where to bind the server
16294
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
16295
+ * buffered data chunks
16296
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
16297
+ * fragments
16298
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
16299
+ * size
16300
+ * @param {Boolean} [options.noServer=false] Enable no server mode
16301
+ * @param {String} [options.path] Accept only connections matching this path
16302
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
16303
+ * permessage-deflate
16304
+ * @param {Number} [options.port] The port where to bind the server
16305
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
16306
+ * server to use
16307
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
16308
+ * not to skip UTF-8 validation for text and close messages
16309
+ * @param {Function} [options.verifyClient] A hook to reject connections
16310
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
16311
+ * class to use. It must be the `WebSocket` class or class that extends it
16312
+ * @param {Function} [callback] A listener for the `listening` event
16313
+ */
16314
+ constructor(options, callback) {
16315
+ super();
16316
+ options = {
16317
+ allowSynchronousEvents: true,
16318
+ autoPong: true,
16319
+ maxBufferedChunks: 256 * 1024,
16320
+ maxFragments: 16 * 1024,
16321
+ maxPayload: 100 * 1024 * 1024,
16322
+ skipUTF8Validation: false,
16323
+ perMessageDeflate: false,
16324
+ handleProtocols: null,
16325
+ clientTracking: true,
16326
+ closeTimeout: CLOSE_TIMEOUT,
16327
+ verifyClient: null,
16328
+ noServer: false,
16329
+ backlog: null,
16330
+ // use default (511 as implemented in net.js)
16331
+ server: null,
16332
+ host: null,
16333
+ path: null,
16334
+ port: null,
16335
+ WebSocket: WebSocket2,
16336
+ ...options
16337
+ };
16338
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
16339
+ throw new TypeError(
16340
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
16341
+ );
16342
+ }
16343
+ if (options.port != null) {
16344
+ this._server = http2.createServer((req, res) => {
16345
+ const body = http2.STATUS_CODES[426];
16346
+ res.writeHead(426, {
16347
+ "Content-Length": body.length,
16348
+ "Content-Type": "text/plain"
16349
+ });
16350
+ res.end(body);
16351
+ });
16352
+ this._server.listen(
16353
+ options.port,
16354
+ options.host,
16355
+ options.backlog,
16356
+ callback
16357
+ );
16358
+ } else if (options.server) {
16359
+ this._server = options.server;
16360
+ }
16361
+ if (this._server) {
16362
+ const emitConnection = this.emit.bind(this, "connection");
16363
+ this._removeListeners = addListeners(this._server, {
16364
+ listening: this.emit.bind(this, "listening"),
16365
+ error: this.emit.bind(this, "error"),
16366
+ upgrade: (req, socket, head) => {
16367
+ this.handleUpgrade(req, socket, head, emitConnection);
16368
+ }
16369
+ });
16370
+ }
16371
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
16372
+ if (options.clientTracking) {
16373
+ this.clients = /* @__PURE__ */ new Set();
16374
+ this._shouldEmitClose = false;
16375
+ }
16376
+ this.options = options;
16377
+ this._state = RUNNING;
16378
+ }
16379
+ /**
16380
+ * Returns the bound address, the address family name, and port of the server
16381
+ * as reported by the operating system if listening on an IP socket.
16382
+ * If the server is listening on a pipe or UNIX domain socket, the name is
16383
+ * returned as a string.
16384
+ *
16385
+ * @return {(Object|String|null)} The address of the server
16386
+ * @public
16387
+ */
16388
+ address() {
16389
+ if (this.options.noServer) {
16390
+ throw new Error('The server is operating in "noServer" mode');
16391
+ }
16392
+ if (!this._server) return null;
16393
+ return this._server.address();
16394
+ }
16395
+ /**
16396
+ * Stop the server from accepting new connections and emit the `'close'` event
16397
+ * when all existing connections are closed.
16398
+ *
16399
+ * @param {Function} [cb] A one-time listener for the `'close'` event
16400
+ * @public
16401
+ */
16402
+ close(cb) {
16403
+ if (this._state === CLOSED) {
16404
+ if (cb) {
16405
+ this.once("close", () => {
16406
+ cb(new Error("The server is not running"));
16407
+ });
16408
+ }
16409
+ process.nextTick(emitClose, this);
16410
+ return;
16411
+ }
16412
+ if (cb) this.once("close", cb);
16413
+ if (this._state === CLOSING) return;
16414
+ this._state = CLOSING;
16415
+ if (this.options.noServer || this.options.server) {
16416
+ if (this._server) {
16417
+ this._removeListeners();
16418
+ this._removeListeners = this._server = null;
16419
+ }
16420
+ if (this.clients) {
16421
+ if (!this.clients.size) {
16422
+ process.nextTick(emitClose, this);
16423
+ } else {
16424
+ this._shouldEmitClose = true;
16425
+ }
16426
+ } else {
16427
+ process.nextTick(emitClose, this);
16428
+ }
16429
+ } else {
16430
+ const server = this._server;
16431
+ this._removeListeners();
16432
+ this._removeListeners = this._server = null;
16433
+ server.close(() => {
16434
+ emitClose(this);
16435
+ });
16436
+ }
16437
+ }
16438
+ /**
16439
+ * See if a given request should be handled by this server instance.
16440
+ *
16441
+ * @param {http.IncomingMessage} req Request object to inspect
16442
+ * @return {Boolean} `true` if the request is valid, else `false`
16443
+ * @public
16444
+ */
16445
+ shouldHandle(req) {
16446
+ if (this.options.path) {
16447
+ const index = req.url.indexOf("?");
16448
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
16449
+ if (pathname !== this.options.path) return false;
16450
+ }
16451
+ return true;
16452
+ }
16453
+ /**
16454
+ * Handle a HTTP Upgrade request.
16455
+ *
16456
+ * @param {http.IncomingMessage} req The request object
16457
+ * @param {Duplex} socket The network socket between the server and client
16458
+ * @param {Buffer} head The first packet of the upgraded stream
16459
+ * @param {Function} cb Callback
16460
+ * @public
16461
+ */
16462
+ handleUpgrade(req, socket, head, cb) {
16463
+ socket.on("error", socketOnError);
16464
+ const key = req.headers["sec-websocket-key"];
16465
+ const upgrade = req.headers.upgrade;
16466
+ const version2 = +req.headers["sec-websocket-version"];
16467
+ if (req.method !== "GET") {
16468
+ const message = "Invalid HTTP method";
16469
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
16470
+ return;
16471
+ }
16472
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
16473
+ const message = "Invalid Upgrade header";
16474
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
16475
+ return;
16476
+ }
16477
+ if (key === void 0 || !keyRegex.test(key)) {
16478
+ const message = "Missing or invalid Sec-WebSocket-Key header";
16479
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
16480
+ return;
16481
+ }
16482
+ if (version2 !== 13 && version2 !== 8) {
16483
+ const message = "Missing or invalid Sec-WebSocket-Version header";
16484
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
16485
+ "Sec-WebSocket-Version": "13, 8"
16486
+ });
16487
+ return;
16488
+ }
16489
+ if (!this.shouldHandle(req)) {
16490
+ abortHandshake(socket, 400);
16491
+ return;
16492
+ }
16493
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
16494
+ let protocols = /* @__PURE__ */ new Set();
16495
+ if (secWebSocketProtocol !== void 0) {
16496
+ try {
16497
+ protocols = subprotocol2.parse(secWebSocketProtocol);
16498
+ } catch (err) {
16499
+ const message = "Invalid Sec-WebSocket-Protocol header";
16500
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
16501
+ return;
16502
+ }
16503
+ }
16504
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
16505
+ const extensions = {};
16506
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
16507
+ const perMessageDeflate = new PerMessageDeflate2({
16508
+ ...this.options.perMessageDeflate,
16509
+ isServer: true,
16510
+ maxPayload: this.options.maxPayload
16511
+ });
16512
+ try {
16513
+ const offers = extension2.parse(secWebSocketExtensions);
16514
+ if (offers[PerMessageDeflate2.extensionName]) {
16515
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
16516
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
16517
+ }
16518
+ } catch (err) {
16519
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
16520
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
16521
+ return;
16522
+ }
16523
+ }
16524
+ if (this.options.verifyClient) {
16525
+ const info = {
16526
+ origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
16527
+ secure: !!(req.socket.authorized || req.socket.encrypted),
16528
+ req
16529
+ };
16530
+ if (this.options.verifyClient.length === 2) {
16531
+ this.options.verifyClient(info, (verified, code, message, headers) => {
16532
+ if (!verified) {
16533
+ return abortHandshake(socket, code || 401, message, headers);
16534
+ }
16535
+ this.completeUpgrade(
16536
+ extensions,
16537
+ key,
16538
+ protocols,
16539
+ req,
16540
+ socket,
16541
+ head,
16542
+ cb
16543
+ );
16544
+ });
16545
+ return;
16546
+ }
16547
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
16548
+ }
16549
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
16550
+ }
16551
+ /**
16552
+ * Upgrade the connection to WebSocket.
16553
+ *
16554
+ * @param {Object} extensions The accepted extensions
16555
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
16556
+ * @param {Set} protocols The subprotocols
16557
+ * @param {http.IncomingMessage} req The request object
16558
+ * @param {Duplex} socket The network socket between the server and client
16559
+ * @param {Buffer} head The first packet of the upgraded stream
16560
+ * @param {Function} cb Callback
16561
+ * @throws {Error} If called more than once with the same socket
16562
+ * @private
16563
+ */
16564
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
16565
+ if (!socket.readable || !socket.writable) return socket.destroy();
16566
+ if (socket[kWebSocket]) {
16567
+ throw new Error(
16568
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
16569
+ );
16570
+ }
16571
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
16572
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
16573
+ const headers = [
16574
+ "HTTP/1.1 101 Switching Protocols",
16575
+ "Upgrade: websocket",
16576
+ "Connection: Upgrade",
16577
+ `Sec-WebSocket-Accept: ${digest}`
16578
+ ];
16579
+ const ws = new this.options.WebSocket(null, void 0, this.options);
16580
+ if (protocols.size) {
16581
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
16582
+ if (protocol) {
16583
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
16584
+ ws._protocol = protocol;
16585
+ }
16586
+ }
16587
+ if (extensions[PerMessageDeflate2.extensionName]) {
16588
+ const params = extensions[PerMessageDeflate2.extensionName].params;
16589
+ const value = extension2.format({
16590
+ [PerMessageDeflate2.extensionName]: [params]
16591
+ });
16592
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
16593
+ ws._extensions = extensions;
16594
+ }
16595
+ this.emit("headers", headers, req);
16596
+ socket.write(headers.concat("\r\n").join("\r\n"));
16597
+ socket.removeListener("error", socketOnError);
16598
+ ws.setSocket(socket, head, {
16599
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
16600
+ maxBufferedChunks: this.options.maxBufferedChunks,
16601
+ maxFragments: this.options.maxFragments,
16602
+ maxPayload: this.options.maxPayload,
16603
+ skipUTF8Validation: this.options.skipUTF8Validation
16604
+ });
16605
+ if (this.clients) {
16606
+ this.clients.add(ws);
16607
+ ws.on("close", () => {
16608
+ this.clients.delete(ws);
16609
+ if (this._shouldEmitClose && !this.clients.size) {
16610
+ process.nextTick(emitClose, this);
16611
+ }
16612
+ });
16613
+ }
16614
+ cb(ws, req);
16615
+ }
16616
+ };
16617
+ module2.exports = WebSocketServer2;
16618
+ function addListeners(server, map2) {
16619
+ for (const event of Object.keys(map2)) server.on(event, map2[event]);
16620
+ return function removeListeners() {
16621
+ for (const event of Object.keys(map2)) {
16622
+ server.removeListener(event, map2[event]);
16623
+ }
16624
+ };
16625
+ }
16626
+ function emitClose(server) {
16627
+ server._state = CLOSED;
16628
+ server.emit("close");
16629
+ }
16630
+ function socketOnError() {
16631
+ this.destroy();
16632
+ }
16633
+ function abortHandshake(socket, code, message, headers) {
16634
+ message = message || http2.STATUS_CODES[code];
16635
+ headers = {
16636
+ Connection: "close",
16637
+ "Content-Type": "text/html",
16638
+ "Content-Length": Buffer.byteLength(message),
16639
+ ...headers
16640
+ };
16641
+ socket.once("finish", socket.destroy);
16642
+ socket.end(
16643
+ `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
16644
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
16645
+ );
16646
+ }
16647
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
16648
+ if (server.listenerCount("wsClientError")) {
16649
+ const err = new Error(message);
16650
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
16651
+ server.emit("wsClientError", err, socket, req);
16652
+ } else {
16653
+ abortHandshake(socket, code, message, headers);
16654
+ }
16655
+ }
16656
+ }
16657
+ });
16658
+
12989
16659
  // apps/mcp/src/cli.ts
12990
- var import_node_fs3 = require("node:fs");
12991
- var import_node_os3 = require("node:os");
12992
- var import_node_path5 = require("node:path");
12993
- var import_node_crypto2 = require("node:crypto");
16660
+ var import_node_fs5 = require("node:fs");
16661
+ var import_node_os4 = require("node:os");
16662
+ var import_node_path6 = require("node:path");
16663
+ var import_node_crypto3 = require("node:crypto");
12994
16664
  var import_node_child_process3 = require("node:child_process");
12995
16665
 
12996
16666
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
@@ -29148,10 +32818,29 @@ var StdioServerTransport = class {
29148
32818
  };
29149
32819
 
29150
32820
  // apps/mcp/src/daemon.ts
32821
+ var import_node_fs = require("node:fs");
29151
32822
  var LABEL_MAC = "vn.hocai.connect";
29152
32823
  var TASK_NAME = "hocai-connect";
32824
+ function logPathFor(home) {
32825
+ return `${home}/.hocai/log/connect.log`;
32826
+ }
32827
+ function cutLogIfBig(file2, maxBytes = 1e6) {
32828
+ try {
32829
+ const { size } = (0, import_node_fs.statSync)(file2);
32830
+ if (size <= maxBytes) return;
32831
+ const fd = (0, import_node_fs.openSync)(file2, "r");
32832
+ try {
32833
+ const buf = Buffer.alloc(maxBytes);
32834
+ const doc = (0, import_node_fs.readSync)(fd, buf, 0, maxBytes, size - maxBytes);
32835
+ (0, import_node_fs.writeFileSync)(file2, buf.subarray(0, doc));
32836
+ } finally {
32837
+ (0, import_node_fs.closeSync)(fd);
32838
+ }
32839
+ } catch {
32840
+ }
32841
+ }
29153
32842
  function daemonPlan(platform2, o) {
29154
- const log = `${o.home}/.hocai/log/connect.log`;
32843
+ const log = logPathFor(o.home);
29155
32844
  if (platform2 === "darwin") {
29156
32845
  return {
29157
32846
  label: LABEL_MAC,
@@ -37480,7 +41169,7 @@ function buildServer(token) {
37480
41169
  }
37481
41170
 
37482
41171
  // apps/mcp/src/http.ts
37483
- var import_node_fs2 = require("node:fs");
41172
+ var import_node_fs3 = require("node:fs");
37484
41173
  var import_node_http = __toESM(require("node:http"));
37485
41174
  var import_node_child_process2 = require("node:child_process");
37486
41175
 
@@ -39537,7 +43226,7 @@ var import_node_path3 = require("node:path");
39537
43226
 
39538
43227
  // apps/mcp/src/job.ts
39539
43228
  var import_node_crypto = require("node:crypto");
39540
- var import_node_fs = require("node:fs");
43229
+ var import_node_fs2 = require("node:fs");
39541
43230
  var import_node_path2 = require("node:path");
39542
43231
  var MAX_RUNNING = 3;
39543
43232
  var TIMEOUT_MS = 15 * 60 * 1e3;
@@ -39546,7 +43235,7 @@ var XONG = /* @__PURE__ */ new Set(["DONE", "FAILED", "STOPPED"]);
39546
43235
  function createJobStore(o) {
39547
43236
  const maxRunning = o.maxRunning ?? MAX_RUNNING;
39548
43237
  const timeoutMs = o.timeoutMs ?? TIMEOUT_MS;
39549
- (0, import_node_fs.mkdirSync)(o.dir, { recursive: true });
43238
+ (0, import_node_fs2.mkdirSync)(o.dir, { recursive: true });
39550
43239
  const jobs = /* @__PURE__ */ new Map();
39551
43240
  const handles = /* @__PURE__ */ new Map();
39552
43241
  const listeners = /* @__PURE__ */ new Map();
@@ -39554,7 +43243,7 @@ function createJobStore(o) {
39554
43243
  const file2 = (id) => (0, import_node_path2.join)(o.dir, `${id}.jsonl`);
39555
43244
  const push = (id, line) => {
39556
43245
  try {
39557
- (0, import_node_fs.appendFileSync)(file2(id), line + "\n");
43246
+ (0, import_node_fs2.appendFileSync)(file2(id), line + "\n");
39558
43247
  } catch {
39559
43248
  }
39560
43249
  for (const fn of listeners.get(id) ?? []) fn(line);
@@ -39616,7 +43305,7 @@ function createJobStore(o) {
39616
43305
  startedAt: Date.now()
39617
43306
  };
39618
43307
  jobs.set(job.id, job);
39619
- (0, import_node_fs.writeFileSync)(file2(job.id), JSON.stringify(job) + "\n");
43308
+ (0, import_node_fs2.writeFileSync)(file2(job.id), JSON.stringify(job) + "\n");
39620
43309
  if (dangChay() < maxRunning) start(job);
39621
43310
  else queue.push(job.id);
39622
43311
  return job;
@@ -39734,7 +43423,7 @@ var TOOLS = {
39734
43423
  ],
39735
43424
  WORK: ["Read", "Write", "Edit", "Glob", "Grep"]
39736
43425
  };
39737
- var VERSION = "0.13.0";
43426
+ var VERSION = "0.14.0";
39738
43427
  function claudeArgs(job, o, port) {
39739
43428
  const mcp = {
39740
43429
  mcpServers: {
@@ -39768,7 +43457,7 @@ function claudeArgs(job, o, port) {
39768
43457
  function buildHttpServer(o) {
39769
43458
  const spawn2 = o.spawn ?? import_node_child_process2.spawn;
39770
43459
  const dangChay = /* @__PURE__ */ new Set();
39771
- const thuMucDaChon = /* @__PURE__ */ new Set();
43460
+ const folders = o.folders;
39772
43461
  const json3 = (res, code, body) => {
39773
43462
  if (!res.headersSent) res.writeHead(code, { "content-type": "application/json" });
39774
43463
  res.end(JSON.stringify(body));
@@ -39883,7 +43572,7 @@ function buildHttpServer(o) {
39883
43572
  json3(res, 400, { error: "Th\u01B0 m\u1EE5c kh\xF4ng h\u1EE3p l\u1EC7" });
39884
43573
  return;
39885
43574
  }
39886
- if (!thuMucDaChon.has(d)) {
43575
+ if (!folders.has(d)) {
39887
43576
  json3(res, 403, {
39888
43577
  error: "H\xE3y b\u1EA5m ch\u1ECDn th\u01B0 m\u1EE5c tr\u01B0\u1EDBc \u2014 m\xE1y ch\u1EC9 ch\u1EA1y trong th\u01B0 m\u1EE5c b\u1EA1n t\u1EF1 ch\u1ECDn."
39889
43578
  });
@@ -39895,7 +43584,7 @@ function buildHttpServer(o) {
39895
43584
  json3(res, 409, { error: "Ch\u1ED7 n\xE0y \u0111ang c\xF3 m\u1ED9t l\u01B0\u1EE3t ch\u1EA1y \u2014 ch\u1EDD n\xF3 xong \u0111\xE3" });
39896
43585
  return;
39897
43586
  }
39898
- (0, import_node_fs2.mkdirSync)(dir, { recursive: true });
43587
+ (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
39899
43588
  const job = store.create({
39900
43589
  kind: i.kind,
39901
43590
  dir,
@@ -39955,8 +43644,8 @@ function buildHttpServer(o) {
39955
43644
  }
39956
43645
  const mo = o.chooseFolder ?? chooseFolder;
39957
43646
  void mo().then((dir) => {
39958
- if (dir) thuMucDaChon.add(dir);
39959
- json3(res, 200, { dir });
43647
+ const entry = dir ? folders.remember(dir) : null;
43648
+ json3(res, 200, { dir, folder: entry });
39960
43649
  }).catch((e) => json3(res, 500, { error: e.message }));
39961
43650
  return;
39962
43651
  }
@@ -40074,7 +43763,7 @@ data: ${JSON.stringify({ status: job.status })}
40074
43763
  res.writeHead(404).end("kh\xF4ng c\xF3 \u0111\u01B0\u1EDDng n\xE0y");
40075
43764
  });
40076
43765
  srv.store = store;
40077
- return srv;
43766
+ return Object.assign(srv, { store });
40078
43767
  }
40079
43768
 
40080
43769
  // apps/mcp/src/connect.ts
@@ -40278,34 +43967,217 @@ function defaultOrigins(env) {
40278
43967
  ];
40279
43968
  }
40280
43969
 
43970
+ // apps/mcp/src/folder-registry.ts
43971
+ var import_node_fs4 = require("node:fs");
43972
+ var import_node_os3 = require("node:os");
43973
+ var import_node_crypto2 = require("node:crypto");
43974
+ var import_node_path5 = require("node:path");
43975
+ var MAC_DINH = (0, import_node_path5.join)((0, import_node_os3.homedir)(), ".hocai", "folders.json");
43976
+ function createFolderRegistry(o = {}) {
43977
+ if (!o.file && process.env.VITEST) {
43978
+ throw new Error(
43979
+ "createFolderRegistry() trong test ph\u1EA3i truy\u1EC1n `file` \u2014 n\u1EBFu kh\xF4ng n\xF3 ghi v\xE0o ~/.hocai/folders.json th\u1EADt."
43980
+ );
43981
+ }
43982
+ const file2 = o.file ?? MAC_DINH;
43983
+ const rows = /* @__PURE__ */ new Map();
43984
+ const { rows: daNap, daLoai } = nap(file2);
43985
+ for (const r of daNap) rows.set(r.id, r);
43986
+ if (daLoai) ghi(file2, rows);
43987
+ const ra = (r) => ({ id: r.id, label: r.label, createdAt: r.createdAt });
43988
+ return {
43989
+ remember(path) {
43990
+ for (const r of rows.values()) if (r.path === path) return ra(r);
43991
+ const row = {
43992
+ id: `f_${(0, import_node_crypto2.randomUUID)().slice(0, 8)}`,
43993
+ label: (0, import_node_path5.basename)(path),
43994
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
43995
+ path
43996
+ };
43997
+ rows.set(row.id, row);
43998
+ ghi(file2, rows);
43999
+ return ra(row);
44000
+ },
44001
+ pathOf: (id) => rows.get(id)?.path ?? null,
44002
+ has: (path) => [...rows.values()].some((r) => r.path === path),
44003
+ list: () => [...rows.values()].map(ra),
44004
+ forget(id) {
44005
+ if (!rows.delete(id)) return false;
44006
+ ghi(file2, rows);
44007
+ return true;
44008
+ }
44009
+ };
44010
+ }
44011
+ function nap(file2) {
44012
+ let raw;
44013
+ try {
44014
+ raw = (0, import_node_fs4.readFileSync)(file2, "utf8");
44015
+ } catch {
44016
+ return { rows: [], daLoai: false };
44017
+ }
44018
+ let data;
44019
+ try {
44020
+ data = JSON.parse(raw);
44021
+ } catch {
44022
+ return { rows: [], daLoai: false };
44023
+ }
44024
+ if (!Array.isArray(data)) return { rows: [], daLoai: false };
44025
+ const giu = data.filter(
44026
+ (r) => !!r && typeof r.id === "string" && typeof r.path === "string" && typeof r.label === "string" && typeof r.createdAt === "string" && (0, import_node_fs4.existsSync)(r.path)
44027
+ );
44028
+ return { rows: giu, daLoai: giu.length !== data.length };
44029
+ }
44030
+ function ghi(file2, rows) {
44031
+ (0, import_node_fs4.mkdirSync)((0, import_node_path5.dirname)(file2), { recursive: true, mode: 448 });
44032
+ (0, import_node_fs4.writeFileSync)(file2, JSON.stringify([...rows.values()], null, 2), { mode: 384 });
44033
+ }
44034
+
44035
+ // node_modules/ws/wrapper.mjs
44036
+ var import_stream = __toESM(require_stream(), 1);
44037
+ var import_extension = __toESM(require_extension(), 1);
44038
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
44039
+ var import_receiver = __toESM(require_receiver(), 1);
44040
+ var import_sender = __toESM(require_sender(), 1);
44041
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
44042
+ var import_websocket = __toESM(require_websocket(), 1);
44043
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
44044
+ var wrapper_default = import_websocket.default;
44045
+
44046
+ // apps/mcp/src/uplink.ts
44047
+ var BACKOFF_MS = 1e3;
44048
+ var MAX_BACKOFF_MS = 3e4;
44049
+ var SILENCE_MS = 6e4;
44050
+ var CONNECT_TIMEOUT_MS = 15e3;
44051
+ function createUplink(o) {
44052
+ const Impl = o.WebSocketImpl ?? wrapper_default;
44053
+ const day = o.backoffMs ?? BACKOFF_MS;
44054
+ const tran = o.maxBackoffMs ?? MAX_BACKOFF_MS;
44055
+ let ws = null;
44056
+ let cho = null;
44057
+ let canh = null;
44058
+ let doi = day;
44059
+ let dungHan = false;
44060
+ function hen() {
44061
+ if (dungHan) return;
44062
+ const cho_ms = Math.min(doi, tran) * (0.5 + Math.random());
44063
+ doi = Math.min(doi * 2, tran);
44064
+ cho = setTimeout(noi, cho_ms);
44065
+ }
44066
+ function noi() {
44067
+ if (dungHan) return;
44068
+ const s = new Impl(o.url, { headers: { authorization: `Bearer ${o.token}` } });
44069
+ ws = s;
44070
+ const hanBatTay = setTimeout(() => s.terminate(), o.connectTimeoutMs ?? CONNECT_TIMEOUT_MS);
44071
+ s.on("open", () => {
44072
+ clearTimeout(hanBatTay);
44073
+ doi = day;
44074
+ s.send(JSON.stringify(o.hello()));
44075
+ canhIm();
44076
+ });
44077
+ s.on("message", (raw) => {
44078
+ canhIm();
44079
+ let msg;
44080
+ try {
44081
+ msg = JSON.parse(String(raw));
44082
+ } catch {
44083
+ return;
44084
+ }
44085
+ o.onMessage(msg);
44086
+ });
44087
+ s.on("error", () => {
44088
+ });
44089
+ s.on("close", () => {
44090
+ clearTimeout(hanBatTay);
44091
+ if (canh) clearTimeout(canh);
44092
+ ws = null;
44093
+ hen();
44094
+ });
44095
+ function canhIm() {
44096
+ if (canh) clearTimeout(canh);
44097
+ canh = setTimeout(() => s.terminate(), o.silenceMs ?? SILENCE_MS);
44098
+ }
44099
+ }
44100
+ return {
44101
+ start() {
44102
+ dungHan = false;
44103
+ noi();
44104
+ },
44105
+ stop() {
44106
+ dungHan = true;
44107
+ if (cho) clearTimeout(cho);
44108
+ if (canh) clearTimeout(canh);
44109
+ cho = null;
44110
+ canh = null;
44111
+ ws?.close();
44112
+ ws = null;
44113
+ },
44114
+ send(msg) {
44115
+ if (ws?.readyState === Impl.OPEN) ws.send(JSON.stringify(msg));
44116
+ }
44117
+ };
44118
+ }
44119
+
44120
+ // apps/mcp/src/remote-jobs.ts
44121
+ var cucBoCua = /* @__PURE__ */ new Map();
44122
+ function handleServerMessage(msg, deps) {
44123
+ const jobId = typeof msg.jobId === "string" ? msg.jobId : null;
44124
+ if (msg.t === "run") {
44125
+ if (!jobId) return;
44126
+ const folderId = typeof msg.folderId === "string" ? msg.folderId : "";
44127
+ const prompt = typeof msg.prompt === "string" ? msg.prompt : "";
44128
+ const dir = deps.folders.pathOf(folderId);
44129
+ if (!dir) {
44130
+ deps.send({
44131
+ t: "done",
44132
+ jobId,
44133
+ status: "FAILED",
44134
+ errorCode: "THU_MUC_KHONG_CHO_PHEP"
44135
+ });
44136
+ return;
44137
+ }
44138
+ const job = deps.store.create({ kind: "WORK", dir, prompt });
44139
+ cucBoCua.set(jobId, job.id);
44140
+ deps.store.onEvent(job.id, (line) => deps.send({ t: "log", jobId, line }));
44141
+ return;
44142
+ }
44143
+ if (msg.t === "stop") {
44144
+ if (!jobId) return;
44145
+ const cucBo = cucBoCua.get(jobId);
44146
+ if (!cucBo) return;
44147
+ deps.store.stop(cucBo);
44148
+ cucBoCua.delete(jobId);
44149
+ return;
44150
+ }
44151
+ }
44152
+
40281
44153
  // apps/mcp/src/cli.ts
40282
- var HOCAI_DIR = (0, import_node_path5.join)((0, import_node_os3.homedir)(), ".hocai");
40283
- var CREDS = (0, import_node_path5.join)(HOCAI_DIR, "config.json");
40284
- var APP_DIR = (0, import_node_path5.join)(HOCAI_DIR, "app");
40285
- var APP_CLI = (0, import_node_path5.join)(APP_DIR, "cli.js");
40286
- var LOG_DIR = (0, import_node_path5.join)(HOCAI_DIR, "log");
44154
+ var HOCAI_DIR = (0, import_node_path6.join)((0, import_node_os4.homedir)(), ".hocai");
44155
+ var CREDS = (0, import_node_path6.join)(HOCAI_DIR, "config.json");
44156
+ var APP_DIR = (0, import_node_path6.join)(HOCAI_DIR, "app");
44157
+ var APP_CLI = (0, import_node_path6.join)(APP_DIR, "cli.js");
44158
+ var LOG_DIR = (0, import_node_path6.join)(HOCAI_DIR, "log");
40287
44159
  var WEB = () => process.env.HOCAI_WEB_URL ?? "https://camerasrent.com";
40288
44160
  var API_DEFAULT = () => process.env.HOCAI_API_URL ?? `${WEB()}/api`;
40289
44161
  var PORT = Number(process.env.MCP_HTTP_PORT ?? 4100);
40290
44162
  var say = (s) => process.stderr.write(s + "\n");
40291
44163
  function loadCreds() {
40292
44164
  try {
40293
- const c = JSON.parse((0, import_node_fs3.readFileSync)(CREDS, "utf8"));
44165
+ const c = JSON.parse((0, import_node_fs5.readFileSync)(CREDS, "utf8"));
40294
44166
  return c.token && c.api ? { token: c.token, api: c.api } : null;
40295
44167
  } catch {
40296
44168
  return null;
40297
44169
  }
40298
44170
  }
40299
44171
  function saveCreds(c) {
40300
- (0, import_node_fs3.mkdirSync)(HOCAI_DIR, { recursive: true, mode: 448 });
40301
- (0, import_node_fs3.writeFileSync)(CREDS, JSON.stringify(c, null, 2));
44172
+ (0, import_node_fs5.mkdirSync)(HOCAI_DIR, { recursive: true, mode: 448 });
44173
+ (0, import_node_fs5.writeFileSync)(CREDS, JSON.stringify(c, null, 2));
40302
44174
  try {
40303
- (0, import_node_fs3.chmodSync)(CREDS, 384);
44175
+ (0, import_node_fs5.chmodSync)(CREDS, 384);
40304
44176
  } catch {
40305
44177
  }
40306
44178
  }
40307
44179
  function openBrowser(url2) {
40308
- const p = (0, import_node_os3.platform)();
44180
+ const p = (0, import_node_os4.platform)();
40309
44181
  const cmd = p === "darwin" ? ["open", url2] : p === "win32" ? ["cmd", "/c", "start", "", url2] : ["xdg-open", url2];
40310
44182
  try {
40311
44183
  (0, import_node_child_process3.spawn)(cmd[0], cmd.slice(1), { stdio: "ignore", detached: true }).unref();
@@ -40313,7 +44185,7 @@ function openBrowser(url2) {
40313
44185
  }
40314
44186
  }
40315
44187
  async function login() {
40316
- const state = (0, import_node_crypto2.randomBytes)(16).toString("hex");
44188
+ const state = (0, import_node_crypto3.randomBytes)(16).toString("hex");
40317
44189
  const l = await listenForToken({ state });
40318
44190
  const cb = `http://127.0.0.1:${l.port}`;
40319
44191
  const url2 = `${WEB()}/ket-noi?callback=${encodeURIComponent(cb)}&state=${state}`;
@@ -40329,22 +44201,22 @@ async function login() {
40329
44201
  return loadCreds();
40330
44202
  }
40331
44203
  function writeDesktop(creds) {
40332
- const path = claudeDesktopConfigPath((0, import_node_os3.platform)(), (0, import_node_os3.homedir)(), process.env.APPDATA);
40333
- if (!(0, import_node_fs3.existsSync)((0, import_node_path5.dirname)(path))) {
44204
+ const path = claudeDesktopConfigPath((0, import_node_os4.platform)(), (0, import_node_os4.homedir)(), process.env.APPDATA);
44205
+ if (!(0, import_node_fs5.existsSync)((0, import_node_path6.dirname)(path))) {
40334
44206
  say("\xB7 Claude Desktop: kh\xF4ng th\u1EA5y tr\xEAn m\xE1y, b\u1ECF qua");
40335
44207
  return;
40336
44208
  }
40337
44209
  let prev;
40338
44210
  try {
40339
- prev = JSON.parse((0, import_node_fs3.readFileSync)(path, "utf8"));
44211
+ prev = JSON.parse((0, import_node_fs5.readFileSync)(path, "utf8"));
40340
44212
  } catch {
40341
44213
  prev = void 0;
40342
44214
  }
40343
- (0, import_node_fs3.writeFileSync)(path, JSON.stringify(mergeClaudeDesktopConfig(prev, creds), null, 2));
44215
+ (0, import_node_fs5.writeFileSync)(path, JSON.stringify(mergeClaudeDesktopConfig(prev, creds), null, 2));
40344
44216
  say(`\u2713 Claude Desktop: \u0111\xE3 ghi ${path} (m\u1EDF l\u1EA1i Claude Desktop \u0111\u1EC3 n\xF3 nh\u1EADn)`);
40345
44217
  }
40346
44218
  function addClaudeCode(creds) {
40347
- const win = (0, import_node_os3.platform)() === "win32";
44219
+ const win = (0, import_node_os4.platform)() === "win32";
40348
44220
  try {
40349
44221
  (0, import_node_child_process3.execFileSync)("claude", ["mcp", "remove", "hocai"], { stdio: "ignore", shell: win });
40350
44222
  } catch {
@@ -40385,7 +44257,7 @@ function chayLay(cmd, args) {
40385
44257
  timeout: 8e3,
40386
44258
  stdio: ["ignore", "pipe", "ignore"]
40387
44259
  };
40388
- return (0, import_node_os3.platform)() === "win32" ? (0, import_node_child_process3.execSync)(dong, o) : (0, import_node_child_process3.execSync)(dong, { ...o, shell: "/bin/sh" });
44260
+ return (0, import_node_os4.platform)() === "win32" ? (0, import_node_child_process3.execSync)(dong, o) : (0, import_node_child_process3.execSync)(dong, { ...o, shell: "/bin/sh" });
40389
44261
  } catch (e) {
40390
44262
  const ra = e.stdout;
40391
44263
  const chu = typeof ra === "string" ? ra : ra?.toString("utf8");
@@ -40404,13 +44276,13 @@ function doTroLy() {
40404
44276
  }
40405
44277
  return r.chayDuocBai;
40406
44278
  }
40407
- var plan = () => daemonPlan((0, import_node_os3.platform)(), { node: process.execPath, script: APP_CLI, home: (0, import_node_os3.homedir)() });
44279
+ var plan = () => daemonPlan((0, import_node_os4.platform)(), { node: process.execPath, script: APP_CLI, home: (0, import_node_os4.homedir)() });
40408
44280
  function nghi(ms) {
40409
44281
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
40410
44282
  }
40411
44283
  function chay(cmd, im = false) {
40412
44284
  try {
40413
- (0, import_node_child_process3.execFileSync)(cmd[0], cmd.slice(1), { stdio: "ignore", shell: (0, import_node_os3.platform)() === "win32" });
44285
+ (0, import_node_child_process3.execFileSync)(cmd[0], cmd.slice(1), { stdio: "ignore", shell: (0, import_node_os4.platform)() === "win32" });
40414
44286
  return true;
40415
44287
  } catch {
40416
44288
  if (!im) return false;
@@ -40423,17 +44295,17 @@ function caiDichVu() {
40423
44295
  say("\xB7 H\u1EC7 \u0111i\u1EC1u h\xE0nh n\xE0y ch\u01B0a h\u1ED7 tr\u1EE3 ch\u1EA1y \u1EA9n. D\xF9ng `npx hocai-connect run` v\xE0 \u0111\u1EC3 c\u1EEDa s\u1ED5 m\u1EDF.");
40424
44296
  return false;
40425
44297
  }
40426
- (0, import_node_fs3.mkdirSync)(APP_DIR, { recursive: true });
40427
- (0, import_node_fs3.mkdirSync)(LOG_DIR, { recursive: true });
40428
- (0, import_node_fs3.copyFileSync)(__filename, APP_CLI);
44298
+ (0, import_node_fs5.mkdirSync)(APP_DIR, { recursive: true });
44299
+ (0, import_node_fs5.mkdirSync)(LOG_DIR, { recursive: true });
44300
+ (0, import_node_fs5.copyFileSync)(__filename, APP_CLI);
40429
44301
  if (p.file && p.content) {
40430
- (0, import_node_fs3.mkdirSync)((0, import_node_path5.dirname)(p.file), { recursive: true });
40431
- (0, import_node_fs3.writeFileSync)(p.file, p.content);
44302
+ (0, import_node_fs5.mkdirSync)((0, import_node_path6.dirname)(p.file), { recursive: true });
44303
+ (0, import_node_fs5.writeFileSync)(p.file, p.content);
40432
44304
  }
40433
44305
  p.install.forEach((c, i) => {
40434
44306
  if (i === 0) {
40435
44307
  chay(c, true);
40436
- if ((0, import_node_os3.platform)() === "darwin") {
44308
+ if ((0, import_node_os4.platform)() === "darwin") {
40437
44309
  const nhan = `gui/${process.getuid?.() ?? 501}/${p.label}`;
40438
44310
  for (let lan = 0; lan < 20; lan++) {
40439
44311
  if (!chay(["launchctl", "print", nhan], true)) break;
@@ -40452,7 +44324,7 @@ function caiDichVu() {
40452
44324
  function goDichVu() {
40453
44325
  const p = plan();
40454
44326
  for (const c of p.uninstall) chay(c, true);
40455
- if (p.file) (0, import_node_fs3.rmSync)(p.file, { force: true });
44327
+ if (p.file) (0, import_node_fs5.rmSync)(p.file, { force: true });
40456
44328
  }
40457
44329
  var LENH = ["mcp", "run", "update", "status", "stop", "logs", "quen", "help", "--help", "-h", "entry"];
40458
44330
  var TRO_GIUP = `hocai-connect \u2014 n\u1ED1i Claude tr\xEAn m\xE1y b\u1EA1n v\xE0o hocAI
@@ -40487,7 +44359,7 @@ async function main() {
40487
44359
  }
40488
44360
  if (cmd === "quen") {
40489
44361
  goDichVu();
40490
- (0, import_node_fs3.rmSync)(CREDS, { force: true });
44362
+ (0, import_node_fs5.rmSync)(CREDS, { force: true });
40491
44363
  say("\u0110\xE3 ng\u1EAFt k\u1EBFt n\u1ED1i v\xE0 g\u1EE1 d\u1ECBch v\u1EE5 n\u1EC1n tr\xEAn m\xE1y n\xE0y.");
40492
44364
  say("Ch\u1EA1y l\u1EA1i `npx hocai-connect` \u0111\u1EC3 k\u1EBFt n\u1ED1i l\u1EA1i.");
40493
44365
  return;
@@ -40506,7 +44378,7 @@ async function main() {
40506
44378
  say("");
40507
44379
  const r = (0, import_node_child_process3.spawnSync)("npx", ["-y", `hocai-connect@${moi}`], {
40508
44380
  stdio: "inherit",
40509
- shell: (0, import_node_os3.platform)() === "win32"
44381
+ shell: (0, import_node_os4.platform)() === "win32"
40510
44382
  });
40511
44383
  process.exit(r.status ?? 1);
40512
44384
  }
@@ -40537,11 +44409,11 @@ async function main() {
40537
44409
  }
40538
44410
  if (cmd === "logs") {
40539
44411
  const f = plan().log;
40540
- if (!(0, import_node_fs3.existsSync)(f)) {
44412
+ if (!(0, import_node_fs5.existsSync)(f)) {
40541
44413
  say(`Ch\u01B0a c\xF3 nh\u1EADt k\xFD n\xE0o \u1EDF ${f}`);
40542
44414
  return;
40543
44415
  }
40544
- say((0, import_node_fs3.readFileSync)(f, "utf8").split("\n").slice(-40).join("\n"));
44416
+ say((0, import_node_fs5.readFileSync)(f, "utf8").split("\n").slice(-40).join("\n"));
40545
44417
  return;
40546
44418
  }
40547
44419
  const creds = loadCreds() ?? await login();
@@ -40591,7 +44463,12 @@ async function main() {
40591
44463
  }
40592
44464
  return;
40593
44465
  }
44466
+ cutLogIfBig(logPathFor((0, import_node_os4.homedir)()));
44467
+ const folders = createFolderRegistry();
40594
44468
  const srv = buildHttpServer({
44469
+ // MỘT sổ dùng chung cho cả đường trình duyệt lẫn đường lên socket. Hai sổ
44470
+ // khác nhau thì người dùng bấm chọn ở hộp thoại mà máy chủ không thấy.
44471
+ folders,
40595
44472
  token: creds.token,
40596
44473
  // Danh sách CỐ ĐỊNH gồm cả địa chỉ cũ, không ghép từ `WEB()`.
40597
44474
  //
@@ -40610,7 +44487,20 @@ async function main() {
40610
44487
  process.exit(d.thoat);
40611
44488
  });
40612
44489
  });
40613
- setInterval(() => void identity.refresh(), 6e4).unref();
44490
+ const uplink = createUplink({
44491
+ url: WEB().replace(/^http/, "ws") + "/ws/machine",
44492
+ token: creds.token,
44493
+ // Gọi LẠI mỗi lượt nối, không dựng sẵn một lần: danh sách thư mục đổi giữa
44494
+ // hai lượt nối là chuyện thường, và máy chủ phải nhận danh sách MỚI NHẤT.
44495
+ hello: () => ({
44496
+ t: "hello",
44497
+ name: (0, import_node_os4.hostname)(),
44498
+ os: (0, import_node_os4.platform)(),
44499
+ folders: folders.list()
44500
+ }),
44501
+ onMessage: (msg) => handleServerMessage(msg, { folders, store: srv.store, send: uplink.send })
44502
+ });
44503
+ uplink.start();
40614
44504
  srv.listen(PORT, "127.0.0.1", () => {
40615
44505
  say("");
40616
44506
  say("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");