zefiro 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -32,6 +32,24 @@ import {
32
32
  union,
33
33
  unknown
34
34
  } from "./cli-z2krvkcq.js";
35
+ import {
36
+ AgentBrowser,
37
+ authenticate
38
+ } from "./cli-b26q1e27.js";
39
+ import {
40
+ generateIndexHtml,
41
+ generateReadme,
42
+ generateSectionMarkdown
43
+ } from "./cli-kjyet1n8.js";
44
+ import {
45
+ ensureDir,
46
+ writeFile
47
+ } from "./cli-zvk8gwe4.js";
48
+ import {
49
+ buildTopology,
50
+ normalizeUrl,
51
+ urlToSlug
52
+ } from "./cli-5w708rbb.js";
35
53
  import {
36
54
  __commonJS,
37
55
  __require,
@@ -6510,183 +6528,3035 @@ var require_dist = __commonJS((exports, module) => {
6510
6528
  exports.default = formatsPlugin;
6511
6529
  });
6512
6530
 
6513
- // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v3/helpers/util.js
6514
- var util;
6515
- (function(util2) {
6516
- util2.assertEqual = (_) => {};
6517
- function assertIs(_arg) {}
6518
- util2.assertIs = assertIs;
6519
- function assertNever(_x) {
6520
- throw new Error;
6531
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/constants.js
6532
+ var require_constants = __commonJS((exports, module) => {
6533
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
6534
+ var hasBlob = typeof Blob !== "undefined";
6535
+ if (hasBlob)
6536
+ BINARY_TYPES.push("blob");
6537
+ module.exports = {
6538
+ BINARY_TYPES,
6539
+ CLOSE_TIMEOUT: 30000,
6540
+ EMPTY_BUFFER: Buffer.alloc(0),
6541
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
6542
+ hasBlob,
6543
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
6544
+ kListener: Symbol("kListener"),
6545
+ kStatusCode: Symbol("status-code"),
6546
+ kWebSocket: Symbol("websocket"),
6547
+ NOOP: () => {}
6548
+ };
6549
+ });
6550
+
6551
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/buffer-util.js
6552
+ var require_buffer_util = __commonJS((exports, module) => {
6553
+ var { EMPTY_BUFFER } = require_constants();
6554
+ var FastBuffer = Buffer[Symbol.species];
6555
+ function concat(list, totalLength) {
6556
+ if (list.length === 0)
6557
+ return EMPTY_BUFFER;
6558
+ if (list.length === 1)
6559
+ return list[0];
6560
+ const target = Buffer.allocUnsafe(totalLength);
6561
+ let offset = 0;
6562
+ for (let i = 0;i < list.length; i++) {
6563
+ const buf = list[i];
6564
+ target.set(buf, offset);
6565
+ offset += buf.length;
6566
+ }
6567
+ if (offset < totalLength) {
6568
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
6569
+ }
6570
+ return target;
6521
6571
  }
6522
- util2.assertNever = assertNever;
6523
- util2.arrayToEnum = (items) => {
6524
- const obj = {};
6525
- for (const item of items) {
6526
- obj[item] = item;
6572
+ function _mask(source, mask, output, offset, length) {
6573
+ for (let i = 0;i < length; i++) {
6574
+ output[offset + i] = source[i] ^ mask[i & 3];
6527
6575
  }
6528
- return obj;
6529
- };
6530
- util2.getValidEnumValues = (obj) => {
6531
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
6532
- const filtered = {};
6533
- for (const k of validKeys) {
6534
- filtered[k] = obj[k];
6576
+ }
6577
+ function _unmask(buffer, mask) {
6578
+ for (let i = 0;i < buffer.length; i++) {
6579
+ buffer[i] ^= mask[i & 3];
6535
6580
  }
6536
- return util2.objectValues(filtered);
6537
- };
6538
- util2.objectValues = (obj) => {
6539
- return util2.objectKeys(obj).map(function(e) {
6540
- return obj[e];
6541
- });
6542
- };
6543
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
6544
- const keys = [];
6545
- for (const key in object2) {
6546
- if (Object.prototype.hasOwnProperty.call(object2, key)) {
6547
- keys.push(key);
6548
- }
6581
+ }
6582
+ function toArrayBuffer(buf) {
6583
+ if (buf.length === buf.buffer.byteLength) {
6584
+ return buf.buffer;
6549
6585
  }
6550
- return keys;
6551
- };
6552
- util2.find = (arr, checker) => {
6553
- for (const item of arr) {
6554
- if (checker(item))
6555
- return item;
6586
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
6587
+ }
6588
+ function toBuffer(data) {
6589
+ toBuffer.readOnly = true;
6590
+ if (Buffer.isBuffer(data))
6591
+ return data;
6592
+ let buf;
6593
+ if (data instanceof ArrayBuffer) {
6594
+ buf = new FastBuffer(data);
6595
+ } else if (ArrayBuffer.isView(data)) {
6596
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
6597
+ } else {
6598
+ buf = Buffer.from(data);
6599
+ toBuffer.readOnly = false;
6556
6600
  }
6557
- return;
6601
+ return buf;
6602
+ }
6603
+ module.exports = {
6604
+ concat,
6605
+ mask: _mask,
6606
+ toArrayBuffer,
6607
+ toBuffer,
6608
+ unmask: _unmask
6558
6609
  };
6559
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
6560
- function joinValues(array2, separator = " | ") {
6561
- return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
6610
+ if (!process.env.WS_NO_BUFFER_UTIL) {
6611
+ try {
6612
+ const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})();
6613
+ module.exports.mask = function(source, mask, output, offset, length) {
6614
+ if (length < 48)
6615
+ _mask(source, mask, output, offset, length);
6616
+ else
6617
+ bufferUtil.mask(source, mask, output, offset, length);
6618
+ };
6619
+ module.exports.unmask = function(buffer, mask) {
6620
+ if (buffer.length < 32)
6621
+ _unmask(buffer, mask);
6622
+ else
6623
+ bufferUtil.unmask(buffer, mask);
6624
+ };
6625
+ } catch (e) {}
6562
6626
  }
6563
- util2.joinValues = joinValues;
6564
- util2.jsonStringifyReplacer = (_, value) => {
6565
- if (typeof value === "bigint") {
6566
- return value.toString();
6627
+ });
6628
+
6629
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/limiter.js
6630
+ var require_limiter = __commonJS((exports, module) => {
6631
+ var kDone = Symbol("kDone");
6632
+ var kRun = Symbol("kRun");
6633
+
6634
+ class Limiter {
6635
+ constructor(concurrency) {
6636
+ this[kDone] = () => {
6637
+ this.pending--;
6638
+ this[kRun]();
6639
+ };
6640
+ this.concurrency = concurrency || Infinity;
6641
+ this.jobs = [];
6642
+ this.pending = 0;
6567
6643
  }
6568
- return value;
6569
- };
6570
- })(util || (util = {}));
6571
- var objectUtil;
6572
- (function(objectUtil2) {
6573
- objectUtil2.mergeShapes = (first, second) => {
6574
- return {
6575
- ...first,
6576
- ...second
6577
- };
6578
- };
6579
- })(objectUtil || (objectUtil = {}));
6580
- var ZodParsedType = util.arrayToEnum([
6581
- "string",
6582
- "nan",
6583
- "number",
6584
- "integer",
6585
- "float",
6586
- "boolean",
6587
- "date",
6588
- "bigint",
6589
- "symbol",
6590
- "function",
6591
- "undefined",
6592
- "null",
6593
- "array",
6594
- "object",
6595
- "unknown",
6596
- "promise",
6597
- "void",
6598
- "never",
6599
- "map",
6600
- "set"
6601
- ]);
6602
- var getParsedType = (data) => {
6603
- const t = typeof data;
6604
- switch (t) {
6605
- case "undefined":
6606
- return ZodParsedType.undefined;
6607
- case "string":
6608
- return ZodParsedType.string;
6609
- case "number":
6610
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
6611
- case "boolean":
6612
- return ZodParsedType.boolean;
6613
- case "function":
6614
- return ZodParsedType.function;
6615
- case "bigint":
6616
- return ZodParsedType.bigint;
6617
- case "symbol":
6618
- return ZodParsedType.symbol;
6619
- case "object":
6620
- if (Array.isArray(data)) {
6621
- return ZodParsedType.array;
6644
+ add(job) {
6645
+ this.jobs.push(job);
6646
+ this[kRun]();
6647
+ }
6648
+ [kRun]() {
6649
+ if (this.pending === this.concurrency)
6650
+ return;
6651
+ if (this.jobs.length) {
6652
+ const job = this.jobs.shift();
6653
+ this.pending++;
6654
+ job(this[kDone]);
6622
6655
  }
6623
- if (data === null) {
6624
- return ZodParsedType.null;
6656
+ }
6657
+ }
6658
+ module.exports = Limiter;
6659
+ });
6660
+
6661
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
6662
+ var require_permessage_deflate = __commonJS((exports, module) => {
6663
+ var zlib = __require("zlib");
6664
+ var bufferUtil = require_buffer_util();
6665
+ var Limiter = require_limiter();
6666
+ var { kStatusCode } = require_constants();
6667
+ var FastBuffer = Buffer[Symbol.species];
6668
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
6669
+ var kPerMessageDeflate = Symbol("permessage-deflate");
6670
+ var kTotalLength = Symbol("total-length");
6671
+ var kCallback = Symbol("callback");
6672
+ var kBuffers = Symbol("buffers");
6673
+ var kError = Symbol("error");
6674
+ var zlibLimiter;
6675
+
6676
+ class PerMessageDeflate {
6677
+ constructor(options) {
6678
+ this._options = options || {};
6679
+ this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
6680
+ this._maxPayload = this._options.maxPayload | 0;
6681
+ this._isServer = !!this._options.isServer;
6682
+ this._deflate = null;
6683
+ this._inflate = null;
6684
+ this.params = null;
6685
+ if (!zlibLimiter) {
6686
+ const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
6687
+ zlibLimiter = new Limiter(concurrency);
6688
+ }
6689
+ }
6690
+ static get extensionName() {
6691
+ return "permessage-deflate";
6692
+ }
6693
+ offer() {
6694
+ const params = {};
6695
+ if (this._options.serverNoContextTakeover) {
6696
+ params.server_no_context_takeover = true;
6697
+ }
6698
+ if (this._options.clientNoContextTakeover) {
6699
+ params.client_no_context_takeover = true;
6700
+ }
6701
+ if (this._options.serverMaxWindowBits) {
6702
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
6703
+ }
6704
+ if (this._options.clientMaxWindowBits) {
6705
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
6706
+ } else if (this._options.clientMaxWindowBits == null) {
6707
+ params.client_max_window_bits = true;
6708
+ }
6709
+ return params;
6710
+ }
6711
+ accept(configurations) {
6712
+ configurations = this.normalizeParams(configurations);
6713
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
6714
+ return this.params;
6715
+ }
6716
+ cleanup() {
6717
+ if (this._inflate) {
6718
+ this._inflate.close();
6719
+ this._inflate = null;
6720
+ }
6721
+ if (this._deflate) {
6722
+ const callback = this._deflate[kCallback];
6723
+ this._deflate.close();
6724
+ this._deflate = null;
6725
+ if (callback) {
6726
+ callback(new Error("The deflate stream was closed while data was being processed"));
6727
+ }
6625
6728
  }
6626
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
6627
- return ZodParsedType.promise;
6729
+ }
6730
+ acceptAsServer(offers) {
6731
+ const opts = this._options;
6732
+ const accepted = offers.find((params) => {
6733
+ 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) {
6734
+ return false;
6735
+ }
6736
+ return true;
6737
+ });
6738
+ if (!accepted) {
6739
+ throw new Error("None of the extension offers can be accepted");
6628
6740
  }
6629
- if (typeof Map !== "undefined" && data instanceof Map) {
6630
- return ZodParsedType.map;
6741
+ if (opts.serverNoContextTakeover) {
6742
+ accepted.server_no_context_takeover = true;
6631
6743
  }
6632
- if (typeof Set !== "undefined" && data instanceof Set) {
6633
- return ZodParsedType.set;
6744
+ if (opts.clientNoContextTakeover) {
6745
+ accepted.client_no_context_takeover = true;
6634
6746
  }
6635
- if (typeof Date !== "undefined" && data instanceof Date) {
6636
- return ZodParsedType.date;
6747
+ if (typeof opts.serverMaxWindowBits === "number") {
6748
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
6637
6749
  }
6638
- return ZodParsedType.object;
6639
- default:
6640
- return ZodParsedType.unknown;
6750
+ if (typeof opts.clientMaxWindowBits === "number") {
6751
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
6752
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
6753
+ delete accepted.client_max_window_bits;
6754
+ }
6755
+ return accepted;
6756
+ }
6757
+ acceptAsClient(response) {
6758
+ const params = response[0];
6759
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
6760
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
6761
+ }
6762
+ if (!params.client_max_window_bits) {
6763
+ if (typeof this._options.clientMaxWindowBits === "number") {
6764
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
6765
+ }
6766
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
6767
+ throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
6768
+ }
6769
+ return params;
6770
+ }
6771
+ normalizeParams(configurations) {
6772
+ configurations.forEach((params) => {
6773
+ Object.keys(params).forEach((key) => {
6774
+ let value = params[key];
6775
+ if (value.length > 1) {
6776
+ throw new Error(`Parameter "${key}" must have only a single value`);
6777
+ }
6778
+ value = value[0];
6779
+ if (key === "client_max_window_bits") {
6780
+ if (value !== true) {
6781
+ const num = +value;
6782
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
6783
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6784
+ }
6785
+ value = num;
6786
+ } else if (!this._isServer) {
6787
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6788
+ }
6789
+ } else if (key === "server_max_window_bits") {
6790
+ const num = +value;
6791
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
6792
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6793
+ }
6794
+ value = num;
6795
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
6796
+ if (value !== true) {
6797
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6798
+ }
6799
+ } else {
6800
+ throw new Error(`Unknown parameter "${key}"`);
6801
+ }
6802
+ params[key] = value;
6803
+ });
6804
+ });
6805
+ return configurations;
6806
+ }
6807
+ decompress(data, fin, callback) {
6808
+ zlibLimiter.add((done) => {
6809
+ this._decompress(data, fin, (err, result) => {
6810
+ done();
6811
+ callback(err, result);
6812
+ });
6813
+ });
6814
+ }
6815
+ compress(data, fin, callback) {
6816
+ zlibLimiter.add((done) => {
6817
+ this._compress(data, fin, (err, result) => {
6818
+ done();
6819
+ callback(err, result);
6820
+ });
6821
+ });
6822
+ }
6823
+ _decompress(data, fin, callback) {
6824
+ const endpoint = this._isServer ? "client" : "server";
6825
+ if (!this._inflate) {
6826
+ const key = `${endpoint}_max_window_bits`;
6827
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6828
+ this._inflate = zlib.createInflateRaw({
6829
+ ...this._options.zlibInflateOptions,
6830
+ windowBits
6831
+ });
6832
+ this._inflate[kPerMessageDeflate] = this;
6833
+ this._inflate[kTotalLength] = 0;
6834
+ this._inflate[kBuffers] = [];
6835
+ this._inflate.on("error", inflateOnError);
6836
+ this._inflate.on("data", inflateOnData);
6837
+ }
6838
+ this._inflate[kCallback] = callback;
6839
+ this._inflate.write(data);
6840
+ if (fin)
6841
+ this._inflate.write(TRAILER);
6842
+ this._inflate.flush(() => {
6843
+ const err = this._inflate[kError];
6844
+ if (err) {
6845
+ this._inflate.close();
6846
+ this._inflate = null;
6847
+ callback(err);
6848
+ return;
6849
+ }
6850
+ const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
6851
+ if (this._inflate._readableState.endEmitted) {
6852
+ this._inflate.close();
6853
+ this._inflate = null;
6854
+ } else {
6855
+ this._inflate[kTotalLength] = 0;
6856
+ this._inflate[kBuffers] = [];
6857
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
6858
+ this._inflate.reset();
6859
+ }
6860
+ }
6861
+ callback(null, data2);
6862
+ });
6863
+ }
6864
+ _compress(data, fin, callback) {
6865
+ const endpoint = this._isServer ? "server" : "client";
6866
+ if (!this._deflate) {
6867
+ const key = `${endpoint}_max_window_bits`;
6868
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6869
+ this._deflate = zlib.createDeflateRaw({
6870
+ ...this._options.zlibDeflateOptions,
6871
+ windowBits
6872
+ });
6873
+ this._deflate[kTotalLength] = 0;
6874
+ this._deflate[kBuffers] = [];
6875
+ this._deflate.on("data", deflateOnData);
6876
+ }
6877
+ this._deflate[kCallback] = callback;
6878
+ this._deflate.write(data);
6879
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
6880
+ if (!this._deflate) {
6881
+ return;
6882
+ }
6883
+ let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
6884
+ if (fin) {
6885
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
6886
+ }
6887
+ this._deflate[kCallback] = null;
6888
+ this._deflate[kTotalLength] = 0;
6889
+ this._deflate[kBuffers] = [];
6890
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
6891
+ this._deflate.reset();
6892
+ }
6893
+ callback(null, data2);
6894
+ });
6895
+ }
6641
6896
  }
6642
- };
6897
+ module.exports = PerMessageDeflate;
6898
+ function deflateOnData(chunk) {
6899
+ this[kBuffers].push(chunk);
6900
+ this[kTotalLength] += chunk.length;
6901
+ }
6902
+ function inflateOnData(chunk) {
6903
+ this[kTotalLength] += chunk.length;
6904
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
6905
+ this[kBuffers].push(chunk);
6906
+ return;
6907
+ }
6908
+ this[kError] = new RangeError("Max payload size exceeded");
6909
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
6910
+ this[kError][kStatusCode] = 1009;
6911
+ this.removeListener("data", inflateOnData);
6912
+ this.reset();
6913
+ }
6914
+ function inflateOnError(err) {
6915
+ this[kPerMessageDeflate]._inflate = null;
6916
+ if (this[kError]) {
6917
+ this[kCallback](this[kError]);
6918
+ return;
6919
+ }
6920
+ err[kStatusCode] = 1007;
6921
+ this[kCallback](err);
6922
+ }
6923
+ });
6643
6924
 
6644
- // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v3/ZodError.js
6645
- var ZodIssueCode = util.arrayToEnum([
6646
- "invalid_type",
6647
- "invalid_literal",
6648
- "custom",
6649
- "invalid_union",
6650
- "invalid_union_discriminator",
6651
- "invalid_enum_value",
6652
- "unrecognized_keys",
6653
- "invalid_arguments",
6654
- "invalid_return_type",
6655
- "invalid_date",
6656
- "invalid_string",
6657
- "too_small",
6658
- "too_big",
6659
- "invalid_intersection_types",
6660
- "not_multiple_of",
6661
- "not_finite"
6662
- ]);
6663
- class ZodError extends Error {
6664
- get errors() {
6665
- return this.issues;
6925
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/validation.js
6926
+ var require_validation2 = __commonJS((exports, module) => {
6927
+ var { isUtf8 } = __require("buffer");
6928
+ var { hasBlob } = require_constants();
6929
+ var tokenChars = [
6930
+ 0,
6931
+ 0,
6932
+ 0,
6933
+ 0,
6934
+ 0,
6935
+ 0,
6936
+ 0,
6937
+ 0,
6938
+ 0,
6939
+ 0,
6940
+ 0,
6941
+ 0,
6942
+ 0,
6943
+ 0,
6944
+ 0,
6945
+ 0,
6946
+ 0,
6947
+ 0,
6948
+ 0,
6949
+ 0,
6950
+ 0,
6951
+ 0,
6952
+ 0,
6953
+ 0,
6954
+ 0,
6955
+ 0,
6956
+ 0,
6957
+ 0,
6958
+ 0,
6959
+ 0,
6960
+ 0,
6961
+ 0,
6962
+ 0,
6963
+ 1,
6964
+ 0,
6965
+ 1,
6966
+ 1,
6967
+ 1,
6968
+ 1,
6969
+ 1,
6970
+ 0,
6971
+ 0,
6972
+ 1,
6973
+ 1,
6974
+ 0,
6975
+ 1,
6976
+ 1,
6977
+ 0,
6978
+ 1,
6979
+ 1,
6980
+ 1,
6981
+ 1,
6982
+ 1,
6983
+ 1,
6984
+ 1,
6985
+ 1,
6986
+ 1,
6987
+ 1,
6988
+ 0,
6989
+ 0,
6990
+ 0,
6991
+ 0,
6992
+ 0,
6993
+ 0,
6994
+ 0,
6995
+ 1,
6996
+ 1,
6997
+ 1,
6998
+ 1,
6999
+ 1,
7000
+ 1,
7001
+ 1,
7002
+ 1,
7003
+ 1,
7004
+ 1,
7005
+ 1,
7006
+ 1,
7007
+ 1,
7008
+ 1,
7009
+ 1,
7010
+ 1,
7011
+ 1,
7012
+ 1,
7013
+ 1,
7014
+ 1,
7015
+ 1,
7016
+ 1,
7017
+ 1,
7018
+ 1,
7019
+ 1,
7020
+ 1,
7021
+ 0,
7022
+ 0,
7023
+ 0,
7024
+ 1,
7025
+ 1,
7026
+ 1,
7027
+ 1,
7028
+ 1,
7029
+ 1,
7030
+ 1,
7031
+ 1,
7032
+ 1,
7033
+ 1,
7034
+ 1,
7035
+ 1,
7036
+ 1,
7037
+ 1,
7038
+ 1,
7039
+ 1,
7040
+ 1,
7041
+ 1,
7042
+ 1,
7043
+ 1,
7044
+ 1,
7045
+ 1,
7046
+ 1,
7047
+ 1,
7048
+ 1,
7049
+ 1,
7050
+ 1,
7051
+ 1,
7052
+ 1,
7053
+ 0,
7054
+ 1,
7055
+ 0,
7056
+ 1,
7057
+ 0
7058
+ ];
7059
+ function isValidStatusCode(code) {
7060
+ return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
6666
7061
  }
6667
- constructor(issues) {
6668
- super();
6669
- this.issues = [];
6670
- this.addIssue = (sub) => {
6671
- this.issues = [...this.issues, sub];
6672
- };
6673
- this.addIssues = (subs = []) => {
6674
- this.issues = [...this.issues, ...subs];
6675
- };
6676
- const actualProto = new.target.prototype;
6677
- if (Object.setPrototypeOf) {
6678
- Object.setPrototypeOf(this, actualProto);
6679
- } else {
6680
- this.__proto__ = actualProto;
7062
+ function _isValidUTF8(buf) {
7063
+ const len = buf.length;
7064
+ let i = 0;
7065
+ while (i < len) {
7066
+ if ((buf[i] & 128) === 0) {
7067
+ i++;
7068
+ } else if ((buf[i] & 224) === 192) {
7069
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
7070
+ return false;
7071
+ }
7072
+ i += 2;
7073
+ } else if ((buf[i] & 240) === 224) {
7074
+ 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) {
7075
+ return false;
7076
+ }
7077
+ i += 3;
7078
+ } else if ((buf[i] & 248) === 240) {
7079
+ 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) {
7080
+ return false;
7081
+ }
7082
+ i += 4;
7083
+ } else {
7084
+ return false;
7085
+ }
6681
7086
  }
6682
- this.name = "ZodError";
6683
- this.issues = issues;
7087
+ return true;
6684
7088
  }
6685
- format(_mapper) {
6686
- const mapper = _mapper || function(issue) {
6687
- return issue.message;
7089
+ function isBlob(value) {
7090
+ 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");
7091
+ }
7092
+ module.exports = {
7093
+ isBlob,
7094
+ isValidStatusCode,
7095
+ isValidUTF8: _isValidUTF8,
7096
+ tokenChars
7097
+ };
7098
+ if (isUtf8) {
7099
+ module.exports.isValidUTF8 = function(buf) {
7100
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
6688
7101
  };
6689
- const fieldErrors = { _errors: [] };
7102
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
7103
+ try {
7104
+ const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})();
7105
+ module.exports.isValidUTF8 = function(buf) {
7106
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
7107
+ };
7108
+ } catch (e) {}
7109
+ }
7110
+ });
7111
+
7112
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/receiver.js
7113
+ var require_receiver = __commonJS((exports, module) => {
7114
+ var { Writable } = __require("stream");
7115
+ var PerMessageDeflate = require_permessage_deflate();
7116
+ var {
7117
+ BINARY_TYPES,
7118
+ EMPTY_BUFFER,
7119
+ kStatusCode,
7120
+ kWebSocket
7121
+ } = require_constants();
7122
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
7123
+ var { isValidStatusCode, isValidUTF8 } = require_validation2();
7124
+ var FastBuffer = Buffer[Symbol.species];
7125
+ var GET_INFO = 0;
7126
+ var GET_PAYLOAD_LENGTH_16 = 1;
7127
+ var GET_PAYLOAD_LENGTH_64 = 2;
7128
+ var GET_MASK = 3;
7129
+ var GET_DATA = 4;
7130
+ var INFLATING = 5;
7131
+ var DEFER_EVENT = 6;
7132
+
7133
+ class Receiver extends Writable {
7134
+ constructor(options = {}) {
7135
+ super();
7136
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
7137
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
7138
+ this._extensions = options.extensions || {};
7139
+ this._isServer = !!options.isServer;
7140
+ this._maxPayload = options.maxPayload | 0;
7141
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
7142
+ this[kWebSocket] = undefined;
7143
+ this._bufferedBytes = 0;
7144
+ this._buffers = [];
7145
+ this._compressed = false;
7146
+ this._payloadLength = 0;
7147
+ this._mask = undefined;
7148
+ this._fragmented = 0;
7149
+ this._masked = false;
7150
+ this._fin = false;
7151
+ this._opcode = 0;
7152
+ this._totalPayloadLength = 0;
7153
+ this._messageLength = 0;
7154
+ this._fragments = [];
7155
+ this._errored = false;
7156
+ this._loop = false;
7157
+ this._state = GET_INFO;
7158
+ }
7159
+ _write(chunk, encoding, cb) {
7160
+ if (this._opcode === 8 && this._state == GET_INFO)
7161
+ return cb();
7162
+ this._bufferedBytes += chunk.length;
7163
+ this._buffers.push(chunk);
7164
+ this.startLoop(cb);
7165
+ }
7166
+ consume(n) {
7167
+ this._bufferedBytes -= n;
7168
+ if (n === this._buffers[0].length)
7169
+ return this._buffers.shift();
7170
+ if (n < this._buffers[0].length) {
7171
+ const buf = this._buffers[0];
7172
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7173
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
7174
+ }
7175
+ const dst = Buffer.allocUnsafe(n);
7176
+ do {
7177
+ const buf = this._buffers[0];
7178
+ const offset = dst.length - n;
7179
+ if (n >= buf.length) {
7180
+ dst.set(this._buffers.shift(), offset);
7181
+ } else {
7182
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
7183
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7184
+ }
7185
+ n -= buf.length;
7186
+ } while (n > 0);
7187
+ return dst;
7188
+ }
7189
+ startLoop(cb) {
7190
+ this._loop = true;
7191
+ do {
7192
+ switch (this._state) {
7193
+ case GET_INFO:
7194
+ this.getInfo(cb);
7195
+ break;
7196
+ case GET_PAYLOAD_LENGTH_16:
7197
+ this.getPayloadLength16(cb);
7198
+ break;
7199
+ case GET_PAYLOAD_LENGTH_64:
7200
+ this.getPayloadLength64(cb);
7201
+ break;
7202
+ case GET_MASK:
7203
+ this.getMask();
7204
+ break;
7205
+ case GET_DATA:
7206
+ this.getData(cb);
7207
+ break;
7208
+ case INFLATING:
7209
+ case DEFER_EVENT:
7210
+ this._loop = false;
7211
+ return;
7212
+ }
7213
+ } while (this._loop);
7214
+ if (!this._errored)
7215
+ cb();
7216
+ }
7217
+ getInfo(cb) {
7218
+ if (this._bufferedBytes < 2) {
7219
+ this._loop = false;
7220
+ return;
7221
+ }
7222
+ const buf = this.consume(2);
7223
+ if ((buf[0] & 48) !== 0) {
7224
+ const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
7225
+ cb(error);
7226
+ return;
7227
+ }
7228
+ const compressed = (buf[0] & 64) === 64;
7229
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
7230
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
7231
+ cb(error);
7232
+ return;
7233
+ }
7234
+ this._fin = (buf[0] & 128) === 128;
7235
+ this._opcode = buf[0] & 15;
7236
+ this._payloadLength = buf[1] & 127;
7237
+ if (this._opcode === 0) {
7238
+ if (compressed) {
7239
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
7240
+ cb(error);
7241
+ return;
7242
+ }
7243
+ if (!this._fragmented) {
7244
+ const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
7245
+ cb(error);
7246
+ return;
7247
+ }
7248
+ this._opcode = this._fragmented;
7249
+ } else if (this._opcode === 1 || this._opcode === 2) {
7250
+ if (this._fragmented) {
7251
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
7252
+ cb(error);
7253
+ return;
7254
+ }
7255
+ this._compressed = compressed;
7256
+ } else if (this._opcode > 7 && this._opcode < 11) {
7257
+ if (!this._fin) {
7258
+ const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
7259
+ cb(error);
7260
+ return;
7261
+ }
7262
+ if (compressed) {
7263
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
7264
+ cb(error);
7265
+ return;
7266
+ }
7267
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
7268
+ const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
7269
+ cb(error);
7270
+ return;
7271
+ }
7272
+ } else {
7273
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
7274
+ cb(error);
7275
+ return;
7276
+ }
7277
+ if (!this._fin && !this._fragmented)
7278
+ this._fragmented = this._opcode;
7279
+ this._masked = (buf[1] & 128) === 128;
7280
+ if (this._isServer) {
7281
+ if (!this._masked) {
7282
+ const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
7283
+ cb(error);
7284
+ return;
7285
+ }
7286
+ } else if (this._masked) {
7287
+ const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
7288
+ cb(error);
7289
+ return;
7290
+ }
7291
+ if (this._payloadLength === 126)
7292
+ this._state = GET_PAYLOAD_LENGTH_16;
7293
+ else if (this._payloadLength === 127)
7294
+ this._state = GET_PAYLOAD_LENGTH_64;
7295
+ else
7296
+ this.haveLength(cb);
7297
+ }
7298
+ getPayloadLength16(cb) {
7299
+ if (this._bufferedBytes < 2) {
7300
+ this._loop = false;
7301
+ return;
7302
+ }
7303
+ this._payloadLength = this.consume(2).readUInt16BE(0);
7304
+ this.haveLength(cb);
7305
+ }
7306
+ getPayloadLength64(cb) {
7307
+ if (this._bufferedBytes < 8) {
7308
+ this._loop = false;
7309
+ return;
7310
+ }
7311
+ const buf = this.consume(8);
7312
+ const num = buf.readUInt32BE(0);
7313
+ if (num > Math.pow(2, 53 - 32) - 1) {
7314
+ const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
7315
+ cb(error);
7316
+ return;
7317
+ }
7318
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
7319
+ this.haveLength(cb);
7320
+ }
7321
+ haveLength(cb) {
7322
+ if (this._payloadLength && this._opcode < 8) {
7323
+ this._totalPayloadLength += this._payloadLength;
7324
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
7325
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
7326
+ cb(error);
7327
+ return;
7328
+ }
7329
+ }
7330
+ if (this._masked)
7331
+ this._state = GET_MASK;
7332
+ else
7333
+ this._state = GET_DATA;
7334
+ }
7335
+ getMask() {
7336
+ if (this._bufferedBytes < 4) {
7337
+ this._loop = false;
7338
+ return;
7339
+ }
7340
+ this._mask = this.consume(4);
7341
+ this._state = GET_DATA;
7342
+ }
7343
+ getData(cb) {
7344
+ let data = EMPTY_BUFFER;
7345
+ if (this._payloadLength) {
7346
+ if (this._bufferedBytes < this._payloadLength) {
7347
+ this._loop = false;
7348
+ return;
7349
+ }
7350
+ data = this.consume(this._payloadLength);
7351
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
7352
+ unmask(data, this._mask);
7353
+ }
7354
+ }
7355
+ if (this._opcode > 7) {
7356
+ this.controlMessage(data, cb);
7357
+ return;
7358
+ }
7359
+ if (this._compressed) {
7360
+ this._state = INFLATING;
7361
+ this.decompress(data, cb);
7362
+ return;
7363
+ }
7364
+ if (data.length) {
7365
+ this._messageLength = this._totalPayloadLength;
7366
+ this._fragments.push(data);
7367
+ }
7368
+ this.dataMessage(cb);
7369
+ }
7370
+ decompress(data, cb) {
7371
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7372
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
7373
+ if (err)
7374
+ return cb(err);
7375
+ if (buf.length) {
7376
+ this._messageLength += buf.length;
7377
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
7378
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
7379
+ cb(error);
7380
+ return;
7381
+ }
7382
+ this._fragments.push(buf);
7383
+ }
7384
+ this.dataMessage(cb);
7385
+ if (this._state === GET_INFO)
7386
+ this.startLoop(cb);
7387
+ });
7388
+ }
7389
+ dataMessage(cb) {
7390
+ if (!this._fin) {
7391
+ this._state = GET_INFO;
7392
+ return;
7393
+ }
7394
+ const messageLength = this._messageLength;
7395
+ const fragments = this._fragments;
7396
+ this._totalPayloadLength = 0;
7397
+ this._messageLength = 0;
7398
+ this._fragmented = 0;
7399
+ this._fragments = [];
7400
+ if (this._opcode === 2) {
7401
+ let data;
7402
+ if (this._binaryType === "nodebuffer") {
7403
+ data = concat(fragments, messageLength);
7404
+ } else if (this._binaryType === "arraybuffer") {
7405
+ data = toArrayBuffer(concat(fragments, messageLength));
7406
+ } else if (this._binaryType === "blob") {
7407
+ data = new Blob(fragments);
7408
+ } else {
7409
+ data = fragments;
7410
+ }
7411
+ if (this._allowSynchronousEvents) {
7412
+ this.emit("message", data, true);
7413
+ this._state = GET_INFO;
7414
+ } else {
7415
+ this._state = DEFER_EVENT;
7416
+ setImmediate(() => {
7417
+ this.emit("message", data, true);
7418
+ this._state = GET_INFO;
7419
+ this.startLoop(cb);
7420
+ });
7421
+ }
7422
+ } else {
7423
+ const buf = concat(fragments, messageLength);
7424
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7425
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
7426
+ cb(error);
7427
+ return;
7428
+ }
7429
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
7430
+ this.emit("message", buf, false);
7431
+ this._state = GET_INFO;
7432
+ } else {
7433
+ this._state = DEFER_EVENT;
7434
+ setImmediate(() => {
7435
+ this.emit("message", buf, false);
7436
+ this._state = GET_INFO;
7437
+ this.startLoop(cb);
7438
+ });
7439
+ }
7440
+ }
7441
+ }
7442
+ controlMessage(data, cb) {
7443
+ if (this._opcode === 8) {
7444
+ if (data.length === 0) {
7445
+ this._loop = false;
7446
+ this.emit("conclude", 1005, EMPTY_BUFFER);
7447
+ this.end();
7448
+ } else {
7449
+ const code = data.readUInt16BE(0);
7450
+ if (!isValidStatusCode(code)) {
7451
+ const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
7452
+ cb(error);
7453
+ return;
7454
+ }
7455
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
7456
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7457
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
7458
+ cb(error);
7459
+ return;
7460
+ }
7461
+ this._loop = false;
7462
+ this.emit("conclude", code, buf);
7463
+ this.end();
7464
+ }
7465
+ this._state = GET_INFO;
7466
+ return;
7467
+ }
7468
+ if (this._allowSynchronousEvents) {
7469
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7470
+ this._state = GET_INFO;
7471
+ } else {
7472
+ this._state = DEFER_EVENT;
7473
+ setImmediate(() => {
7474
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7475
+ this._state = GET_INFO;
7476
+ this.startLoop(cb);
7477
+ });
7478
+ }
7479
+ }
7480
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
7481
+ this._loop = false;
7482
+ this._errored = true;
7483
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
7484
+ Error.captureStackTrace(err, this.createError);
7485
+ err.code = errorCode;
7486
+ err[kStatusCode] = statusCode;
7487
+ return err;
7488
+ }
7489
+ }
7490
+ module.exports = Receiver;
7491
+ });
7492
+
7493
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/sender.js
7494
+ var require_sender = __commonJS((exports, module) => {
7495
+ var { Duplex } = __require("stream");
7496
+ var { randomFillSync } = __require("crypto");
7497
+ var PerMessageDeflate = require_permessage_deflate();
7498
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
7499
+ var { isBlob, isValidStatusCode } = require_validation2();
7500
+ var { mask: applyMask, toBuffer } = require_buffer_util();
7501
+ var kByteLength = Symbol("kByteLength");
7502
+ var maskBuffer = Buffer.alloc(4);
7503
+ var RANDOM_POOL_SIZE = 8 * 1024;
7504
+ var randomPool;
7505
+ var randomPoolPointer = RANDOM_POOL_SIZE;
7506
+ var DEFAULT = 0;
7507
+ var DEFLATING = 1;
7508
+ var GET_BLOB_DATA = 2;
7509
+
7510
+ class Sender {
7511
+ constructor(socket, extensions, generateMask) {
7512
+ this._extensions = extensions || {};
7513
+ if (generateMask) {
7514
+ this._generateMask = generateMask;
7515
+ this._maskBuffer = Buffer.alloc(4);
7516
+ }
7517
+ this._socket = socket;
7518
+ this._firstFragment = true;
7519
+ this._compress = false;
7520
+ this._bufferedBytes = 0;
7521
+ this._queue = [];
7522
+ this._state = DEFAULT;
7523
+ this.onerror = NOOP;
7524
+ this[kWebSocket] = undefined;
7525
+ }
7526
+ static frame(data, options) {
7527
+ let mask;
7528
+ let merge = false;
7529
+ let offset = 2;
7530
+ let skipMasking = false;
7531
+ if (options.mask) {
7532
+ mask = options.maskBuffer || maskBuffer;
7533
+ if (options.generateMask) {
7534
+ options.generateMask(mask);
7535
+ } else {
7536
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
7537
+ if (randomPool === undefined) {
7538
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
7539
+ }
7540
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
7541
+ randomPoolPointer = 0;
7542
+ }
7543
+ mask[0] = randomPool[randomPoolPointer++];
7544
+ mask[1] = randomPool[randomPoolPointer++];
7545
+ mask[2] = randomPool[randomPoolPointer++];
7546
+ mask[3] = randomPool[randomPoolPointer++];
7547
+ }
7548
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
7549
+ offset = 6;
7550
+ }
7551
+ let dataLength;
7552
+ if (typeof data === "string") {
7553
+ if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
7554
+ dataLength = options[kByteLength];
7555
+ } else {
7556
+ data = Buffer.from(data);
7557
+ dataLength = data.length;
7558
+ }
7559
+ } else {
7560
+ dataLength = data.length;
7561
+ merge = options.mask && options.readOnly && !skipMasking;
7562
+ }
7563
+ let payloadLength = dataLength;
7564
+ if (dataLength >= 65536) {
7565
+ offset += 8;
7566
+ payloadLength = 127;
7567
+ } else if (dataLength > 125) {
7568
+ offset += 2;
7569
+ payloadLength = 126;
7570
+ }
7571
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
7572
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
7573
+ if (options.rsv1)
7574
+ target[0] |= 64;
7575
+ target[1] = payloadLength;
7576
+ if (payloadLength === 126) {
7577
+ target.writeUInt16BE(dataLength, 2);
7578
+ } else if (payloadLength === 127) {
7579
+ target[2] = target[3] = 0;
7580
+ target.writeUIntBE(dataLength, 4, 6);
7581
+ }
7582
+ if (!options.mask)
7583
+ return [target, data];
7584
+ target[1] |= 128;
7585
+ target[offset - 4] = mask[0];
7586
+ target[offset - 3] = mask[1];
7587
+ target[offset - 2] = mask[2];
7588
+ target[offset - 1] = mask[3];
7589
+ if (skipMasking)
7590
+ return [target, data];
7591
+ if (merge) {
7592
+ applyMask(data, mask, target, offset, dataLength);
7593
+ return [target];
7594
+ }
7595
+ applyMask(data, mask, data, 0, dataLength);
7596
+ return [target, data];
7597
+ }
7598
+ close(code, data, mask, cb) {
7599
+ let buf;
7600
+ if (code === undefined) {
7601
+ buf = EMPTY_BUFFER;
7602
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
7603
+ throw new TypeError("First argument must be a valid error code number");
7604
+ } else if (data === undefined || !data.length) {
7605
+ buf = Buffer.allocUnsafe(2);
7606
+ buf.writeUInt16BE(code, 0);
7607
+ } else {
7608
+ const length = Buffer.byteLength(data);
7609
+ if (length > 123) {
7610
+ throw new RangeError("The message must not be greater than 123 bytes");
7611
+ }
7612
+ buf = Buffer.allocUnsafe(2 + length);
7613
+ buf.writeUInt16BE(code, 0);
7614
+ if (typeof data === "string") {
7615
+ buf.write(data, 2);
7616
+ } else {
7617
+ buf.set(data, 2);
7618
+ }
7619
+ }
7620
+ const options = {
7621
+ [kByteLength]: buf.length,
7622
+ fin: true,
7623
+ generateMask: this._generateMask,
7624
+ mask,
7625
+ maskBuffer: this._maskBuffer,
7626
+ opcode: 8,
7627
+ readOnly: false,
7628
+ rsv1: false
7629
+ };
7630
+ if (this._state !== DEFAULT) {
7631
+ this.enqueue([this.dispatch, buf, false, options, cb]);
7632
+ } else {
7633
+ this.sendFrame(Sender.frame(buf, options), cb);
7634
+ }
7635
+ }
7636
+ ping(data, mask, cb) {
7637
+ let byteLength;
7638
+ let readOnly;
7639
+ if (typeof data === "string") {
7640
+ byteLength = Buffer.byteLength(data);
7641
+ readOnly = false;
7642
+ } else if (isBlob(data)) {
7643
+ byteLength = data.size;
7644
+ readOnly = false;
7645
+ } else {
7646
+ data = toBuffer(data);
7647
+ byteLength = data.length;
7648
+ readOnly = toBuffer.readOnly;
7649
+ }
7650
+ if (byteLength > 125) {
7651
+ throw new RangeError("The data size must not be greater than 125 bytes");
7652
+ }
7653
+ const options = {
7654
+ [kByteLength]: byteLength,
7655
+ fin: true,
7656
+ generateMask: this._generateMask,
7657
+ mask,
7658
+ maskBuffer: this._maskBuffer,
7659
+ opcode: 9,
7660
+ readOnly,
7661
+ rsv1: false
7662
+ };
7663
+ if (isBlob(data)) {
7664
+ if (this._state !== DEFAULT) {
7665
+ this.enqueue([this.getBlobData, data, false, options, cb]);
7666
+ } else {
7667
+ this.getBlobData(data, false, options, cb);
7668
+ }
7669
+ } else if (this._state !== DEFAULT) {
7670
+ this.enqueue([this.dispatch, data, false, options, cb]);
7671
+ } else {
7672
+ this.sendFrame(Sender.frame(data, options), cb);
7673
+ }
7674
+ }
7675
+ pong(data, mask, cb) {
7676
+ let byteLength;
7677
+ let readOnly;
7678
+ if (typeof data === "string") {
7679
+ byteLength = Buffer.byteLength(data);
7680
+ readOnly = false;
7681
+ } else if (isBlob(data)) {
7682
+ byteLength = data.size;
7683
+ readOnly = false;
7684
+ } else {
7685
+ data = toBuffer(data);
7686
+ byteLength = data.length;
7687
+ readOnly = toBuffer.readOnly;
7688
+ }
7689
+ if (byteLength > 125) {
7690
+ throw new RangeError("The data size must not be greater than 125 bytes");
7691
+ }
7692
+ const options = {
7693
+ [kByteLength]: byteLength,
7694
+ fin: true,
7695
+ generateMask: this._generateMask,
7696
+ mask,
7697
+ maskBuffer: this._maskBuffer,
7698
+ opcode: 10,
7699
+ readOnly,
7700
+ rsv1: false
7701
+ };
7702
+ if (isBlob(data)) {
7703
+ if (this._state !== DEFAULT) {
7704
+ this.enqueue([this.getBlobData, data, false, options, cb]);
7705
+ } else {
7706
+ this.getBlobData(data, false, options, cb);
7707
+ }
7708
+ } else if (this._state !== DEFAULT) {
7709
+ this.enqueue([this.dispatch, data, false, options, cb]);
7710
+ } else {
7711
+ this.sendFrame(Sender.frame(data, options), cb);
7712
+ }
7713
+ }
7714
+ send(data, options, cb) {
7715
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7716
+ let opcode = options.binary ? 2 : 1;
7717
+ let rsv1 = options.compress;
7718
+ let byteLength;
7719
+ let readOnly;
7720
+ if (typeof data === "string") {
7721
+ byteLength = Buffer.byteLength(data);
7722
+ readOnly = false;
7723
+ } else if (isBlob(data)) {
7724
+ byteLength = data.size;
7725
+ readOnly = false;
7726
+ } else {
7727
+ data = toBuffer(data);
7728
+ byteLength = data.length;
7729
+ readOnly = toBuffer.readOnly;
7730
+ }
7731
+ if (this._firstFragment) {
7732
+ this._firstFragment = false;
7733
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
7734
+ rsv1 = byteLength >= perMessageDeflate._threshold;
7735
+ }
7736
+ this._compress = rsv1;
7737
+ } else {
7738
+ rsv1 = false;
7739
+ opcode = 0;
7740
+ }
7741
+ if (options.fin)
7742
+ this._firstFragment = true;
7743
+ const opts = {
7744
+ [kByteLength]: byteLength,
7745
+ fin: options.fin,
7746
+ generateMask: this._generateMask,
7747
+ mask: options.mask,
7748
+ maskBuffer: this._maskBuffer,
7749
+ opcode,
7750
+ readOnly,
7751
+ rsv1
7752
+ };
7753
+ if (isBlob(data)) {
7754
+ if (this._state !== DEFAULT) {
7755
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
7756
+ } else {
7757
+ this.getBlobData(data, this._compress, opts, cb);
7758
+ }
7759
+ } else if (this._state !== DEFAULT) {
7760
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
7761
+ } else {
7762
+ this.dispatch(data, this._compress, opts, cb);
7763
+ }
7764
+ }
7765
+ getBlobData(blob, compress, options, cb) {
7766
+ this._bufferedBytes += options[kByteLength];
7767
+ this._state = GET_BLOB_DATA;
7768
+ blob.arrayBuffer().then((arrayBuffer) => {
7769
+ if (this._socket.destroyed) {
7770
+ const err = new Error("The socket was closed while the blob was being read");
7771
+ process.nextTick(callCallbacks, this, err, cb);
7772
+ return;
7773
+ }
7774
+ this._bufferedBytes -= options[kByteLength];
7775
+ const data = toBuffer(arrayBuffer);
7776
+ if (!compress) {
7777
+ this._state = DEFAULT;
7778
+ this.sendFrame(Sender.frame(data, options), cb);
7779
+ this.dequeue();
7780
+ } else {
7781
+ this.dispatch(data, compress, options, cb);
7782
+ }
7783
+ }).catch((err) => {
7784
+ process.nextTick(onError, this, err, cb);
7785
+ });
7786
+ }
7787
+ dispatch(data, compress, options, cb) {
7788
+ if (!compress) {
7789
+ this.sendFrame(Sender.frame(data, options), cb);
7790
+ return;
7791
+ }
7792
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7793
+ this._bufferedBytes += options[kByteLength];
7794
+ this._state = DEFLATING;
7795
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
7796
+ if (this._socket.destroyed) {
7797
+ const err = new Error("The socket was closed while data was being compressed");
7798
+ callCallbacks(this, err, cb);
7799
+ return;
7800
+ }
7801
+ this._bufferedBytes -= options[kByteLength];
7802
+ this._state = DEFAULT;
7803
+ options.readOnly = false;
7804
+ this.sendFrame(Sender.frame(buf, options), cb);
7805
+ this.dequeue();
7806
+ });
7807
+ }
7808
+ dequeue() {
7809
+ while (this._state === DEFAULT && this._queue.length) {
7810
+ const params = this._queue.shift();
7811
+ this._bufferedBytes -= params[3][kByteLength];
7812
+ Reflect.apply(params[0], this, params.slice(1));
7813
+ }
7814
+ }
7815
+ enqueue(params) {
7816
+ this._bufferedBytes += params[3][kByteLength];
7817
+ this._queue.push(params);
7818
+ }
7819
+ sendFrame(list, cb) {
7820
+ if (list.length === 2) {
7821
+ this._socket.cork();
7822
+ this._socket.write(list[0]);
7823
+ this._socket.write(list[1], cb);
7824
+ this._socket.uncork();
7825
+ } else {
7826
+ this._socket.write(list[0], cb);
7827
+ }
7828
+ }
7829
+ }
7830
+ module.exports = Sender;
7831
+ function callCallbacks(sender, err, cb) {
7832
+ if (typeof cb === "function")
7833
+ cb(err);
7834
+ for (let i = 0;i < sender._queue.length; i++) {
7835
+ const params = sender._queue[i];
7836
+ const callback = params[params.length - 1];
7837
+ if (typeof callback === "function")
7838
+ callback(err);
7839
+ }
7840
+ }
7841
+ function onError(sender, err, cb) {
7842
+ callCallbacks(sender, err, cb);
7843
+ sender.onerror(err);
7844
+ }
7845
+ });
7846
+
7847
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/event-target.js
7848
+ var require_event_target = __commonJS((exports, module) => {
7849
+ var { kForOnEventAttribute, kListener } = require_constants();
7850
+ var kCode = Symbol("kCode");
7851
+ var kData = Symbol("kData");
7852
+ var kError = Symbol("kError");
7853
+ var kMessage = Symbol("kMessage");
7854
+ var kReason = Symbol("kReason");
7855
+ var kTarget = Symbol("kTarget");
7856
+ var kType = Symbol("kType");
7857
+ var kWasClean = Symbol("kWasClean");
7858
+
7859
+ class Event {
7860
+ constructor(type) {
7861
+ this[kTarget] = null;
7862
+ this[kType] = type;
7863
+ }
7864
+ get target() {
7865
+ return this[kTarget];
7866
+ }
7867
+ get type() {
7868
+ return this[kType];
7869
+ }
7870
+ }
7871
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
7872
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
7873
+
7874
+ class CloseEvent extends Event {
7875
+ constructor(type, options = {}) {
7876
+ super(type);
7877
+ this[kCode] = options.code === undefined ? 0 : options.code;
7878
+ this[kReason] = options.reason === undefined ? "" : options.reason;
7879
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
7880
+ }
7881
+ get code() {
7882
+ return this[kCode];
7883
+ }
7884
+ get reason() {
7885
+ return this[kReason];
7886
+ }
7887
+ get wasClean() {
7888
+ return this[kWasClean];
7889
+ }
7890
+ }
7891
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
7892
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
7893
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
7894
+
7895
+ class ErrorEvent extends Event {
7896
+ constructor(type, options = {}) {
7897
+ super(type);
7898
+ this[kError] = options.error === undefined ? null : options.error;
7899
+ this[kMessage] = options.message === undefined ? "" : options.message;
7900
+ }
7901
+ get error() {
7902
+ return this[kError];
7903
+ }
7904
+ get message() {
7905
+ return this[kMessage];
7906
+ }
7907
+ }
7908
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
7909
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
7910
+
7911
+ class MessageEvent extends Event {
7912
+ constructor(type, options = {}) {
7913
+ super(type);
7914
+ this[kData] = options.data === undefined ? null : options.data;
7915
+ }
7916
+ get data() {
7917
+ return this[kData];
7918
+ }
7919
+ }
7920
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
7921
+ var EventTarget = {
7922
+ addEventListener(type, handler, options = {}) {
7923
+ for (const listener of this.listeners(type)) {
7924
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
7925
+ return;
7926
+ }
7927
+ }
7928
+ let wrapper;
7929
+ if (type === "message") {
7930
+ wrapper = function onMessage(data, isBinary) {
7931
+ const event = new MessageEvent("message", {
7932
+ data: isBinary ? data : data.toString()
7933
+ });
7934
+ event[kTarget] = this;
7935
+ callListener(handler, this, event);
7936
+ };
7937
+ } else if (type === "close") {
7938
+ wrapper = function onClose(code, message) {
7939
+ const event = new CloseEvent("close", {
7940
+ code,
7941
+ reason: message.toString(),
7942
+ wasClean: this._closeFrameReceived && this._closeFrameSent
7943
+ });
7944
+ event[kTarget] = this;
7945
+ callListener(handler, this, event);
7946
+ };
7947
+ } else if (type === "error") {
7948
+ wrapper = function onError(error) {
7949
+ const event = new ErrorEvent("error", {
7950
+ error,
7951
+ message: error.message
7952
+ });
7953
+ event[kTarget] = this;
7954
+ callListener(handler, this, event);
7955
+ };
7956
+ } else if (type === "open") {
7957
+ wrapper = function onOpen() {
7958
+ const event = new Event("open");
7959
+ event[kTarget] = this;
7960
+ callListener(handler, this, event);
7961
+ };
7962
+ } else {
7963
+ return;
7964
+ }
7965
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
7966
+ wrapper[kListener] = handler;
7967
+ if (options.once) {
7968
+ this.once(type, wrapper);
7969
+ } else {
7970
+ this.on(type, wrapper);
7971
+ }
7972
+ },
7973
+ removeEventListener(type, handler) {
7974
+ for (const listener of this.listeners(type)) {
7975
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
7976
+ this.removeListener(type, listener);
7977
+ break;
7978
+ }
7979
+ }
7980
+ }
7981
+ };
7982
+ module.exports = {
7983
+ CloseEvent,
7984
+ ErrorEvent,
7985
+ Event,
7986
+ EventTarget,
7987
+ MessageEvent
7988
+ };
7989
+ function callListener(listener, thisArg, event) {
7990
+ if (typeof listener === "object" && listener.handleEvent) {
7991
+ listener.handleEvent.call(listener, event);
7992
+ } else {
7993
+ listener.call(thisArg, event);
7994
+ }
7995
+ }
7996
+ });
7997
+
7998
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/extension.js
7999
+ var require_extension = __commonJS((exports, module) => {
8000
+ var { tokenChars } = require_validation2();
8001
+ function push(dest, name, elem) {
8002
+ if (dest[name] === undefined)
8003
+ dest[name] = [elem];
8004
+ else
8005
+ dest[name].push(elem);
8006
+ }
8007
+ function parse3(header) {
8008
+ const offers = Object.create(null);
8009
+ let params = Object.create(null);
8010
+ let mustUnescape = false;
8011
+ let isEscaping = false;
8012
+ let inQuotes = false;
8013
+ let extensionName;
8014
+ let paramName;
8015
+ let start = -1;
8016
+ let code = -1;
8017
+ let end = -1;
8018
+ let i = 0;
8019
+ for (;i < header.length; i++) {
8020
+ code = header.charCodeAt(i);
8021
+ if (extensionName === undefined) {
8022
+ if (end === -1 && tokenChars[code] === 1) {
8023
+ if (start === -1)
8024
+ start = i;
8025
+ } else if (i !== 0 && (code === 32 || code === 9)) {
8026
+ if (end === -1 && start !== -1)
8027
+ end = i;
8028
+ } else if (code === 59 || code === 44) {
8029
+ if (start === -1) {
8030
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8031
+ }
8032
+ if (end === -1)
8033
+ end = i;
8034
+ const name = header.slice(start, end);
8035
+ if (code === 44) {
8036
+ push(offers, name, params);
8037
+ params = Object.create(null);
8038
+ } else {
8039
+ extensionName = name;
8040
+ }
8041
+ start = end = -1;
8042
+ } else {
8043
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8044
+ }
8045
+ } else if (paramName === undefined) {
8046
+ if (end === -1 && tokenChars[code] === 1) {
8047
+ if (start === -1)
8048
+ start = i;
8049
+ } else if (code === 32 || code === 9) {
8050
+ if (end === -1 && start !== -1)
8051
+ end = i;
8052
+ } else if (code === 59 || code === 44) {
8053
+ if (start === -1) {
8054
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8055
+ }
8056
+ if (end === -1)
8057
+ end = i;
8058
+ push(params, header.slice(start, end), true);
8059
+ if (code === 44) {
8060
+ push(offers, extensionName, params);
8061
+ params = Object.create(null);
8062
+ extensionName = undefined;
8063
+ }
8064
+ start = end = -1;
8065
+ } else if (code === 61 && start !== -1 && end === -1) {
8066
+ paramName = header.slice(start, i);
8067
+ start = end = -1;
8068
+ } else {
8069
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8070
+ }
8071
+ } else {
8072
+ if (isEscaping) {
8073
+ if (tokenChars[code] !== 1) {
8074
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8075
+ }
8076
+ if (start === -1)
8077
+ start = i;
8078
+ else if (!mustUnescape)
8079
+ mustUnescape = true;
8080
+ isEscaping = false;
8081
+ } else if (inQuotes) {
8082
+ if (tokenChars[code] === 1) {
8083
+ if (start === -1)
8084
+ start = i;
8085
+ } else if (code === 34 && start !== -1) {
8086
+ inQuotes = false;
8087
+ end = i;
8088
+ } else if (code === 92) {
8089
+ isEscaping = true;
8090
+ } else {
8091
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8092
+ }
8093
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
8094
+ inQuotes = true;
8095
+ } else if (end === -1 && tokenChars[code] === 1) {
8096
+ if (start === -1)
8097
+ start = i;
8098
+ } else if (start !== -1 && (code === 32 || code === 9)) {
8099
+ if (end === -1)
8100
+ end = i;
8101
+ } else if (code === 59 || code === 44) {
8102
+ if (start === -1) {
8103
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8104
+ }
8105
+ if (end === -1)
8106
+ end = i;
8107
+ let value = header.slice(start, end);
8108
+ if (mustUnescape) {
8109
+ value = value.replace(/\\/g, "");
8110
+ mustUnescape = false;
8111
+ }
8112
+ push(params, paramName, value);
8113
+ if (code === 44) {
8114
+ push(offers, extensionName, params);
8115
+ params = Object.create(null);
8116
+ extensionName = undefined;
8117
+ }
8118
+ paramName = undefined;
8119
+ start = end = -1;
8120
+ } else {
8121
+ throw new SyntaxError(`Unexpected character at index ${i}`);
8122
+ }
8123
+ }
8124
+ }
8125
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
8126
+ throw new SyntaxError("Unexpected end of input");
8127
+ }
8128
+ if (end === -1)
8129
+ end = i;
8130
+ const token = header.slice(start, end);
8131
+ if (extensionName === undefined) {
8132
+ push(offers, token, params);
8133
+ } else {
8134
+ if (paramName === undefined) {
8135
+ push(params, token, true);
8136
+ } else if (mustUnescape) {
8137
+ push(params, paramName, token.replace(/\\/g, ""));
8138
+ } else {
8139
+ push(params, paramName, token);
8140
+ }
8141
+ push(offers, extensionName, params);
8142
+ }
8143
+ return offers;
8144
+ }
8145
+ function format(extensions) {
8146
+ return Object.keys(extensions).map((extension) => {
8147
+ let configurations = extensions[extension];
8148
+ if (!Array.isArray(configurations))
8149
+ configurations = [configurations];
8150
+ return configurations.map((params) => {
8151
+ return [extension].concat(Object.keys(params).map((k) => {
8152
+ let values = params[k];
8153
+ if (!Array.isArray(values))
8154
+ values = [values];
8155
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
8156
+ })).join("; ");
8157
+ }).join(", ");
8158
+ }).join(", ");
8159
+ }
8160
+ module.exports = { format, parse: parse3 };
8161
+ });
8162
+
8163
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/websocket.js
8164
+ var require_websocket = __commonJS((exports, module) => {
8165
+ var EventEmitter = __require("events");
8166
+ var https = __require("https");
8167
+ var http = __require("http");
8168
+ var net = __require("net");
8169
+ var tls = __require("tls");
8170
+ var { randomBytes, createHash } = __require("crypto");
8171
+ var { Duplex, Readable } = __require("stream");
8172
+ var { URL: URL2 } = __require("url");
8173
+ var PerMessageDeflate = require_permessage_deflate();
8174
+ var Receiver = require_receiver();
8175
+ var Sender = require_sender();
8176
+ var { isBlob } = require_validation2();
8177
+ var {
8178
+ BINARY_TYPES,
8179
+ CLOSE_TIMEOUT,
8180
+ EMPTY_BUFFER,
8181
+ GUID,
8182
+ kForOnEventAttribute,
8183
+ kListener,
8184
+ kStatusCode,
8185
+ kWebSocket,
8186
+ NOOP
8187
+ } = require_constants();
8188
+ var {
8189
+ EventTarget: { addEventListener, removeEventListener }
8190
+ } = require_event_target();
8191
+ var { format, parse: parse3 } = require_extension();
8192
+ var { toBuffer } = require_buffer_util();
8193
+ var kAborted = Symbol("kAborted");
8194
+ var protocolVersions = [8, 13];
8195
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
8196
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
8197
+
8198
+ class WebSocket extends EventEmitter {
8199
+ constructor(address, protocols, options) {
8200
+ super();
8201
+ this._binaryType = BINARY_TYPES[0];
8202
+ this._closeCode = 1006;
8203
+ this._closeFrameReceived = false;
8204
+ this._closeFrameSent = false;
8205
+ this._closeMessage = EMPTY_BUFFER;
8206
+ this._closeTimer = null;
8207
+ this._errorEmitted = false;
8208
+ this._extensions = {};
8209
+ this._paused = false;
8210
+ this._protocol = "";
8211
+ this._readyState = WebSocket.CONNECTING;
8212
+ this._receiver = null;
8213
+ this._sender = null;
8214
+ this._socket = null;
8215
+ if (address !== null) {
8216
+ this._bufferedAmount = 0;
8217
+ this._isServer = false;
8218
+ this._redirects = 0;
8219
+ if (protocols === undefined) {
8220
+ protocols = [];
8221
+ } else if (!Array.isArray(protocols)) {
8222
+ if (typeof protocols === "object" && protocols !== null) {
8223
+ options = protocols;
8224
+ protocols = [];
8225
+ } else {
8226
+ protocols = [protocols];
8227
+ }
8228
+ }
8229
+ initAsClient(this, address, protocols, options);
8230
+ } else {
8231
+ this._autoPong = options.autoPong;
8232
+ this._closeTimeout = options.closeTimeout;
8233
+ this._isServer = true;
8234
+ }
8235
+ }
8236
+ get binaryType() {
8237
+ return this._binaryType;
8238
+ }
8239
+ set binaryType(type) {
8240
+ if (!BINARY_TYPES.includes(type))
8241
+ return;
8242
+ this._binaryType = type;
8243
+ if (this._receiver)
8244
+ this._receiver._binaryType = type;
8245
+ }
8246
+ get bufferedAmount() {
8247
+ if (!this._socket)
8248
+ return this._bufferedAmount;
8249
+ return this._socket._writableState.length + this._sender._bufferedBytes;
8250
+ }
8251
+ get extensions() {
8252
+ return Object.keys(this._extensions).join();
8253
+ }
8254
+ get isPaused() {
8255
+ return this._paused;
8256
+ }
8257
+ get onclose() {
8258
+ return null;
8259
+ }
8260
+ get onerror() {
8261
+ return null;
8262
+ }
8263
+ get onopen() {
8264
+ return null;
8265
+ }
8266
+ get onmessage() {
8267
+ return null;
8268
+ }
8269
+ get protocol() {
8270
+ return this._protocol;
8271
+ }
8272
+ get readyState() {
8273
+ return this._readyState;
8274
+ }
8275
+ get url() {
8276
+ return this._url;
8277
+ }
8278
+ setSocket(socket, head, options) {
8279
+ const receiver = new Receiver({
8280
+ allowSynchronousEvents: options.allowSynchronousEvents,
8281
+ binaryType: this.binaryType,
8282
+ extensions: this._extensions,
8283
+ isServer: this._isServer,
8284
+ maxPayload: options.maxPayload,
8285
+ skipUTF8Validation: options.skipUTF8Validation
8286
+ });
8287
+ const sender = new Sender(socket, this._extensions, options.generateMask);
8288
+ this._receiver = receiver;
8289
+ this._sender = sender;
8290
+ this._socket = socket;
8291
+ receiver[kWebSocket] = this;
8292
+ sender[kWebSocket] = this;
8293
+ socket[kWebSocket] = this;
8294
+ receiver.on("conclude", receiverOnConclude);
8295
+ receiver.on("drain", receiverOnDrain);
8296
+ receiver.on("error", receiverOnError);
8297
+ receiver.on("message", receiverOnMessage);
8298
+ receiver.on("ping", receiverOnPing);
8299
+ receiver.on("pong", receiverOnPong);
8300
+ sender.onerror = senderOnError;
8301
+ if (socket.setTimeout)
8302
+ socket.setTimeout(0);
8303
+ if (socket.setNoDelay)
8304
+ socket.setNoDelay();
8305
+ if (head.length > 0)
8306
+ socket.unshift(head);
8307
+ socket.on("close", socketOnClose);
8308
+ socket.on("data", socketOnData);
8309
+ socket.on("end", socketOnEnd);
8310
+ socket.on("error", socketOnError);
8311
+ this._readyState = WebSocket.OPEN;
8312
+ this.emit("open");
8313
+ }
8314
+ emitClose() {
8315
+ if (!this._socket) {
8316
+ this._readyState = WebSocket.CLOSED;
8317
+ this.emit("close", this._closeCode, this._closeMessage);
8318
+ return;
8319
+ }
8320
+ if (this._extensions[PerMessageDeflate.extensionName]) {
8321
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
8322
+ }
8323
+ this._receiver.removeAllListeners();
8324
+ this._readyState = WebSocket.CLOSED;
8325
+ this.emit("close", this._closeCode, this._closeMessage);
8326
+ }
8327
+ close(code, data) {
8328
+ if (this.readyState === WebSocket.CLOSED)
8329
+ return;
8330
+ if (this.readyState === WebSocket.CONNECTING) {
8331
+ const msg = "WebSocket was closed before the connection was established";
8332
+ abortHandshake(this, this._req, msg);
8333
+ return;
8334
+ }
8335
+ if (this.readyState === WebSocket.CLOSING) {
8336
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
8337
+ this._socket.end();
8338
+ }
8339
+ return;
8340
+ }
8341
+ this._readyState = WebSocket.CLOSING;
8342
+ this._sender.close(code, data, !this._isServer, (err) => {
8343
+ if (err)
8344
+ return;
8345
+ this._closeFrameSent = true;
8346
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
8347
+ this._socket.end();
8348
+ }
8349
+ });
8350
+ setCloseTimer(this);
8351
+ }
8352
+ pause() {
8353
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
8354
+ return;
8355
+ }
8356
+ this._paused = true;
8357
+ this._socket.pause();
8358
+ }
8359
+ ping(data, mask, cb) {
8360
+ if (this.readyState === WebSocket.CONNECTING) {
8361
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8362
+ }
8363
+ if (typeof data === "function") {
8364
+ cb = data;
8365
+ data = mask = undefined;
8366
+ } else if (typeof mask === "function") {
8367
+ cb = mask;
8368
+ mask = undefined;
8369
+ }
8370
+ if (typeof data === "number")
8371
+ data = data.toString();
8372
+ if (this.readyState !== WebSocket.OPEN) {
8373
+ sendAfterClose(this, data, cb);
8374
+ return;
8375
+ }
8376
+ if (mask === undefined)
8377
+ mask = !this._isServer;
8378
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
8379
+ }
8380
+ pong(data, mask, cb) {
8381
+ if (this.readyState === WebSocket.CONNECTING) {
8382
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8383
+ }
8384
+ if (typeof data === "function") {
8385
+ cb = data;
8386
+ data = mask = undefined;
8387
+ } else if (typeof mask === "function") {
8388
+ cb = mask;
8389
+ mask = undefined;
8390
+ }
8391
+ if (typeof data === "number")
8392
+ data = data.toString();
8393
+ if (this.readyState !== WebSocket.OPEN) {
8394
+ sendAfterClose(this, data, cb);
8395
+ return;
8396
+ }
8397
+ if (mask === undefined)
8398
+ mask = !this._isServer;
8399
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
8400
+ }
8401
+ resume() {
8402
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
8403
+ return;
8404
+ }
8405
+ this._paused = false;
8406
+ if (!this._receiver._writableState.needDrain)
8407
+ this._socket.resume();
8408
+ }
8409
+ send(data, options, cb) {
8410
+ if (this.readyState === WebSocket.CONNECTING) {
8411
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8412
+ }
8413
+ if (typeof options === "function") {
8414
+ cb = options;
8415
+ options = {};
8416
+ }
8417
+ if (typeof data === "number")
8418
+ data = data.toString();
8419
+ if (this.readyState !== WebSocket.OPEN) {
8420
+ sendAfterClose(this, data, cb);
8421
+ return;
8422
+ }
8423
+ const opts = {
8424
+ binary: typeof data !== "string",
8425
+ mask: !this._isServer,
8426
+ compress: true,
8427
+ fin: true,
8428
+ ...options
8429
+ };
8430
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
8431
+ opts.compress = false;
8432
+ }
8433
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
8434
+ }
8435
+ terminate() {
8436
+ if (this.readyState === WebSocket.CLOSED)
8437
+ return;
8438
+ if (this.readyState === WebSocket.CONNECTING) {
8439
+ const msg = "WebSocket was closed before the connection was established";
8440
+ abortHandshake(this, this._req, msg);
8441
+ return;
8442
+ }
8443
+ if (this._socket) {
8444
+ this._readyState = WebSocket.CLOSING;
8445
+ this._socket.destroy();
8446
+ }
8447
+ }
8448
+ }
8449
+ Object.defineProperty(WebSocket, "CONNECTING", {
8450
+ enumerable: true,
8451
+ value: readyStates.indexOf("CONNECTING")
8452
+ });
8453
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
8454
+ enumerable: true,
8455
+ value: readyStates.indexOf("CONNECTING")
8456
+ });
8457
+ Object.defineProperty(WebSocket, "OPEN", {
8458
+ enumerable: true,
8459
+ value: readyStates.indexOf("OPEN")
8460
+ });
8461
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
8462
+ enumerable: true,
8463
+ value: readyStates.indexOf("OPEN")
8464
+ });
8465
+ Object.defineProperty(WebSocket, "CLOSING", {
8466
+ enumerable: true,
8467
+ value: readyStates.indexOf("CLOSING")
8468
+ });
8469
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
8470
+ enumerable: true,
8471
+ value: readyStates.indexOf("CLOSING")
8472
+ });
8473
+ Object.defineProperty(WebSocket, "CLOSED", {
8474
+ enumerable: true,
8475
+ value: readyStates.indexOf("CLOSED")
8476
+ });
8477
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
8478
+ enumerable: true,
8479
+ value: readyStates.indexOf("CLOSED")
8480
+ });
8481
+ [
8482
+ "binaryType",
8483
+ "bufferedAmount",
8484
+ "extensions",
8485
+ "isPaused",
8486
+ "protocol",
8487
+ "readyState",
8488
+ "url"
8489
+ ].forEach((property) => {
8490
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
8491
+ });
8492
+ ["open", "error", "close", "message"].forEach((method) => {
8493
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
8494
+ enumerable: true,
8495
+ get() {
8496
+ for (const listener of this.listeners(method)) {
8497
+ if (listener[kForOnEventAttribute])
8498
+ return listener[kListener];
8499
+ }
8500
+ return null;
8501
+ },
8502
+ set(handler) {
8503
+ for (const listener of this.listeners(method)) {
8504
+ if (listener[kForOnEventAttribute]) {
8505
+ this.removeListener(method, listener);
8506
+ break;
8507
+ }
8508
+ }
8509
+ if (typeof handler !== "function")
8510
+ return;
8511
+ this.addEventListener(method, handler, {
8512
+ [kForOnEventAttribute]: true
8513
+ });
8514
+ }
8515
+ });
8516
+ });
8517
+ WebSocket.prototype.addEventListener = addEventListener;
8518
+ WebSocket.prototype.removeEventListener = removeEventListener;
8519
+ module.exports = WebSocket;
8520
+ function initAsClient(websocket, address, protocols, options) {
8521
+ const opts = {
8522
+ allowSynchronousEvents: true,
8523
+ autoPong: true,
8524
+ closeTimeout: CLOSE_TIMEOUT,
8525
+ protocolVersion: protocolVersions[1],
8526
+ maxPayload: 100 * 1024 * 1024,
8527
+ skipUTF8Validation: false,
8528
+ perMessageDeflate: true,
8529
+ followRedirects: false,
8530
+ maxRedirects: 10,
8531
+ ...options,
8532
+ socketPath: undefined,
8533
+ hostname: undefined,
8534
+ protocol: undefined,
8535
+ timeout: undefined,
8536
+ method: "GET",
8537
+ host: undefined,
8538
+ path: undefined,
8539
+ port: undefined
8540
+ };
8541
+ websocket._autoPong = opts.autoPong;
8542
+ websocket._closeTimeout = opts.closeTimeout;
8543
+ if (!protocolVersions.includes(opts.protocolVersion)) {
8544
+ throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
8545
+ }
8546
+ let parsedUrl;
8547
+ if (address instanceof URL2) {
8548
+ parsedUrl = address;
8549
+ } else {
8550
+ try {
8551
+ parsedUrl = new URL2(address);
8552
+ } catch {
8553
+ throw new SyntaxError(`Invalid URL: ${address}`);
8554
+ }
8555
+ }
8556
+ if (parsedUrl.protocol === "http:") {
8557
+ parsedUrl.protocol = "ws:";
8558
+ } else if (parsedUrl.protocol === "https:") {
8559
+ parsedUrl.protocol = "wss:";
8560
+ }
8561
+ websocket._url = parsedUrl.href;
8562
+ const isSecure = parsedUrl.protocol === "wss:";
8563
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
8564
+ let invalidUrlMessage;
8565
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
8566
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
8567
+ } else if (isIpcUrl && !parsedUrl.pathname) {
8568
+ invalidUrlMessage = "The URL's pathname is empty";
8569
+ } else if (parsedUrl.hash) {
8570
+ invalidUrlMessage = "The URL contains a fragment identifier";
8571
+ }
8572
+ if (invalidUrlMessage) {
8573
+ const err = new SyntaxError(invalidUrlMessage);
8574
+ if (websocket._redirects === 0) {
8575
+ throw err;
8576
+ } else {
8577
+ emitErrorAndClose(websocket, err);
8578
+ return;
8579
+ }
8580
+ }
8581
+ const defaultPort = isSecure ? 443 : 80;
8582
+ const key = randomBytes(16).toString("base64");
8583
+ const request = isSecure ? https.request : http.request;
8584
+ const protocolSet = new Set;
8585
+ let perMessageDeflate;
8586
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
8587
+ opts.defaultPort = opts.defaultPort || defaultPort;
8588
+ opts.port = parsedUrl.port || defaultPort;
8589
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
8590
+ opts.headers = {
8591
+ ...opts.headers,
8592
+ "Sec-WebSocket-Version": opts.protocolVersion,
8593
+ "Sec-WebSocket-Key": key,
8594
+ Connection: "Upgrade",
8595
+ Upgrade: "websocket"
8596
+ };
8597
+ opts.path = parsedUrl.pathname + parsedUrl.search;
8598
+ opts.timeout = opts.handshakeTimeout;
8599
+ if (opts.perMessageDeflate) {
8600
+ perMessageDeflate = new PerMessageDeflate({
8601
+ ...opts.perMessageDeflate,
8602
+ isServer: false,
8603
+ maxPayload: opts.maxPayload
8604
+ });
8605
+ opts.headers["Sec-WebSocket-Extensions"] = format({
8606
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
8607
+ });
8608
+ }
8609
+ if (protocols.length) {
8610
+ for (const protocol of protocols) {
8611
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
8612
+ throw new SyntaxError("An invalid or duplicated subprotocol was specified");
8613
+ }
8614
+ protocolSet.add(protocol);
8615
+ }
8616
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
8617
+ }
8618
+ if (opts.origin) {
8619
+ if (opts.protocolVersion < 13) {
8620
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
8621
+ } else {
8622
+ opts.headers.Origin = opts.origin;
8623
+ }
8624
+ }
8625
+ if (parsedUrl.username || parsedUrl.password) {
8626
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
8627
+ }
8628
+ if (isIpcUrl) {
8629
+ const parts = opts.path.split(":");
8630
+ opts.socketPath = parts[0];
8631
+ opts.path = parts[1];
8632
+ }
8633
+ let req;
8634
+ if (opts.followRedirects) {
8635
+ if (websocket._redirects === 0) {
8636
+ websocket._originalIpc = isIpcUrl;
8637
+ websocket._originalSecure = isSecure;
8638
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
8639
+ const headers = options && options.headers;
8640
+ options = { ...options, headers: {} };
8641
+ if (headers) {
8642
+ for (const [key2, value] of Object.entries(headers)) {
8643
+ options.headers[key2.toLowerCase()] = value;
8644
+ }
8645
+ }
8646
+ } else if (websocket.listenerCount("redirect") === 0) {
8647
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
8648
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
8649
+ delete opts.headers.authorization;
8650
+ delete opts.headers.cookie;
8651
+ if (!isSameHost)
8652
+ delete opts.headers.host;
8653
+ opts.auth = undefined;
8654
+ }
8655
+ }
8656
+ if (opts.auth && !options.headers.authorization) {
8657
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
8658
+ }
8659
+ req = websocket._req = request(opts);
8660
+ if (websocket._redirects) {
8661
+ websocket.emit("redirect", websocket.url, req);
8662
+ }
8663
+ } else {
8664
+ req = websocket._req = request(opts);
8665
+ }
8666
+ if (opts.timeout) {
8667
+ req.on("timeout", () => {
8668
+ abortHandshake(websocket, req, "Opening handshake has timed out");
8669
+ });
8670
+ }
8671
+ req.on("error", (err) => {
8672
+ if (req === null || req[kAborted])
8673
+ return;
8674
+ req = websocket._req = null;
8675
+ emitErrorAndClose(websocket, err);
8676
+ });
8677
+ req.on("response", (res) => {
8678
+ const location = res.headers.location;
8679
+ const statusCode = res.statusCode;
8680
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
8681
+ if (++websocket._redirects > opts.maxRedirects) {
8682
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
8683
+ return;
8684
+ }
8685
+ req.abort();
8686
+ let addr;
8687
+ try {
8688
+ addr = new URL2(location, address);
8689
+ } catch (e) {
8690
+ const err = new SyntaxError(`Invalid URL: ${location}`);
8691
+ emitErrorAndClose(websocket, err);
8692
+ return;
8693
+ }
8694
+ initAsClient(websocket, addr, protocols, options);
8695
+ } else if (!websocket.emit("unexpected-response", req, res)) {
8696
+ abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
8697
+ }
8698
+ });
8699
+ req.on("upgrade", (res, socket, head) => {
8700
+ websocket.emit("upgrade", res);
8701
+ if (websocket.readyState !== WebSocket.CONNECTING)
8702
+ return;
8703
+ req = websocket._req = null;
8704
+ const upgrade = res.headers.upgrade;
8705
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
8706
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
8707
+ return;
8708
+ }
8709
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
8710
+ if (res.headers["sec-websocket-accept"] !== digest) {
8711
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
8712
+ return;
8713
+ }
8714
+ const serverProt = res.headers["sec-websocket-protocol"];
8715
+ let protError;
8716
+ if (serverProt !== undefined) {
8717
+ if (!protocolSet.size) {
8718
+ protError = "Server sent a subprotocol but none was requested";
8719
+ } else if (!protocolSet.has(serverProt)) {
8720
+ protError = "Server sent an invalid subprotocol";
8721
+ }
8722
+ } else if (protocolSet.size) {
8723
+ protError = "Server sent no subprotocol";
8724
+ }
8725
+ if (protError) {
8726
+ abortHandshake(websocket, socket, protError);
8727
+ return;
8728
+ }
8729
+ if (serverProt)
8730
+ websocket._protocol = serverProt;
8731
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
8732
+ if (secWebSocketExtensions !== undefined) {
8733
+ if (!perMessageDeflate) {
8734
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
8735
+ abortHandshake(websocket, socket, message);
8736
+ return;
8737
+ }
8738
+ let extensions;
8739
+ try {
8740
+ extensions = parse3(secWebSocketExtensions);
8741
+ } catch (err) {
8742
+ const message = "Invalid Sec-WebSocket-Extensions header";
8743
+ abortHandshake(websocket, socket, message);
8744
+ return;
8745
+ }
8746
+ const extensionNames = Object.keys(extensions);
8747
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
8748
+ const message = "Server indicated an extension that was not requested";
8749
+ abortHandshake(websocket, socket, message);
8750
+ return;
8751
+ }
8752
+ try {
8753
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
8754
+ } catch (err) {
8755
+ const message = "Invalid Sec-WebSocket-Extensions header";
8756
+ abortHandshake(websocket, socket, message);
8757
+ return;
8758
+ }
8759
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
8760
+ }
8761
+ websocket.setSocket(socket, head, {
8762
+ allowSynchronousEvents: opts.allowSynchronousEvents,
8763
+ generateMask: opts.generateMask,
8764
+ maxPayload: opts.maxPayload,
8765
+ skipUTF8Validation: opts.skipUTF8Validation
8766
+ });
8767
+ });
8768
+ if (opts.finishRequest) {
8769
+ opts.finishRequest(req, websocket);
8770
+ } else {
8771
+ req.end();
8772
+ }
8773
+ }
8774
+ function emitErrorAndClose(websocket, err) {
8775
+ websocket._readyState = WebSocket.CLOSING;
8776
+ websocket._errorEmitted = true;
8777
+ websocket.emit("error", err);
8778
+ websocket.emitClose();
8779
+ }
8780
+ function netConnect(options) {
8781
+ options.path = options.socketPath;
8782
+ return net.connect(options);
8783
+ }
8784
+ function tlsConnect(options) {
8785
+ options.path = undefined;
8786
+ if (!options.servername && options.servername !== "") {
8787
+ options.servername = net.isIP(options.host) ? "" : options.host;
8788
+ }
8789
+ return tls.connect(options);
8790
+ }
8791
+ function abortHandshake(websocket, stream, message) {
8792
+ websocket._readyState = WebSocket.CLOSING;
8793
+ const err = new Error(message);
8794
+ Error.captureStackTrace(err, abortHandshake);
8795
+ if (stream.setHeader) {
8796
+ stream[kAborted] = true;
8797
+ stream.abort();
8798
+ if (stream.socket && !stream.socket.destroyed) {
8799
+ stream.socket.destroy();
8800
+ }
8801
+ process.nextTick(emitErrorAndClose, websocket, err);
8802
+ } else {
8803
+ stream.destroy(err);
8804
+ stream.once("error", websocket.emit.bind(websocket, "error"));
8805
+ stream.once("close", websocket.emitClose.bind(websocket));
8806
+ }
8807
+ }
8808
+ function sendAfterClose(websocket, data, cb) {
8809
+ if (data) {
8810
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
8811
+ if (websocket._socket)
8812
+ websocket._sender._bufferedBytes += length;
8813
+ else
8814
+ websocket._bufferedAmount += length;
8815
+ }
8816
+ if (cb) {
8817
+ const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
8818
+ process.nextTick(cb, err);
8819
+ }
8820
+ }
8821
+ function receiverOnConclude(code, reason) {
8822
+ const websocket = this[kWebSocket];
8823
+ websocket._closeFrameReceived = true;
8824
+ websocket._closeMessage = reason;
8825
+ websocket._closeCode = code;
8826
+ if (websocket._socket[kWebSocket] === undefined)
8827
+ return;
8828
+ websocket._socket.removeListener("data", socketOnData);
8829
+ process.nextTick(resume, websocket._socket);
8830
+ if (code === 1005)
8831
+ websocket.close();
8832
+ else
8833
+ websocket.close(code, reason);
8834
+ }
8835
+ function receiverOnDrain() {
8836
+ const websocket = this[kWebSocket];
8837
+ if (!websocket.isPaused)
8838
+ websocket._socket.resume();
8839
+ }
8840
+ function receiverOnError(err) {
8841
+ const websocket = this[kWebSocket];
8842
+ if (websocket._socket[kWebSocket] !== undefined) {
8843
+ websocket._socket.removeListener("data", socketOnData);
8844
+ process.nextTick(resume, websocket._socket);
8845
+ websocket.close(err[kStatusCode]);
8846
+ }
8847
+ if (!websocket._errorEmitted) {
8848
+ websocket._errorEmitted = true;
8849
+ websocket.emit("error", err);
8850
+ }
8851
+ }
8852
+ function receiverOnFinish() {
8853
+ this[kWebSocket].emitClose();
8854
+ }
8855
+ function receiverOnMessage(data, isBinary) {
8856
+ this[kWebSocket].emit("message", data, isBinary);
8857
+ }
8858
+ function receiverOnPing(data) {
8859
+ const websocket = this[kWebSocket];
8860
+ if (websocket._autoPong)
8861
+ websocket.pong(data, !this._isServer, NOOP);
8862
+ websocket.emit("ping", data);
8863
+ }
8864
+ function receiverOnPong(data) {
8865
+ this[kWebSocket].emit("pong", data);
8866
+ }
8867
+ function resume(stream) {
8868
+ stream.resume();
8869
+ }
8870
+ function senderOnError(err) {
8871
+ const websocket = this[kWebSocket];
8872
+ if (websocket.readyState === WebSocket.CLOSED)
8873
+ return;
8874
+ if (websocket.readyState === WebSocket.OPEN) {
8875
+ websocket._readyState = WebSocket.CLOSING;
8876
+ setCloseTimer(websocket);
8877
+ }
8878
+ this._socket.end();
8879
+ if (!websocket._errorEmitted) {
8880
+ websocket._errorEmitted = true;
8881
+ websocket.emit("error", err);
8882
+ }
8883
+ }
8884
+ function setCloseTimer(websocket) {
8885
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
8886
+ }
8887
+ function socketOnClose() {
8888
+ const websocket = this[kWebSocket];
8889
+ this.removeListener("close", socketOnClose);
8890
+ this.removeListener("data", socketOnData);
8891
+ this.removeListener("end", socketOnEnd);
8892
+ websocket._readyState = WebSocket.CLOSING;
8893
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
8894
+ const chunk = this.read(this._readableState.length);
8895
+ websocket._receiver.write(chunk);
8896
+ }
8897
+ websocket._receiver.end();
8898
+ this[kWebSocket] = undefined;
8899
+ clearTimeout(websocket._closeTimer);
8900
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
8901
+ websocket.emitClose();
8902
+ } else {
8903
+ websocket._receiver.on("error", receiverOnFinish);
8904
+ websocket._receiver.on("finish", receiverOnFinish);
8905
+ }
8906
+ }
8907
+ function socketOnData(chunk) {
8908
+ if (!this[kWebSocket]._receiver.write(chunk)) {
8909
+ this.pause();
8910
+ }
8911
+ }
8912
+ function socketOnEnd() {
8913
+ const websocket = this[kWebSocket];
8914
+ websocket._readyState = WebSocket.CLOSING;
8915
+ websocket._receiver.end();
8916
+ this.end();
8917
+ }
8918
+ function socketOnError() {
8919
+ const websocket = this[kWebSocket];
8920
+ this.removeListener("error", socketOnError);
8921
+ this.on("error", NOOP);
8922
+ if (websocket) {
8923
+ websocket._readyState = WebSocket.CLOSING;
8924
+ this.destroy();
8925
+ }
8926
+ }
8927
+ });
8928
+
8929
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/stream.js
8930
+ var require_stream = __commonJS((exports, module) => {
8931
+ var WebSocket = require_websocket();
8932
+ var { Duplex } = __require("stream");
8933
+ function emitClose(stream) {
8934
+ stream.emit("close");
8935
+ }
8936
+ function duplexOnEnd() {
8937
+ if (!this.destroyed && this._writableState.finished) {
8938
+ this.destroy();
8939
+ }
8940
+ }
8941
+ function duplexOnError(err) {
8942
+ this.removeListener("error", duplexOnError);
8943
+ this.destroy();
8944
+ if (this.listenerCount("error") === 0) {
8945
+ this.emit("error", err);
8946
+ }
8947
+ }
8948
+ function createWebSocketStream(ws, options) {
8949
+ let terminateOnDestroy = true;
8950
+ const duplex = new Duplex({
8951
+ ...options,
8952
+ autoDestroy: false,
8953
+ emitClose: false,
8954
+ objectMode: false,
8955
+ writableObjectMode: false
8956
+ });
8957
+ ws.on("message", function message(msg, isBinary) {
8958
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
8959
+ if (!duplex.push(data))
8960
+ ws.pause();
8961
+ });
8962
+ ws.once("error", function error(err) {
8963
+ if (duplex.destroyed)
8964
+ return;
8965
+ terminateOnDestroy = false;
8966
+ duplex.destroy(err);
8967
+ });
8968
+ ws.once("close", function close() {
8969
+ if (duplex.destroyed)
8970
+ return;
8971
+ duplex.push(null);
8972
+ });
8973
+ duplex._destroy = function(err, callback) {
8974
+ if (ws.readyState === ws.CLOSED) {
8975
+ callback(err);
8976
+ process.nextTick(emitClose, duplex);
8977
+ return;
8978
+ }
8979
+ let called = false;
8980
+ ws.once("error", function error(err2) {
8981
+ called = true;
8982
+ callback(err2);
8983
+ });
8984
+ ws.once("close", function close() {
8985
+ if (!called)
8986
+ callback(err);
8987
+ process.nextTick(emitClose, duplex);
8988
+ });
8989
+ if (terminateOnDestroy)
8990
+ ws.terminate();
8991
+ };
8992
+ duplex._final = function(callback) {
8993
+ if (ws.readyState === ws.CONNECTING) {
8994
+ ws.once("open", function open() {
8995
+ duplex._final(callback);
8996
+ });
8997
+ return;
8998
+ }
8999
+ if (ws._socket === null)
9000
+ return;
9001
+ if (ws._socket._writableState.finished) {
9002
+ callback();
9003
+ if (duplex._readableState.endEmitted)
9004
+ duplex.destroy();
9005
+ } else {
9006
+ ws._socket.once("finish", function finish() {
9007
+ callback();
9008
+ });
9009
+ ws.close();
9010
+ }
9011
+ };
9012
+ duplex._read = function() {
9013
+ if (ws.isPaused)
9014
+ ws.resume();
9015
+ };
9016
+ duplex._write = function(chunk, encoding, callback) {
9017
+ if (ws.readyState === ws.CONNECTING) {
9018
+ ws.once("open", function open() {
9019
+ duplex._write(chunk, encoding, callback);
9020
+ });
9021
+ return;
9022
+ }
9023
+ ws.send(chunk, callback);
9024
+ };
9025
+ duplex.on("end", duplexOnEnd);
9026
+ duplex.on("error", duplexOnError);
9027
+ return duplex;
9028
+ }
9029
+ module.exports = createWebSocketStream;
9030
+ });
9031
+
9032
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/subprotocol.js
9033
+ var require_subprotocol = __commonJS((exports, module) => {
9034
+ var { tokenChars } = require_validation2();
9035
+ function parse3(header) {
9036
+ const protocols = new Set;
9037
+ let start = -1;
9038
+ let end = -1;
9039
+ let i = 0;
9040
+ for (i;i < header.length; i++) {
9041
+ const code = header.charCodeAt(i);
9042
+ if (end === -1 && tokenChars[code] === 1) {
9043
+ if (start === -1)
9044
+ start = i;
9045
+ } else if (i !== 0 && (code === 32 || code === 9)) {
9046
+ if (end === -1 && start !== -1)
9047
+ end = i;
9048
+ } else if (code === 44) {
9049
+ if (start === -1) {
9050
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9051
+ }
9052
+ if (end === -1)
9053
+ end = i;
9054
+ const protocol2 = header.slice(start, end);
9055
+ if (protocols.has(protocol2)) {
9056
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
9057
+ }
9058
+ protocols.add(protocol2);
9059
+ start = end = -1;
9060
+ } else {
9061
+ throw new SyntaxError(`Unexpected character at index ${i}`);
9062
+ }
9063
+ }
9064
+ if (start === -1 || end !== -1) {
9065
+ throw new SyntaxError("Unexpected end of input");
9066
+ }
9067
+ const protocol = header.slice(start, i);
9068
+ if (protocols.has(protocol)) {
9069
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
9070
+ }
9071
+ protocols.add(protocol);
9072
+ return protocols;
9073
+ }
9074
+ module.exports = { parse: parse3 };
9075
+ });
9076
+
9077
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/lib/websocket-server.js
9078
+ var require_websocket_server = __commonJS((exports, module) => {
9079
+ var EventEmitter = __require("events");
9080
+ var http = __require("http");
9081
+ var { Duplex } = __require("stream");
9082
+ var { createHash } = __require("crypto");
9083
+ var extension = require_extension();
9084
+ var PerMessageDeflate = require_permessage_deflate();
9085
+ var subprotocol = require_subprotocol();
9086
+ var WebSocket = require_websocket();
9087
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
9088
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
9089
+ var RUNNING = 0;
9090
+ var CLOSING = 1;
9091
+ var CLOSED = 2;
9092
+
9093
+ class WebSocketServer extends EventEmitter {
9094
+ constructor(options, callback) {
9095
+ super();
9096
+ options = {
9097
+ allowSynchronousEvents: true,
9098
+ autoPong: true,
9099
+ maxPayload: 100 * 1024 * 1024,
9100
+ skipUTF8Validation: false,
9101
+ perMessageDeflate: false,
9102
+ handleProtocols: null,
9103
+ clientTracking: true,
9104
+ closeTimeout: CLOSE_TIMEOUT,
9105
+ verifyClient: null,
9106
+ noServer: false,
9107
+ backlog: null,
9108
+ server: null,
9109
+ host: null,
9110
+ path: null,
9111
+ port: null,
9112
+ WebSocket,
9113
+ ...options
9114
+ };
9115
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
9116
+ throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
9117
+ }
9118
+ if (options.port != null) {
9119
+ this._server = http.createServer((req, res) => {
9120
+ const body = http.STATUS_CODES[426];
9121
+ res.writeHead(426, {
9122
+ "Content-Length": body.length,
9123
+ "Content-Type": "text/plain"
9124
+ });
9125
+ res.end(body);
9126
+ });
9127
+ this._server.listen(options.port, options.host, options.backlog, callback);
9128
+ } else if (options.server) {
9129
+ this._server = options.server;
9130
+ }
9131
+ if (this._server) {
9132
+ const emitConnection = this.emit.bind(this, "connection");
9133
+ this._removeListeners = addListeners(this._server, {
9134
+ listening: this.emit.bind(this, "listening"),
9135
+ error: this.emit.bind(this, "error"),
9136
+ upgrade: (req, socket, head) => {
9137
+ this.handleUpgrade(req, socket, head, emitConnection);
9138
+ }
9139
+ });
9140
+ }
9141
+ if (options.perMessageDeflate === true)
9142
+ options.perMessageDeflate = {};
9143
+ if (options.clientTracking) {
9144
+ this.clients = new Set;
9145
+ this._shouldEmitClose = false;
9146
+ }
9147
+ this.options = options;
9148
+ this._state = RUNNING;
9149
+ }
9150
+ address() {
9151
+ if (this.options.noServer) {
9152
+ throw new Error('The server is operating in "noServer" mode');
9153
+ }
9154
+ if (!this._server)
9155
+ return null;
9156
+ return this._server.address();
9157
+ }
9158
+ close(cb) {
9159
+ if (this._state === CLOSED) {
9160
+ if (cb) {
9161
+ this.once("close", () => {
9162
+ cb(new Error("The server is not running"));
9163
+ });
9164
+ }
9165
+ process.nextTick(emitClose, this);
9166
+ return;
9167
+ }
9168
+ if (cb)
9169
+ this.once("close", cb);
9170
+ if (this._state === CLOSING)
9171
+ return;
9172
+ this._state = CLOSING;
9173
+ if (this.options.noServer || this.options.server) {
9174
+ if (this._server) {
9175
+ this._removeListeners();
9176
+ this._removeListeners = this._server = null;
9177
+ }
9178
+ if (this.clients) {
9179
+ if (!this.clients.size) {
9180
+ process.nextTick(emitClose, this);
9181
+ } else {
9182
+ this._shouldEmitClose = true;
9183
+ }
9184
+ } else {
9185
+ process.nextTick(emitClose, this);
9186
+ }
9187
+ } else {
9188
+ const server = this._server;
9189
+ this._removeListeners();
9190
+ this._removeListeners = this._server = null;
9191
+ server.close(() => {
9192
+ emitClose(this);
9193
+ });
9194
+ }
9195
+ }
9196
+ shouldHandle(req) {
9197
+ if (this.options.path) {
9198
+ const index = req.url.indexOf("?");
9199
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
9200
+ if (pathname !== this.options.path)
9201
+ return false;
9202
+ }
9203
+ return true;
9204
+ }
9205
+ handleUpgrade(req, socket, head, cb) {
9206
+ socket.on("error", socketOnError);
9207
+ const key = req.headers["sec-websocket-key"];
9208
+ const upgrade = req.headers.upgrade;
9209
+ const version = +req.headers["sec-websocket-version"];
9210
+ if (req.method !== "GET") {
9211
+ const message = "Invalid HTTP method";
9212
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
9213
+ return;
9214
+ }
9215
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
9216
+ const message = "Invalid Upgrade header";
9217
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
9218
+ return;
9219
+ }
9220
+ if (key === undefined || !keyRegex.test(key)) {
9221
+ const message = "Missing or invalid Sec-WebSocket-Key header";
9222
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
9223
+ return;
9224
+ }
9225
+ if (version !== 13 && version !== 8) {
9226
+ const message = "Missing or invalid Sec-WebSocket-Version header";
9227
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
9228
+ "Sec-WebSocket-Version": "13, 8"
9229
+ });
9230
+ return;
9231
+ }
9232
+ if (!this.shouldHandle(req)) {
9233
+ abortHandshake(socket, 400);
9234
+ return;
9235
+ }
9236
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
9237
+ let protocols = new Set;
9238
+ if (secWebSocketProtocol !== undefined) {
9239
+ try {
9240
+ protocols = subprotocol.parse(secWebSocketProtocol);
9241
+ } catch (err) {
9242
+ const message = "Invalid Sec-WebSocket-Protocol header";
9243
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
9244
+ return;
9245
+ }
9246
+ }
9247
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
9248
+ const extensions = {};
9249
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
9250
+ const perMessageDeflate = new PerMessageDeflate({
9251
+ ...this.options.perMessageDeflate,
9252
+ isServer: true,
9253
+ maxPayload: this.options.maxPayload
9254
+ });
9255
+ try {
9256
+ const offers = extension.parse(secWebSocketExtensions);
9257
+ if (offers[PerMessageDeflate.extensionName]) {
9258
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
9259
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
9260
+ }
9261
+ } catch (err) {
9262
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
9263
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
9264
+ return;
9265
+ }
9266
+ }
9267
+ if (this.options.verifyClient) {
9268
+ const info = {
9269
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
9270
+ secure: !!(req.socket.authorized || req.socket.encrypted),
9271
+ req
9272
+ };
9273
+ if (this.options.verifyClient.length === 2) {
9274
+ this.options.verifyClient(info, (verified, code, message, headers) => {
9275
+ if (!verified) {
9276
+ return abortHandshake(socket, code || 401, message, headers);
9277
+ }
9278
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9279
+ });
9280
+ return;
9281
+ }
9282
+ if (!this.options.verifyClient(info))
9283
+ return abortHandshake(socket, 401);
9284
+ }
9285
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9286
+ }
9287
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
9288
+ if (!socket.readable || !socket.writable)
9289
+ return socket.destroy();
9290
+ if (socket[kWebSocket]) {
9291
+ throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
9292
+ }
9293
+ if (this._state > RUNNING)
9294
+ return abortHandshake(socket, 503);
9295
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
9296
+ const headers = [
9297
+ "HTTP/1.1 101 Switching Protocols",
9298
+ "Upgrade: websocket",
9299
+ "Connection: Upgrade",
9300
+ `Sec-WebSocket-Accept: ${digest}`
9301
+ ];
9302
+ const ws = new this.options.WebSocket(null, undefined, this.options);
9303
+ if (protocols.size) {
9304
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
9305
+ if (protocol) {
9306
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
9307
+ ws._protocol = protocol;
9308
+ }
9309
+ }
9310
+ if (extensions[PerMessageDeflate.extensionName]) {
9311
+ const params = extensions[PerMessageDeflate.extensionName].params;
9312
+ const value = extension.format({
9313
+ [PerMessageDeflate.extensionName]: [params]
9314
+ });
9315
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
9316
+ ws._extensions = extensions;
9317
+ }
9318
+ this.emit("headers", headers, req);
9319
+ socket.write(headers.concat(`\r
9320
+ `).join(`\r
9321
+ `));
9322
+ socket.removeListener("error", socketOnError);
9323
+ ws.setSocket(socket, head, {
9324
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
9325
+ maxPayload: this.options.maxPayload,
9326
+ skipUTF8Validation: this.options.skipUTF8Validation
9327
+ });
9328
+ if (this.clients) {
9329
+ this.clients.add(ws);
9330
+ ws.on("close", () => {
9331
+ this.clients.delete(ws);
9332
+ if (this._shouldEmitClose && !this.clients.size) {
9333
+ process.nextTick(emitClose, this);
9334
+ }
9335
+ });
9336
+ }
9337
+ cb(ws, req);
9338
+ }
9339
+ }
9340
+ module.exports = WebSocketServer;
9341
+ function addListeners(server, map2) {
9342
+ for (const event of Object.keys(map2))
9343
+ server.on(event, map2[event]);
9344
+ return function removeListeners() {
9345
+ for (const event of Object.keys(map2)) {
9346
+ server.removeListener(event, map2[event]);
9347
+ }
9348
+ };
9349
+ }
9350
+ function emitClose(server) {
9351
+ server._state = CLOSED;
9352
+ server.emit("close");
9353
+ }
9354
+ function socketOnError() {
9355
+ this.destroy();
9356
+ }
9357
+ function abortHandshake(socket, code, message, headers) {
9358
+ message = message || http.STATUS_CODES[code];
9359
+ headers = {
9360
+ Connection: "close",
9361
+ "Content-Type": "text/html",
9362
+ "Content-Length": Buffer.byteLength(message),
9363
+ ...headers
9364
+ };
9365
+ socket.once("finish", socket.destroy);
9366
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
9367
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
9368
+ `) + `\r
9369
+ \r
9370
+ ` + message);
9371
+ }
9372
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
9373
+ if (server.listenerCount("wsClientError")) {
9374
+ const err = new Error(message);
9375
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
9376
+ server.emit("wsClientError", err, socket, req);
9377
+ } else {
9378
+ abortHandshake(socket, code, message, headers);
9379
+ }
9380
+ }
9381
+ });
9382
+
9383
+ // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v3/helpers/util.js
9384
+ var util;
9385
+ (function(util2) {
9386
+ util2.assertEqual = (_) => {};
9387
+ function assertIs(_arg) {}
9388
+ util2.assertIs = assertIs;
9389
+ function assertNever(_x) {
9390
+ throw new Error;
9391
+ }
9392
+ util2.assertNever = assertNever;
9393
+ util2.arrayToEnum = (items) => {
9394
+ const obj = {};
9395
+ for (const item of items) {
9396
+ obj[item] = item;
9397
+ }
9398
+ return obj;
9399
+ };
9400
+ util2.getValidEnumValues = (obj) => {
9401
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
9402
+ const filtered = {};
9403
+ for (const k of validKeys) {
9404
+ filtered[k] = obj[k];
9405
+ }
9406
+ return util2.objectValues(filtered);
9407
+ };
9408
+ util2.objectValues = (obj) => {
9409
+ return util2.objectKeys(obj).map(function(e) {
9410
+ return obj[e];
9411
+ });
9412
+ };
9413
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
9414
+ const keys = [];
9415
+ for (const key in object2) {
9416
+ if (Object.prototype.hasOwnProperty.call(object2, key)) {
9417
+ keys.push(key);
9418
+ }
9419
+ }
9420
+ return keys;
9421
+ };
9422
+ util2.find = (arr, checker) => {
9423
+ for (const item of arr) {
9424
+ if (checker(item))
9425
+ return item;
9426
+ }
9427
+ return;
9428
+ };
9429
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
9430
+ function joinValues(array2, separator = " | ") {
9431
+ return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
9432
+ }
9433
+ util2.joinValues = joinValues;
9434
+ util2.jsonStringifyReplacer = (_, value) => {
9435
+ if (typeof value === "bigint") {
9436
+ return value.toString();
9437
+ }
9438
+ return value;
9439
+ };
9440
+ })(util || (util = {}));
9441
+ var objectUtil;
9442
+ (function(objectUtil2) {
9443
+ objectUtil2.mergeShapes = (first, second) => {
9444
+ return {
9445
+ ...first,
9446
+ ...second
9447
+ };
9448
+ };
9449
+ })(objectUtil || (objectUtil = {}));
9450
+ var ZodParsedType = util.arrayToEnum([
9451
+ "string",
9452
+ "nan",
9453
+ "number",
9454
+ "integer",
9455
+ "float",
9456
+ "boolean",
9457
+ "date",
9458
+ "bigint",
9459
+ "symbol",
9460
+ "function",
9461
+ "undefined",
9462
+ "null",
9463
+ "array",
9464
+ "object",
9465
+ "unknown",
9466
+ "promise",
9467
+ "void",
9468
+ "never",
9469
+ "map",
9470
+ "set"
9471
+ ]);
9472
+ var getParsedType = (data) => {
9473
+ const t = typeof data;
9474
+ switch (t) {
9475
+ case "undefined":
9476
+ return ZodParsedType.undefined;
9477
+ case "string":
9478
+ return ZodParsedType.string;
9479
+ case "number":
9480
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
9481
+ case "boolean":
9482
+ return ZodParsedType.boolean;
9483
+ case "function":
9484
+ return ZodParsedType.function;
9485
+ case "bigint":
9486
+ return ZodParsedType.bigint;
9487
+ case "symbol":
9488
+ return ZodParsedType.symbol;
9489
+ case "object":
9490
+ if (Array.isArray(data)) {
9491
+ return ZodParsedType.array;
9492
+ }
9493
+ if (data === null) {
9494
+ return ZodParsedType.null;
9495
+ }
9496
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
9497
+ return ZodParsedType.promise;
9498
+ }
9499
+ if (typeof Map !== "undefined" && data instanceof Map) {
9500
+ return ZodParsedType.map;
9501
+ }
9502
+ if (typeof Set !== "undefined" && data instanceof Set) {
9503
+ return ZodParsedType.set;
9504
+ }
9505
+ if (typeof Date !== "undefined" && data instanceof Date) {
9506
+ return ZodParsedType.date;
9507
+ }
9508
+ return ZodParsedType.object;
9509
+ default:
9510
+ return ZodParsedType.unknown;
9511
+ }
9512
+ };
9513
+
9514
+ // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v3/ZodError.js
9515
+ var ZodIssueCode = util.arrayToEnum([
9516
+ "invalid_type",
9517
+ "invalid_literal",
9518
+ "custom",
9519
+ "invalid_union",
9520
+ "invalid_union_discriminator",
9521
+ "invalid_enum_value",
9522
+ "unrecognized_keys",
9523
+ "invalid_arguments",
9524
+ "invalid_return_type",
9525
+ "invalid_date",
9526
+ "invalid_string",
9527
+ "too_small",
9528
+ "too_big",
9529
+ "invalid_intersection_types",
9530
+ "not_multiple_of",
9531
+ "not_finite"
9532
+ ]);
9533
+ class ZodError extends Error {
9534
+ get errors() {
9535
+ return this.issues;
9536
+ }
9537
+ constructor(issues) {
9538
+ super();
9539
+ this.issues = [];
9540
+ this.addIssue = (sub) => {
9541
+ this.issues = [...this.issues, sub];
9542
+ };
9543
+ this.addIssues = (subs = []) => {
9544
+ this.issues = [...this.issues, ...subs];
9545
+ };
9546
+ const actualProto = new.target.prototype;
9547
+ if (Object.setPrototypeOf) {
9548
+ Object.setPrototypeOf(this, actualProto);
9549
+ } else {
9550
+ this.__proto__ = actualProto;
9551
+ }
9552
+ this.name = "ZodError";
9553
+ this.issues = issues;
9554
+ }
9555
+ format(_mapper) {
9556
+ const mapper = _mapper || function(issue) {
9557
+ return issue.message;
9558
+ };
9559
+ const fieldErrors = { _errors: [] };
6690
9560
  const processError = (error) => {
6691
9561
  for (const issue of error.issues) {
6692
9562
  if (issue.code === "invalid_union") {
@@ -14807,115 +17677,897 @@ class StdioServerTransport {
14807
17677
  this.onerror?.(error);
14808
17678
  };
14809
17679
  }
14810
- async start() {
14811
- if (this._started) {
14812
- throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
17680
+ async start() {
17681
+ if (this._started) {
17682
+ throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
17683
+ }
17684
+ this._started = true;
17685
+ this._stdin.on("data", this._ondata);
17686
+ this._stdin.on("error", this._onerror);
17687
+ }
17688
+ processReadBuffer() {
17689
+ while (true) {
17690
+ try {
17691
+ const message = this._readBuffer.readMessage();
17692
+ if (message === null) {
17693
+ break;
17694
+ }
17695
+ this.onmessage?.(message);
17696
+ } catch (error) {
17697
+ this.onerror?.(error);
17698
+ }
17699
+ }
17700
+ }
17701
+ async close() {
17702
+ this._stdin.off("data", this._ondata);
17703
+ this._stdin.off("error", this._onerror);
17704
+ const remainingDataListeners = this._stdin.listenerCount("data");
17705
+ if (remainingDataListeners === 0) {
17706
+ this._stdin.pause();
17707
+ }
17708
+ this._readBuffer.clear();
17709
+ this.onclose?.();
17710
+ }
17711
+ send(message) {
17712
+ return new Promise((resolve) => {
17713
+ const json = serializeMessage(message);
17714
+ if (this._stdout.write(json)) {
17715
+ resolve();
17716
+ } else {
17717
+ this._stdout.once("drain", resolve);
17718
+ }
17719
+ });
17720
+ }
17721
+ }
17722
+
17723
+ // src/mcp.ts
17724
+ import { existsSync as existsSync5, readFileSync as readFileSync3, readdirSync as readdirSync2 } from "node:fs";
17725
+ import { join as join6 } from "node:path";
17726
+
17727
+ // src/utils/scan.ts
17728
+ import { readdirSync, existsSync, readFileSync } from "node:fs";
17729
+ import { join, relative } from "node:path";
17730
+ async function scanCodebase(root) {
17731
+ const scan = {
17732
+ testFiles: [],
17733
+ configFiles: [],
17734
+ fixtureFiles: [],
17735
+ featureFiles: [],
17736
+ tsconfigPaths: {},
17737
+ playwrightConfig: null,
17738
+ sampleTestContent: null
17739
+ };
17740
+ function walk(dir, depth = 0) {
17741
+ if (depth > 5)
17742
+ return [];
17743
+ const files = [];
17744
+ try {
17745
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
17746
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist")
17747
+ continue;
17748
+ const full = join(dir, entry.name);
17749
+ if (entry.isDirectory()) {
17750
+ files.push(...walk(full, depth + 1));
17751
+ } else {
17752
+ files.push(full);
17753
+ }
17754
+ }
17755
+ } catch {}
17756
+ return files;
17757
+ }
17758
+ const allFiles = walk(root);
17759
+ for (const file of allFiles) {
17760
+ const rel = relative(root, file);
17761
+ if (rel.endsWith(".test.ts") || rel.endsWith(".spec.ts")) {
17762
+ scan.testFiles.push(rel);
17763
+ if (!scan.sampleTestContent && scan.testFiles.length <= 3) {
17764
+ try {
17765
+ scan.sampleTestContent = readFileSync(file, "utf-8").slice(0, 3000);
17766
+ } catch {}
17767
+ }
17768
+ }
17769
+ if (rel.endsWith(".feature.ts"))
17770
+ scan.featureFiles.push(rel);
17771
+ if (rel.includes("fixture") && rel.endsWith(".ts"))
17772
+ scan.fixtureFiles.push(rel);
17773
+ if (rel === "playwright.config.ts" || rel === "playwright.config.js")
17774
+ scan.playwrightConfig = rel;
17775
+ if (rel === "tsconfig.json" || rel.endsWith("/tsconfig.json")) {
17776
+ try {
17777
+ const tsconfig = JSON.parse(readFileSync(file, "utf-8"));
17778
+ if (tsconfig.compilerOptions?.paths) {
17779
+ scan.tsconfigPaths = { ...scan.tsconfigPaths, ...tsconfig.compilerOptions.paths };
17780
+ }
17781
+ } catch {}
17782
+ }
17783
+ }
17784
+ for (const name of ["playwright.config.ts", "vitest.config.ts", "jest.config.ts", "tsconfig.json", "package.json"]) {
17785
+ if (existsSync(join(root, name)))
17786
+ scan.configFiles.push(name);
17787
+ }
17788
+ return scan;
17789
+ }
17790
+
17791
+ // src/copilot/tools.ts
17792
+ import { join as join5 } from "node:path";
17793
+
17794
+ // src/copilot/session.ts
17795
+ import { randomUUID } from "node:crypto";
17796
+ import { join as join2 } from "node:path";
17797
+ var sessions = new Map;
17798
+ function createSession(baseUrl, mode, outputDir) {
17799
+ const id = randomUUID().slice(0, 8);
17800
+ const session = {
17801
+ id,
17802
+ baseUrl,
17803
+ mode,
17804
+ startedAt: new Date().toISOString(),
17805
+ outputDir,
17806
+ pages: new Map,
17807
+ topology: [],
17808
+ actionLog: [],
17809
+ annotations: [],
17810
+ pendingProposal: null,
17811
+ voiceQueue: [],
17812
+ companionPort: null,
17813
+ overlayPid: null
17814
+ };
17815
+ ensureDir(join2(outputDir, "screenshots"));
17816
+ ensureDir(join2(outputDir, "sections"));
17817
+ sessions.set(id, session);
17818
+ return session;
17819
+ }
17820
+ function getSession(id) {
17821
+ return sessions.get(id);
17822
+ }
17823
+ function destroySession(id) {
17824
+ sessions.delete(id);
17825
+ }
17826
+ function addPage(session, page) {
17827
+ session.pages.set(page.url, page);
17828
+ session.topology = buildTopology(session.pages);
17829
+ }
17830
+ function logAction(session, action, result, source = "agent") {
17831
+ session.actionLog.push({
17832
+ action,
17833
+ timestamp: new Date().toISOString(),
17834
+ result,
17835
+ source
17836
+ });
17837
+ }
17838
+ function enqueueVoiceInput(session, input) {
17839
+ session.voiceQueue.push(input);
17840
+ }
17841
+ function drainVoiceQueue(session) {
17842
+ const commands = session.voiceQueue.filter((v) => v.type === "command");
17843
+ const comments = session.voiceQueue.filter((v) => v.type === "comment");
17844
+ for (const comment of comments) {
17845
+ session.annotations.push(comment);
17846
+ }
17847
+ session.voiceQueue = [];
17848
+ return { commands, comments };
17849
+ }
17850
+ function setProposal(session, action, reason) {
17851
+ const proposal = {
17852
+ id: randomUUID().slice(0, 8),
17853
+ action,
17854
+ reason,
17855
+ timestamp: new Date().toISOString(),
17856
+ status: "pending"
17857
+ };
17858
+ session.pendingProposal = proposal;
17859
+ return proposal;
17860
+ }
17861
+ function resolveProposal(session, approved, feedback) {
17862
+ if (session.pendingProposal) {
17863
+ session.pendingProposal.status = approved ? "approved" : "rejected";
17864
+ session.pendingProposal.feedback = feedback;
17865
+ }
17866
+ }
17867
+ function serializeSession(session) {
17868
+ return {
17869
+ id: session.id,
17870
+ baseUrl: session.baseUrl,
17871
+ mode: session.mode,
17872
+ startedAt: session.startedAt,
17873
+ outputDir: session.outputDir,
17874
+ pages: Array.from(session.pages.values()).map((p) => ({
17875
+ url: p.url,
17876
+ path: p.path,
17877
+ title: p.title,
17878
+ slug: p.slug,
17879
+ status: p.status,
17880
+ elements: p.elements.length,
17881
+ outgoingLinks: p.outgoingLinks.length,
17882
+ hasAnalysis: !!p.analysis
17883
+ })),
17884
+ topology: session.topology,
17885
+ stats: {
17886
+ pagesExplored: Array.from(session.pages.values()).filter((p) => p.status === "visited").length,
17887
+ totalAnnotations: session.annotations.length,
17888
+ totalActions: session.actionLog.length
17889
+ },
17890
+ annotations: session.annotations
17891
+ };
17892
+ }
17893
+
17894
+ // src/copilot/companion/server.ts
17895
+ import { createServer } from "node:http";
17896
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
17897
+ import { resolve, dirname } from "node:path";
17898
+ import { fileURLToPath } from "node:url";
17899
+
17900
+ // ../../node_modules/.bun/ws@8.20.0/node_modules/ws/wrapper.mjs
17901
+ var import_stream = __toESM(require_stream(), 1);
17902
+ var import_extension = __toESM(require_extension(), 1);
17903
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
17904
+ var import_receiver = __toESM(require_receiver(), 1);
17905
+ var import_sender = __toESM(require_sender(), 1);
17906
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
17907
+ var import_websocket = __toESM(require_websocket(), 1);
17908
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
17909
+
17910
+ // src/copilot/companion/state.ts
17911
+ function createCompanionState(mode) {
17912
+ return {
17913
+ mode,
17914
+ currentPage: null,
17915
+ actionLog: [],
17916
+ pendingProposal: null,
17917
+ voiceQueue: []
17918
+ };
17919
+ }
17920
+
17921
+ // src/copilot/companion/server.ts
17922
+ var __dirname2 = dirname(fileURLToPath(import.meta.url));
17923
+ var uiDir = resolve(__dirname2, "ui");
17924
+ var state;
17925
+ var clients = new Set;
17926
+ var _httpServer = null;
17927
+ var _wss = null;
17928
+ function broadcast(msg) {
17929
+ const data = JSON.stringify(msg);
17930
+ for (const ws of clients) {
17931
+ if (ws.readyState === 1)
17932
+ ws.send(data);
17933
+ }
17934
+ }
17935
+ function broadcastState() {
17936
+ broadcast({ type: "state:update", state });
17937
+ }
17938
+ function startCompanionServer(mode, port = 0) {
17939
+ state = createCompanionState(mode);
17940
+ return new Promise((resolvePromise, reject) => {
17941
+ const startTime = Date.now();
17942
+ const httpServer = createServer((req, res) => {
17943
+ const url = req.url?.split("?")[0];
17944
+ const cors = { "Access-Control-Allow-Origin": "*" };
17945
+ if (url === "/" || url === "/companion") {
17946
+ const htmlPath = resolve(uiDir, "companion.html");
17947
+ if (existsSync2(htmlPath)) {
17948
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", ...cors });
17949
+ res.end(readFileSync2(htmlPath));
17950
+ } else {
17951
+ res.writeHead(200, { "Content-Type": "text/html", ...cors });
17952
+ res.end("<html><body><h1>Companion UI not found</h1></body></html>");
17953
+ }
17954
+ return;
17955
+ }
17956
+ if (url === "/logo.svg") {
17957
+ const svgPath = resolve(uiDir, "logo.svg");
17958
+ if (existsSync2(svgPath)) {
17959
+ res.writeHead(200, { "Content-Type": "image/svg+xml", ...cors });
17960
+ res.end(readFileSync2(svgPath));
17961
+ } else {
17962
+ res.writeHead(404);
17963
+ res.end("Not found");
17964
+ }
17965
+ return;
17966
+ }
17967
+ if (url === "/health") {
17968
+ res.writeHead(200, { "Content-Type": "application/json", ...cors });
17969
+ res.end(JSON.stringify({ status: "ok", uptime: Math.floor((Date.now() - startTime) / 1000) }));
17970
+ return;
17971
+ }
17972
+ if (url === "/track" && req.method === "POST") {
17973
+ let body = "";
17974
+ req.on("data", (chunk) => {
17975
+ body += chunk.toString();
17976
+ });
17977
+ req.on("end", () => {
17978
+ try {
17979
+ const data = JSON.parse(body);
17980
+ const entry = {
17981
+ action: data.action ?? "unknown",
17982
+ timestamp: new Date().toISOString(),
17983
+ result: data.result,
17984
+ source: data.source ?? "agent"
17985
+ };
17986
+ state.actionLog.push(entry);
17987
+ if (state.actionLog.length > 100)
17988
+ state.actionLog = state.actionLog.slice(-100);
17989
+ if (data.url) {
17990
+ state.currentPage = { url: data.url, title: data.title ?? data.url };
17991
+ }
17992
+ broadcastState();
17993
+ res.writeHead(200, { "Content-Type": "application/json", ...cors });
17994
+ res.end(JSON.stringify({ success: true, tracked_at: entry.timestamp }));
17995
+ } catch {
17996
+ res.writeHead(400, { "Content-Type": "application/json", ...cors });
17997
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
17998
+ }
17999
+ });
18000
+ return;
18001
+ }
18002
+ if (url === "/track" && req.method === "OPTIONS") {
18003
+ res.writeHead(204, { ...cors, "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "Content-Type" });
18004
+ res.end();
18005
+ return;
18006
+ }
18007
+ res.writeHead(404);
18008
+ res.end("Not found");
18009
+ });
18010
+ const wss = new import_websocket_server.default({ server: httpServer });
18011
+ wss.on("connection", (ws) => {
18012
+ clients.add(ws);
18013
+ ws.send(JSON.stringify({ type: "state:update", state }));
18014
+ ws.on("message", (raw) => {
18015
+ let msg;
18016
+ try {
18017
+ msg = JSON.parse(raw.toString());
18018
+ } catch {
18019
+ return;
18020
+ }
18021
+ switch (msg.type) {
18022
+ case "voice:input": {
18023
+ const input = {
18024
+ type: msg.inputType,
18025
+ text: msg.text,
18026
+ timestamp: new Date().toISOString(),
18027
+ pageSlug: state.currentPage?.url
18028
+ };
18029
+ state.voiceQueue.push(input);
18030
+ broadcastState();
18031
+ break;
18032
+ }
18033
+ case "text:input": {
18034
+ const input = {
18035
+ type: "command",
18036
+ text: msg.text,
18037
+ timestamp: new Date().toISOString()
18038
+ };
18039
+ state.voiceQueue.push(input);
18040
+ broadcastState();
18041
+ break;
18042
+ }
18043
+ case "proposal:respond": {
18044
+ if (state.pendingProposal) {
18045
+ state.pendingProposal.status = msg.approved ? "approved" : "rejected";
18046
+ state.pendingProposal.feedback = msg.feedback;
18047
+ broadcastState();
18048
+ }
18049
+ break;
18050
+ }
18051
+ case "mode:change": {
18052
+ state.mode = msg.mode;
18053
+ broadcastState();
18054
+ break;
18055
+ }
18056
+ }
18057
+ });
18058
+ ws.on("close", () => {
18059
+ clients.delete(ws);
18060
+ });
18061
+ });
18062
+ _httpServer = httpServer;
18063
+ _wss = wss;
18064
+ httpServer.listen(port, "127.0.0.1", () => {
18065
+ const addr = httpServer.address();
18066
+ const actualPort = typeof addr === "object" && addr ? addr.port : port;
18067
+ resolvePromise({ port: actualPort, url: `http://localhost:${actualPort}` });
18068
+ });
18069
+ httpServer.on("error", reject);
18070
+ });
18071
+ }
18072
+ function stopCompanionServer() {
18073
+ broadcast({ type: "session:end" });
18074
+ for (const ws of clients) {
18075
+ try {
18076
+ ws.close();
18077
+ } catch {}
18078
+ }
18079
+ clients.clear();
18080
+ if (_wss) {
18081
+ _wss.close();
18082
+ _wss = null;
18083
+ }
18084
+ if (_httpServer) {
18085
+ _httpServer.close();
18086
+ _httpServer = null;
18087
+ }
18088
+ state = createCompanionState("auto");
18089
+ }
18090
+ function updateCurrentPage(url, title, screenshotPath) {
18091
+ if (state) {
18092
+ state.currentPage = { url, title, screenshotPath };
18093
+ broadcastState();
18094
+ }
18095
+ }
18096
+ function addActionToLog(entry) {
18097
+ if (state) {
18098
+ state.actionLog.push(entry);
18099
+ if (state.actionLog.length > 100)
18100
+ state.actionLog = state.actionLog.slice(-100);
18101
+ broadcastState();
18102
+ }
18103
+ }
18104
+ function setCompanionProposal(proposal) {
18105
+ if (state) {
18106
+ state.pendingProposal = proposal;
18107
+ broadcastState();
18108
+ }
18109
+ }
18110
+ function getCompanionVoiceQueue() {
18111
+ if (!state)
18112
+ return [];
18113
+ const queue = [...state.voiceQueue];
18114
+ state.voiceQueue = [];
18115
+ return queue;
18116
+ }
18117
+ function getCompanionProposalResult() {
18118
+ if (!state?.pendingProposal)
18119
+ return null;
18120
+ if (state.pendingProposal.status === "pending")
18121
+ return null;
18122
+ const result = { ...state.pendingProposal };
18123
+ state.pendingProposal = null;
18124
+ return result;
18125
+ }
18126
+
18127
+ // src/copilot/overlay-launcher.ts
18128
+ import { existsSync as existsSync4 } from "node:fs";
18129
+ import { join as join4 } from "node:path";
18130
+ import { homedir } from "node:os";
18131
+ import { spawn } from "node:child_process";
18132
+
18133
+ // src/copilot/overlay-download.ts
18134
+ import { createHash } from "node:crypto";
18135
+ import { chmodSync, createWriteStream, existsSync as existsSync3, mkdirSync } from "node:fs";
18136
+ import { readFile, unlink } from "node:fs/promises";
18137
+ import { join as join3 } from "node:path";
18138
+ import { createInterface } from "node:readline";
18139
+ import { Readable } from "node:stream";
18140
+ import { pipeline as pipeline2 } from "node:stream/promises";
18141
+ var OVERLAY_VERSION = "0.1.0";
18142
+ var GITHUB_REPO = "davide97g/qaligent";
18143
+ function resolveArch() {
18144
+ if (process.arch === "arm64")
18145
+ return "aarch64";
18146
+ return null;
18147
+ }
18148
+ async function confirm(message) {
18149
+ if (!process.stdin.isTTY)
18150
+ return false;
18151
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
18152
+ return new Promise((resolve2) => {
18153
+ rl.question(`${message} (Y/n) `, (answer) => {
18154
+ rl.close();
18155
+ resolve2(answer.trim().toLowerCase() !== "n");
18156
+ });
18157
+ });
18158
+ }
18159
+ async function fetchWithProgress(url, destPath) {
18160
+ const response = await fetch(url, { redirect: "follow" });
18161
+ if (!response.ok)
18162
+ throw new Error(`Download failed: ${response.status} ${response.statusText}`);
18163
+ const contentLength = Number(response.headers.get("content-length") || 0);
18164
+ const body = response.body;
18165
+ if (!body)
18166
+ throw new Error("No response body");
18167
+ let downloaded = 0;
18168
+ const fileStream = createWriteStream(destPath);
18169
+ const reader = body.getReader();
18170
+ const nodeStream = new Readable({
18171
+ async read() {
18172
+ const { done, value } = await reader.read();
18173
+ if (done) {
18174
+ this.push(null);
18175
+ } else {
18176
+ downloaded += value.byteLength;
18177
+ if (contentLength > 0) {
18178
+ const pct = Math.round(downloaded / contentLength * 100);
18179
+ const mb = (downloaded / 1024 / 1024).toFixed(1);
18180
+ process.stdout.write(`\r Downloading... ${mb} MB (${pct}%)`);
18181
+ }
18182
+ this.push(Buffer.from(value));
18183
+ }
18184
+ }
18185
+ });
18186
+ await pipeline2(nodeStream, fileStream);
18187
+ if (contentLength > 0)
18188
+ process.stdout.write(`
18189
+ `);
18190
+ }
18191
+ async function verifyChecksum(filePath, expectedHash) {
18192
+ const data = await readFile(filePath);
18193
+ const hash = createHash("sha256").update(data).digest("hex");
18194
+ return hash === expectedHash;
18195
+ }
18196
+ async function downloadOverlay(binDir, options) {
18197
+ if (process.platform !== "darwin") {
18198
+ if (!options?.silent) {
18199
+ console.log(" Native overlay is only available on macOS.");
18200
+ }
18201
+ return false;
18202
+ }
18203
+ const arch = resolveArch();
18204
+ if (!arch) {
18205
+ if (!options?.silent) {
18206
+ console.log(" Native overlay is only available on Apple Silicon Macs (M1/M2/M3/M4).");
14813
18207
  }
14814
- this._started = true;
14815
- this._stdin.on("data", this._ondata);
14816
- this._stdin.on("error", this._onerror);
18208
+ return false;
14817
18209
  }
14818
- processReadBuffer() {
14819
- while (true) {
14820
- try {
14821
- const message = this._readBuffer.readMessage();
14822
- if (message === null) {
14823
- break;
18210
+ const shouldDownload = await confirm(`
18211
+ Native overlay not found. Download Zefiro Overlay? (~10 MB)`);
18212
+ if (!shouldDownload)
18213
+ return false;
18214
+ if (!existsSync3(binDir)) {
18215
+ mkdirSync(binDir, { recursive: true });
18216
+ }
18217
+ const assetName = `zefiro-overlay-${OVERLAY_VERSION}-darwin-${arch}.tar.gz`;
18218
+ const checksumName = `zefiro-overlay-${OVERLAY_VERSION}-checksums.sha256`;
18219
+ const baseUrl = `https://github.com/${GITHUB_REPO}/releases/download/overlay-v${OVERLAY_VERSION}`;
18220
+ const tarPath = join3(binDir, assetName);
18221
+ const binPath = join3(binDir, "zefiro-overlay");
18222
+ try {
18223
+ await fetchWithProgress(`${baseUrl}/${assetName}`, tarPath);
18224
+ try {
18225
+ const checksumResponse = await fetch(`${baseUrl}/${checksumName}`);
18226
+ if (checksumResponse.ok) {
18227
+ const checksumText = await checksumResponse.text();
18228
+ const expectedHash = checksumText.split(`
18229
+ `).find((line) => line.includes(assetName))?.split(/\s+/)[0];
18230
+ if (expectedHash) {
18231
+ const valid = await verifyChecksum(tarPath, expectedHash);
18232
+ if (!valid) {
18233
+ console.log(" Checksum verification failed. Download may be corrupted.");
18234
+ await unlink(tarPath).catch(() => {});
18235
+ return false;
18236
+ }
14824
18237
  }
14825
- this.onmessage?.(message);
14826
- } catch (error) {
14827
- this.onerror?.(error);
14828
18238
  }
18239
+ } catch {}
18240
+ const { execSync } = await import("node:child_process");
18241
+ execSync(`tar -xzf "${tarPath}" -C "${binDir}"`, { stdio: "ignore" });
18242
+ if (existsSync3(binPath)) {
18243
+ chmodSync(binPath, 493);
14829
18244
  }
14830
- }
14831
- async close() {
14832
- this._stdin.off("data", this._ondata);
14833
- this._stdin.off("error", this._onerror);
14834
- const remainingDataListeners = this._stdin.listenerCount("data");
14835
- if (remainingDataListeners === 0) {
14836
- this._stdin.pause();
18245
+ await unlink(tarPath).catch(() => {});
18246
+ console.log(` Installed to ${binPath}`);
18247
+ return true;
18248
+ } catch (err) {
18249
+ const message = err instanceof Error ? err.message : String(err);
18250
+ if (!options?.silent) {
18251
+ console.log(` Download failed: ${message}`);
14837
18252
  }
14838
- this._readBuffer.clear();
14839
- this.onclose?.();
18253
+ await unlink(tarPath).catch(() => {});
18254
+ return false;
14840
18255
  }
14841
- send(message) {
14842
- return new Promise((resolve) => {
14843
- const json = serializeMessage(message);
14844
- if (this._stdout.write(json)) {
14845
- resolve();
14846
- } else {
14847
- this._stdout.once("drain", resolve);
14848
- }
18256
+ }
18257
+
18258
+ // src/copilot/overlay-launcher.ts
18259
+ var OVERLAY_BIN_NAME = "zefiro-overlay";
18260
+ function searchPaths() {
18261
+ const home = homedir();
18262
+ return [
18263
+ join4(home, ".qai", "bin", OVERLAY_BIN_NAME),
18264
+ join4("/opt", "homebrew", "bin", OVERLAY_BIN_NAME),
18265
+ join4("/usr", "local", "bin", OVERLAY_BIN_NAME)
18266
+ ];
18267
+ }
18268
+ async function resolveOverlayBinary(options) {
18269
+ const envPath = process.env.ZEFIRO_OVERLAY_PATH;
18270
+ if (envPath) {
18271
+ return existsSync4(envPath) ? envPath : null;
18272
+ }
18273
+ if (process.env.ZEFIRO_NO_OVERLAY === "1")
18274
+ return null;
18275
+ for (const p of searchPaths()) {
18276
+ if (existsSync4(p))
18277
+ return p;
18278
+ }
18279
+ if (options?.skipDownload)
18280
+ return null;
18281
+ if (!process.stdin.isTTY)
18282
+ return null;
18283
+ const binDir = join4(homedir(), ".qai", "bin");
18284
+ const downloaded = await downloadOverlay(binDir, { silent: options?.silent });
18285
+ if (downloaded) {
18286
+ return join4(binDir, OVERLAY_BIN_NAME);
18287
+ }
18288
+ return null;
18289
+ }
18290
+ function spawnOverlay(binPath, wsPort) {
18291
+ try {
18292
+ const child = spawn(binPath, ["--ws-port", String(wsPort)], {
18293
+ detached: true,
18294
+ stdio: "ignore"
14849
18295
  });
18296
+ child.unref();
18297
+ return child;
18298
+ } catch {
18299
+ return null;
14850
18300
  }
14851
18301
  }
14852
18302
 
14853
- // src/mcp.ts
14854
- import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "node:fs";
14855
- import { join as join2 } from "node:path";
14856
-
14857
- // src/utils/scan.ts
14858
- import { readdirSync, existsSync, readFileSync } from "node:fs";
14859
- import { join, relative } from "node:path";
14860
- async function scanCodebase(root) {
14861
- const scan = {
14862
- testFiles: [],
14863
- configFiles: [],
14864
- fixtureFiles: [],
14865
- featureFiles: [],
14866
- tsconfigPaths: {},
14867
- playwrightConfig: null,
14868
- sampleTestContent: null
18303
+ // src/copilot/tools.ts
18304
+ var browsers = new Map;
18305
+ function syncAction(action, result, source = "agent") {
18306
+ addActionToLog({ action, timestamp: new Date().toISOString(), result, source });
18307
+ }
18308
+ async function handleCopilotStart(params) {
18309
+ const mode = params.mode || "auto";
18310
+ const cwd = process.cwd();
18311
+ const outputDir = params.outputDir ? join5(cwd, params.outputDir) : join5(cwd, "copilot-report");
18312
+ const session = createSession(params.baseUrl, mode, outputDir);
18313
+ if (params.browser !== "chrome") {
18314
+ const browser = new AgentBrowser({
18315
+ session: `copilot-${session.id}`,
18316
+ headed: params.headed ?? true
18317
+ });
18318
+ browsers.set(session.id, browser);
18319
+ if (params.authState) {
18320
+ const config = {
18321
+ baseUrl: params.baseUrl,
18322
+ outputDir,
18323
+ maxPages: params.maxPages ?? 100,
18324
+ excludePatterns: [],
18325
+ headed: params.headed ?? true,
18326
+ waitStrategy: "networkidle",
18327
+ waitDelay: 1500,
18328
+ pageTimeout: 30000,
18329
+ auth: { method: "state-file", stateFile: params.authState },
18330
+ sessionName: `copilot-${session.id}`
18331
+ };
18332
+ await authenticate(browser, config);
18333
+ }
18334
+ await browser.setViewport(1440, 900);
18335
+ await browser.open(params.baseUrl);
18336
+ await browser.waitForLoad("networkidle", 1500);
18337
+ }
18338
+ const companion = await startCompanionServer(mode, 0);
18339
+ session.companionPort = companion.port;
18340
+ const overlayBin = await resolveOverlayBinary({ silent: true });
18341
+ if (overlayBin) {
18342
+ const child = spawnOverlay(overlayBin, companion.port);
18343
+ if (child?.pid)
18344
+ session.overlayPid = child.pid;
18345
+ }
18346
+ logAction(session, `copilot_start: ${params.baseUrl} (mode: ${mode})`);
18347
+ syncAction(`copilot_start: ${params.baseUrl} (mode: ${mode})`);
18348
+ return {
18349
+ session_id: session.id,
18350
+ mode: session.mode,
18351
+ base_url: params.baseUrl,
18352
+ output_dir: outputDir,
18353
+ companion_url: `http://localhost:${companion.port}`,
18354
+ browser: params.browser ?? "playwright"
14869
18355
  };
14870
- function walk(dir, depth = 0) {
14871
- if (depth > 5)
14872
- return [];
14873
- const files = [];
18356
+ }
18357
+ async function handleCopilotStop(params) {
18358
+ const session = getSession(params.session_id);
18359
+ if (!session)
18360
+ throw new Error(`Session not found: ${params.session_id}`);
18361
+ const browser = browsers.get(params.session_id);
18362
+ const state2 = {
18363
+ baseUrl: session.baseUrl,
18364
+ startedAt: session.startedAt,
18365
+ completedAt: new Date().toISOString(),
18366
+ pages: session.pages,
18367
+ queue: [],
18368
+ topology: session.topology
18369
+ };
18370
+ const readme = generateReadme(state2);
18371
+ writeFile(join5(session.outputDir, "README.md"), readme);
18372
+ const html = generateIndexHtml(state2);
18373
+ writeFile(join5(session.outputDir, "index.html"), html);
18374
+ logAction(session, "copilot_stop: report generated");
18375
+ syncAction("copilot_stop: report generated");
18376
+ if (browser) {
18377
+ await browser.close();
18378
+ browsers.delete(params.session_id);
18379
+ }
18380
+ stopCompanionServer();
18381
+ if (session.overlayPid) {
14874
18382
  try {
14875
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
14876
- if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist")
14877
- continue;
14878
- const full = join(dir, entry.name);
14879
- if (entry.isDirectory()) {
14880
- files.push(...walk(full, depth + 1));
14881
- } else {
14882
- files.push(full);
14883
- }
14884
- }
18383
+ process.kill(session.overlayPid);
14885
18384
  } catch {}
14886
- return files;
14887
18385
  }
14888
- const allFiles = walk(root);
14889
- for (const file of allFiles) {
14890
- const rel = relative(root, file);
14891
- if (rel.endsWith(".test.ts") || rel.endsWith(".spec.ts")) {
14892
- scan.testFiles.push(rel);
14893
- if (!scan.sampleTestContent && scan.testFiles.length <= 3) {
14894
- try {
14895
- scan.sampleTestContent = readFileSync(file, "utf-8").slice(0, 3000);
14896
- } catch {}
18386
+ const reportPath = join5(session.outputDir, "README.md");
18387
+ destroySession(params.session_id);
18388
+ return { report_path: reportPath, output_dir: session.outputDir };
18389
+ }
18390
+ function requireBrowser(sessionId) {
18391
+ const session = getSession(sessionId);
18392
+ if (!session)
18393
+ throw new Error(`Session not found: ${sessionId}`);
18394
+ const browser = browsers.get(sessionId);
18395
+ if (!browser)
18396
+ throw new Error(`Browser not found for session: ${sessionId}`);
18397
+ return { browser, session };
18398
+ }
18399
+ async function handleCopilotNavigate(params) {
18400
+ const { browser, session } = requireBrowser(params.session_id);
18401
+ await browser.open(params.url);
18402
+ await browser.waitForLoad("networkidle", 1500);
18403
+ const actualUrl = await browser.getUrl();
18404
+ const title = await browser.getTitle();
18405
+ logAction(session, `navigate: ${params.url}`, `title: ${title}, actual: ${actualUrl}`);
18406
+ syncAction(`navigate: ${params.url}`, `title: ${title}, actual: ${actualUrl}`);
18407
+ updateCurrentPage(actualUrl, title);
18408
+ return { title, actual_url: actualUrl, redirected: actualUrl !== params.url };
18409
+ }
18410
+ async function handleCopilotSnapshot(params) {
18411
+ const { browser, session } = requireBrowser(params.session_id);
18412
+ const elements = await browser.snapshot();
18413
+ const url = await browser.getUrl();
18414
+ const title = await browser.getTitle();
18415
+ logAction(session, `snapshot: ${elements.length} elements`);
18416
+ syncAction(`snapshot: ${elements.length} elements`);
18417
+ return {
18418
+ url,
18419
+ title,
18420
+ elements: elements.map((e) => ({ ref: e.ref, role: e.role, label: e.label })),
18421
+ element_count: elements.length
18422
+ };
18423
+ }
18424
+ async function handleCopilotScreenshot(params) {
18425
+ const { browser, session } = requireBrowser(params.session_id);
18426
+ const url = await browser.getUrl();
18427
+ const slug = urlToSlug(url, session.baseUrl);
18428
+ const label = params.label ?? "default";
18429
+ const filename = `${slug}-${label}.png`;
18430
+ const filePath = join5(session.outputDir, "screenshots", slug, `${label}.png`);
18431
+ ensureDir(join5(session.outputDir, "screenshots", slug));
18432
+ await browser.screenshot(filePath);
18433
+ logAction(session, `screenshot: ${filename}`);
18434
+ syncAction(`screenshot: ${filename}`);
18435
+ return { file_path: filePath, slug, label };
18436
+ }
18437
+ async function handleCopilotClick(params) {
18438
+ const { browser, session } = requireBrowser(params.session_id);
18439
+ const urlBefore = await browser.getUrl();
18440
+ await browser.click(params.ref);
18441
+ await browser.waitForLoad("load", 500);
18442
+ const urlAfter = await browser.getUrl();
18443
+ const navigated = urlAfter !== urlBefore;
18444
+ logAction(session, `click: ${params.ref}`, navigated ? `navigated to ${urlAfter}` : "no navigation");
18445
+ syncAction(`click: ${params.ref}`, navigated ? `navigated to ${urlAfter}` : "no navigation");
18446
+ return { success: true, navigated, new_url: navigated ? urlAfter : undefined };
18447
+ }
18448
+ async function handleCopilotFill(params) {
18449
+ const { browser, session } = requireBrowser(params.session_id);
18450
+ await browser.fill(params.ref, params.text);
18451
+ logAction(session, `fill: ${params.ref} = "${params.text}"`);
18452
+ syncAction(`fill: ${params.ref} = "${params.text}"`);
18453
+ return { success: true };
18454
+ }
18455
+ async function handleCopilotGetLinks(params) {
18456
+ const { browser, session } = requireBrowser(params.session_id);
18457
+ const elements = await browser.snapshot();
18458
+ const linkElements = elements.filter((e) => e.role === "link");
18459
+ const currentUrl = await browser.getUrl();
18460
+ const visited = new Set(Array.from(session.pages.keys()));
18461
+ const links = [];
18462
+ for (const el of linkElements) {
18463
+ try {
18464
+ const href = await browser.getAttribute(el.ref, "href");
18465
+ if (href) {
18466
+ const normalized = normalizeUrl(href, currentUrl);
18467
+ links.push({ ref: el.ref, label: el.label, url: normalized, visited: visited.has(normalized) });
14897
18468
  }
14898
- }
14899
- if (rel.endsWith(".feature.ts"))
14900
- scan.featureFiles.push(rel);
14901
- if (rel.includes("fixture") && rel.endsWith(".ts"))
14902
- scan.fixtureFiles.push(rel);
14903
- if (rel === "playwright.config.ts" || rel === "playwright.config.js")
14904
- scan.playwrightConfig = rel;
14905
- if (rel === "tsconfig.json" || rel.endsWith("/tsconfig.json")) {
14906
- try {
14907
- const tsconfig = JSON.parse(readFileSync(file, "utf-8"));
14908
- if (tsconfig.compilerOptions?.paths) {
14909
- scan.tsconfigPaths = { ...scan.tsconfigPaths, ...tsconfig.compilerOptions.paths };
14910
- }
14911
- } catch {}
18469
+ } catch {
18470
+ links.push({ ref: el.ref, label: el.label, visited: false });
14912
18471
  }
14913
18472
  }
14914
- for (const name of ["playwright.config.ts", "vitest.config.ts", "jest.config.ts", "tsconfig.json", "package.json"]) {
14915
- if (existsSync(join(root, name)))
14916
- scan.configFiles.push(name);
18473
+ logAction(session, `get_links: ${links.length} links found`);
18474
+ syncAction(`get_links: ${links.length} links found`);
18475
+ return { links, total: links.length, unvisited: links.filter((l) => !l.visited).length };
18476
+ }
18477
+ async function handleCopilotRecordPage(params) {
18478
+ const { browser, session } = requireBrowser(params.session_id);
18479
+ const url = await browser.getUrl();
18480
+ const title = await browser.getTitle();
18481
+ const normalizedUrl = normalizeUrl(url, session.baseUrl);
18482
+ let page = session.pages.get(normalizedUrl);
18483
+ if (!page) {
18484
+ page = {
18485
+ url: normalizedUrl,
18486
+ path: new URL(normalizedUrl).pathname,
18487
+ title,
18488
+ slug: params.slug,
18489
+ stableId: `page:${params.slug}`,
18490
+ depth: new URL(normalizedUrl).pathname.split("/").filter(Boolean).length,
18491
+ screenshot: `screenshots/${params.slug}/default.png`,
18492
+ elements: [],
18493
+ outgoingLinks: [],
18494
+ status: "visited",
18495
+ visitedAt: new Date().toISOString()
18496
+ };
14917
18497
  }
14918
- return scan;
18498
+ page.analysis = params.analysis;
18499
+ page.status = "visited";
18500
+ page.visitedAt = new Date().toISOString();
18501
+ addPage(session, page);
18502
+ const relatedPages = Array.from(session.pages.values()).filter((p) => p.status === "visited").map((p) => ({ slug: p.slug, name: p.analysis?.pageName ?? p.title, path: p.path }));
18503
+ const pageAnnotations = session.annotations.filter((a) => a.pageSlug === params.slug).map((a) => ({ text: a.text, timestamp: a.timestamp }));
18504
+ const markdown = generateSectionMarkdown(page, relatedPages, pageAnnotations);
18505
+ writeFile(join5(session.outputDir, "sections", `${params.slug}.md`), markdown);
18506
+ logAction(session, `record_page: ${params.slug}`, `components: ${params.analysis.sections?.length ?? 0}`);
18507
+ syncAction(`record_page: ${params.slug}`, `components: ${params.analysis.sections?.length ?? 0}`);
18508
+ return { success: true, page_url: normalizedUrl, slug: params.slug };
18509
+ }
18510
+ async function handleCopilotGetSession(params) {
18511
+ const session = getSession(params.session_id);
18512
+ if (!session)
18513
+ throw new Error(`Session not found: ${params.session_id}`);
18514
+ return serializeSession(session);
18515
+ }
18516
+ async function handleCopilotCheckInput(params) {
18517
+ const session = getSession(params.session_id);
18518
+ if (!session)
18519
+ throw new Error(`Session not found: ${params.session_id}`);
18520
+ const companionInputs = getCompanionVoiceQueue();
18521
+ for (const input of companionInputs) {
18522
+ enqueueVoiceInput(session, input);
18523
+ }
18524
+ const { commands, comments } = drainVoiceQueue(session);
18525
+ const companionProposal = getCompanionProposalResult();
18526
+ let proposalResult = null;
18527
+ if (companionProposal && companionProposal.status !== "pending") {
18528
+ proposalResult = {
18529
+ id: companionProposal.id,
18530
+ action: companionProposal.action,
18531
+ approved: companionProposal.status === "approved",
18532
+ feedback: companionProposal.feedback
18533
+ };
18534
+ resolveProposal(session, companionProposal.status === "approved", companionProposal.feedback);
18535
+ }
18536
+ return {
18537
+ commands: commands.map((c) => ({ text: c.text, timestamp: c.timestamp })),
18538
+ comments: comments.map((c) => ({ text: c.text, timestamp: c.timestamp, pageSlug: c.pageSlug })),
18539
+ proposal_result: proposalResult,
18540
+ mode: session.mode
18541
+ };
18542
+ }
18543
+ async function handleCopilotProposeAction(params) {
18544
+ const session = getSession(params.session_id);
18545
+ if (!session)
18546
+ throw new Error(`Session not found: ${params.session_id}`);
18547
+ const proposal = setProposal(session, params.action, params.reason);
18548
+ setCompanionProposal(proposal);
18549
+ return {
18550
+ proposal_id: proposal.id,
18551
+ action: params.action,
18552
+ reason: params.reason,
18553
+ status: "pending",
18554
+ message: "Proposal sent to companion UI. Call copilot_check_input to get the result."
18555
+ };
18556
+ }
18557
+ async function handleCopilotTrack(params) {
18558
+ const session = getSession(params.session_id);
18559
+ if (!session)
18560
+ throw new Error(`Session not found: ${params.session_id}`);
18561
+ logAction(session, params.action, params.result);
18562
+ syncAction(params.action, params.result);
18563
+ if (params.url) {
18564
+ updateCurrentPage(params.url, params.title ?? params.url);
18565
+ }
18566
+ return {
18567
+ success: true,
18568
+ action: params.action,
18569
+ tracked_at: new Date().toISOString()
18570
+ };
14919
18571
  }
14920
18572
 
14921
18573
  // src/mcp.ts
@@ -14933,6 +18585,7 @@ It produces markdown documentation organized as a knowledge network, with an int
14933
18585
 
14934
18586
  1. **Explore.** \`zefiro_explore({ baseUrl: "http://localhost:3000" })\` — BFS exploration of the application
14935
18587
  2. **Read.** \`zefiro_read_docs()\` — read the generated documentation (README or specific sections)
18588
+ 3. **Push.** \`zefiro_push({ apiKey: "..." })\` — push report to QA Intelligence (builds graph automatically)
14936
18589
 
14937
18590
  ## Output Structure
14938
18591
 
@@ -14948,9 +18601,43 @@ app-report/
14948
18601
 
14949
18602
  - \`zefiro_explore\` — explore a web application via BFS, generating documentation and screenshots
14950
18603
  - \`zefiro_read_docs\` — read generated documentation (README or specific section files)
18604
+ - \`zefiro_push\` — push exploration report to QA Intelligence (auto-builds graph with stable IDs)
14951
18605
  - \`zefiro_scan_codebase\` — scan project for test files, configs, and path aliases (static analysis helper)
18606
+
18607
+ ## Copilot — Interactive Browser Co-Pilot
18608
+
18609
+ Use these tools when the user asks to explore, map, or document a running web application interactively.
18610
+
18611
+ ### Workflow
18612
+ 1. \`zefiro_copilot_start({ baseUrl, mode })\` — Launch browser + session
18613
+ 2. Navigate + snapshot + analyze pages using browser tools
18614
+ 3. Record findings with \`zefiro_copilot_record_page\`
18615
+ 4. Check for human input periodically with \`zefiro_copilot_check_input\`
18616
+ 5. Generate report with \`zefiro_copilot_stop\`
18617
+
18618
+ ### Copilot Tools
18619
+ - \`zefiro_copilot_start\` — Start a copilot session (launches browser)
18620
+ - \`zefiro_copilot_stop\` — Stop session, generate report, close browser
18621
+ - \`zefiro_copilot_navigate\` — Navigate to a URL
18622
+ - \`zefiro_copilot_snapshot\` — Get accessibility tree of current page
18623
+ - \`zefiro_copilot_screenshot\` — Capture screenshot
18624
+ - \`zefiro_copilot_click\` — Click element by ref
18625
+ - \`zefiro_copilot_fill\` — Fill input field
18626
+ - \`zefiro_copilot_get_links\` — Get outgoing links from current page
18627
+ - \`zefiro_copilot_record_page\` — Save page analysis to session
18628
+ - \`zefiro_copilot_get_session\` — Get session state (explored pages, stats)
18629
+ - \`zefiro_copilot_check_input\` — Read pending human input (voice/text)
18630
+ - \`zefiro_copilot_propose_action\` — ASSIST mode: propose action for approval
18631
+ - \`zefiro_copilot_track\` — Chrome Bridge: sync an external browser action to the session log
18632
+
18633
+ ### Chrome Bridge Mode
18634
+ Use \`browser: "chrome"\` with \`copilot_start\` to track actions from an external browser (e.g., Claude-in-Chrome).
18635
+ 1. \`zefiro_copilot_start({ baseUrl, mode: "assist", browser: "chrome" })\` — starts companion only
18636
+ 2. Open the \`companion_url\` in your browser
18637
+ 3. Use Claude-in-Chrome tools to browse; call \`zefiro_copilot_track\` after each action
18638
+ 4. \`zefiro_copilot_stop\` — generates report
14952
18639
  `.trim();
14953
- var server = new McpServer({ name: "zefiro", version: "0.7.4" }, { instructions: SERVER_INSTRUCTIONS });
18640
+ var server = new McpServer({ name: "zefiro", version: "0.10.0" }, { instructions: SERVER_INSTRUCTIONS });
14954
18641
  server.registerTool("zefiro_explore", {
14955
18642
  title: "Explore Application",
14956
18643
  description: "Explore a web application using browser automation (BFS). " + "Visits pages, takes screenshots, and generates markdown documentation. " + "Requires agent-browser to be installed globally.",
@@ -14962,12 +18649,12 @@ server.registerTool("zefiro_explore", {
14962
18649
  })
14963
18650
  }, async ({ baseUrl, maxPages, outputDir, headed }) => {
14964
18651
  try {
14965
- const { runExploration } = await import("./explorer-2fpgcxsx.js");
14966
- const { generateReadme, generateIndexHtml } = await import("./report-ne2r2e59.js");
14967
- const { writeFile, ensureDir } = await import("./fs-9dhtxzmg.js");
18652
+ const { runExploration } = await import("./explorer-ckk9bkff.js");
18653
+ const { generateReadme: generateReadme2, generateIndexHtml: generateIndexHtml2 } = await import("./report-wh0mnnxb.js");
18654
+ const { writeFile: writeFile2, ensureDir: ensureDir2 } = await import("./fs-9dhtxzmg.js");
14968
18655
  const cwd = process.cwd();
14969
- const outDir = outputDir ? join2(cwd, outputDir) : join2(cwd, "app-report");
14970
- ensureDir(outDir);
18656
+ const outDir = outputDir ? join6(cwd, outputDir) : join6(cwd, "app-report");
18657
+ ensureDir2(outDir);
14971
18658
  const config = {
14972
18659
  baseUrl,
14973
18660
  outputDir: outDir,
@@ -14980,13 +18667,15 @@ server.registerTool("zefiro_explore", {
14980
18667
  auth: { method: "manual" },
14981
18668
  sessionName: "zefiro"
14982
18669
  };
14983
- const state = await runExploration(config);
14984
- const readme = generateReadme(state);
14985
- writeFile(join2(outDir, "README.md"), readme);
14986
- const html = generateIndexHtml(state);
14987
- writeFile(join2(outDir, "index.html"), html);
14988
- const visited = Array.from(state.pages.values()).filter((p) => p.status === "visited");
14989
- const errors = Array.from(state.pages.values()).filter((p) => p.status === "error");
18670
+ const state2 = await runExploration(config);
18671
+ const serializableState = { ...state2, pages: Object.fromEntries(state2.pages) };
18672
+ writeFile2(join6(outDir, ".exploration-state.json"), JSON.stringify(serializableState, null, 2));
18673
+ const readme = generateReadme2(state2);
18674
+ writeFile2(join6(outDir, "README.md"), readme);
18675
+ const html = generateIndexHtml2(state2);
18676
+ writeFile2(join6(outDir, "index.html"), html);
18677
+ const visited = Array.from(state2.pages.values()).filter((p) => p.status === "visited");
18678
+ const errors = Array.from(state2.pages.values()).filter((p) => p.status === "error");
14990
18679
  return {
14991
18680
  content: [{
14992
18681
  type: "text",
@@ -15018,13 +18707,13 @@ server.registerTool("zefiro_read_docs", {
15018
18707
  }, async ({ section, outputDir }) => {
15019
18708
  try {
15020
18709
  const cwd = process.cwd();
15021
- const outDir = outputDir ? join2(cwd, outputDir) : join2(cwd, "app-report");
18710
+ const outDir = outputDir ? join6(cwd, outputDir) : join6(cwd, "app-report");
15022
18711
  if (section) {
15023
- const sectionPath = join2(outDir, "sections", `${section}.md`);
15024
- if (!existsSync2(sectionPath)) {
15025
- const sectionsDir = join2(outDir, "sections");
18712
+ const sectionPath = join6(outDir, "sections", `${section}.md`);
18713
+ if (!existsSync5(sectionPath)) {
18714
+ const sectionsDir = join6(outDir, "sections");
15026
18715
  let available = [];
15027
- if (existsSync2(sectionsDir)) {
18716
+ if (existsSync5(sectionsDir)) {
15028
18717
  available = readdirSync2(sectionsDir).filter((f) => f.endsWith(".md")).map((f) => f.replace(".md", ""));
15029
18718
  }
15030
18719
  return {
@@ -15035,10 +18724,10 @@ server.registerTool("zefiro_read_docs", {
15035
18724
  isError: true
15036
18725
  };
15037
18726
  }
15038
- return { content: [{ type: "text", text: readFileSync2(sectionPath, "utf-8") }] };
18727
+ return { content: [{ type: "text", text: readFileSync3(sectionPath, "utf-8") }] };
15039
18728
  }
15040
- const readmePath = join2(outDir, "README.md");
15041
- if (!existsSync2(readmePath)) {
18729
+ const readmePath = join6(outDir, "README.md");
18730
+ if (!existsSync5(readmePath)) {
15042
18731
  return {
15043
18732
  content: [{
15044
18733
  type: "text",
@@ -15047,7 +18736,7 @@ server.registerTool("zefiro_read_docs", {
15047
18736
  isError: true
15048
18737
  };
15049
18738
  }
15050
- return { content: [{ type: "text", text: readFileSync2(readmePath, "utf-8") }] };
18739
+ return { content: [{ type: "text", text: readFileSync3(readmePath, "utf-8") }] };
15051
18740
  } catch (err) {
15052
18741
  return { content: [{ type: "text", text: `Error reading docs: ${err.message}` }], isError: true };
15053
18742
  }
@@ -15067,6 +18756,322 @@ server.registerTool("zefiro_scan_codebase", {
15067
18756
  return { content: [{ type: "text", text: `Error scanning codebase: ${err.message}` }], isError: true };
15068
18757
  }
15069
18758
  });
18759
+ server.registerTool("zefiro_push", {
18760
+ title: "Push Report",
18761
+ description: "Push the exploration report to QA Intelligence. " + "Builds a graph from the exploration state, encodes screenshots, and pushes to the API. " + "Requires a prior zefiro_explore run and an API key.",
18762
+ inputSchema: exports_external.object({
18763
+ apiKey: exports_external.string().describe("App API key for QA Intelligence"),
18764
+ apiUrl: exports_external.string().optional().describe("API base URL (default: https://qaligent.space)"),
18765
+ outputDir: exports_external.string().optional().describe("Exploration output directory (default: app-report)"),
18766
+ commitSha: exports_external.string().optional().describe("Git commit SHA to associate")
18767
+ })
18768
+ }, async ({ apiKey, apiUrl, outputDir, commitSha }) => {
18769
+ try {
18770
+ const { buildReportGraph, buildReportSections } = await import("./graph-builder-ca71yjkc.js");
18771
+ const cwd = process.cwd();
18772
+ const outDir = outputDir ? join6(cwd, outputDir) : join6(cwd, "app-report");
18773
+ const url = apiUrl ?? "https://qaligent.space";
18774
+ const statePath = join6(outDir, ".exploration-state.json");
18775
+ if (!existsSync5(statePath)) {
18776
+ return {
18777
+ content: [{ type: "text", text: "No exploration state found. Run zefiro_explore first." }],
18778
+ isError: true
18779
+ };
18780
+ }
18781
+ const raw = JSON.parse(readFileSync3(statePath, "utf-8"));
18782
+ const pages = new Map(Object.entries(raw.pages));
18783
+ const state2 = { ...raw, pages };
18784
+ const visitedPages = Array.from(pages.values()).filter((p) => p.status === "visited");
18785
+ const graph = buildReportGraph(state2);
18786
+ const sectionsDir = join6(outDir, "sections");
18787
+ const markdowns = new Map;
18788
+ if (existsSync5(sectionsDir)) {
18789
+ for (const file of readdirSync2(sectionsDir)) {
18790
+ if (file.endsWith(".md")) {
18791
+ markdowns.set(file.replace(/\.md$/, ""), readFileSync3(join6(sectionsDir, file), "utf-8"));
18792
+ }
18793
+ }
18794
+ }
18795
+ const sections = buildReportSections(visitedPages, markdowns);
18796
+ const screenshotsDir = join6(outDir, "screenshots");
18797
+ const screenshots = [];
18798
+ if (existsSync5(screenshotsDir)) {
18799
+ for (const slugDir of readdirSync2(screenshotsDir)) {
18800
+ const fullDir = join6(screenshotsDir, slugDir);
18801
+ try {
18802
+ const files = readdirSync2(fullDir);
18803
+ for (let i = 0;i < files.length; i++) {
18804
+ const file = files[i];
18805
+ if (!file.endsWith(".png") && !file.endsWith(".jpg"))
18806
+ continue;
18807
+ screenshots.push({
18808
+ sectionSlug: slugDir,
18809
+ filename: file,
18810
+ label: file.replace(/^\d+-/, "").replace(/\.\w+$/, ""),
18811
+ sortOrder: i,
18812
+ data: readFileSync3(join6(fullDir, file)).toString("base64")
18813
+ });
18814
+ }
18815
+ } catch {}
18816
+ }
18817
+ }
18818
+ const readmePath = join6(outDir, "README.md");
18819
+ const readme = existsSync5(readmePath) ? readFileSync3(readmePath, "utf-8") : `# Application Map
18820
+
18821
+ ${visitedPages.length} pages explored.`;
18822
+ const payload = {
18823
+ title: `Zefiro Scan — ${new Date().toISOString().split("T")[0]}`,
18824
+ readme,
18825
+ sections,
18826
+ graph,
18827
+ screenshots,
18828
+ commitSha: commitSha || undefined
18829
+ };
18830
+ const res = await fetch(`${url}/api/v2/push-report`, {
18831
+ method: "POST",
18832
+ headers: {
18833
+ "Content-Type": "application/json",
18834
+ Authorization: `Bearer ${apiKey}`
18835
+ },
18836
+ body: JSON.stringify(payload)
18837
+ });
18838
+ if (!res.ok) {
18839
+ const body = await res.text();
18840
+ return { content: [{ type: "text", text: `Push failed (${res.status}): ${body}` }], isError: true };
18841
+ }
18842
+ const result = await res.json();
18843
+ return {
18844
+ content: [{
18845
+ type: "text",
18846
+ text: JSON.stringify(result, null, 2)
18847
+ }]
18848
+ };
18849
+ } catch (err) {
18850
+ return { content: [{ type: "text", text: `Error pushing report: ${err.message}` }], isError: true };
18851
+ }
18852
+ });
18853
+ server.registerTool("zefiro_copilot_start", {
18854
+ title: "Start Copilot Session",
18855
+ description: "Start an interactive copilot session. Launches a browser and creates a session. " + "Returns a session_id to use with all other copilot tools.",
18856
+ inputSchema: exports_external.object({
18857
+ baseUrl: exports_external.string().describe("Base URL of the application (e.g., http://localhost:3000)"),
18858
+ mode: exports_external.enum(["auto", "assist", "manual"]).optional().describe("Copilot mode: auto (AI drives), assist (AI proposes, human approves), manual (human drives)"),
18859
+ browser: exports_external.enum(["playwright", "chrome"]).optional().describe('Browser engine: "playwright" (default, launches new browser) or "chrome" (companion-only, use with Claude-in-Chrome)'),
18860
+ headed: exports_external.boolean().optional().describe("Show browser window (default: true)"),
18861
+ authState: exports_external.string().optional().describe("Path to Playwright auth state JSON file"),
18862
+ outputDir: exports_external.string().optional().describe("Output directory for report (default: copilot-report)")
18863
+ })
18864
+ }, async (params) => {
18865
+ try {
18866
+ const result = await handleCopilotStart(params);
18867
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18868
+ } catch (err) {
18869
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18870
+ }
18871
+ });
18872
+ server.registerTool("zefiro_copilot_stop", {
18873
+ title: "Stop Copilot Session",
18874
+ description: "Stop a copilot session, generate the final report, and close the browser.",
18875
+ inputSchema: exports_external.object({
18876
+ session_id: exports_external.string().describe("Session ID returned by copilot_start")
18877
+ })
18878
+ }, async (params) => {
18879
+ try {
18880
+ const result = await handleCopilotStop(params);
18881
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18882
+ } catch (err) {
18883
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18884
+ }
18885
+ });
18886
+ server.registerTool("zefiro_copilot_navigate", {
18887
+ title: "Navigate to URL",
18888
+ description: "Navigate the copilot browser to a specific URL.",
18889
+ inputSchema: exports_external.object({
18890
+ session_id: exports_external.string().describe("Session ID"),
18891
+ url: exports_external.string().describe("URL to navigate to")
18892
+ })
18893
+ }, async (params) => {
18894
+ try {
18895
+ const result = await handleCopilotNavigate(params);
18896
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18897
+ } catch (err) {
18898
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18899
+ }
18900
+ });
18901
+ server.registerTool("zefiro_copilot_snapshot", {
18902
+ title: "Get Accessibility Snapshot",
18903
+ description: "Get the accessibility tree of the current page. Returns element refs, roles, and labels.",
18904
+ inputSchema: exports_external.object({
18905
+ session_id: exports_external.string().describe("Session ID")
18906
+ })
18907
+ }, async (params) => {
18908
+ try {
18909
+ const result = await handleCopilotSnapshot(params);
18910
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18911
+ } catch (err) {
18912
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18913
+ }
18914
+ });
18915
+ server.registerTool("zefiro_copilot_screenshot", {
18916
+ title: "Capture Screenshot",
18917
+ description: "Capture a screenshot of the current page.",
18918
+ inputSchema: exports_external.object({
18919
+ session_id: exports_external.string().describe("Session ID"),
18920
+ label: exports_external.string().optional().describe('Label for the screenshot (default: "default")')
18921
+ })
18922
+ }, async (params) => {
18923
+ try {
18924
+ const result = await handleCopilotScreenshot(params);
18925
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18926
+ } catch (err) {
18927
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18928
+ }
18929
+ });
18930
+ server.registerTool("zefiro_copilot_click", {
18931
+ title: "Click Element",
18932
+ description: "Click an element by its accessibility ref (from snapshot).",
18933
+ inputSchema: exports_external.object({
18934
+ session_id: exports_external.string().describe("Session ID"),
18935
+ ref: exports_external.string().describe("Element ref from snapshot")
18936
+ })
18937
+ }, async (params) => {
18938
+ try {
18939
+ const result = await handleCopilotClick(params);
18940
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18941
+ } catch (err) {
18942
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18943
+ }
18944
+ });
18945
+ server.registerTool("zefiro_copilot_fill", {
18946
+ title: "Fill Input Field",
18947
+ description: "Fill a text input field by its accessibility ref.",
18948
+ inputSchema: exports_external.object({
18949
+ session_id: exports_external.string().describe("Session ID"),
18950
+ ref: exports_external.string().describe("Element ref from snapshot"),
18951
+ text: exports_external.string().describe("Text to fill into the input")
18952
+ })
18953
+ }, async (params) => {
18954
+ try {
18955
+ const result = await handleCopilotFill(params);
18956
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18957
+ } catch (err) {
18958
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18959
+ }
18960
+ });
18961
+ server.registerTool("zefiro_copilot_get_links", {
18962
+ title: "Get Page Links",
18963
+ description: "Get all outgoing links from the current page, with visited status.",
18964
+ inputSchema: exports_external.object({
18965
+ session_id: exports_external.string().describe("Session ID")
18966
+ })
18967
+ }, async (params) => {
18968
+ try {
18969
+ const result = await handleCopilotGetLinks(params);
18970
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
18971
+ } catch (err) {
18972
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
18973
+ }
18974
+ });
18975
+ server.registerTool("zefiro_copilot_record_page", {
18976
+ title: "Record Page Analysis",
18977
+ description: "Save a page analysis to the session. Call after analyzing a page via snapshot/screenshot.",
18978
+ inputSchema: exports_external.object({
18979
+ session_id: exports_external.string().describe("Session ID"),
18980
+ slug: exports_external.string().describe('URL slug for the page (e.g., "dashboard", "settings-general")'),
18981
+ analysis: exports_external.object({
18982
+ pageName: exports_external.string().describe("Human-readable page name"),
18983
+ description: exports_external.string().describe("Brief description of the page"),
18984
+ route: exports_external.string().describe("Route pattern (e.g., /dashboard, /settings/:tab)"),
18985
+ sections: exports_external.array(exports_external.object({
18986
+ name: exports_external.string(),
18987
+ type: exports_external.string(),
18988
+ elements: exports_external.array(exports_external.object({
18989
+ name: exports_external.string(),
18990
+ type: exports_external.string(),
18991
+ required: exports_external.boolean().optional(),
18992
+ default: exports_external.string().nullable().optional(),
18993
+ description: exports_external.string()
18994
+ })).optional().default([])
18995
+ })).default([]),
18996
+ actions: exports_external.array(exports_external.string()).default([]),
18997
+ navigation: exports_external.object({
18998
+ tabs: exports_external.array(exports_external.string()).optional().default([]),
18999
+ breadcrumbs: exports_external.array(exports_external.string()).optional().default([]),
19000
+ sidebarItems: exports_external.array(exports_external.string()).optional().default([])
19001
+ }).optional().default({ tabs: [], breadcrumbs: [], sidebarItems: [] }),
19002
+ observations: exports_external.array(exports_external.string()).default([])
19003
+ }).describe("Structured page analysis")
19004
+ })
19005
+ }, async (params) => {
19006
+ try {
19007
+ const result = await handleCopilotRecordPage(params);
19008
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
19009
+ } catch (err) {
19010
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
19011
+ }
19012
+ });
19013
+ server.registerTool("zefiro_copilot_get_session", {
19014
+ title: "Get Session State",
19015
+ description: "Get the current session state including explored pages, stats, and mode.",
19016
+ inputSchema: exports_external.object({
19017
+ session_id: exports_external.string().describe("Session ID")
19018
+ })
19019
+ }, async (params) => {
19020
+ try {
19021
+ const result = await handleCopilotGetSession(params);
19022
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
19023
+ } catch (err) {
19024
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
19025
+ }
19026
+ });
19027
+ server.registerTool("zefiro_copilot_check_input", {
19028
+ title: "Check Human Input",
19029
+ description: "Read pending human input (voice commands, text comments, proposal results). " + "Call periodically during exploration to check for user guidance.",
19030
+ inputSchema: exports_external.object({
19031
+ session_id: exports_external.string().describe("Session ID")
19032
+ })
19033
+ }, async (params) => {
19034
+ try {
19035
+ const result = await handleCopilotCheckInput(params);
19036
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
19037
+ } catch (err) {
19038
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
19039
+ }
19040
+ });
19041
+ server.registerTool("zefiro_copilot_propose_action", {
19042
+ title: "Propose Action (Assist Mode)",
19043
+ description: "In ASSIST mode, propose an action for human approval before executing. " + "Call copilot_check_input later to get the approval result.",
19044
+ inputSchema: exports_external.object({
19045
+ session_id: exports_external.string().describe("Session ID"),
19046
+ action: exports_external.string().describe("Description of the proposed action"),
19047
+ reason: exports_external.string().describe("Why this action is recommended")
19048
+ })
19049
+ }, async (params) => {
19050
+ try {
19051
+ const result = await handleCopilotProposeAction(params);
19052
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
19053
+ } catch (err) {
19054
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
19055
+ }
19056
+ });
19057
+ server.registerTool("zefiro_copilot_track", {
19058
+ title: "Track Chrome Action",
19059
+ description: "Track a browser action performed via external browser (e.g., Claude-in-Chrome). " + "Syncs the action to the companion UI and session log. Use after each chrome tool call.",
19060
+ inputSchema: exports_external.object({
19061
+ session_id: exports_external.string().describe("Session ID"),
19062
+ action: exports_external.string().describe('Description of the action (e.g., "navigate: https://example.com", "click: Submit button")'),
19063
+ url: exports_external.string().optional().describe("Current page URL after the action (updates companion page display)"),
19064
+ title: exports_external.string().optional().describe("Current page title"),
19065
+ result: exports_external.string().optional().describe("Action result or details")
19066
+ })
19067
+ }, async (params) => {
19068
+ try {
19069
+ const result = await handleCopilotTrack(params);
19070
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
19071
+ } catch (err) {
19072
+ return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
19073
+ }
19074
+ });
15070
19075
  async function main() {
15071
19076
  const transport = new StdioServerTransport;
15072
19077
  await server.connect(transport);