@kevisual/cli 0.0.75 → 0.0.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/assistant.js CHANGED
@@ -14441,2815 +14441,6 @@ var require_send = __commonJS((exports, module) => {
14441
14441
  }
14442
14442
  });
14443
14443
 
14444
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/constants.js
14445
- var require_constants = __commonJS((exports, module) => {
14446
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
14447
- var hasBlob = typeof Blob !== "undefined";
14448
- if (hasBlob)
14449
- BINARY_TYPES.push("blob");
14450
- module.exports = {
14451
- BINARY_TYPES,
14452
- EMPTY_BUFFER: Buffer.alloc(0),
14453
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
14454
- hasBlob,
14455
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
14456
- kListener: Symbol("kListener"),
14457
- kStatusCode: Symbol("status-code"),
14458
- kWebSocket: Symbol("websocket"),
14459
- NOOP: () => {}
14460
- };
14461
- });
14462
-
14463
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/buffer-util.js
14464
- var require_buffer_util = __commonJS((exports, module) => {
14465
- var { EMPTY_BUFFER } = require_constants();
14466
- var FastBuffer = Buffer[Symbol.species];
14467
- function concat(list, totalLength) {
14468
- if (list.length === 0)
14469
- return EMPTY_BUFFER;
14470
- if (list.length === 1)
14471
- return list[0];
14472
- const target = Buffer.allocUnsafe(totalLength);
14473
- let offset = 0;
14474
- for (let i = 0;i < list.length; i++) {
14475
- const buf = list[i];
14476
- target.set(buf, offset);
14477
- offset += buf.length;
14478
- }
14479
- if (offset < totalLength) {
14480
- return new FastBuffer(target.buffer, target.byteOffset, offset);
14481
- }
14482
- return target;
14483
- }
14484
- function _mask(source, mask, output, offset, length) {
14485
- for (let i = 0;i < length; i++) {
14486
- output[offset + i] = source[i] ^ mask[i & 3];
14487
- }
14488
- }
14489
- function _unmask(buffer, mask) {
14490
- for (let i = 0;i < buffer.length; i++) {
14491
- buffer[i] ^= mask[i & 3];
14492
- }
14493
- }
14494
- function toArrayBuffer(buf) {
14495
- if (buf.length === buf.buffer.byteLength) {
14496
- return buf.buffer;
14497
- }
14498
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
14499
- }
14500
- function toBuffer(data) {
14501
- toBuffer.readOnly = true;
14502
- if (Buffer.isBuffer(data))
14503
- return data;
14504
- let buf;
14505
- if (data instanceof ArrayBuffer) {
14506
- buf = new FastBuffer(data);
14507
- } else if (ArrayBuffer.isView(data)) {
14508
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
14509
- } else {
14510
- buf = Buffer.from(data);
14511
- toBuffer.readOnly = false;
14512
- }
14513
- return buf;
14514
- }
14515
- module.exports = {
14516
- concat,
14517
- mask: _mask,
14518
- toArrayBuffer,
14519
- toBuffer,
14520
- unmask: _unmask
14521
- };
14522
- });
14523
-
14524
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/limiter.js
14525
- var require_limiter = __commonJS((exports, module) => {
14526
- var kDone = Symbol("kDone");
14527
- var kRun = Symbol("kRun");
14528
-
14529
- class Limiter {
14530
- constructor(concurrency) {
14531
- this[kDone] = () => {
14532
- this.pending--;
14533
- this[kRun]();
14534
- };
14535
- this.concurrency = concurrency || Infinity;
14536
- this.jobs = [];
14537
- this.pending = 0;
14538
- }
14539
- add(job) {
14540
- this.jobs.push(job);
14541
- this[kRun]();
14542
- }
14543
- [kRun]() {
14544
- if (this.pending === this.concurrency)
14545
- return;
14546
- if (this.jobs.length) {
14547
- const job = this.jobs.shift();
14548
- this.pending++;
14549
- job(this[kDone]);
14550
- }
14551
- }
14552
- }
14553
- module.exports = Limiter;
14554
- });
14555
-
14556
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/permessage-deflate.js
14557
- var require_permessage_deflate = __commonJS((exports, module) => {
14558
- var zlib = __require("zlib");
14559
- var bufferUtil = require_buffer_util();
14560
- var Limiter = require_limiter();
14561
- var { kStatusCode } = require_constants();
14562
- var FastBuffer = Buffer[Symbol.species];
14563
- var TRAILER = Buffer.from([0, 0, 255, 255]);
14564
- var kPerMessageDeflate = Symbol("permessage-deflate");
14565
- var kTotalLength = Symbol("total-length");
14566
- var kCallback = Symbol("callback");
14567
- var kBuffers = Symbol("buffers");
14568
- var kError = Symbol("error");
14569
- var zlibLimiter;
14570
-
14571
- class PerMessageDeflate {
14572
- constructor(options, isServer, maxPayload) {
14573
- this._maxPayload = maxPayload | 0;
14574
- this._options = options || {};
14575
- this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
14576
- this._isServer = !!isServer;
14577
- this._deflate = null;
14578
- this._inflate = null;
14579
- this.params = null;
14580
- if (!zlibLimiter) {
14581
- const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
14582
- zlibLimiter = new Limiter(concurrency);
14583
- }
14584
- }
14585
- static get extensionName() {
14586
- return "permessage-deflate";
14587
- }
14588
- offer() {
14589
- const params = {};
14590
- if (this._options.serverNoContextTakeover) {
14591
- params.server_no_context_takeover = true;
14592
- }
14593
- if (this._options.clientNoContextTakeover) {
14594
- params.client_no_context_takeover = true;
14595
- }
14596
- if (this._options.serverMaxWindowBits) {
14597
- params.server_max_window_bits = this._options.serverMaxWindowBits;
14598
- }
14599
- if (this._options.clientMaxWindowBits) {
14600
- params.client_max_window_bits = this._options.clientMaxWindowBits;
14601
- } else if (this._options.clientMaxWindowBits == null) {
14602
- params.client_max_window_bits = true;
14603
- }
14604
- return params;
14605
- }
14606
- accept(configurations) {
14607
- configurations = this.normalizeParams(configurations);
14608
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
14609
- return this.params;
14610
- }
14611
- cleanup() {
14612
- if (this._inflate) {
14613
- this._inflate.close();
14614
- this._inflate = null;
14615
- }
14616
- if (this._deflate) {
14617
- const callback = this._deflate[kCallback];
14618
- this._deflate.close();
14619
- this._deflate = null;
14620
- if (callback) {
14621
- callback(new Error("The deflate stream was closed while data was being processed"));
14622
- }
14623
- }
14624
- }
14625
- acceptAsServer(offers) {
14626
- const opts = this._options;
14627
- const accepted = offers.find((params) => {
14628
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
14629
- return false;
14630
- }
14631
- return true;
14632
- });
14633
- if (!accepted) {
14634
- throw new Error("None of the extension offers can be accepted");
14635
- }
14636
- if (opts.serverNoContextTakeover) {
14637
- accepted.server_no_context_takeover = true;
14638
- }
14639
- if (opts.clientNoContextTakeover) {
14640
- accepted.client_no_context_takeover = true;
14641
- }
14642
- if (typeof opts.serverMaxWindowBits === "number") {
14643
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
14644
- }
14645
- if (typeof opts.clientMaxWindowBits === "number") {
14646
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
14647
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
14648
- delete accepted.client_max_window_bits;
14649
- }
14650
- return accepted;
14651
- }
14652
- acceptAsClient(response) {
14653
- const params = response[0];
14654
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
14655
- throw new Error('Unexpected parameter "client_no_context_takeover"');
14656
- }
14657
- if (!params.client_max_window_bits) {
14658
- if (typeof this._options.clientMaxWindowBits === "number") {
14659
- params.client_max_window_bits = this._options.clientMaxWindowBits;
14660
- }
14661
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
14662
- throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
14663
- }
14664
- return params;
14665
- }
14666
- normalizeParams(configurations) {
14667
- configurations.forEach((params) => {
14668
- Object.keys(params).forEach((key) => {
14669
- let value = params[key];
14670
- if (value.length > 1) {
14671
- throw new Error(`Parameter "${key}" must have only a single value`);
14672
- }
14673
- value = value[0];
14674
- if (key === "client_max_window_bits") {
14675
- if (value !== true) {
14676
- const num = +value;
14677
- if (!Number.isInteger(num) || num < 8 || num > 15) {
14678
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
14679
- }
14680
- value = num;
14681
- } else if (!this._isServer) {
14682
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
14683
- }
14684
- } else if (key === "server_max_window_bits") {
14685
- const num = +value;
14686
- if (!Number.isInteger(num) || num < 8 || num > 15) {
14687
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
14688
- }
14689
- value = num;
14690
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
14691
- if (value !== true) {
14692
- throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
14693
- }
14694
- } else {
14695
- throw new Error(`Unknown parameter "${key}"`);
14696
- }
14697
- params[key] = value;
14698
- });
14699
- });
14700
- return configurations;
14701
- }
14702
- decompress(data, fin, callback) {
14703
- zlibLimiter.add((done) => {
14704
- this._decompress(data, fin, (err, result) => {
14705
- done();
14706
- callback(err, result);
14707
- });
14708
- });
14709
- }
14710
- compress(data, fin, callback) {
14711
- zlibLimiter.add((done) => {
14712
- this._compress(data, fin, (err, result) => {
14713
- done();
14714
- callback(err, result);
14715
- });
14716
- });
14717
- }
14718
- _decompress(data, fin, callback) {
14719
- const endpoint = this._isServer ? "client" : "server";
14720
- if (!this._inflate) {
14721
- const key = `${endpoint}_max_window_bits`;
14722
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
14723
- this._inflate = zlib.createInflateRaw({
14724
- ...this._options.zlibInflateOptions,
14725
- windowBits
14726
- });
14727
- this._inflate[kPerMessageDeflate] = this;
14728
- this._inflate[kTotalLength] = 0;
14729
- this._inflate[kBuffers] = [];
14730
- this._inflate.on("error", inflateOnError);
14731
- this._inflate.on("data", inflateOnData);
14732
- }
14733
- this._inflate[kCallback] = callback;
14734
- this._inflate.write(data);
14735
- if (fin)
14736
- this._inflate.write(TRAILER);
14737
- this._inflate.flush(() => {
14738
- const err = this._inflate[kError];
14739
- if (err) {
14740
- this._inflate.close();
14741
- this._inflate = null;
14742
- callback(err);
14743
- return;
14744
- }
14745
- const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
14746
- if (this._inflate._readableState.endEmitted) {
14747
- this._inflate.close();
14748
- this._inflate = null;
14749
- } else {
14750
- this._inflate[kTotalLength] = 0;
14751
- this._inflate[kBuffers] = [];
14752
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
14753
- this._inflate.reset();
14754
- }
14755
- }
14756
- callback(null, data2);
14757
- });
14758
- }
14759
- _compress(data, fin, callback) {
14760
- const endpoint = this._isServer ? "server" : "client";
14761
- if (!this._deflate) {
14762
- const key = `${endpoint}_max_window_bits`;
14763
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
14764
- this._deflate = zlib.createDeflateRaw({
14765
- ...this._options.zlibDeflateOptions,
14766
- windowBits
14767
- });
14768
- this._deflate[kTotalLength] = 0;
14769
- this._deflate[kBuffers] = [];
14770
- this._deflate.on("data", deflateOnData);
14771
- }
14772
- this._deflate[kCallback] = callback;
14773
- this._deflate.write(data);
14774
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
14775
- if (!this._deflate) {
14776
- return;
14777
- }
14778
- let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
14779
- if (fin) {
14780
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
14781
- }
14782
- this._deflate[kCallback] = null;
14783
- this._deflate[kTotalLength] = 0;
14784
- this._deflate[kBuffers] = [];
14785
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
14786
- this._deflate.reset();
14787
- }
14788
- callback(null, data2);
14789
- });
14790
- }
14791
- }
14792
- module.exports = PerMessageDeflate;
14793
- function deflateOnData(chunk) {
14794
- this[kBuffers].push(chunk);
14795
- this[kTotalLength] += chunk.length;
14796
- }
14797
- function inflateOnData(chunk) {
14798
- this[kTotalLength] += chunk.length;
14799
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
14800
- this[kBuffers].push(chunk);
14801
- return;
14802
- }
14803
- this[kError] = new RangeError("Max payload size exceeded");
14804
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
14805
- this[kError][kStatusCode] = 1009;
14806
- this.removeListener("data", inflateOnData);
14807
- this.reset();
14808
- }
14809
- function inflateOnError(err) {
14810
- this[kPerMessageDeflate]._inflate = null;
14811
- err[kStatusCode] = 1007;
14812
- this[kCallback](err);
14813
- }
14814
- });
14815
-
14816
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/validation.js
14817
- var require_validation = __commonJS((exports, module) => {
14818
- var { isUtf8 } = __require("buffer");
14819
- var { hasBlob } = require_constants();
14820
- var tokenChars = [
14821
- 0,
14822
- 0,
14823
- 0,
14824
- 0,
14825
- 0,
14826
- 0,
14827
- 0,
14828
- 0,
14829
- 0,
14830
- 0,
14831
- 0,
14832
- 0,
14833
- 0,
14834
- 0,
14835
- 0,
14836
- 0,
14837
- 0,
14838
- 0,
14839
- 0,
14840
- 0,
14841
- 0,
14842
- 0,
14843
- 0,
14844
- 0,
14845
- 0,
14846
- 0,
14847
- 0,
14848
- 0,
14849
- 0,
14850
- 0,
14851
- 0,
14852
- 0,
14853
- 0,
14854
- 1,
14855
- 0,
14856
- 1,
14857
- 1,
14858
- 1,
14859
- 1,
14860
- 1,
14861
- 0,
14862
- 0,
14863
- 1,
14864
- 1,
14865
- 0,
14866
- 1,
14867
- 1,
14868
- 0,
14869
- 1,
14870
- 1,
14871
- 1,
14872
- 1,
14873
- 1,
14874
- 1,
14875
- 1,
14876
- 1,
14877
- 1,
14878
- 1,
14879
- 0,
14880
- 0,
14881
- 0,
14882
- 0,
14883
- 0,
14884
- 0,
14885
- 0,
14886
- 1,
14887
- 1,
14888
- 1,
14889
- 1,
14890
- 1,
14891
- 1,
14892
- 1,
14893
- 1,
14894
- 1,
14895
- 1,
14896
- 1,
14897
- 1,
14898
- 1,
14899
- 1,
14900
- 1,
14901
- 1,
14902
- 1,
14903
- 1,
14904
- 1,
14905
- 1,
14906
- 1,
14907
- 1,
14908
- 1,
14909
- 1,
14910
- 1,
14911
- 1,
14912
- 0,
14913
- 0,
14914
- 0,
14915
- 1,
14916
- 1,
14917
- 1,
14918
- 1,
14919
- 1,
14920
- 1,
14921
- 1,
14922
- 1,
14923
- 1,
14924
- 1,
14925
- 1,
14926
- 1,
14927
- 1,
14928
- 1,
14929
- 1,
14930
- 1,
14931
- 1,
14932
- 1,
14933
- 1,
14934
- 1,
14935
- 1,
14936
- 1,
14937
- 1,
14938
- 1,
14939
- 1,
14940
- 1,
14941
- 1,
14942
- 1,
14943
- 1,
14944
- 0,
14945
- 1,
14946
- 0,
14947
- 1,
14948
- 0
14949
- ];
14950
- function isValidStatusCode(code) {
14951
- return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
14952
- }
14953
- function _isValidUTF8(buf) {
14954
- const len = buf.length;
14955
- let i = 0;
14956
- while (i < len) {
14957
- if ((buf[i] & 128) === 0) {
14958
- i++;
14959
- } else if ((buf[i] & 224) === 192) {
14960
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
14961
- return false;
14962
- }
14963
- i += 2;
14964
- } else if ((buf[i] & 240) === 224) {
14965
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
14966
- return false;
14967
- }
14968
- i += 3;
14969
- } else if ((buf[i] & 248) === 240) {
14970
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
14971
- return false;
14972
- }
14973
- i += 4;
14974
- } else {
14975
- return false;
14976
- }
14977
- }
14978
- return true;
14979
- }
14980
- function isBlob(value) {
14981
- 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");
14982
- }
14983
- module.exports = {
14984
- isBlob,
14985
- isValidStatusCode,
14986
- isValidUTF8: _isValidUTF8,
14987
- tokenChars
14988
- };
14989
- if (isUtf8) {
14990
- module.exports.isValidUTF8 = function(buf) {
14991
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
14992
- };
14993
- }
14994
- });
14995
-
14996
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/receiver.js
14997
- var require_receiver = __commonJS((exports, module) => {
14998
- var { Writable } = __require("stream");
14999
- var PerMessageDeflate = require_permessage_deflate();
15000
- var {
15001
- BINARY_TYPES,
15002
- EMPTY_BUFFER,
15003
- kStatusCode,
15004
- kWebSocket
15005
- } = require_constants();
15006
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
15007
- var { isValidStatusCode, isValidUTF8 } = require_validation();
15008
- var FastBuffer = Buffer[Symbol.species];
15009
- var GET_INFO = 0;
15010
- var GET_PAYLOAD_LENGTH_16 = 1;
15011
- var GET_PAYLOAD_LENGTH_64 = 2;
15012
- var GET_MASK = 3;
15013
- var GET_DATA = 4;
15014
- var INFLATING = 5;
15015
- var DEFER_EVENT = 6;
15016
-
15017
- class Receiver extends Writable {
15018
- constructor(options = {}) {
15019
- super();
15020
- this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
15021
- this._binaryType = options.binaryType || BINARY_TYPES[0];
15022
- this._extensions = options.extensions || {};
15023
- this._isServer = !!options.isServer;
15024
- this._maxPayload = options.maxPayload | 0;
15025
- this._skipUTF8Validation = !!options.skipUTF8Validation;
15026
- this[kWebSocket] = undefined;
15027
- this._bufferedBytes = 0;
15028
- this._buffers = [];
15029
- this._compressed = false;
15030
- this._payloadLength = 0;
15031
- this._mask = undefined;
15032
- this._fragmented = 0;
15033
- this._masked = false;
15034
- this._fin = false;
15035
- this._opcode = 0;
15036
- this._totalPayloadLength = 0;
15037
- this._messageLength = 0;
15038
- this._fragments = [];
15039
- this._errored = false;
15040
- this._loop = false;
15041
- this._state = GET_INFO;
15042
- }
15043
- _write(chunk, encoding, cb) {
15044
- if (this._opcode === 8 && this._state == GET_INFO)
15045
- return cb();
15046
- this._bufferedBytes += chunk.length;
15047
- this._buffers.push(chunk);
15048
- this.startLoop(cb);
15049
- }
15050
- consume(n) {
15051
- this._bufferedBytes -= n;
15052
- if (n === this._buffers[0].length)
15053
- return this._buffers.shift();
15054
- if (n < this._buffers[0].length) {
15055
- const buf = this._buffers[0];
15056
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
15057
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
15058
- }
15059
- const dst = Buffer.allocUnsafe(n);
15060
- do {
15061
- const buf = this._buffers[0];
15062
- const offset = dst.length - n;
15063
- if (n >= buf.length) {
15064
- dst.set(this._buffers.shift(), offset);
15065
- } else {
15066
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
15067
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
15068
- }
15069
- n -= buf.length;
15070
- } while (n > 0);
15071
- return dst;
15072
- }
15073
- startLoop(cb) {
15074
- this._loop = true;
15075
- do {
15076
- switch (this._state) {
15077
- case GET_INFO:
15078
- this.getInfo(cb);
15079
- break;
15080
- case GET_PAYLOAD_LENGTH_16:
15081
- this.getPayloadLength16(cb);
15082
- break;
15083
- case GET_PAYLOAD_LENGTH_64:
15084
- this.getPayloadLength64(cb);
15085
- break;
15086
- case GET_MASK:
15087
- this.getMask();
15088
- break;
15089
- case GET_DATA:
15090
- this.getData(cb);
15091
- break;
15092
- case INFLATING:
15093
- case DEFER_EVENT:
15094
- this._loop = false;
15095
- return;
15096
- }
15097
- } while (this._loop);
15098
- if (!this._errored)
15099
- cb();
15100
- }
15101
- getInfo(cb) {
15102
- if (this._bufferedBytes < 2) {
15103
- this._loop = false;
15104
- return;
15105
- }
15106
- const buf = this.consume(2);
15107
- if ((buf[0] & 48) !== 0) {
15108
- const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
15109
- cb(error);
15110
- return;
15111
- }
15112
- const compressed = (buf[0] & 64) === 64;
15113
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
15114
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
15115
- cb(error);
15116
- return;
15117
- }
15118
- this._fin = (buf[0] & 128) === 128;
15119
- this._opcode = buf[0] & 15;
15120
- this._payloadLength = buf[1] & 127;
15121
- if (this._opcode === 0) {
15122
- if (compressed) {
15123
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
15124
- cb(error);
15125
- return;
15126
- }
15127
- if (!this._fragmented) {
15128
- const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
15129
- cb(error);
15130
- return;
15131
- }
15132
- this._opcode = this._fragmented;
15133
- } else if (this._opcode === 1 || this._opcode === 2) {
15134
- if (this._fragmented) {
15135
- const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
15136
- cb(error);
15137
- return;
15138
- }
15139
- this._compressed = compressed;
15140
- } else if (this._opcode > 7 && this._opcode < 11) {
15141
- if (!this._fin) {
15142
- const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
15143
- cb(error);
15144
- return;
15145
- }
15146
- if (compressed) {
15147
- const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
15148
- cb(error);
15149
- return;
15150
- }
15151
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
15152
- const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
15153
- cb(error);
15154
- return;
15155
- }
15156
- } else {
15157
- const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
15158
- cb(error);
15159
- return;
15160
- }
15161
- if (!this._fin && !this._fragmented)
15162
- this._fragmented = this._opcode;
15163
- this._masked = (buf[1] & 128) === 128;
15164
- if (this._isServer) {
15165
- if (!this._masked) {
15166
- const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
15167
- cb(error);
15168
- return;
15169
- }
15170
- } else if (this._masked) {
15171
- const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
15172
- cb(error);
15173
- return;
15174
- }
15175
- if (this._payloadLength === 126)
15176
- this._state = GET_PAYLOAD_LENGTH_16;
15177
- else if (this._payloadLength === 127)
15178
- this._state = GET_PAYLOAD_LENGTH_64;
15179
- else
15180
- this.haveLength(cb);
15181
- }
15182
- getPayloadLength16(cb) {
15183
- if (this._bufferedBytes < 2) {
15184
- this._loop = false;
15185
- return;
15186
- }
15187
- this._payloadLength = this.consume(2).readUInt16BE(0);
15188
- this.haveLength(cb);
15189
- }
15190
- getPayloadLength64(cb) {
15191
- if (this._bufferedBytes < 8) {
15192
- this._loop = false;
15193
- return;
15194
- }
15195
- const buf = this.consume(8);
15196
- const num = buf.readUInt32BE(0);
15197
- if (num > Math.pow(2, 53 - 32) - 1) {
15198
- const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
15199
- cb(error);
15200
- return;
15201
- }
15202
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
15203
- this.haveLength(cb);
15204
- }
15205
- haveLength(cb) {
15206
- if (this._payloadLength && this._opcode < 8) {
15207
- this._totalPayloadLength += this._payloadLength;
15208
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
15209
- const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
15210
- cb(error);
15211
- return;
15212
- }
15213
- }
15214
- if (this._masked)
15215
- this._state = GET_MASK;
15216
- else
15217
- this._state = GET_DATA;
15218
- }
15219
- getMask() {
15220
- if (this._bufferedBytes < 4) {
15221
- this._loop = false;
15222
- return;
15223
- }
15224
- this._mask = this.consume(4);
15225
- this._state = GET_DATA;
15226
- }
15227
- getData(cb) {
15228
- let data = EMPTY_BUFFER;
15229
- if (this._payloadLength) {
15230
- if (this._bufferedBytes < this._payloadLength) {
15231
- this._loop = false;
15232
- return;
15233
- }
15234
- data = this.consume(this._payloadLength);
15235
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
15236
- unmask(data, this._mask);
15237
- }
15238
- }
15239
- if (this._opcode > 7) {
15240
- this.controlMessage(data, cb);
15241
- return;
15242
- }
15243
- if (this._compressed) {
15244
- this._state = INFLATING;
15245
- this.decompress(data, cb);
15246
- return;
15247
- }
15248
- if (data.length) {
15249
- this._messageLength = this._totalPayloadLength;
15250
- this._fragments.push(data);
15251
- }
15252
- this.dataMessage(cb);
15253
- }
15254
- decompress(data, cb) {
15255
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
15256
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
15257
- if (err)
15258
- return cb(err);
15259
- if (buf.length) {
15260
- this._messageLength += buf.length;
15261
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
15262
- const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
15263
- cb(error);
15264
- return;
15265
- }
15266
- this._fragments.push(buf);
15267
- }
15268
- this.dataMessage(cb);
15269
- if (this._state === GET_INFO)
15270
- this.startLoop(cb);
15271
- });
15272
- }
15273
- dataMessage(cb) {
15274
- if (!this._fin) {
15275
- this._state = GET_INFO;
15276
- return;
15277
- }
15278
- const messageLength = this._messageLength;
15279
- const fragments = this._fragments;
15280
- this._totalPayloadLength = 0;
15281
- this._messageLength = 0;
15282
- this._fragmented = 0;
15283
- this._fragments = [];
15284
- if (this._opcode === 2) {
15285
- let data;
15286
- if (this._binaryType === "nodebuffer") {
15287
- data = concat(fragments, messageLength);
15288
- } else if (this._binaryType === "arraybuffer") {
15289
- data = toArrayBuffer(concat(fragments, messageLength));
15290
- } else if (this._binaryType === "blob") {
15291
- data = new Blob(fragments);
15292
- } else {
15293
- data = fragments;
15294
- }
15295
- if (this._allowSynchronousEvents) {
15296
- this.emit("message", data, true);
15297
- this._state = GET_INFO;
15298
- } else {
15299
- this._state = DEFER_EVENT;
15300
- setImmediate(() => {
15301
- this.emit("message", data, true);
15302
- this._state = GET_INFO;
15303
- this.startLoop(cb);
15304
- });
15305
- }
15306
- } else {
15307
- const buf = concat(fragments, messageLength);
15308
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
15309
- const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
15310
- cb(error);
15311
- return;
15312
- }
15313
- if (this._state === INFLATING || this._allowSynchronousEvents) {
15314
- this.emit("message", buf, false);
15315
- this._state = GET_INFO;
15316
- } else {
15317
- this._state = DEFER_EVENT;
15318
- setImmediate(() => {
15319
- this.emit("message", buf, false);
15320
- this._state = GET_INFO;
15321
- this.startLoop(cb);
15322
- });
15323
- }
15324
- }
15325
- }
15326
- controlMessage(data, cb) {
15327
- if (this._opcode === 8) {
15328
- if (data.length === 0) {
15329
- this._loop = false;
15330
- this.emit("conclude", 1005, EMPTY_BUFFER);
15331
- this.end();
15332
- } else {
15333
- const code = data.readUInt16BE(0);
15334
- if (!isValidStatusCode(code)) {
15335
- const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
15336
- cb(error);
15337
- return;
15338
- }
15339
- const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
15340
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
15341
- const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
15342
- cb(error);
15343
- return;
15344
- }
15345
- this._loop = false;
15346
- this.emit("conclude", code, buf);
15347
- this.end();
15348
- }
15349
- this._state = GET_INFO;
15350
- return;
15351
- }
15352
- if (this._allowSynchronousEvents) {
15353
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
15354
- this._state = GET_INFO;
15355
- } else {
15356
- this._state = DEFER_EVENT;
15357
- setImmediate(() => {
15358
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
15359
- this._state = GET_INFO;
15360
- this.startLoop(cb);
15361
- });
15362
- }
15363
- }
15364
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
15365
- this._loop = false;
15366
- this._errored = true;
15367
- const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
15368
- Error.captureStackTrace(err, this.createError);
15369
- err.code = errorCode;
15370
- err[kStatusCode] = statusCode;
15371
- return err;
15372
- }
15373
- }
15374
- module.exports = Receiver;
15375
- });
15376
-
15377
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/sender.js
15378
- var require_sender = __commonJS((exports, module) => {
15379
- var { Duplex } = __require("stream");
15380
- var { randomFillSync } = __require("crypto");
15381
- var PerMessageDeflate = require_permessage_deflate();
15382
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
15383
- var { isBlob, isValidStatusCode } = require_validation();
15384
- var { mask: applyMask, toBuffer } = require_buffer_util();
15385
- var kByteLength = Symbol("kByteLength");
15386
- var maskBuffer = Buffer.alloc(4);
15387
- var RANDOM_POOL_SIZE = 8 * 1024;
15388
- var randomPool;
15389
- var randomPoolPointer = RANDOM_POOL_SIZE;
15390
- var DEFAULT = 0;
15391
- var DEFLATING = 1;
15392
- var GET_BLOB_DATA = 2;
15393
-
15394
- class Sender {
15395
- constructor(socket, extensions, generateMask) {
15396
- this._extensions = extensions || {};
15397
- if (generateMask) {
15398
- this._generateMask = generateMask;
15399
- this._maskBuffer = Buffer.alloc(4);
15400
- }
15401
- this._socket = socket;
15402
- this._firstFragment = true;
15403
- this._compress = false;
15404
- this._bufferedBytes = 0;
15405
- this._queue = [];
15406
- this._state = DEFAULT;
15407
- this.onerror = NOOP;
15408
- this[kWebSocket] = undefined;
15409
- }
15410
- static frame(data, options) {
15411
- let mask;
15412
- let merge = false;
15413
- let offset = 2;
15414
- let skipMasking = false;
15415
- if (options.mask) {
15416
- mask = options.maskBuffer || maskBuffer;
15417
- if (options.generateMask) {
15418
- options.generateMask(mask);
15419
- } else {
15420
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
15421
- if (randomPool === undefined) {
15422
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
15423
- }
15424
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
15425
- randomPoolPointer = 0;
15426
- }
15427
- mask[0] = randomPool[randomPoolPointer++];
15428
- mask[1] = randomPool[randomPoolPointer++];
15429
- mask[2] = randomPool[randomPoolPointer++];
15430
- mask[3] = randomPool[randomPoolPointer++];
15431
- }
15432
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
15433
- offset = 6;
15434
- }
15435
- let dataLength;
15436
- if (typeof data === "string") {
15437
- if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
15438
- dataLength = options[kByteLength];
15439
- } else {
15440
- data = Buffer.from(data);
15441
- dataLength = data.length;
15442
- }
15443
- } else {
15444
- dataLength = data.length;
15445
- merge = options.mask && options.readOnly && !skipMasking;
15446
- }
15447
- let payloadLength = dataLength;
15448
- if (dataLength >= 65536) {
15449
- offset += 8;
15450
- payloadLength = 127;
15451
- } else if (dataLength > 125) {
15452
- offset += 2;
15453
- payloadLength = 126;
15454
- }
15455
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
15456
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
15457
- if (options.rsv1)
15458
- target[0] |= 64;
15459
- target[1] = payloadLength;
15460
- if (payloadLength === 126) {
15461
- target.writeUInt16BE(dataLength, 2);
15462
- } else if (payloadLength === 127) {
15463
- target[2] = target[3] = 0;
15464
- target.writeUIntBE(dataLength, 4, 6);
15465
- }
15466
- if (!options.mask)
15467
- return [target, data];
15468
- target[1] |= 128;
15469
- target[offset - 4] = mask[0];
15470
- target[offset - 3] = mask[1];
15471
- target[offset - 2] = mask[2];
15472
- target[offset - 1] = mask[3];
15473
- if (skipMasking)
15474
- return [target, data];
15475
- if (merge) {
15476
- applyMask(data, mask, target, offset, dataLength);
15477
- return [target];
15478
- }
15479
- applyMask(data, mask, data, 0, dataLength);
15480
- return [target, data];
15481
- }
15482
- close(code, data, mask, cb) {
15483
- let buf;
15484
- if (code === undefined) {
15485
- buf = EMPTY_BUFFER;
15486
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
15487
- throw new TypeError("First argument must be a valid error code number");
15488
- } else if (data === undefined || !data.length) {
15489
- buf = Buffer.allocUnsafe(2);
15490
- buf.writeUInt16BE(code, 0);
15491
- } else {
15492
- const length = Buffer.byteLength(data);
15493
- if (length > 123) {
15494
- throw new RangeError("The message must not be greater than 123 bytes");
15495
- }
15496
- buf = Buffer.allocUnsafe(2 + length);
15497
- buf.writeUInt16BE(code, 0);
15498
- if (typeof data === "string") {
15499
- buf.write(data, 2);
15500
- } else {
15501
- buf.set(data, 2);
15502
- }
15503
- }
15504
- const options = {
15505
- [kByteLength]: buf.length,
15506
- fin: true,
15507
- generateMask: this._generateMask,
15508
- mask,
15509
- maskBuffer: this._maskBuffer,
15510
- opcode: 8,
15511
- readOnly: false,
15512
- rsv1: false
15513
- };
15514
- if (this._state !== DEFAULT) {
15515
- this.enqueue([this.dispatch, buf, false, options, cb]);
15516
- } else {
15517
- this.sendFrame(Sender.frame(buf, options), cb);
15518
- }
15519
- }
15520
- ping(data, mask, cb) {
15521
- let byteLength;
15522
- let readOnly;
15523
- if (typeof data === "string") {
15524
- byteLength = Buffer.byteLength(data);
15525
- readOnly = false;
15526
- } else if (isBlob(data)) {
15527
- byteLength = data.size;
15528
- readOnly = false;
15529
- } else {
15530
- data = toBuffer(data);
15531
- byteLength = data.length;
15532
- readOnly = toBuffer.readOnly;
15533
- }
15534
- if (byteLength > 125) {
15535
- throw new RangeError("The data size must not be greater than 125 bytes");
15536
- }
15537
- const options = {
15538
- [kByteLength]: byteLength,
15539
- fin: true,
15540
- generateMask: this._generateMask,
15541
- mask,
15542
- maskBuffer: this._maskBuffer,
15543
- opcode: 9,
15544
- readOnly,
15545
- rsv1: false
15546
- };
15547
- if (isBlob(data)) {
15548
- if (this._state !== DEFAULT) {
15549
- this.enqueue([this.getBlobData, data, false, options, cb]);
15550
- } else {
15551
- this.getBlobData(data, false, options, cb);
15552
- }
15553
- } else if (this._state !== DEFAULT) {
15554
- this.enqueue([this.dispatch, data, false, options, cb]);
15555
- } else {
15556
- this.sendFrame(Sender.frame(data, options), cb);
15557
- }
15558
- }
15559
- pong(data, mask, cb) {
15560
- let byteLength;
15561
- let readOnly;
15562
- if (typeof data === "string") {
15563
- byteLength = Buffer.byteLength(data);
15564
- readOnly = false;
15565
- } else if (isBlob(data)) {
15566
- byteLength = data.size;
15567
- readOnly = false;
15568
- } else {
15569
- data = toBuffer(data);
15570
- byteLength = data.length;
15571
- readOnly = toBuffer.readOnly;
15572
- }
15573
- if (byteLength > 125) {
15574
- throw new RangeError("The data size must not be greater than 125 bytes");
15575
- }
15576
- const options = {
15577
- [kByteLength]: byteLength,
15578
- fin: true,
15579
- generateMask: this._generateMask,
15580
- mask,
15581
- maskBuffer: this._maskBuffer,
15582
- opcode: 10,
15583
- readOnly,
15584
- rsv1: false
15585
- };
15586
- if (isBlob(data)) {
15587
- if (this._state !== DEFAULT) {
15588
- this.enqueue([this.getBlobData, data, false, options, cb]);
15589
- } else {
15590
- this.getBlobData(data, false, options, cb);
15591
- }
15592
- } else if (this._state !== DEFAULT) {
15593
- this.enqueue([this.dispatch, data, false, options, cb]);
15594
- } else {
15595
- this.sendFrame(Sender.frame(data, options), cb);
15596
- }
15597
- }
15598
- send(data, options, cb) {
15599
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
15600
- let opcode = options.binary ? 2 : 1;
15601
- let rsv1 = options.compress;
15602
- let byteLength;
15603
- let readOnly;
15604
- if (typeof data === "string") {
15605
- byteLength = Buffer.byteLength(data);
15606
- readOnly = false;
15607
- } else if (isBlob(data)) {
15608
- byteLength = data.size;
15609
- readOnly = false;
15610
- } else {
15611
- data = toBuffer(data);
15612
- byteLength = data.length;
15613
- readOnly = toBuffer.readOnly;
15614
- }
15615
- if (this._firstFragment) {
15616
- this._firstFragment = false;
15617
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
15618
- rsv1 = byteLength >= perMessageDeflate._threshold;
15619
- }
15620
- this._compress = rsv1;
15621
- } else {
15622
- rsv1 = false;
15623
- opcode = 0;
15624
- }
15625
- if (options.fin)
15626
- this._firstFragment = true;
15627
- const opts = {
15628
- [kByteLength]: byteLength,
15629
- fin: options.fin,
15630
- generateMask: this._generateMask,
15631
- mask: options.mask,
15632
- maskBuffer: this._maskBuffer,
15633
- opcode,
15634
- readOnly,
15635
- rsv1
15636
- };
15637
- if (isBlob(data)) {
15638
- if (this._state !== DEFAULT) {
15639
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
15640
- } else {
15641
- this.getBlobData(data, this._compress, opts, cb);
15642
- }
15643
- } else if (this._state !== DEFAULT) {
15644
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
15645
- } else {
15646
- this.dispatch(data, this._compress, opts, cb);
15647
- }
15648
- }
15649
- getBlobData(blob, compress, options, cb) {
15650
- this._bufferedBytes += options[kByteLength];
15651
- this._state = GET_BLOB_DATA;
15652
- blob.arrayBuffer().then((arrayBuffer) => {
15653
- if (this._socket.destroyed) {
15654
- const err = new Error("The socket was closed while the blob was being read");
15655
- process.nextTick(callCallbacks, this, err, cb);
15656
- return;
15657
- }
15658
- this._bufferedBytes -= options[kByteLength];
15659
- const data = toBuffer(arrayBuffer);
15660
- if (!compress) {
15661
- this._state = DEFAULT;
15662
- this.sendFrame(Sender.frame(data, options), cb);
15663
- this.dequeue();
15664
- } else {
15665
- this.dispatch(data, compress, options, cb);
15666
- }
15667
- }).catch((err) => {
15668
- process.nextTick(onError, this, err, cb);
15669
- });
15670
- }
15671
- dispatch(data, compress, options, cb) {
15672
- if (!compress) {
15673
- this.sendFrame(Sender.frame(data, options), cb);
15674
- return;
15675
- }
15676
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
15677
- this._bufferedBytes += options[kByteLength];
15678
- this._state = DEFLATING;
15679
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
15680
- if (this._socket.destroyed) {
15681
- const err = new Error("The socket was closed while data was being compressed");
15682
- callCallbacks(this, err, cb);
15683
- return;
15684
- }
15685
- this._bufferedBytes -= options[kByteLength];
15686
- this._state = DEFAULT;
15687
- options.readOnly = false;
15688
- this.sendFrame(Sender.frame(buf, options), cb);
15689
- this.dequeue();
15690
- });
15691
- }
15692
- dequeue() {
15693
- while (this._state === DEFAULT && this._queue.length) {
15694
- const params = this._queue.shift();
15695
- this._bufferedBytes -= params[3][kByteLength];
15696
- Reflect.apply(params[0], this, params.slice(1));
15697
- }
15698
- }
15699
- enqueue(params) {
15700
- this._bufferedBytes += params[3][kByteLength];
15701
- this._queue.push(params);
15702
- }
15703
- sendFrame(list, cb) {
15704
- if (list.length === 2) {
15705
- this._socket.cork();
15706
- this._socket.write(list[0]);
15707
- this._socket.write(list[1], cb);
15708
- this._socket.uncork();
15709
- } else {
15710
- this._socket.write(list[0], cb);
15711
- }
15712
- }
15713
- }
15714
- module.exports = Sender;
15715
- function callCallbacks(sender, err, cb) {
15716
- if (typeof cb === "function")
15717
- cb(err);
15718
- for (let i = 0;i < sender._queue.length; i++) {
15719
- const params = sender._queue[i];
15720
- const callback = params[params.length - 1];
15721
- if (typeof callback === "function")
15722
- callback(err);
15723
- }
15724
- }
15725
- function onError(sender, err, cb) {
15726
- callCallbacks(sender, err, cb);
15727
- sender.onerror(err);
15728
- }
15729
- });
15730
-
15731
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/event-target.js
15732
- var require_event_target = __commonJS((exports, module) => {
15733
- var { kForOnEventAttribute, kListener } = require_constants();
15734
- var kCode = Symbol("kCode");
15735
- var kData = Symbol("kData");
15736
- var kError = Symbol("kError");
15737
- var kMessage = Symbol("kMessage");
15738
- var kReason = Symbol("kReason");
15739
- var kTarget = Symbol("kTarget");
15740
- var kType = Symbol("kType");
15741
- var kWasClean = Symbol("kWasClean");
15742
-
15743
- class Event {
15744
- constructor(type) {
15745
- this[kTarget] = null;
15746
- this[kType] = type;
15747
- }
15748
- get target() {
15749
- return this[kTarget];
15750
- }
15751
- get type() {
15752
- return this[kType];
15753
- }
15754
- }
15755
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
15756
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
15757
-
15758
- class CloseEvent extends Event {
15759
- constructor(type, options = {}) {
15760
- super(type);
15761
- this[kCode] = options.code === undefined ? 0 : options.code;
15762
- this[kReason] = options.reason === undefined ? "" : options.reason;
15763
- this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
15764
- }
15765
- get code() {
15766
- return this[kCode];
15767
- }
15768
- get reason() {
15769
- return this[kReason];
15770
- }
15771
- get wasClean() {
15772
- return this[kWasClean];
15773
- }
15774
- }
15775
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
15776
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
15777
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
15778
-
15779
- class ErrorEvent extends Event {
15780
- constructor(type, options = {}) {
15781
- super(type);
15782
- this[kError] = options.error === undefined ? null : options.error;
15783
- this[kMessage] = options.message === undefined ? "" : options.message;
15784
- }
15785
- get error() {
15786
- return this[kError];
15787
- }
15788
- get message() {
15789
- return this[kMessage];
15790
- }
15791
- }
15792
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
15793
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
15794
-
15795
- class MessageEvent extends Event {
15796
- constructor(type, options = {}) {
15797
- super(type);
15798
- this[kData] = options.data === undefined ? null : options.data;
15799
- }
15800
- get data() {
15801
- return this[kData];
15802
- }
15803
- }
15804
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
15805
- var EventTarget = {
15806
- addEventListener(type, handler, options = {}) {
15807
- for (const listener of this.listeners(type)) {
15808
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
15809
- return;
15810
- }
15811
- }
15812
- let wrapper;
15813
- if (type === "message") {
15814
- wrapper = function onMessage(data, isBinary) {
15815
- const event = new MessageEvent("message", {
15816
- data: isBinary ? data : data.toString()
15817
- });
15818
- event[kTarget] = this;
15819
- callListener(handler, this, event);
15820
- };
15821
- } else if (type === "close") {
15822
- wrapper = function onClose(code, message) {
15823
- const event = new CloseEvent("close", {
15824
- code,
15825
- reason: message.toString(),
15826
- wasClean: this._closeFrameReceived && this._closeFrameSent
15827
- });
15828
- event[kTarget] = this;
15829
- callListener(handler, this, event);
15830
- };
15831
- } else if (type === "error") {
15832
- wrapper = function onError(error) {
15833
- const event = new ErrorEvent("error", {
15834
- error,
15835
- message: error.message
15836
- });
15837
- event[kTarget] = this;
15838
- callListener(handler, this, event);
15839
- };
15840
- } else if (type === "open") {
15841
- wrapper = function onOpen() {
15842
- const event = new Event("open");
15843
- event[kTarget] = this;
15844
- callListener(handler, this, event);
15845
- };
15846
- } else {
15847
- return;
15848
- }
15849
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
15850
- wrapper[kListener] = handler;
15851
- if (options.once) {
15852
- this.once(type, wrapper);
15853
- } else {
15854
- this.on(type, wrapper);
15855
- }
15856
- },
15857
- removeEventListener(type, handler) {
15858
- for (const listener of this.listeners(type)) {
15859
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
15860
- this.removeListener(type, listener);
15861
- break;
15862
- }
15863
- }
15864
- }
15865
- };
15866
- module.exports = {
15867
- CloseEvent,
15868
- ErrorEvent,
15869
- Event,
15870
- EventTarget,
15871
- MessageEvent
15872
- };
15873
- function callListener(listener, thisArg, event) {
15874
- if (typeof listener === "object" && listener.handleEvent) {
15875
- listener.handleEvent.call(listener, event);
15876
- } else {
15877
- listener.call(thisArg, event);
15878
- }
15879
- }
15880
- });
15881
-
15882
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/extension.js
15883
- var require_extension = __commonJS((exports, module) => {
15884
- var { tokenChars } = require_validation();
15885
- function push(dest, name, elem) {
15886
- if (dest[name] === undefined)
15887
- dest[name] = [elem];
15888
- else
15889
- dest[name].push(elem);
15890
- }
15891
- function parse(header) {
15892
- const offers = Object.create(null);
15893
- let params = Object.create(null);
15894
- let mustUnescape = false;
15895
- let isEscaping = false;
15896
- let inQuotes = false;
15897
- let extensionName;
15898
- let paramName;
15899
- let start = -1;
15900
- let code = -1;
15901
- let end = -1;
15902
- let i = 0;
15903
- for (;i < header.length; i++) {
15904
- code = header.charCodeAt(i);
15905
- if (extensionName === undefined) {
15906
- if (end === -1 && tokenChars[code] === 1) {
15907
- if (start === -1)
15908
- start = i;
15909
- } else if (i !== 0 && (code === 32 || code === 9)) {
15910
- if (end === -1 && start !== -1)
15911
- end = i;
15912
- } else if (code === 59 || code === 44) {
15913
- if (start === -1) {
15914
- throw new SyntaxError(`Unexpected character at index ${i}`);
15915
- }
15916
- if (end === -1)
15917
- end = i;
15918
- const name = header.slice(start, end);
15919
- if (code === 44) {
15920
- push(offers, name, params);
15921
- params = Object.create(null);
15922
- } else {
15923
- extensionName = name;
15924
- }
15925
- start = end = -1;
15926
- } else {
15927
- throw new SyntaxError(`Unexpected character at index ${i}`);
15928
- }
15929
- } else if (paramName === undefined) {
15930
- if (end === -1 && tokenChars[code] === 1) {
15931
- if (start === -1)
15932
- start = i;
15933
- } else if (code === 32 || code === 9) {
15934
- if (end === -1 && start !== -1)
15935
- end = i;
15936
- } else if (code === 59 || code === 44) {
15937
- if (start === -1) {
15938
- throw new SyntaxError(`Unexpected character at index ${i}`);
15939
- }
15940
- if (end === -1)
15941
- end = i;
15942
- push(params, header.slice(start, end), true);
15943
- if (code === 44) {
15944
- push(offers, extensionName, params);
15945
- params = Object.create(null);
15946
- extensionName = undefined;
15947
- }
15948
- start = end = -1;
15949
- } else if (code === 61 && start !== -1 && end === -1) {
15950
- paramName = header.slice(start, i);
15951
- start = end = -1;
15952
- } else {
15953
- throw new SyntaxError(`Unexpected character at index ${i}`);
15954
- }
15955
- } else {
15956
- if (isEscaping) {
15957
- if (tokenChars[code] !== 1) {
15958
- throw new SyntaxError(`Unexpected character at index ${i}`);
15959
- }
15960
- if (start === -1)
15961
- start = i;
15962
- else if (!mustUnescape)
15963
- mustUnescape = true;
15964
- isEscaping = false;
15965
- } else if (inQuotes) {
15966
- if (tokenChars[code] === 1) {
15967
- if (start === -1)
15968
- start = i;
15969
- } else if (code === 34 && start !== -1) {
15970
- inQuotes = false;
15971
- end = i;
15972
- } else if (code === 92) {
15973
- isEscaping = true;
15974
- } else {
15975
- throw new SyntaxError(`Unexpected character at index ${i}`);
15976
- }
15977
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
15978
- inQuotes = true;
15979
- } else if (end === -1 && tokenChars[code] === 1) {
15980
- if (start === -1)
15981
- start = i;
15982
- } else if (start !== -1 && (code === 32 || code === 9)) {
15983
- if (end === -1)
15984
- end = i;
15985
- } else if (code === 59 || code === 44) {
15986
- if (start === -1) {
15987
- throw new SyntaxError(`Unexpected character at index ${i}`);
15988
- }
15989
- if (end === -1)
15990
- end = i;
15991
- let value = header.slice(start, end);
15992
- if (mustUnescape) {
15993
- value = value.replace(/\\/g, "");
15994
- mustUnescape = false;
15995
- }
15996
- push(params, paramName, value);
15997
- if (code === 44) {
15998
- push(offers, extensionName, params);
15999
- params = Object.create(null);
16000
- extensionName = undefined;
16001
- }
16002
- paramName = undefined;
16003
- start = end = -1;
16004
- } else {
16005
- throw new SyntaxError(`Unexpected character at index ${i}`);
16006
- }
16007
- }
16008
- }
16009
- if (start === -1 || inQuotes || code === 32 || code === 9) {
16010
- throw new SyntaxError("Unexpected end of input");
16011
- }
16012
- if (end === -1)
16013
- end = i;
16014
- const token = header.slice(start, end);
16015
- if (extensionName === undefined) {
16016
- push(offers, token, params);
16017
- } else {
16018
- if (paramName === undefined) {
16019
- push(params, token, true);
16020
- } else if (mustUnescape) {
16021
- push(params, paramName, token.replace(/\\/g, ""));
16022
- } else {
16023
- push(params, paramName, token);
16024
- }
16025
- push(offers, extensionName, params);
16026
- }
16027
- return offers;
16028
- }
16029
- function format(extensions) {
16030
- return Object.keys(extensions).map((extension) => {
16031
- let configurations = extensions[extension];
16032
- if (!Array.isArray(configurations))
16033
- configurations = [configurations];
16034
- return configurations.map((params) => {
16035
- return [extension].concat(Object.keys(params).map((k) => {
16036
- let values = params[k];
16037
- if (!Array.isArray(values))
16038
- values = [values];
16039
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
16040
- })).join("; ");
16041
- }).join(", ");
16042
- }).join(", ");
16043
- }
16044
- module.exports = { format, parse };
16045
- });
16046
-
16047
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/websocket.js
16048
- var require_websocket = __commonJS((exports, module) => {
16049
- var EventEmitter = __require("events");
16050
- var https = __require("https");
16051
- var http = __require("http");
16052
- var net = __require("net");
16053
- var tls = __require("tls");
16054
- var { randomBytes, createHash } = __require("crypto");
16055
- var { Duplex, Readable } = __require("stream");
16056
- var { URL: URL2 } = __require("url");
16057
- var PerMessageDeflate = require_permessage_deflate();
16058
- var Receiver = require_receiver();
16059
- var Sender = require_sender();
16060
- var { isBlob } = require_validation();
16061
- var {
16062
- BINARY_TYPES,
16063
- EMPTY_BUFFER,
16064
- GUID,
16065
- kForOnEventAttribute,
16066
- kListener,
16067
- kStatusCode,
16068
- kWebSocket,
16069
- NOOP
16070
- } = require_constants();
16071
- var {
16072
- EventTarget: { addEventListener, removeEventListener }
16073
- } = require_event_target();
16074
- var { format, parse } = require_extension();
16075
- var { toBuffer } = require_buffer_util();
16076
- var closeTimeout = 30 * 1000;
16077
- var kAborted = Symbol("kAborted");
16078
- var protocolVersions = [8, 13];
16079
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
16080
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
16081
-
16082
- class WebSocket extends EventEmitter {
16083
- constructor(address, protocols, options) {
16084
- super();
16085
- this._binaryType = BINARY_TYPES[0];
16086
- this._closeCode = 1006;
16087
- this._closeFrameReceived = false;
16088
- this._closeFrameSent = false;
16089
- this._closeMessage = EMPTY_BUFFER;
16090
- this._closeTimer = null;
16091
- this._errorEmitted = false;
16092
- this._extensions = {};
16093
- this._paused = false;
16094
- this._protocol = "";
16095
- this._readyState = WebSocket.CONNECTING;
16096
- this._receiver = null;
16097
- this._sender = null;
16098
- this._socket = null;
16099
- if (address !== null) {
16100
- this._bufferedAmount = 0;
16101
- this._isServer = false;
16102
- this._redirects = 0;
16103
- if (protocols === undefined) {
16104
- protocols = [];
16105
- } else if (!Array.isArray(protocols)) {
16106
- if (typeof protocols === "object" && protocols !== null) {
16107
- options = protocols;
16108
- protocols = [];
16109
- } else {
16110
- protocols = [protocols];
16111
- }
16112
- }
16113
- initAsClient(this, address, protocols, options);
16114
- } else {
16115
- this._autoPong = options.autoPong;
16116
- this._isServer = true;
16117
- }
16118
- }
16119
- get binaryType() {
16120
- return this._binaryType;
16121
- }
16122
- set binaryType(type) {
16123
- if (!BINARY_TYPES.includes(type))
16124
- return;
16125
- this._binaryType = type;
16126
- if (this._receiver)
16127
- this._receiver._binaryType = type;
16128
- }
16129
- get bufferedAmount() {
16130
- if (!this._socket)
16131
- return this._bufferedAmount;
16132
- return this._socket._writableState.length + this._sender._bufferedBytes;
16133
- }
16134
- get extensions() {
16135
- return Object.keys(this._extensions).join();
16136
- }
16137
- get isPaused() {
16138
- return this._paused;
16139
- }
16140
- get onclose() {
16141
- return null;
16142
- }
16143
- get onerror() {
16144
- return null;
16145
- }
16146
- get onopen() {
16147
- return null;
16148
- }
16149
- get onmessage() {
16150
- return null;
16151
- }
16152
- get protocol() {
16153
- return this._protocol;
16154
- }
16155
- get readyState() {
16156
- return this._readyState;
16157
- }
16158
- get url() {
16159
- return this._url;
16160
- }
16161
- setSocket(socket, head, options) {
16162
- const receiver = new Receiver({
16163
- allowSynchronousEvents: options.allowSynchronousEvents,
16164
- binaryType: this.binaryType,
16165
- extensions: this._extensions,
16166
- isServer: this._isServer,
16167
- maxPayload: options.maxPayload,
16168
- skipUTF8Validation: options.skipUTF8Validation
16169
- });
16170
- const sender = new Sender(socket, this._extensions, options.generateMask);
16171
- this._receiver = receiver;
16172
- this._sender = sender;
16173
- this._socket = socket;
16174
- receiver[kWebSocket] = this;
16175
- sender[kWebSocket] = this;
16176
- socket[kWebSocket] = this;
16177
- receiver.on("conclude", receiverOnConclude);
16178
- receiver.on("drain", receiverOnDrain);
16179
- receiver.on("error", receiverOnError);
16180
- receiver.on("message", receiverOnMessage);
16181
- receiver.on("ping", receiverOnPing);
16182
- receiver.on("pong", receiverOnPong);
16183
- sender.onerror = senderOnError;
16184
- if (socket.setTimeout)
16185
- socket.setTimeout(0);
16186
- if (socket.setNoDelay)
16187
- socket.setNoDelay();
16188
- if (head.length > 0)
16189
- socket.unshift(head);
16190
- socket.on("close", socketOnClose);
16191
- socket.on("data", socketOnData);
16192
- socket.on("end", socketOnEnd);
16193
- socket.on("error", socketOnError);
16194
- this._readyState = WebSocket.OPEN;
16195
- this.emit("open");
16196
- }
16197
- emitClose() {
16198
- if (!this._socket) {
16199
- this._readyState = WebSocket.CLOSED;
16200
- this.emit("close", this._closeCode, this._closeMessage);
16201
- return;
16202
- }
16203
- if (this._extensions[PerMessageDeflate.extensionName]) {
16204
- this._extensions[PerMessageDeflate.extensionName].cleanup();
16205
- }
16206
- this._receiver.removeAllListeners();
16207
- this._readyState = WebSocket.CLOSED;
16208
- this.emit("close", this._closeCode, this._closeMessage);
16209
- }
16210
- close(code, data) {
16211
- if (this.readyState === WebSocket.CLOSED)
16212
- return;
16213
- if (this.readyState === WebSocket.CONNECTING) {
16214
- const msg = "WebSocket was closed before the connection was established";
16215
- abortHandshake(this, this._req, msg);
16216
- return;
16217
- }
16218
- if (this.readyState === WebSocket.CLOSING) {
16219
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
16220
- this._socket.end();
16221
- }
16222
- return;
16223
- }
16224
- this._readyState = WebSocket.CLOSING;
16225
- this._sender.close(code, data, !this._isServer, (err) => {
16226
- if (err)
16227
- return;
16228
- this._closeFrameSent = true;
16229
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
16230
- this._socket.end();
16231
- }
16232
- });
16233
- setCloseTimer(this);
16234
- }
16235
- pause() {
16236
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
16237
- return;
16238
- }
16239
- this._paused = true;
16240
- this._socket.pause();
16241
- }
16242
- ping(data, mask, cb) {
16243
- if (this.readyState === WebSocket.CONNECTING) {
16244
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16245
- }
16246
- if (typeof data === "function") {
16247
- cb = data;
16248
- data = mask = undefined;
16249
- } else if (typeof mask === "function") {
16250
- cb = mask;
16251
- mask = undefined;
16252
- }
16253
- if (typeof data === "number")
16254
- data = data.toString();
16255
- if (this.readyState !== WebSocket.OPEN) {
16256
- sendAfterClose(this, data, cb);
16257
- return;
16258
- }
16259
- if (mask === undefined)
16260
- mask = !this._isServer;
16261
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
16262
- }
16263
- pong(data, mask, cb) {
16264
- if (this.readyState === WebSocket.CONNECTING) {
16265
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16266
- }
16267
- if (typeof data === "function") {
16268
- cb = data;
16269
- data = mask = undefined;
16270
- } else if (typeof mask === "function") {
16271
- cb = mask;
16272
- mask = undefined;
16273
- }
16274
- if (typeof data === "number")
16275
- data = data.toString();
16276
- if (this.readyState !== WebSocket.OPEN) {
16277
- sendAfterClose(this, data, cb);
16278
- return;
16279
- }
16280
- if (mask === undefined)
16281
- mask = !this._isServer;
16282
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
16283
- }
16284
- resume() {
16285
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
16286
- return;
16287
- }
16288
- this._paused = false;
16289
- if (!this._receiver._writableState.needDrain)
16290
- this._socket.resume();
16291
- }
16292
- send(data, options, cb) {
16293
- if (this.readyState === WebSocket.CONNECTING) {
16294
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16295
- }
16296
- if (typeof options === "function") {
16297
- cb = options;
16298
- options = {};
16299
- }
16300
- if (typeof data === "number")
16301
- data = data.toString();
16302
- if (this.readyState !== WebSocket.OPEN) {
16303
- sendAfterClose(this, data, cb);
16304
- return;
16305
- }
16306
- const opts = {
16307
- binary: typeof data !== "string",
16308
- mask: !this._isServer,
16309
- compress: true,
16310
- fin: true,
16311
- ...options
16312
- };
16313
- if (!this._extensions[PerMessageDeflate.extensionName]) {
16314
- opts.compress = false;
16315
- }
16316
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
16317
- }
16318
- terminate() {
16319
- if (this.readyState === WebSocket.CLOSED)
16320
- return;
16321
- if (this.readyState === WebSocket.CONNECTING) {
16322
- const msg = "WebSocket was closed before the connection was established";
16323
- abortHandshake(this, this._req, msg);
16324
- return;
16325
- }
16326
- if (this._socket) {
16327
- this._readyState = WebSocket.CLOSING;
16328
- this._socket.destroy();
16329
- }
16330
- }
16331
- }
16332
- Object.defineProperty(WebSocket, "CONNECTING", {
16333
- enumerable: true,
16334
- value: readyStates.indexOf("CONNECTING")
16335
- });
16336
- Object.defineProperty(WebSocket.prototype, "CONNECTING", {
16337
- enumerable: true,
16338
- value: readyStates.indexOf("CONNECTING")
16339
- });
16340
- Object.defineProperty(WebSocket, "OPEN", {
16341
- enumerable: true,
16342
- value: readyStates.indexOf("OPEN")
16343
- });
16344
- Object.defineProperty(WebSocket.prototype, "OPEN", {
16345
- enumerable: true,
16346
- value: readyStates.indexOf("OPEN")
16347
- });
16348
- Object.defineProperty(WebSocket, "CLOSING", {
16349
- enumerable: true,
16350
- value: readyStates.indexOf("CLOSING")
16351
- });
16352
- Object.defineProperty(WebSocket.prototype, "CLOSING", {
16353
- enumerable: true,
16354
- value: readyStates.indexOf("CLOSING")
16355
- });
16356
- Object.defineProperty(WebSocket, "CLOSED", {
16357
- enumerable: true,
16358
- value: readyStates.indexOf("CLOSED")
16359
- });
16360
- Object.defineProperty(WebSocket.prototype, "CLOSED", {
16361
- enumerable: true,
16362
- value: readyStates.indexOf("CLOSED")
16363
- });
16364
- [
16365
- "binaryType",
16366
- "bufferedAmount",
16367
- "extensions",
16368
- "isPaused",
16369
- "protocol",
16370
- "readyState",
16371
- "url"
16372
- ].forEach((property) => {
16373
- Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
16374
- });
16375
- ["open", "error", "close", "message"].forEach((method) => {
16376
- Object.defineProperty(WebSocket.prototype, `on${method}`, {
16377
- enumerable: true,
16378
- get() {
16379
- for (const listener of this.listeners(method)) {
16380
- if (listener[kForOnEventAttribute])
16381
- return listener[kListener];
16382
- }
16383
- return null;
16384
- },
16385
- set(handler) {
16386
- for (const listener of this.listeners(method)) {
16387
- if (listener[kForOnEventAttribute]) {
16388
- this.removeListener(method, listener);
16389
- break;
16390
- }
16391
- }
16392
- if (typeof handler !== "function")
16393
- return;
16394
- this.addEventListener(method, handler, {
16395
- [kForOnEventAttribute]: true
16396
- });
16397
- }
16398
- });
16399
- });
16400
- WebSocket.prototype.addEventListener = addEventListener;
16401
- WebSocket.prototype.removeEventListener = removeEventListener;
16402
- module.exports = WebSocket;
16403
- function initAsClient(websocket, address, protocols, options) {
16404
- const opts = {
16405
- allowSynchronousEvents: true,
16406
- autoPong: true,
16407
- protocolVersion: protocolVersions[1],
16408
- maxPayload: 100 * 1024 * 1024,
16409
- skipUTF8Validation: false,
16410
- perMessageDeflate: true,
16411
- followRedirects: false,
16412
- maxRedirects: 10,
16413
- ...options,
16414
- socketPath: undefined,
16415
- hostname: undefined,
16416
- protocol: undefined,
16417
- timeout: undefined,
16418
- method: "GET",
16419
- host: undefined,
16420
- path: undefined,
16421
- port: undefined
16422
- };
16423
- websocket._autoPong = opts.autoPong;
16424
- if (!protocolVersions.includes(opts.protocolVersion)) {
16425
- throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
16426
- }
16427
- let parsedUrl;
16428
- if (address instanceof URL2) {
16429
- parsedUrl = address;
16430
- } else {
16431
- try {
16432
- parsedUrl = new URL2(address);
16433
- } catch (e) {
16434
- throw new SyntaxError(`Invalid URL: ${address}`);
16435
- }
16436
- }
16437
- if (parsedUrl.protocol === "http:") {
16438
- parsedUrl.protocol = "ws:";
16439
- } else if (parsedUrl.protocol === "https:") {
16440
- parsedUrl.protocol = "wss:";
16441
- }
16442
- websocket._url = parsedUrl.href;
16443
- const isSecure = parsedUrl.protocol === "wss:";
16444
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
16445
- let invalidUrlMessage;
16446
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
16447
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
16448
- } else if (isIpcUrl && !parsedUrl.pathname) {
16449
- invalidUrlMessage = "The URL's pathname is empty";
16450
- } else if (parsedUrl.hash) {
16451
- invalidUrlMessage = "The URL contains a fragment identifier";
16452
- }
16453
- if (invalidUrlMessage) {
16454
- const err = new SyntaxError(invalidUrlMessage);
16455
- if (websocket._redirects === 0) {
16456
- throw err;
16457
- } else {
16458
- emitErrorAndClose(websocket, err);
16459
- return;
16460
- }
16461
- }
16462
- const defaultPort = isSecure ? 443 : 80;
16463
- const key = randomBytes(16).toString("base64");
16464
- const request = isSecure ? https.request : http.request;
16465
- const protocolSet = new Set;
16466
- let perMessageDeflate;
16467
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
16468
- opts.defaultPort = opts.defaultPort || defaultPort;
16469
- opts.port = parsedUrl.port || defaultPort;
16470
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
16471
- opts.headers = {
16472
- ...opts.headers,
16473
- "Sec-WebSocket-Version": opts.protocolVersion,
16474
- "Sec-WebSocket-Key": key,
16475
- Connection: "Upgrade",
16476
- Upgrade: "websocket"
16477
- };
16478
- opts.path = parsedUrl.pathname + parsedUrl.search;
16479
- opts.timeout = opts.handshakeTimeout;
16480
- if (opts.perMessageDeflate) {
16481
- perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
16482
- opts.headers["Sec-WebSocket-Extensions"] = format({
16483
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
16484
- });
16485
- }
16486
- if (protocols.length) {
16487
- for (const protocol of protocols) {
16488
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
16489
- throw new SyntaxError("An invalid or duplicated subprotocol was specified");
16490
- }
16491
- protocolSet.add(protocol);
16492
- }
16493
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
16494
- }
16495
- if (opts.origin) {
16496
- if (opts.protocolVersion < 13) {
16497
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
16498
- } else {
16499
- opts.headers.Origin = opts.origin;
16500
- }
16501
- }
16502
- if (parsedUrl.username || parsedUrl.password) {
16503
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
16504
- }
16505
- if (isIpcUrl) {
16506
- const parts = opts.path.split(":");
16507
- opts.socketPath = parts[0];
16508
- opts.path = parts[1];
16509
- }
16510
- let req;
16511
- if (opts.followRedirects) {
16512
- if (websocket._redirects === 0) {
16513
- websocket._originalIpc = isIpcUrl;
16514
- websocket._originalSecure = isSecure;
16515
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
16516
- const headers = options && options.headers;
16517
- options = { ...options, headers: {} };
16518
- if (headers) {
16519
- for (const [key2, value] of Object.entries(headers)) {
16520
- options.headers[key2.toLowerCase()] = value;
16521
- }
16522
- }
16523
- } else if (websocket.listenerCount("redirect") === 0) {
16524
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
16525
- if (!isSameHost || websocket._originalSecure && !isSecure) {
16526
- delete opts.headers.authorization;
16527
- delete opts.headers.cookie;
16528
- if (!isSameHost)
16529
- delete opts.headers.host;
16530
- opts.auth = undefined;
16531
- }
16532
- }
16533
- if (opts.auth && !options.headers.authorization) {
16534
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
16535
- }
16536
- req = websocket._req = request(opts);
16537
- if (websocket._redirects) {
16538
- websocket.emit("redirect", websocket.url, req);
16539
- }
16540
- } else {
16541
- req = websocket._req = request(opts);
16542
- }
16543
- if (opts.timeout) {
16544
- req.on("timeout", () => {
16545
- abortHandshake(websocket, req, "Opening handshake has timed out");
16546
- });
16547
- }
16548
- req.on("error", (err) => {
16549
- if (req === null || req[kAborted])
16550
- return;
16551
- req = websocket._req = null;
16552
- emitErrorAndClose(websocket, err);
16553
- });
16554
- req.on("response", (res) => {
16555
- const location = res.headers.location;
16556
- const statusCode = res.statusCode;
16557
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
16558
- if (++websocket._redirects > opts.maxRedirects) {
16559
- abortHandshake(websocket, req, "Maximum redirects exceeded");
16560
- return;
16561
- }
16562
- req.abort();
16563
- let addr;
16564
- try {
16565
- addr = new URL2(location, address);
16566
- } catch (e) {
16567
- const err = new SyntaxError(`Invalid URL: ${location}`);
16568
- emitErrorAndClose(websocket, err);
16569
- return;
16570
- }
16571
- initAsClient(websocket, addr, protocols, options);
16572
- } else if (!websocket.emit("unexpected-response", req, res)) {
16573
- abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
16574
- }
16575
- });
16576
- req.on("upgrade", (res, socket, head) => {
16577
- websocket.emit("upgrade", res);
16578
- if (websocket.readyState !== WebSocket.CONNECTING)
16579
- return;
16580
- req = websocket._req = null;
16581
- const upgrade = res.headers.upgrade;
16582
- if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
16583
- abortHandshake(websocket, socket, "Invalid Upgrade header");
16584
- return;
16585
- }
16586
- const digest = createHash("sha1").update(key + GUID).digest("base64");
16587
- if (res.headers["sec-websocket-accept"] !== digest) {
16588
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
16589
- return;
16590
- }
16591
- const serverProt = res.headers["sec-websocket-protocol"];
16592
- let protError;
16593
- if (serverProt !== undefined) {
16594
- if (!protocolSet.size) {
16595
- protError = "Server sent a subprotocol but none was requested";
16596
- } else if (!protocolSet.has(serverProt)) {
16597
- protError = "Server sent an invalid subprotocol";
16598
- }
16599
- } else if (protocolSet.size) {
16600
- protError = "Server sent no subprotocol";
16601
- }
16602
- if (protError) {
16603
- abortHandshake(websocket, socket, protError);
16604
- return;
16605
- }
16606
- if (serverProt)
16607
- websocket._protocol = serverProt;
16608
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
16609
- if (secWebSocketExtensions !== undefined) {
16610
- if (!perMessageDeflate) {
16611
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
16612
- abortHandshake(websocket, socket, message);
16613
- return;
16614
- }
16615
- let extensions;
16616
- try {
16617
- extensions = parse(secWebSocketExtensions);
16618
- } catch (err) {
16619
- const message = "Invalid Sec-WebSocket-Extensions header";
16620
- abortHandshake(websocket, socket, message);
16621
- return;
16622
- }
16623
- const extensionNames = Object.keys(extensions);
16624
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
16625
- const message = "Server indicated an extension that was not requested";
16626
- abortHandshake(websocket, socket, message);
16627
- return;
16628
- }
16629
- try {
16630
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
16631
- } catch (err) {
16632
- const message = "Invalid Sec-WebSocket-Extensions header";
16633
- abortHandshake(websocket, socket, message);
16634
- return;
16635
- }
16636
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
16637
- }
16638
- websocket.setSocket(socket, head, {
16639
- allowSynchronousEvents: opts.allowSynchronousEvents,
16640
- generateMask: opts.generateMask,
16641
- maxPayload: opts.maxPayload,
16642
- skipUTF8Validation: opts.skipUTF8Validation
16643
- });
16644
- });
16645
- if (opts.finishRequest) {
16646
- opts.finishRequest(req, websocket);
16647
- } else {
16648
- req.end();
16649
- }
16650
- }
16651
- function emitErrorAndClose(websocket, err) {
16652
- websocket._readyState = WebSocket.CLOSING;
16653
- websocket._errorEmitted = true;
16654
- websocket.emit("error", err);
16655
- websocket.emitClose();
16656
- }
16657
- function netConnect(options) {
16658
- options.path = options.socketPath;
16659
- return net.connect(options);
16660
- }
16661
- function tlsConnect(options) {
16662
- options.path = undefined;
16663
- if (!options.servername && options.servername !== "") {
16664
- options.servername = net.isIP(options.host) ? "" : options.host;
16665
- }
16666
- return tls.connect(options);
16667
- }
16668
- function abortHandshake(websocket, stream, message) {
16669
- websocket._readyState = WebSocket.CLOSING;
16670
- const err = new Error(message);
16671
- Error.captureStackTrace(err, abortHandshake);
16672
- if (stream.setHeader) {
16673
- stream[kAborted] = true;
16674
- stream.abort();
16675
- if (stream.socket && !stream.socket.destroyed) {
16676
- stream.socket.destroy();
16677
- }
16678
- process.nextTick(emitErrorAndClose, websocket, err);
16679
- } else {
16680
- stream.destroy(err);
16681
- stream.once("error", websocket.emit.bind(websocket, "error"));
16682
- stream.once("close", websocket.emitClose.bind(websocket));
16683
- }
16684
- }
16685
- function sendAfterClose(websocket, data, cb) {
16686
- if (data) {
16687
- const length = isBlob(data) ? data.size : toBuffer(data).length;
16688
- if (websocket._socket)
16689
- websocket._sender._bufferedBytes += length;
16690
- else
16691
- websocket._bufferedAmount += length;
16692
- }
16693
- if (cb) {
16694
- const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
16695
- process.nextTick(cb, err);
16696
- }
16697
- }
16698
- function receiverOnConclude(code, reason) {
16699
- const websocket = this[kWebSocket];
16700
- websocket._closeFrameReceived = true;
16701
- websocket._closeMessage = reason;
16702
- websocket._closeCode = code;
16703
- if (websocket._socket[kWebSocket] === undefined)
16704
- return;
16705
- websocket._socket.removeListener("data", socketOnData);
16706
- process.nextTick(resume, websocket._socket);
16707
- if (code === 1005)
16708
- websocket.close();
16709
- else
16710
- websocket.close(code, reason);
16711
- }
16712
- function receiverOnDrain() {
16713
- const websocket = this[kWebSocket];
16714
- if (!websocket.isPaused)
16715
- websocket._socket.resume();
16716
- }
16717
- function receiverOnError(err) {
16718
- const websocket = this[kWebSocket];
16719
- if (websocket._socket[kWebSocket] !== undefined) {
16720
- websocket._socket.removeListener("data", socketOnData);
16721
- process.nextTick(resume, websocket._socket);
16722
- websocket.close(err[kStatusCode]);
16723
- }
16724
- if (!websocket._errorEmitted) {
16725
- websocket._errorEmitted = true;
16726
- websocket.emit("error", err);
16727
- }
16728
- }
16729
- function receiverOnFinish() {
16730
- this[kWebSocket].emitClose();
16731
- }
16732
- function receiverOnMessage(data, isBinary) {
16733
- this[kWebSocket].emit("message", data, isBinary);
16734
- }
16735
- function receiverOnPing(data) {
16736
- const websocket = this[kWebSocket];
16737
- if (websocket._autoPong)
16738
- websocket.pong(data, !this._isServer, NOOP);
16739
- websocket.emit("ping", data);
16740
- }
16741
- function receiverOnPong(data) {
16742
- this[kWebSocket].emit("pong", data);
16743
- }
16744
- function resume(stream) {
16745
- stream.resume();
16746
- }
16747
- function senderOnError(err) {
16748
- const websocket = this[kWebSocket];
16749
- if (websocket.readyState === WebSocket.CLOSED)
16750
- return;
16751
- if (websocket.readyState === WebSocket.OPEN) {
16752
- websocket._readyState = WebSocket.CLOSING;
16753
- setCloseTimer(websocket);
16754
- }
16755
- this._socket.end();
16756
- if (!websocket._errorEmitted) {
16757
- websocket._errorEmitted = true;
16758
- websocket.emit("error", err);
16759
- }
16760
- }
16761
- function setCloseTimer(websocket) {
16762
- websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), closeTimeout);
16763
- }
16764
- function socketOnClose() {
16765
- const websocket = this[kWebSocket];
16766
- this.removeListener("close", socketOnClose);
16767
- this.removeListener("data", socketOnData);
16768
- this.removeListener("end", socketOnEnd);
16769
- websocket._readyState = WebSocket.CLOSING;
16770
- let chunk;
16771
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
16772
- websocket._receiver.write(chunk);
16773
- }
16774
- websocket._receiver.end();
16775
- this[kWebSocket] = undefined;
16776
- clearTimeout(websocket._closeTimer);
16777
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
16778
- websocket.emitClose();
16779
- } else {
16780
- websocket._receiver.on("error", receiverOnFinish);
16781
- websocket._receiver.on("finish", receiverOnFinish);
16782
- }
16783
- }
16784
- function socketOnData(chunk) {
16785
- if (!this[kWebSocket]._receiver.write(chunk)) {
16786
- this.pause();
16787
- }
16788
- }
16789
- function socketOnEnd() {
16790
- const websocket = this[kWebSocket];
16791
- websocket._readyState = WebSocket.CLOSING;
16792
- websocket._receiver.end();
16793
- this.end();
16794
- }
16795
- function socketOnError() {
16796
- const websocket = this[kWebSocket];
16797
- this.removeListener("error", socketOnError);
16798
- this.on("error", NOOP);
16799
- if (websocket) {
16800
- websocket._readyState = WebSocket.CLOSING;
16801
- this.destroy();
16802
- }
16803
- }
16804
- });
16805
-
16806
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/stream.js
16807
- var require_stream = __commonJS((exports, module) => {
16808
- var WebSocket = require_websocket();
16809
- var { Duplex } = __require("stream");
16810
- function emitClose(stream) {
16811
- stream.emit("close");
16812
- }
16813
- function duplexOnEnd() {
16814
- if (!this.destroyed && this._writableState.finished) {
16815
- this.destroy();
16816
- }
16817
- }
16818
- function duplexOnError(err) {
16819
- this.removeListener("error", duplexOnError);
16820
- this.destroy();
16821
- if (this.listenerCount("error") === 0) {
16822
- this.emit("error", err);
16823
- }
16824
- }
16825
- function createWebSocketStream(ws, options) {
16826
- let terminateOnDestroy = true;
16827
- const duplex = new Duplex({
16828
- ...options,
16829
- autoDestroy: false,
16830
- emitClose: false,
16831
- objectMode: false,
16832
- writableObjectMode: false
16833
- });
16834
- ws.on("message", function message(msg, isBinary) {
16835
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
16836
- if (!duplex.push(data))
16837
- ws.pause();
16838
- });
16839
- ws.once("error", function error(err) {
16840
- if (duplex.destroyed)
16841
- return;
16842
- terminateOnDestroy = false;
16843
- duplex.destroy(err);
16844
- });
16845
- ws.once("close", function close() {
16846
- if (duplex.destroyed)
16847
- return;
16848
- duplex.push(null);
16849
- });
16850
- duplex._destroy = function(err, callback) {
16851
- if (ws.readyState === ws.CLOSED) {
16852
- callback(err);
16853
- process.nextTick(emitClose, duplex);
16854
- return;
16855
- }
16856
- let called = false;
16857
- ws.once("error", function error(err2) {
16858
- called = true;
16859
- callback(err2);
16860
- });
16861
- ws.once("close", function close() {
16862
- if (!called)
16863
- callback(err);
16864
- process.nextTick(emitClose, duplex);
16865
- });
16866
- if (terminateOnDestroy)
16867
- ws.terminate();
16868
- };
16869
- duplex._final = function(callback) {
16870
- if (ws.readyState === ws.CONNECTING) {
16871
- ws.once("open", function open() {
16872
- duplex._final(callback);
16873
- });
16874
- return;
16875
- }
16876
- if (ws._socket === null)
16877
- return;
16878
- if (ws._socket._writableState.finished) {
16879
- callback();
16880
- if (duplex._readableState.endEmitted)
16881
- duplex.destroy();
16882
- } else {
16883
- ws._socket.once("finish", function finish() {
16884
- callback();
16885
- });
16886
- ws.close();
16887
- }
16888
- };
16889
- duplex._read = function() {
16890
- if (ws.isPaused)
16891
- ws.resume();
16892
- };
16893
- duplex._write = function(chunk, encoding, callback) {
16894
- if (ws.readyState === ws.CONNECTING) {
16895
- ws.once("open", function open() {
16896
- duplex._write(chunk, encoding, callback);
16897
- });
16898
- return;
16899
- }
16900
- ws.send(chunk, callback);
16901
- };
16902
- duplex.on("end", duplexOnEnd);
16903
- duplex.on("error", duplexOnError);
16904
- return duplex;
16905
- }
16906
- module.exports = createWebSocketStream;
16907
- });
16908
-
16909
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/subprotocol.js
16910
- var require_subprotocol = __commonJS((exports, module) => {
16911
- var { tokenChars } = require_validation();
16912
- function parse(header) {
16913
- const protocols = new Set;
16914
- let start = -1;
16915
- let end = -1;
16916
- let i = 0;
16917
- for (i;i < header.length; i++) {
16918
- const code = header.charCodeAt(i);
16919
- if (end === -1 && tokenChars[code] === 1) {
16920
- if (start === -1)
16921
- start = i;
16922
- } else if (i !== 0 && (code === 32 || code === 9)) {
16923
- if (end === -1 && start !== -1)
16924
- end = i;
16925
- } else if (code === 44) {
16926
- if (start === -1) {
16927
- throw new SyntaxError(`Unexpected character at index ${i}`);
16928
- }
16929
- if (end === -1)
16930
- end = i;
16931
- const protocol2 = header.slice(start, end);
16932
- if (protocols.has(protocol2)) {
16933
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
16934
- }
16935
- protocols.add(protocol2);
16936
- start = end = -1;
16937
- } else {
16938
- throw new SyntaxError(`Unexpected character at index ${i}`);
16939
- }
16940
- }
16941
- if (start === -1 || end !== -1) {
16942
- throw new SyntaxError("Unexpected end of input");
16943
- }
16944
- const protocol = header.slice(start, i);
16945
- if (protocols.has(protocol)) {
16946
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
16947
- }
16948
- protocols.add(protocol);
16949
- return protocols;
16950
- }
16951
- module.exports = { parse };
16952
- });
16953
-
16954
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/lib/websocket-server.js
16955
- var require_websocket_server = __commonJS((exports, module) => {
16956
- var EventEmitter = __require("events");
16957
- var http = __require("http");
16958
- var { Duplex } = __require("stream");
16959
- var { createHash } = __require("crypto");
16960
- var extension = require_extension();
16961
- var PerMessageDeflate = require_permessage_deflate();
16962
- var subprotocol = require_subprotocol();
16963
- var WebSocket = require_websocket();
16964
- var { GUID, kWebSocket } = require_constants();
16965
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
16966
- var RUNNING = 0;
16967
- var CLOSING = 1;
16968
- var CLOSED = 2;
16969
-
16970
- class WebSocketServer extends EventEmitter {
16971
- constructor(options, callback) {
16972
- super();
16973
- options = {
16974
- allowSynchronousEvents: true,
16975
- autoPong: true,
16976
- maxPayload: 100 * 1024 * 1024,
16977
- skipUTF8Validation: false,
16978
- perMessageDeflate: false,
16979
- handleProtocols: null,
16980
- clientTracking: true,
16981
- verifyClient: null,
16982
- noServer: false,
16983
- backlog: null,
16984
- server: null,
16985
- host: null,
16986
- path: null,
16987
- port: null,
16988
- WebSocket,
16989
- ...options
16990
- };
16991
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
16992
- throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
16993
- }
16994
- if (options.port != null) {
16995
- this._server = http.createServer((req, res) => {
16996
- const body = http.STATUS_CODES[426];
16997
- res.writeHead(426, {
16998
- "Content-Length": body.length,
16999
- "Content-Type": "text/plain"
17000
- });
17001
- res.end(body);
17002
- });
17003
- this._server.listen(options.port, options.host, options.backlog, callback);
17004
- } else if (options.server) {
17005
- this._server = options.server;
17006
- }
17007
- if (this._server) {
17008
- const emitConnection = this.emit.bind(this, "connection");
17009
- this._removeListeners = addListeners(this._server, {
17010
- listening: this.emit.bind(this, "listening"),
17011
- error: this.emit.bind(this, "error"),
17012
- upgrade: (req, socket, head) => {
17013
- this.handleUpgrade(req, socket, head, emitConnection);
17014
- }
17015
- });
17016
- }
17017
- if (options.perMessageDeflate === true)
17018
- options.perMessageDeflate = {};
17019
- if (options.clientTracking) {
17020
- this.clients = new Set;
17021
- this._shouldEmitClose = false;
17022
- }
17023
- this.options = options;
17024
- this._state = RUNNING;
17025
- }
17026
- address() {
17027
- if (this.options.noServer) {
17028
- throw new Error('The server is operating in "noServer" mode');
17029
- }
17030
- if (!this._server)
17031
- return null;
17032
- return this._server.address();
17033
- }
17034
- close(cb) {
17035
- if (this._state === CLOSED) {
17036
- if (cb) {
17037
- this.once("close", () => {
17038
- cb(new Error("The server is not running"));
17039
- });
17040
- }
17041
- process.nextTick(emitClose, this);
17042
- return;
17043
- }
17044
- if (cb)
17045
- this.once("close", cb);
17046
- if (this._state === CLOSING)
17047
- return;
17048
- this._state = CLOSING;
17049
- if (this.options.noServer || this.options.server) {
17050
- if (this._server) {
17051
- this._removeListeners();
17052
- this._removeListeners = this._server = null;
17053
- }
17054
- if (this.clients) {
17055
- if (!this.clients.size) {
17056
- process.nextTick(emitClose, this);
17057
- } else {
17058
- this._shouldEmitClose = true;
17059
- }
17060
- } else {
17061
- process.nextTick(emitClose, this);
17062
- }
17063
- } else {
17064
- const server = this._server;
17065
- this._removeListeners();
17066
- this._removeListeners = this._server = null;
17067
- server.close(() => {
17068
- emitClose(this);
17069
- });
17070
- }
17071
- }
17072
- shouldHandle(req) {
17073
- if (this.options.path) {
17074
- const index = req.url.indexOf("?");
17075
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
17076
- if (pathname !== this.options.path)
17077
- return false;
17078
- }
17079
- return true;
17080
- }
17081
- handleUpgrade(req, socket, head, cb) {
17082
- socket.on("error", socketOnError);
17083
- const key = req.headers["sec-websocket-key"];
17084
- const upgrade = req.headers.upgrade;
17085
- const version = +req.headers["sec-websocket-version"];
17086
- if (req.method !== "GET") {
17087
- const message = "Invalid HTTP method";
17088
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
17089
- return;
17090
- }
17091
- if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
17092
- const message = "Invalid Upgrade header";
17093
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17094
- return;
17095
- }
17096
- if (key === undefined || !keyRegex.test(key)) {
17097
- const message = "Missing or invalid Sec-WebSocket-Key header";
17098
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17099
- return;
17100
- }
17101
- if (version !== 8 && version !== 13) {
17102
- const message = "Missing or invalid Sec-WebSocket-Version header";
17103
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17104
- return;
17105
- }
17106
- if (!this.shouldHandle(req)) {
17107
- abortHandshake(socket, 400);
17108
- return;
17109
- }
17110
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
17111
- let protocols = new Set;
17112
- if (secWebSocketProtocol !== undefined) {
17113
- try {
17114
- protocols = subprotocol.parse(secWebSocketProtocol);
17115
- } catch (err) {
17116
- const message = "Invalid Sec-WebSocket-Protocol header";
17117
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17118
- return;
17119
- }
17120
- }
17121
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
17122
- const extensions = {};
17123
- if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
17124
- const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
17125
- try {
17126
- const offers = extension.parse(secWebSocketExtensions);
17127
- if (offers[PerMessageDeflate.extensionName]) {
17128
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
17129
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
17130
- }
17131
- } catch (err) {
17132
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
17133
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17134
- return;
17135
- }
17136
- }
17137
- if (this.options.verifyClient) {
17138
- const info = {
17139
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
17140
- secure: !!(req.socket.authorized || req.socket.encrypted),
17141
- req
17142
- };
17143
- if (this.options.verifyClient.length === 2) {
17144
- this.options.verifyClient(info, (verified, code, message, headers) => {
17145
- if (!verified) {
17146
- return abortHandshake(socket, code || 401, message, headers);
17147
- }
17148
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
17149
- });
17150
- return;
17151
- }
17152
- if (!this.options.verifyClient(info))
17153
- return abortHandshake(socket, 401);
17154
- }
17155
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
17156
- }
17157
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
17158
- if (!socket.readable || !socket.writable)
17159
- return socket.destroy();
17160
- if (socket[kWebSocket]) {
17161
- throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
17162
- }
17163
- if (this._state > RUNNING)
17164
- return abortHandshake(socket, 503);
17165
- const digest = createHash("sha1").update(key + GUID).digest("base64");
17166
- const headers = [
17167
- "HTTP/1.1 101 Switching Protocols",
17168
- "Upgrade: websocket",
17169
- "Connection: Upgrade",
17170
- `Sec-WebSocket-Accept: ${digest}`
17171
- ];
17172
- const ws = new this.options.WebSocket(null, undefined, this.options);
17173
- if (protocols.size) {
17174
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
17175
- if (protocol) {
17176
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
17177
- ws._protocol = protocol;
17178
- }
17179
- }
17180
- if (extensions[PerMessageDeflate.extensionName]) {
17181
- const params = extensions[PerMessageDeflate.extensionName].params;
17182
- const value = extension.format({
17183
- [PerMessageDeflate.extensionName]: [params]
17184
- });
17185
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
17186
- ws._extensions = extensions;
17187
- }
17188
- this.emit("headers", headers, req);
17189
- socket.write(headers.concat(`\r
17190
- `).join(`\r
17191
- `));
17192
- socket.removeListener("error", socketOnError);
17193
- ws.setSocket(socket, head, {
17194
- allowSynchronousEvents: this.options.allowSynchronousEvents,
17195
- maxPayload: this.options.maxPayload,
17196
- skipUTF8Validation: this.options.skipUTF8Validation
17197
- });
17198
- if (this.clients) {
17199
- this.clients.add(ws);
17200
- ws.on("close", () => {
17201
- this.clients.delete(ws);
17202
- if (this._shouldEmitClose && !this.clients.size) {
17203
- process.nextTick(emitClose, this);
17204
- }
17205
- });
17206
- }
17207
- cb(ws, req);
17208
- }
17209
- }
17210
- module.exports = WebSocketServer;
17211
- function addListeners(server, map) {
17212
- for (const event of Object.keys(map))
17213
- server.on(event, map[event]);
17214
- return function removeListeners() {
17215
- for (const event of Object.keys(map)) {
17216
- server.removeListener(event, map[event]);
17217
- }
17218
- };
17219
- }
17220
- function emitClose(server) {
17221
- server._state = CLOSED;
17222
- server.emit("close");
17223
- }
17224
- function socketOnError() {
17225
- this.destroy();
17226
- }
17227
- function abortHandshake(socket, code, message, headers) {
17228
- message = message || http.STATUS_CODES[code];
17229
- headers = {
17230
- Connection: "close",
17231
- "Content-Type": "text/html",
17232
- "Content-Length": Buffer.byteLength(message),
17233
- ...headers
17234
- };
17235
- socket.once("finish", socket.destroy);
17236
- socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
17237
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
17238
- `) + `\r
17239
- \r
17240
- ` + message);
17241
- }
17242
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
17243
- if (server.listenerCount("wsClientError")) {
17244
- const err = new Error(message);
17245
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
17246
- server.emit("wsClientError", err, socket, req);
17247
- } else {
17248
- abortHandshake(socket, code, message);
17249
- }
17250
- }
17251
- });
17252
-
17253
14444
  // ../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/array.js
17254
14445
  var require_array = __commonJS((exports) => {
17255
14446
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -18242,7 +15433,7 @@ var require_expand = __commonJS((exports, module) => {
18242
15433
  });
18243
15434
 
18244
15435
  // ../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js
18245
- var require_constants2 = __commonJS((exports, module) => {
15436
+ var require_constants = __commonJS((exports, module) => {
18246
15437
  module.exports = {
18247
15438
  MAX_LENGTH: 1e4,
18248
15439
  CHAR_0: "0",
@@ -18312,7 +15503,7 @@ var require_parse = __commonJS((exports, module) => {
18312
15503
  CHAR_SINGLE_QUOTE,
18313
15504
  CHAR_NO_BREAK_SPACE,
18314
15505
  CHAR_ZERO_WIDTH_NOBREAK_SPACE
18315
- } = require_constants2();
15506
+ } = require_constants();
18316
15507
  var parse = (input, options = {}) => {
18317
15508
  if (typeof input !== "string") {
18318
15509
  throw new TypeError("Expected a string");
@@ -18581,7 +15772,7 @@ var require_braces = __commonJS((exports, module) => {
18581
15772
  });
18582
15773
 
18583
15774
  // ../node_modules/.pnpm/picomatch@2.3.1/node_modules/picomatch/lib/constants.js
18584
- var require_constants3 = __commonJS((exports, module) => {
15775
+ var require_constants2 = __commonJS((exports, module) => {
18585
15776
  var path6 = __require("path");
18586
15777
  var WIN_SLASH = "\\\\/";
18587
15778
  var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
@@ -18729,7 +15920,7 @@ var require_utils2 = __commonJS((exports) => {
18729
15920
  REGEX_REMOVE_BACKSLASH,
18730
15921
  REGEX_SPECIAL_CHARS,
18731
15922
  REGEX_SPECIAL_CHARS_GLOBAL
18732
- } = require_constants3();
15923
+ } = require_constants2();
18733
15924
  exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
18734
15925
  exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
18735
15926
  exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
@@ -18799,7 +15990,7 @@ var require_scan = __commonJS((exports, module) => {
18799
15990
  CHAR_RIGHT_CURLY_BRACE,
18800
15991
  CHAR_RIGHT_PARENTHESES,
18801
15992
  CHAR_RIGHT_SQUARE_BRACKET
18802
- } = require_constants3();
15993
+ } = require_constants2();
18803
15994
  var isPathSeparator = (code) => {
18804
15995
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
18805
15996
  };
@@ -19097,7 +16288,7 @@ var require_scan = __commonJS((exports, module) => {
19097
16288
 
19098
16289
  // ../node_modules/.pnpm/picomatch@2.3.1/node_modules/picomatch/lib/parse.js
19099
16290
  var require_parse2 = __commonJS((exports, module) => {
19100
- var constants2 = require_constants3();
16291
+ var constants2 = require_constants2();
19101
16292
  var utils2 = require_utils2();
19102
16293
  var {
19103
16294
  MAX_LENGTH,
@@ -19879,7 +17070,7 @@ var require_picomatch = __commonJS((exports, module) => {
19879
17070
  var scan = require_scan();
19880
17071
  var parse = require_parse2();
19881
17072
  var utils2 = require_utils2();
19882
- var constants2 = require_constants3();
17073
+ var constants2 = require_constants2();
19883
17074
  var isObject3 = (val) => val && typeof val === "object" && !Array.isArray(val);
19884
17075
  var picomatch2 = (glob2, options, returnState = false) => {
19885
17076
  if (Array.isArray(glob2)) {
@@ -20457,7 +17648,7 @@ var require_merge2 = __commonJS((exports, module) => {
20457
17648
  });
20458
17649
 
20459
17650
  // ../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/stream.js
20460
- var require_stream2 = __commonJS((exports) => {
17651
+ var require_stream = __commonJS((exports) => {
20461
17652
  Object.defineProperty(exports, "__esModule", { value: true });
20462
17653
  exports.merge = undefined;
20463
17654
  var merge22 = require_merge2();
@@ -20504,7 +17695,7 @@ var require_utils3 = __commonJS((exports) => {
20504
17695
  exports.path = path6;
20505
17696
  var pattern2 = require_pattern();
20506
17697
  exports.pattern = pattern2;
20507
- var stream2 = require_stream2();
17698
+ var stream2 = require_stream();
20508
17699
  exports.stream = stream2;
20509
17700
  var string2 = require_string();
20510
17701
  exports.string = string2;
@@ -20788,7 +17979,7 @@ var require_run_parallel = __commonJS((exports, module) => {
20788
17979
  });
20789
17980
 
20790
17981
  // ../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/constants.js
20791
- var require_constants4 = __commonJS((exports) => {
17982
+ var require_constants3 = __commonJS((exports) => {
20792
17983
  Object.defineProperty(exports, "__esModule", { value: true });
20793
17984
  exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = undefined;
20794
17985
  var NODE_PROCESS_VERSION_PARTS = process.versions.node.split(".");
@@ -20854,7 +18045,7 @@ var require_async2 = __commonJS((exports) => {
20854
18045
  exports.readdir = exports.readdirWithFileTypes = exports.read = undefined;
20855
18046
  var fsStat = require_out();
20856
18047
  var rpl = require_run_parallel();
20857
- var constants_1 = require_constants4();
18048
+ var constants_1 = require_constants3();
20858
18049
  var utils2 = require_utils4();
20859
18050
  var common2 = require_common2();
20860
18051
  function read(directory, settings2, callback) {
@@ -20960,7 +18151,7 @@ var require_sync2 = __commonJS((exports) => {
20960
18151
  Object.defineProperty(exports, "__esModule", { value: true });
20961
18152
  exports.readdir = exports.readdirWithFileTypes = exports.read = undefined;
20962
18153
  var fsStat = require_out();
20963
- var constants_1 = require_constants4();
18154
+ var constants_1 = require_constants3();
20964
18155
  var utils2 = require_utils4();
20965
18156
  var common2 = require_common2();
20966
18157
  function read(directory, settings2) {
@@ -21557,7 +18748,7 @@ var require_async4 = __commonJS((exports) => {
21557
18748
  });
21558
18749
 
21559
18750
  // ../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/stream.js
21560
- var require_stream3 = __commonJS((exports) => {
18751
+ var require_stream2 = __commonJS((exports) => {
21561
18752
  Object.defineProperty(exports, "__esModule", { value: true });
21562
18753
  var stream_1 = __require("stream");
21563
18754
  var async_1 = require_async3();
@@ -21709,7 +18900,7 @@ var require_out3 = __commonJS((exports) => {
21709
18900
  Object.defineProperty(exports, "__esModule", { value: true });
21710
18901
  exports.Settings = exports.walkStream = exports.walkSync = exports.walk = undefined;
21711
18902
  var async_1 = require_async4();
21712
- var stream_1 = require_stream3();
18903
+ var stream_1 = require_stream2();
21713
18904
  var sync_1 = require_sync4();
21714
18905
  var settings_1 = require_settings3();
21715
18906
  exports.Settings = settings_1.default;
@@ -21779,7 +18970,7 @@ var require_reader2 = __commonJS((exports) => {
21779
18970
  });
21780
18971
 
21781
18972
  // ../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/stream.js
21782
- var require_stream4 = __commonJS((exports) => {
18973
+ var require_stream3 = __commonJS((exports) => {
21783
18974
  Object.defineProperty(exports, "__esModule", { value: true });
21784
18975
  var stream_1 = __require("stream");
21785
18976
  var fsStat = require_out();
@@ -21838,7 +19029,7 @@ var require_async5 = __commonJS((exports) => {
21838
19029
  Object.defineProperty(exports, "__esModule", { value: true });
21839
19030
  var fsWalk = require_out3();
21840
19031
  var reader_1 = require_reader2();
21841
- var stream_1 = require_stream4();
19032
+ var stream_1 = require_stream3();
21842
19033
 
21843
19034
  class ReaderAsync extends reader_1.default {
21844
19035
  constructor() {
@@ -22232,10 +19423,10 @@ var require_async6 = __commonJS((exports) => {
22232
19423
  });
22233
19424
 
22234
19425
  // ../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/stream.js
22235
- var require_stream5 = __commonJS((exports) => {
19426
+ var require_stream4 = __commonJS((exports) => {
22236
19427
  Object.defineProperty(exports, "__esModule", { value: true });
22237
19428
  var stream_1 = __require("stream");
22238
- var stream_2 = require_stream4();
19429
+ var stream_2 = require_stream3();
22239
19430
  var provider_1 = require_provider();
22240
19431
 
22241
19432
  class ProviderStream extends provider_1.default {
@@ -22397,7 +19588,7 @@ var require_settings4 = __commonJS((exports) => {
22397
19588
  var require_out4 = __commonJS((exports, module) => {
22398
19589
  var taskManager = require_tasks();
22399
19590
  var async_1 = require_async6();
22400
- var stream_1 = require_stream5();
19591
+ var stream_1 = require_stream4();
22401
19592
  var sync_1 = require_sync6();
22402
19593
  var settings_1 = require_settings4();
22403
19594
  var utils2 = require_utils3();
@@ -22491,6 +19682,184 @@ var require_out4 = __commonJS((exports, module) => {
22491
19682
  module.exports = FastGlob;
22492
19683
  });
22493
19684
 
19685
+ // ../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js
19686
+ var require_eventemitter3 = __commonJS((exports, module) => {
19687
+ var has = Object.prototype.hasOwnProperty;
19688
+ var prefix = "~";
19689
+ function Events() {}
19690
+ if (Object.create) {
19691
+ Events.prototype = Object.create(null);
19692
+ if (!new Events().__proto__)
19693
+ prefix = false;
19694
+ }
19695
+ function EE(fn, context, once) {
19696
+ this.fn = fn;
19697
+ this.context = context;
19698
+ this.once = once || false;
19699
+ }
19700
+ function addListener(emitter, event, fn, context, once) {
19701
+ if (typeof fn !== "function") {
19702
+ throw new TypeError("The listener must be a function");
19703
+ }
19704
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
19705
+ if (!emitter._events[evt])
19706
+ emitter._events[evt] = listener, emitter._eventsCount++;
19707
+ else if (!emitter._events[evt].fn)
19708
+ emitter._events[evt].push(listener);
19709
+ else
19710
+ emitter._events[evt] = [emitter._events[evt], listener];
19711
+ return emitter;
19712
+ }
19713
+ function clearEvent(emitter, evt) {
19714
+ if (--emitter._eventsCount === 0)
19715
+ emitter._events = new Events;
19716
+ else
19717
+ delete emitter._events[evt];
19718
+ }
19719
+ function EventEmitter() {
19720
+ this._events = new Events;
19721
+ this._eventsCount = 0;
19722
+ }
19723
+ EventEmitter.prototype.eventNames = function eventNames() {
19724
+ var names = [], events, name;
19725
+ if (this._eventsCount === 0)
19726
+ return names;
19727
+ for (name in events = this._events) {
19728
+ if (has.call(events, name))
19729
+ names.push(prefix ? name.slice(1) : name);
19730
+ }
19731
+ if (Object.getOwnPropertySymbols) {
19732
+ return names.concat(Object.getOwnPropertySymbols(events));
19733
+ }
19734
+ return names;
19735
+ };
19736
+ EventEmitter.prototype.listeners = function listeners(event) {
19737
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
19738
+ if (!handlers)
19739
+ return [];
19740
+ if (handlers.fn)
19741
+ return [handlers.fn];
19742
+ for (var i = 0, l = handlers.length, ee = new Array(l);i < l; i++) {
19743
+ ee[i] = handlers[i].fn;
19744
+ }
19745
+ return ee;
19746
+ };
19747
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
19748
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
19749
+ if (!listeners)
19750
+ return 0;
19751
+ if (listeners.fn)
19752
+ return 1;
19753
+ return listeners.length;
19754
+ };
19755
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
19756
+ var evt = prefix ? prefix + event : event;
19757
+ if (!this._events[evt])
19758
+ return false;
19759
+ var listeners = this._events[evt], len = arguments.length, args, i;
19760
+ if (listeners.fn) {
19761
+ if (listeners.once)
19762
+ this.removeListener(event, listeners.fn, undefined, true);
19763
+ switch (len) {
19764
+ case 1:
19765
+ return listeners.fn.call(listeners.context), true;
19766
+ case 2:
19767
+ return listeners.fn.call(listeners.context, a1), true;
19768
+ case 3:
19769
+ return listeners.fn.call(listeners.context, a1, a2), true;
19770
+ case 4:
19771
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
19772
+ case 5:
19773
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
19774
+ case 6:
19775
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
19776
+ }
19777
+ for (i = 1, args = new Array(len - 1);i < len; i++) {
19778
+ args[i - 1] = arguments[i];
19779
+ }
19780
+ listeners.fn.apply(listeners.context, args);
19781
+ } else {
19782
+ var length = listeners.length, j;
19783
+ for (i = 0;i < length; i++) {
19784
+ if (listeners[i].once)
19785
+ this.removeListener(event, listeners[i].fn, undefined, true);
19786
+ switch (len) {
19787
+ case 1:
19788
+ listeners[i].fn.call(listeners[i].context);
19789
+ break;
19790
+ case 2:
19791
+ listeners[i].fn.call(listeners[i].context, a1);
19792
+ break;
19793
+ case 3:
19794
+ listeners[i].fn.call(listeners[i].context, a1, a2);
19795
+ break;
19796
+ case 4:
19797
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
19798
+ break;
19799
+ default:
19800
+ if (!args)
19801
+ for (j = 1, args = new Array(len - 1);j < len; j++) {
19802
+ args[j - 1] = arguments[j];
19803
+ }
19804
+ listeners[i].fn.apply(listeners[i].context, args);
19805
+ }
19806
+ }
19807
+ }
19808
+ return true;
19809
+ };
19810
+ EventEmitter.prototype.on = function on(event, fn, context) {
19811
+ return addListener(this, event, fn, context, false);
19812
+ };
19813
+ EventEmitter.prototype.once = function once(event, fn, context) {
19814
+ return addListener(this, event, fn, context, true);
19815
+ };
19816
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
19817
+ var evt = prefix ? prefix + event : event;
19818
+ if (!this._events[evt])
19819
+ return this;
19820
+ if (!fn) {
19821
+ clearEvent(this, evt);
19822
+ return this;
19823
+ }
19824
+ var listeners = this._events[evt];
19825
+ if (listeners.fn) {
19826
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
19827
+ clearEvent(this, evt);
19828
+ }
19829
+ } else {
19830
+ for (var i = 0, events = [], length = listeners.length;i < length; i++) {
19831
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
19832
+ events.push(listeners[i]);
19833
+ }
19834
+ }
19835
+ if (events.length)
19836
+ this._events[evt] = events.length === 1 ? events[0] : events;
19837
+ else
19838
+ clearEvent(this, evt);
19839
+ }
19840
+ return this;
19841
+ };
19842
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
19843
+ var evt;
19844
+ if (event) {
19845
+ evt = prefix ? prefix + event : event;
19846
+ if (this._events[evt])
19847
+ clearEvent(this, evt);
19848
+ } else {
19849
+ this._events = new Events;
19850
+ this._eventsCount = 0;
19851
+ }
19852
+ return this;
19853
+ };
19854
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
19855
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
19856
+ EventEmitter.prefixed = prefix;
19857
+ EventEmitter.EventEmitter = EventEmitter;
19858
+ if (typeof module !== "undefined") {
19859
+ module.exports = EventEmitter;
19860
+ }
19861
+ });
19862
+
22494
19863
  // ../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/dayjs.min.js
22495
19864
  var require_dayjs_min = __commonJS((exports, module) => {
22496
19865
  (function(t, e) {
@@ -41393,7 +38762,9 @@ class AssistantConfig {
41393
38762
  if (!checkFileExists(this.configPath.configPath)) {
41394
38763
  fs2.writeFileSync(this.configPath.configPath, JSON.stringify({ proxy: [] }, null, 2));
41395
38764
  return {
41396
- pageApi: "",
38765
+ app: {
38766
+ url: "https://kevisual.cn"
38767
+ },
41397
38768
  proxy: []
41398
38769
  };
41399
38770
  }
@@ -41402,7 +38773,9 @@ class AssistantConfig {
41402
38773
  } catch (error) {
41403
38774
  console.error("file read", error.message);
41404
38775
  return {
41405
- pageApi: "",
38776
+ app: {
38777
+ url: "https://kevisual.cn"
38778
+ },
41406
38779
  proxy: []
41407
38780
  };
41408
38781
  }
@@ -41415,9 +38788,14 @@ class AssistantConfig {
41415
38788
  }
41416
38789
  getRegistry() {
41417
38790
  const config = this.getCacheAssistantConfig();
41418
- return config?.registry || config?.pageApi;
38791
+ return config?.registry || config?.app?.url || "https://kevisual.cn";
41419
38792
  }
41420
- setConfig(config) {
38793
+ setConfig(config, force) {
38794
+ if (force) {
38795
+ this.config = config || {};
38796
+ fs2.writeFileSync(this.configPath.configPath, JSON.stringify(this.config, null, 2));
38797
+ return this.config;
38798
+ }
41421
38799
  const myConfig = this.getCacheAssistantConfig();
41422
38800
  const newConfig = { ...myConfig, ...config };
41423
38801
  this.config = newConfig;
@@ -41645,17 +39023,10 @@ var console2 = {
41645
39023
  // src/module/assistant/proxy/index.ts
41646
39024
  var import_send2 = __toESM(require_send(), 1);
41647
39025
 
41648
- // ../node_modules/.pnpm/@kevisual+ws@8.0.0/node_modules/@kevisual/ws/wrapper.mjs
41649
- var import_stream = __toESM(require_stream(), 1);
41650
- var import_receiver = __toESM(require_receiver(), 1);
41651
- var import_sender = __toESM(require_sender(), 1);
41652
- var import_websocket = __toESM(require_websocket(), 1);
41653
- var import_websocket_server = __toESM(require_websocket_server(), 1);
41654
-
41655
- // src/module/assistant/proxy/ws-proxy.ts
41656
- var wss = new import_websocket_server.default({
41657
- noServer: true
41658
- });
39026
+ // src/module/assistant/proxy/utils.ts
39027
+ var isBun = typeof Bun !== "undefined" && Bun?.version != null;
39028
+ var isNode = typeof process !== "undefined" && process?.versions != null && process.versions?.node != null;
39029
+ var isDeno = typeof Deno !== "undefined" && Deno?.version != null && Deno?.version?.deno != null;
41659
39030
  // ../node_modules/.pnpm/@kevisual+local-app-manager@0.1.32_supports-color@10.2.2/node_modules/@kevisual/local-app-manager/dist/manager.mjs
41660
39031
  var exports_manager = {};
41661
39032
  __export(exports_manager, {
@@ -50404,9 +47775,173 @@ var import_fast_glob2 = __toESM(require_out4(), 1);
50404
47775
  import path7 from "node:path";
50405
47776
  import fs8 from "node:fs";
50406
47777
 
47778
+ // ../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs
47779
+ var import__2 = __toESM(require_eventemitter3(), 1);
47780
+
47781
+ // src/module/remote-app/remote-app.ts
47782
+ class RemoteApp {
47783
+ mainApp;
47784
+ url;
47785
+ id;
47786
+ emitter;
47787
+ isConnected;
47788
+ ws;
47789
+ remoteIsConnected;
47790
+ isError = false;
47791
+ constructor(opts) {
47792
+ this.mainApp = opts?.app;
47793
+ const token = opts.token;
47794
+ const url = opts.url;
47795
+ const id = opts.id;
47796
+ this.emitter = opts?.emitter || new import__2.default;
47797
+ const _url = new URL(url);
47798
+ if (token) {
47799
+ _url.searchParams.set("token", token);
47800
+ }
47801
+ _url.searchParams.set("id", id);
47802
+ this.url = _url.toString();
47803
+ this.id = id;
47804
+ this.init();
47805
+ }
47806
+ async isConnect() {
47807
+ const that = this;
47808
+ if (this.isConnected) {
47809
+ return true;
47810
+ }
47811
+ return new Promise((resolve) => {
47812
+ const timeout = setTimeout(() => {
47813
+ resolve(false);
47814
+ that.emitter.off("open", listenOnce);
47815
+ }, 5000);
47816
+ const listenOnce = () => {
47817
+ clearTimeout(timeout);
47818
+ that.isConnected = true;
47819
+ that.remoteIsConnected = true;
47820
+ resolve(true);
47821
+ };
47822
+ that.emitter.once("open", listenOnce);
47823
+ });
47824
+ }
47825
+ getWsURL(url) {
47826
+ const { protocol } = new URL(url);
47827
+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
47828
+ const wsURL = url.toString().replace(protocol, wsProtocol);
47829
+ return wsURL;
47830
+ }
47831
+ async init() {
47832
+ if (!this.url) {
47833
+ throw new Error("No url provided for remote app");
47834
+ }
47835
+ if (!this.id) {
47836
+ throw new Error("No id provided for remote app");
47837
+ }
47838
+ this.isError = false;
47839
+ const ws = new WebSocket(this.getWsURL(this.url));
47840
+ const that = this;
47841
+ ws.onopen = function() {
47842
+ that.isConnected = true;
47843
+ that.onOpen();
47844
+ };
47845
+ ws.onclose = function() {
47846
+ that.isConnected = false;
47847
+ that.onClose();
47848
+ };
47849
+ ws.onmessage = function(event) {
47850
+ that.onMessage(event.data);
47851
+ };
47852
+ ws.onerror = function(error2) {
47853
+ that.onError(error2);
47854
+ };
47855
+ this.ws = ws;
47856
+ }
47857
+ onOpen() {
47858
+ this.emitter.emit("open", this.id);
47859
+ }
47860
+ onClose() {
47861
+ console.log("远程应用关闭:", this.id);
47862
+ this.emitter.emit("close", this.id);
47863
+ this.isConnected = false;
47864
+ }
47865
+ onMessage(data) {
47866
+ this.emitter.emit("message", data);
47867
+ }
47868
+ onError(error2) {
47869
+ console.error("远程应用错误:", this.id, error2);
47870
+ this.isError = true;
47871
+ this.emitter.emit("error", error2);
47872
+ }
47873
+ on(event, listener) {
47874
+ this.emitter.on(event, listener);
47875
+ return () => {
47876
+ this.emitter.off(event, listener);
47877
+ };
47878
+ }
47879
+ sendData(data) {}
47880
+ json(data) {
47881
+ this.ws.send(JSON.stringify(data));
47882
+ }
47883
+ listenProxy() {
47884
+ const remoteApp = this;
47885
+ const app = this.mainApp;
47886
+ const listenFn = async (event) => {
47887
+ try {
47888
+ const data = event.toString();
47889
+ const body = JSON.parse(data);
47890
+ const message = body.data || {};
47891
+ if (body?.code === 401) {
47892
+ console.error("远程应用认证失败,请检查 token 是否正确");
47893
+ this.isError = true;
47894
+ return;
47895
+ }
47896
+ if (body?.type !== "proxy")
47897
+ return;
47898
+ if (!body.id) {
47899
+ remoteApp.json({
47900
+ id: body.id,
47901
+ data: {
47902
+ code: 400,
47903
+ message: "id is required"
47904
+ }
47905
+ });
47906
+ return;
47907
+ }
47908
+ const res = await app.call(message);
47909
+ remoteApp.json({
47910
+ id: body.id,
47911
+ data: {
47912
+ code: res.code,
47913
+ data: res.body,
47914
+ message: res.message
47915
+ }
47916
+ });
47917
+ } catch (error2) {
47918
+ console.error("处理远程代理请求出错:", error2);
47919
+ }
47920
+ };
47921
+ remoteApp.json({
47922
+ id: this.id,
47923
+ type: "registryClient"
47924
+ });
47925
+ remoteApp.emitter.on("message", listenFn);
47926
+ const closeMessage = () => {
47927
+ remoteApp.emitter.off("message", listenFn);
47928
+ };
47929
+ remoteApp.emitter.once("close", () => {
47930
+ closeMessage();
47931
+ });
47932
+ return () => {
47933
+ closeMessage();
47934
+ };
47935
+ }
47936
+ }
47937
+
47938
+ // src/module/assistant/local-app-manager/assistant-app.ts
50407
47939
  class AssistantApp extends Manager2 {
50408
47940
  config;
50409
47941
  pagesPath;
47942
+ remoteIsConnected = false;
47943
+ attemptedConnectTimes = 0;
47944
+ remoteApp = null;
50410
47945
  constructor(config, mainApp) {
50411
47946
  config.checkMounted();
50412
47947
  const appsPath = config?.configPath?.appsDir || path7.join(process.cwd(), "apps");
@@ -50464,8 +47999,61 @@ class AssistantApp extends Manager2 {
50464
47999
  });
50465
48000
  return pagesParse;
50466
48001
  }
48002
+ async initRemoteApp() {
48003
+ const config = this.config.getConfig();
48004
+ const share = config?.share;
48005
+ if (share && share.enabled !== false) {
48006
+ const token = config?.token;
48007
+ const url = new URL(share.url || "https://kevisual.cn/ws/proxy");
48008
+ const id = config?.app?.id;
48009
+ if (token && url && id) {
48010
+ const remoteApp = new RemoteApp({
48011
+ url: url.toString(),
48012
+ token,
48013
+ id,
48014
+ app: this.mainApp
48015
+ });
48016
+ const isConnect = await remoteApp.isConnect();
48017
+ if (isConnect) {
48018
+ remoteApp.listenProxy();
48019
+ this.remoteIsConnected = true;
48020
+ remoteApp.emitter.once("close", () => {
48021
+ setTimeout(() => {
48022
+ if (remoteApp.isError) {
48023
+ console.error("远程应用发生错误,不重连");
48024
+ } else {
48025
+ this.reconnectRemoteApp();
48026
+ }
48027
+ }, 5 * 1000);
48028
+ });
48029
+ logger.debug("链接到了远程应用服务器");
48030
+ } else {
48031
+ console.log("Not connected to remote app server");
48032
+ }
48033
+ this.remoteApp = remoteApp;
48034
+ } else {}
48035
+ }
48036
+ }
48037
+ async reconnectRemoteApp() {
48038
+ console.log("重新连接到远程应用服务器...", this.attemptedConnectTimes);
48039
+ const remoteApp = this.remoteApp;
48040
+ if (remoteApp) {
48041
+ remoteApp.init();
48042
+ this.attemptedConnectTimes += 1;
48043
+ const isConnect = await remoteApp.isConnect();
48044
+ if (isConnect) {
48045
+ remoteApp.listenProxy();
48046
+ this.attemptedConnectTimes = 0;
48047
+ console.log("重新连接到了远程应用服务器");
48048
+ } else {
48049
+ setTimeout(() => {
48050
+ this.reconnectRemoteApp();
48051
+ }, 30 * 1000);
48052
+ }
48053
+ }
48054
+ }
50467
48055
  }
50468
- // ../node_modules/.pnpm/@kevisual+query@0.0.32/node_modules/@kevisual/query/dist/query.js
48056
+ // ../node_modules/.pnpm/@kevisual+query@0.0.33/node_modules/@kevisual/query/dist/query.js
50469
48057
  var isTextForContentType = (contentType) => {
50470
48058
  if (!contentType)
50471
48059
  return false;
@@ -50532,7 +48120,7 @@ var adapter = async (opts = {}, overloadOpts) => {
50532
48120
  return await response.json();
50533
48121
  } else if (isTextForContentType(contentType)) {
50534
48122
  return {
50535
- code: 200,
48123
+ code: response.status,
50536
48124
  status: response.status,
50537
48125
  data: await response.text()
50538
48126
  };
@@ -50571,9 +48159,11 @@ class Query {
50571
48159
  timeout;
50572
48160
  stop;
50573
48161
  qws;
48162
+ isClient = false;
50574
48163
  constructor(opts) {
50575
48164
  this.adapter = opts?.adapter || adapter;
50576
- this.url = opts?.url || "/api/router";
48165
+ const defaultURL = opts?.isClient ? "/client/router" : "/api/router";
48166
+ this.url = opts?.url || defaultURL;
50577
48167
  this.headers = opts?.headers || {
50578
48168
  "Content-Type": "application/json"
50579
48169
  };
@@ -51215,7 +48805,7 @@ var source_default = chalk;
51215
48805
  // src/module/chalk.ts
51216
48806
  var chalk2 = new Chalk({ level: 3 });
51217
48807
 
51218
- // ../node_modules/.pnpm/@kevisual+router@0.0.39_supports-color@10.2.2/node_modules/@kevisual/router/dist/router-sign.js
48808
+ // ../node_modules/.pnpm/@kevisual+router@0.0.49_supports-color@10.2.2/node_modules/@kevisual/router/dist/router-sign.js
51219
48809
  import require$$1 from "node:crypto";
51220
48810
  var commonjsGlobal2 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
51221
48811
  function getAugmentedNamespace(n) {
@@ -54012,7 +51602,9 @@ class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
54012
51602
  return new ArrayBuffer(this.valueHexView.byteLength + 1);
54013
51603
  }
54014
51604
  if (!this.valueHexView.byteLength) {
54015
- return EMPTY_BUFFER;
51605
+ const empty = new Uint8Array(1);
51606
+ empty[0] = 0;
51607
+ return empty.buffer;
54016
51608
  }
54017
51609
  const retView = new Uint8Array(this.valueHexView.length + 1);
54018
51610
  retView[0] = this.unusedBits;
@@ -64530,9 +62122,12 @@ class AssistantInit extends AssistantConfig {
64530
62122
  }
64531
62123
  return this.#query;
64532
62124
  }
62125
+ get baseURL() {
62126
+ return `${this.getConfig()?.app?.url || "https://kevisual.cn"}/api/router`;
62127
+ }
64533
62128
  setQuery(query2) {
64534
62129
  this.#query = query2 || new Query({
64535
- url: `${this.getConfig()?.pageApi || "https://kevisual.cn"}/api/router`
62130
+ url: `${this.getConfig()?.app?.url || "https://kevisual.cn"}/api/router`
64536
62131
  });
64537
62132
  }
64538
62133
  checkConfigPath() {
@@ -64566,6 +62161,16 @@ class AssistantInit extends AssistantConfig {
64566
62161
  if (!checkFileExists(assistantPath, true)) {
64567
62162
  this.setConfig(this.getDefaultInitAssistantConfig());
64568
62163
  console.log(chalk2.green("助手配置文件assistant-config.json创建成功"));
62164
+ } else {
62165
+ const config2 = this.getConfig();
62166
+ if (!config2?.app?.id) {
62167
+ if (!config2.app) {
62168
+ config2.app = {};
62169
+ }
62170
+ config2.app.id = randomId();
62171
+ this.setConfig(config2);
62172
+ console.log(chalk2.green("助手配置文件assistant-config.json更新成功"));
62173
+ }
64569
62174
  }
64570
62175
  }
64571
62176
  initPnpm() {
@@ -64589,7 +62194,7 @@ class AssistantInit extends AssistantConfig {
64589
62194
  "type": "module",
64590
62195
  "scripts": {
64591
62196
  "start": "pm2 start apps/root/code-center/app.mjs --name root/code-center",
64592
- "proxy": "pm2 start apps/root/page-proxy/app.mjs --name root/page-proxy"
62197
+ "cnb": "ASSISTANT_CONFIG_DIR=/workspace asst server -s -p 7878"
64593
62198
  },
64594
62199
  "keywords": [],
64595
62200
  "author": "",
@@ -64664,19 +62269,17 @@ ${line}`;
64664
62269
  getDefaultInitAssistantConfig() {
64665
62270
  const id = randomId();
64666
62271
  return {
64667
- id,
62272
+ app: {
62273
+ url: "https://kevisual.cn",
62274
+ id
62275
+ },
64668
62276
  description: "助手配置文件",
64669
- docs: "https://kevisual.cn/root/cli-docs/",
62277
+ docs: "https://kevisual.cn/root/cli/docs/",
64670
62278
  home: "/root/home",
64671
62279
  proxy: [],
64672
- apiProxyList: [],
64673
62280
  share: {
64674
62281
  enabled: false,
64675
- name: "abc",
64676
62282
  url: "https://kevisual.cn/ws/proxy"
64677
- },
64678
- watch: {
64679
- enabled: true
64680
62283
  }
64681
62284
  };
64682
62285
  }