lynx-proxy 0.0.1 → 0.0.2

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/tui.mjs ADDED
@@ -0,0 +1,4415 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
3
+ import { Input, Key, ProcessTerminal, SelectList, TUI, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+ import pc from "picocolors";
5
+ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { dump, load } from "js-yaml";
8
+ import { homedir } from "node:os";
9
+ import axios from "axios";
10
+ import { execFile, spawn } from "node:child_process";
11
+ import { createConnection } from "node:net";
12
+ import { promisify } from "node:util";
13
+ //#region src/utils/format.ts
14
+ /**
15
+ * 从字节数生成人类可读的体积字符串。
16
+ * 覆盖 B / KB / MB / GB 四个量级,使用 1024 进制。
17
+ */
18
+ /**
19
+ * 解析 "host:port" 格式字符串,返回 host 与 port。
20
+ *
21
+ * 注意:不支持 IPv6 字面量(如 `[::1]:7890`),当前调用点均使用
22
+ * IPv4 地址(127.0.0.1 / 0.0.0.0 / 局域网 IP),暂不处理方括号。
23
+ */
24
+ function parseHostPort(input, defaultHost, defaultPort) {
25
+ const parts = input?.split(":") ?? [];
26
+ const rawHost = parts[0];
27
+ return {
28
+ host: rawHost !== void 0 && rawHost.length > 0 ? rawHost : defaultHost,
29
+ port: Number(parts[1]) || defaultPort
30
+ };
31
+ }
32
+ function formatBytes(bytes) {
33
+ if (bytes < 1024) return `${bytes} B`;
34
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
35
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
36
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
37
+ }
38
+ //#endregion
39
+ //#region src/tui/format.ts
40
+ /** 字节速率,如 "1.2 MB/s"。 */
41
+ function formatRate(bytesPerSecond) {
42
+ if (!Number.isFinite(bytesPerSecond) || bytesPerSecond <= 0) return "0 B/s";
43
+ return `${formatBytes(bytesPerSecond)}/s`;
44
+ }
45
+ /** 毫秒时长格式化为 "1d 2h" / "3h 04m" / "05:12" / "12s"。 */
46
+ function formatUptime(ms) {
47
+ if (ms < 0 || !Number.isFinite(ms)) return "-";
48
+ const totalSeconds = Math.floor(ms / 1e3);
49
+ const days = Math.floor(totalSeconds / 86400);
50
+ const hours = Math.floor(totalSeconds % 86400 / 3600);
51
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
52
+ const seconds = totalSeconds % 60;
53
+ if (days > 0) return `${days}d ${hours}h`;
54
+ if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
55
+ if (minutes > 0) return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
56
+ return `${seconds}s`;
57
+ }
58
+ /** 连接/运行时长,mm:ss 或 h:mm:ss。 */
59
+ function formatDuration(ms) {
60
+ if (ms < 0 || !Number.isFinite(ms)) return "-";
61
+ const totalSeconds = Math.floor(ms / 1e3);
62
+ const hours = Math.floor(totalSeconds / 3600);
63
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
64
+ const seconds = totalSeconds % 60;
65
+ const mm = String(minutes).padStart(2, "0");
66
+ const ss = String(seconds).padStart(2, "0");
67
+ return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;
68
+ }
69
+ /** 延迟毫秒数:0/失败显示超时,否则 "123ms"。 */
70
+ function formatDelay(ms) {
71
+ if (ms === void 0 || ms === 0) return " - ";
72
+ if (ms < 0) return "超时";
73
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(1)}s`;
74
+ return `${Math.round(ms)}ms`;
75
+ }
76
+ //#endregion
77
+ //#region src/tui/layout.ts
78
+ /**
79
+ * 纯布局函数。pi-tui 没有列布局引擎,根组件用这些函数手动拼装侧栏与内容。
80
+ * 所有返回行的可见宽度都精确等于目标宽度,避免 pi-tui 抛 "line exceeds width"。
81
+ */
82
+ /** 把一行截断并填充到精确宽度(ANSI 码不计宽)。 */
83
+ function fitLine(line, width) {
84
+ return truncateToWidth(line, width, "…", true);
85
+ }
86
+ /** 把数组补齐/截断到指定行数。 */
87
+ function fitRows(lines, height) {
88
+ if (lines.length >= height) return lines.slice(0, height);
89
+ return [...lines, ...Array.from({ length: height - lines.length }, () => "")];
90
+ }
91
+ /**
92
+ * 左右双列布局:左列固定宽度 + 分隔符 + 右列占满剩余宽度,逐行 zip,
93
+ * 短列补空行,每行 pad 到精确 width。
94
+ */
95
+ function sideBySide(options) {
96
+ const { left, right, leftWidth, width, height } = options;
97
+ const separator = options.separator ?? "│";
98
+ const rightWidth = width - leftWidth - separator.length;
99
+ if (rightWidth < 1) return fitRows(left, height).map((line) => fitLine(line, width));
100
+ const leftRows = fitRows(left, height);
101
+ const rightRows = fitRows(right, height);
102
+ const result = [];
103
+ for (let i = 0; i < height; i += 1) {
104
+ const composed = `${truncateToWidth(leftRows[i] ?? "", leftWidth, "…", true)}${separator}${truncateToWidth(rightRows[i] ?? "", rightWidth, "…", true)}`;
105
+ result.push(fitLine(composed, width));
106
+ }
107
+ return result;
108
+ }
109
+ /** 居中放置文本块(左右补空格到目标宽度)。 */
110
+ function centerLine(line, width) {
111
+ const w = visibleWidth(line);
112
+ if (w >= width) return fitLine(line, width);
113
+ const left = Math.floor((width - w) / 2);
114
+ const right = width - w - left;
115
+ return `${" ".repeat(left)}${line}${" ".repeat(right)}`;
116
+ }
117
+ /** 把内容左侧填充到精确可见宽度(ANSI/CJK 安全)。 */
118
+ function padEndVisible(text, width) {
119
+ const pad = width - visibleWidth(text);
120
+ return pad <= 0 ? text : text + " ".repeat(pad);
121
+ }
122
+ /**
123
+ * 带标题的框线卡片(纯 ASCII 边框)。width 为含边框的总宽度。
124
+ * 标题形如 "┌─ 标题 ────┐",内容行 "│ 文本… │",底框 "└────┘"。
125
+ * CJK/ANSI 安全:内部按 visibleWidth 截断与填充。
126
+ */
127
+ function card(title, lines, width) {
128
+ const inner = Math.max(1, width - 2);
129
+ const titleText = ` ${title} `;
130
+ const titlePad = Math.max(0, inner - 1 - visibleWidth(titleText));
131
+ const out = [truncateToWidth(`┌─${titleText}${"─".repeat(titlePad)}┐`, width, "…", true)];
132
+ for (const line of lines) out.push(`│${padEndVisible(truncateToWidth(line, inner, "…", false), inner)}│`);
133
+ out.push(`└${"─".repeat(inner)}┘`);
134
+ return out;
135
+ }
136
+ //#endregion
137
+ //#region src/tui/runtime/types.ts
138
+ const PANELS = [
139
+ {
140
+ id: "overview",
141
+ label: "概览",
142
+ hotkey: "1"
143
+ },
144
+ {
145
+ id: "proxies",
146
+ label: "代理",
147
+ hotkey: "2"
148
+ },
149
+ {
150
+ id: "connections",
151
+ label: "连接",
152
+ hotkey: "3"
153
+ },
154
+ {
155
+ id: "logs",
156
+ label: "日志",
157
+ hotkey: "4"
158
+ },
159
+ {
160
+ id: "settings",
161
+ label: "设置",
162
+ hotkey: "5"
163
+ }
164
+ ];
165
+ /** 日志级别显示顺序(数字越大越严重,用于阈值过滤)。 */
166
+ const LOG_LEVEL_ORDER = {
167
+ debug: 0,
168
+ info: 1,
169
+ warning: 2,
170
+ error: 3
171
+ };
172
+ /** 把 mihomo ConnectionEntry 投影为连接视图(累计字节,速率由 reducer 差分)。 */
173
+ function toConnectionView(entry) {
174
+ const metadata = entry.metadata;
175
+ const hostRaw = metadata.host ?? metadata.destinationIP ?? "(unknown)";
176
+ const port = metadata.destinationPort;
177
+ const hostWithPort = port !== void 0 && port !== "" && port !== "443" && port !== "80" ? `${hostRaw}:${port}` : hostRaw;
178
+ const rule = entry.rulePayload !== void 0 && entry.rulePayload.length > 0 ? `${entry.rule}:${entry.rulePayload}` : entry.rule;
179
+ return {
180
+ id: entry.id,
181
+ host: hostWithPort,
182
+ hostRaw,
183
+ network: metadata.network ?? "",
184
+ type: metadata.type ?? "",
185
+ rule,
186
+ chain: entry.chains[0] ?? "",
187
+ chainsFull: entry.chains.slice(),
188
+ up: entry.upload,
189
+ down: entry.download,
190
+ upRate: 0,
191
+ downRate: 0,
192
+ startedAt: Date.parse(entry.start),
193
+ sourceIP: metadata.sourceIP ?? "",
194
+ sourcePort: metadata.sourcePort ?? "",
195
+ destinationIP: metadata.destinationIP ?? "",
196
+ destinationPort: metadata.destinationPort ?? "",
197
+ processPath: metadata.processPath ?? "",
198
+ dnsMode: metadata.dnsMode ?? ""
199
+ };
200
+ }
201
+ //#endregion
202
+ //#region src/tui/theme.ts
203
+ const theme = {
204
+ title: (s) => pc.bold(s),
205
+ dim: (s) => pc.dim(s),
206
+ accent: (s) => pc.cyan(s),
207
+ accentBold: (s) => pc.bold(pc.cyan(s)),
208
+ success: (s) => pc.green(s),
209
+ warn: (s) => pc.yellow(s),
210
+ error: (s) => pc.red(s),
211
+ info: (s) => pc.blue(s),
212
+ selected: (s) => pc.inverse(s),
213
+ sidebarActive: (s) => pc.cyan(`▸ ${s}`),
214
+ sidebarIdle: (s) => ` ${s}`,
215
+ barBg: (s) => pc.bgCyan(pc.black(s)),
216
+ tableHeader: (s) => pc.bold(pc.dim(s)),
217
+ flash: (s) => pc.black(pc.bgYellow(s))
218
+ };
219
+ function statusColor(status) {
220
+ switch (status) {
221
+ case "running": return pc.green;
222
+ case "starting": return pc.yellow;
223
+ case "reconnecting": return pc.yellow;
224
+ case "stopped": return pc.red;
225
+ }
226
+ }
227
+ const statusDot = {
228
+ running: pc.green("●"),
229
+ starting: pc.yellow("●"),
230
+ reconnecting: pc.yellow("●"),
231
+ stopped: pc.red("●")
232
+ };
233
+ /** SelectList 主题(节点/组/模态共用)。 */
234
+ const selectListTheme = {
235
+ selectedPrefix: (text) => pc.cyan(text),
236
+ selectedText: (text) => pc.bold(pc.cyan(text)),
237
+ description: (text) => pc.dim(text),
238
+ scrollInfo: (text) => pc.dim(text),
239
+ noMatch: (text) => pc.dim(text)
240
+ };
241
+ //#endregion
242
+ //#region src/tui/widgets/sparkline.ts
243
+ const BARS = "▁▂▃▄▅▆▇█";
244
+ /**
245
+ * 把一组数值采样渲染为单行柱状图(sparkline)。
246
+ *
247
+ * @param samples 数值采样(按时间顺序,最旧在前)。
248
+ * @param width 输出列数;采样多于 width 时只保留最近 width 个。
249
+ * @param color 着色函数(默认绿色)。
250
+ * @param floor 显示下限,全零/极小时把柱高抬到 1,避免一条平线看不出在动。
251
+ */
252
+ function renderSparkline(samples, width, color = pc.green, floor = 1) {
253
+ if (width <= 0) return "";
254
+ const window = samples.length > width ? samples.slice(samples.length - width) : [...samples];
255
+ while (window.length < width) window.unshift(0);
256
+ const max = Math.max(floor, ...window);
257
+ let out = "";
258
+ for (const value of window) {
259
+ if (value <= 0) {
260
+ out += " ";
261
+ continue;
262
+ }
263
+ const ratio = Math.min(1, value / max);
264
+ const index = Math.max(0, Math.min(7, Math.round(ratio * 7)));
265
+ out += BARS[index] ?? " ";
266
+ }
267
+ return color(out);
268
+ }
269
+ //#endregion
270
+ //#region src/tui/widgets/modal.ts
271
+ /**
272
+ * 用 Overlay + SelectList 弹一个模态选择框,返回用户选中项;
273
+ * Esc/Cancel 返回 undefined。
274
+ */
275
+ function selectFromList(tui, items, options = {}) {
276
+ return new Promise((resolve) => {
277
+ const width = options.width ?? 40;
278
+ const maxHeight = options.maxHeight ?? Math.min(20, items.length + 2);
279
+ const list = new SelectList(items, maxHeight, selectListTheme);
280
+ let settled = false;
281
+ const finish = (value) => {
282
+ if (settled) return;
283
+ settled = true;
284
+ handle.hide();
285
+ resolve(value);
286
+ };
287
+ list.onSelect = (item) => finish(item);
288
+ list.onCancel = () => finish(void 0);
289
+ const handle = tui.showOverlay(list, {
290
+ width,
291
+ maxHeight,
292
+ anchor: "center"
293
+ });
294
+ handle.focus();
295
+ });
296
+ }
297
+ //#endregion
298
+ //#region src/tui/panels/overview-panel.ts
299
+ const MODES$2 = [
300
+ "rule",
301
+ "global",
302
+ "direct",
303
+ "script"
304
+ ];
305
+ var OverviewPanel = class {
306
+ runtime;
307
+ tui;
308
+ constructor(runtime, tui) {
309
+ this.runtime = runtime;
310
+ this.tui = tui;
311
+ }
312
+ hints() {
313
+ return [
314
+ "[Enter] 切换",
315
+ "[↑/↓] 选择",
316
+ "[R] 刷新"
317
+ ];
318
+ }
319
+ handleInput(data) {
320
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.space)) {
321
+ this.activateRow(this.cursor);
322
+ return;
323
+ }
324
+ if (matchesKey(data, Key.up) || data === "k") {
325
+ this.cursor = Math.max(0, this.cursor - 1);
326
+ this.runtime.scheduleRender();
327
+ return;
328
+ }
329
+ if (matchesKey(data, Key.down) || data === "j") {
330
+ this.cursor = Math.min(1, this.cursor + 1);
331
+ this.runtime.scheduleRender();
332
+ return;
333
+ }
334
+ if (data === "r") {
335
+ this.runtime.refreshOverview?.();
336
+ this.runtime.flash("正在刷新…");
337
+ }
338
+ }
339
+ cursor = 0;
340
+ async activateRow(row) {
341
+ if (row === 0) {
342
+ const item = await selectFromList(this.tui, MODES$2.map((m) => ({
343
+ value: m,
344
+ label: m
345
+ })), {
346
+ width: 24,
347
+ maxHeight: 6
348
+ });
349
+ if (item !== void 0) await this.runtime.setMode(item.value);
350
+ } else if (row === 1) await this.runtime.toggleSystemProxy();
351
+ }
352
+ render(width) {
353
+ const state = this.runtime.state;
354
+ const ov = state.overview;
355
+ const ds = state.daemonState;
356
+ const online = this.runtime.apiClient !== void 0;
357
+ const out = [];
358
+ const gap = 2;
359
+ const cardWidth = Math.max(20, Math.floor((width - gap) / 2));
360
+ const sparkWidth = Math.max(8, cardWidth - 20);
361
+ const statusDot = online ? pc.green("●") : pc.red("●");
362
+ const statusText = online ? "运行中" : "未运行";
363
+ const uptime = online && ds?.startedAt !== void 0 ? formatUptime(Date.now() - Date.parse(ds.startedAt)) : "—";
364
+ const kernelVer = online ? ov.version !== void 0 ? ov.version.version : ov.kernelVersion ?? "加载中…" : ov.kernelVersion ?? "—";
365
+ const kernelLine = `${ov.kernelChannel} ${kernelVer}`;
366
+ const listen = online && ds !== void 0 ? `${ds.host}:${ds.port}` : "—";
367
+ const pid = online && ds !== void 0 ? String(ds.pid) : "—";
368
+ const statusLines = [
369
+ `${statusDot} ${statusText}`,
370
+ `运行时长 ${uptime}`,
371
+ `Profile ${ov.profileName ?? "—"}`,
372
+ `内核 ${kernelLine}`,
373
+ `监听 ${listen}`,
374
+ `PID ${pid}`,
375
+ ""
376
+ ];
377
+ const upTxt = online ? formatRate(state.upRate) : "—";
378
+ const downTxt = online ? formatRate(state.downRate) : "—";
379
+ const upTotal = online ? formatBytes(ov.uploadTotal) : "—";
380
+ const downTotal = online ? formatBytes(ov.downloadTotal) : "—";
381
+ const mem = online && ov.memory !== void 0 ? `${formatBytes(ov.memory.inuse)} / ${formatBytes(ov.memory.oslimit)}` : "—";
382
+ const trafficLines = [
383
+ `${pc.green("↑")} ${upTxt.padEnd(10)} ${renderSparkline(state.traffic.up, sparkWidth, pc.green)}`,
384
+ ` 总计 ${upTotal}`,
385
+ "",
386
+ `${pc.cyan("↓")} ${downTxt.padEnd(10)} ${renderSparkline(state.traffic.down, sparkWidth, pc.cyan)}`,
387
+ ` 总计 ${downTotal}`,
388
+ "",
389
+ `${pc.dim("活跃连接")} ${online ? state.connections.rows.length : "—"} ${pc.dim("内存")} ${mem}`
390
+ ];
391
+ const left = card("状态", statusLines, cardWidth);
392
+ const right = card("流量", trafficLines, cardWidth);
393
+ const rows = Math.max(left.length, right.length);
394
+ for (let i = 0; i < rows; i += 1) {
395
+ const l = left[i] ?? "";
396
+ const r = right[i] ?? "";
397
+ const pad = cardWidth - visibleWidth(l) + gap;
398
+ out.push(l + " ".repeat(Math.max(1, pad)) + r);
399
+ }
400
+ out.push("");
401
+ out.push(pc.bold(pc.cyan("快速操作")));
402
+ const modeRow = ` 路由模式 ${ov.mode ?? "—"}`;
403
+ const proxyRow = ` 系统代理 ${ov.systemProxy}`;
404
+ const modeLine = this.cursor === 0 ? pc.inverse(fitLine(modeRow, width)) : modeRow;
405
+ const proxyLine = this.cursor === 1 ? pc.inverse(fitLine(proxyRow, width)) : proxyRow;
406
+ out.push(modeLine);
407
+ out.push(proxyLine);
408
+ if (ov.systemProxy === "not-supported") out.push(pc.dim(" (当前平台不支持系统代理接管)"));
409
+ return out.map((line) => fitLine(line, width));
410
+ }
411
+ invalidate() {}
412
+ };
413
+ //#endregion
414
+ //#region src/tui/widgets/offline-state.ts
415
+ function headline(opts) {
416
+ if (opts.status === "starting") return pc.yellow("● daemon 启动中…");
417
+ if (opts.secretMissing) return pc.yellow("● 凭据缺失");
418
+ if (opts.status === "reconnecting") return pc.yellow("● 重连中…");
419
+ return pc.red("● daemon 未运行");
420
+ }
421
+ function sublines(opts) {
422
+ if (opts.status === "starting") return ["正在等待 mihomo 就绪,请稍候"];
423
+ if (opts.secretMissing) return ["当前 daemon 为旧版本,缺少外部控制器凭据。", "按 S 重启 daemon 以启用控制台"];
424
+ if (opts.status === "reconnecting") return ["mihomo API 暂时不可达,正在重连…"];
425
+ return ["按 S 启动 daemon", "或在另一终端执行: lynx proxy start"];
426
+ }
427
+ /**
428
+ * 渲染一块居中的离线占位,占满 height 行、每行 fit 到 width。
429
+ * 含状态标题、说明文字、内联 [S] 启动按钮、可选错误。
430
+ */
431
+ function renderOfflineHint(width, height, opts) {
432
+ const inner = Math.min(width - 4, 56);
433
+ const blank = " ".repeat(inner);
434
+ const center = (text) => centerLine(text, inner);
435
+ const lines = [];
436
+ const topPad = Math.max(1, Math.floor((height - 8) / 2));
437
+ for (let i = 0; i < topPad; i += 1) lines.push(blank);
438
+ lines.push(center(headline(opts)));
439
+ lines.push(blank);
440
+ for (const sub of sublines(opts)) lines.push(center(pc.dim(sub)));
441
+ lines.push(blank);
442
+ if (opts.status !== "starting") lines.push(center(pc.inverse(" [S] 启动 daemon ")));
443
+ if (opts.error !== void 0 && opts.error.length > 0) {
444
+ lines.push(blank);
445
+ lines.push(center(pc.red(opts.error)));
446
+ }
447
+ while (lines.length < height) lines.push(blank);
448
+ return lines.slice(0, height).map((line) => fitLine(line, width));
449
+ }
450
+ //#endregion
451
+ //#region src/tui/panels/proxies-panel.ts
452
+ const BUILTIN_NODES = /* @__PURE__ */ new Set([
453
+ "DIRECT",
454
+ "REJECT",
455
+ "PASS",
456
+ "COMPATIBLE"
457
+ ]);
458
+ var ProxiesPanel = class {
459
+ runtime;
460
+ groupList;
461
+ nodeList;
462
+ focus = "groups";
463
+ height = 20;
464
+ groupKey = "";
465
+ nodeKey = "";
466
+ filtering = false;
467
+ filterText = "";
468
+ constructor(runtime) {
469
+ this.runtime = runtime;
470
+ this.groupList = new SelectList([], 10, selectListTheme);
471
+ this.nodeList = new SelectList([], 10, selectListTheme);
472
+ this.groupList.onSelectionChange = (item) => {
473
+ if (item.value.length > 0) this.runtime.selectGroup(item.value);
474
+ };
475
+ this.groupList.onSelect = () => {
476
+ this.setFocus("nodes");
477
+ };
478
+ this.nodeList.onSelect = (item) => {
479
+ const group = this.runtime.state.proxies.selectedGroup;
480
+ if (group.length > 0 && item.value.length > 0) this.runtime.selectProxy(group, item.value);
481
+ };
482
+ }
483
+ hints() {
484
+ return [
485
+ "[↑/↓] 移动",
486
+ "[Tab/←→] 切列",
487
+ "[Enter] 选择",
488
+ "[t] 测延迟",
489
+ "[/] 过滤"
490
+ ];
491
+ }
492
+ setFocus(focus) {
493
+ if (this.focus === focus) return;
494
+ this.focus = focus;
495
+ this.filtering = false;
496
+ this.filterText = "";
497
+ this.groupList.setFilter("");
498
+ this.nodeList.setFilter("");
499
+ this.runtime.scheduleRender();
500
+ }
501
+ activate() {
502
+ this.focus = "groups";
503
+ }
504
+ handleInput(data) {
505
+ if (this.filtering) {
506
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.escape)) {
507
+ this.filtering = false;
508
+ this.filterText = "";
509
+ this.activeList.setFilter("");
510
+ this.runtime.scheduleRender();
511
+ return;
512
+ }
513
+ if (matchesKey(data, Key.backspace)) this.filterText = this.filterText.slice(0, -1);
514
+ else if (data.length === 1 && data >= " ") this.filterText += data;
515
+ this.activeList.setFilter(this.filterText);
516
+ this.runtime.scheduleRender();
517
+ return;
518
+ }
519
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.right) || data === "l") {
520
+ this.setFocus("nodes");
521
+ return;
522
+ }
523
+ if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left) || data === "h") {
524
+ this.setFocus("groups");
525
+ return;
526
+ }
527
+ if (data === "t") {
528
+ if (this.runtime.apiClient === void 0) {
529
+ this.runtime.flash("需要运行中的 daemon 才能测速。");
530
+ return;
531
+ }
532
+ const group = this.runtime.state.proxies.selectedGroup;
533
+ if (group.length > 0) this.runtime.testGroupDelay(group);
534
+ return;
535
+ }
536
+ if (data === "/") {
537
+ this.filtering = true;
538
+ this.filterText = "";
539
+ this.activeList.setFilter("");
540
+ this.runtime.scheduleRender();
541
+ return;
542
+ }
543
+ (this.focus === "groups" ? this.groupList : this.nodeList).handleInput(data);
544
+ this.runtime.scheduleRender();
545
+ }
546
+ get activeList() {
547
+ return this.focus === "groups" ? this.groupList : this.nodeList;
548
+ }
549
+ buildGroupItems() {
550
+ const { groups } = this.runtime.state.proxies;
551
+ return groups.map((g) => ({
552
+ value: g.name,
553
+ label: g.name,
554
+ description: `[${g.type}] ${g.now}`
555
+ }));
556
+ }
557
+ nodeDelay(info, name) {
558
+ const override = this.runtime.state.proxies.delayOverrides[name];
559
+ if (override !== void 0) return override;
560
+ return (info?.history.at(-1))?.delay;
561
+ }
562
+ buildNodeItems() {
563
+ const { groups, proxies, selectedGroup } = this.runtime.state.proxies;
564
+ const group = groups.find((g) => g.name === selectedGroup);
565
+ if (group === void 0) return [];
566
+ const items = [];
567
+ for (const name of group.all) {
568
+ const info = proxies[name];
569
+ if (info !== void 0 && this.isGroupType(info.type)) continue;
570
+ const delayText = formatDelay(BUILTIN_NODES.has(name) ? void 0 : this.nodeDelay(info, name));
571
+ items.push({
572
+ value: name,
573
+ label: name,
574
+ description: delayText
575
+ });
576
+ }
577
+ return items;
578
+ }
579
+ isGroupType(type) {
580
+ return type === "Selector" || type === "URLTest" || type === "Fallback" || type === "LoadBalance" || type === "Relay";
581
+ }
582
+ render(width) {
583
+ const { groups } = this.runtime.state.proxies;
584
+ if (this.runtime.apiClient === void 0 && groups.length === 0) return renderOfflineHint(width, Math.max(1, this.height - 1), {
585
+ status: this.runtime.state.daemon,
586
+ secretMissing: this.runtime.state.secretMissing,
587
+ error: this.runtime.state.error
588
+ });
589
+ const { selectedGroup, testing } = this.runtime.state.proxies;
590
+ const groupItems = this.buildGroupItems();
591
+ const nextGroupKey = groupItems.map((i) => i.value).join("|") + "#" + selectedGroup;
592
+ if (nextGroupKey !== this.groupKey) {
593
+ this.groupKey = nextGroupKey;
594
+ this.groupList = new SelectList(groupItems, 10, selectListTheme);
595
+ const idx = Math.max(0, groupItems.findIndex((i) => i.value === selectedGroup));
596
+ this.groupList.setSelectedIndex(idx);
597
+ this.groupList.onSelectionChange = (item) => {
598
+ if (item.value.length > 0) this.runtime.selectGroup(item.value);
599
+ };
600
+ this.groupList.onSelect = () => this.setFocus("nodes");
601
+ }
602
+ const nodeItems = this.buildNodeItems();
603
+ const nowNode = groups.find((g) => g.name === selectedGroup)?.now ?? "";
604
+ const nextNodeKey = `${selectedGroup}#${nowNode}#${nodeItems.map((i) => `${i.value}:${i.description ?? ""}`).join("|")}#${testing ? "t" : "f"}`;
605
+ if (nextNodeKey !== this.nodeKey) {
606
+ this.nodeKey = nextNodeKey;
607
+ this.nodeList = new SelectList(nodeItems, 10, selectListTheme);
608
+ const idx = nodeItems.findIndex((i) => i.value === nowNode);
609
+ if (idx >= 0) this.nodeList.setSelectedIndex(idx);
610
+ this.nodeList.onSelect = (item) => {
611
+ if (selectedGroup.length > 0 && item.value.length > 0) this.runtime.selectProxy(selectedGroup, item.value);
612
+ };
613
+ }
614
+ const GROUP_COL = 26;
615
+ const offline = this.runtime.apiClient === void 0;
616
+ const leftHeader = theme.tableHeader(fitLine(` 代理组 (${groups.length})`, GROUP_COL));
617
+ const rightTitle = offline ? ` 节点 ${pc.dim("(离线)")}` : ` 节点 ${testing ? pc.yellow("(测速中…)") : ""}`;
618
+ const rightHeader = theme.tableHeader(fitLine(rightTitle, width - GROUP_COL - 1));
619
+ if (this.filtering) this.activeList.setFilter(this.filterText);
620
+ const leftLines = [leftHeader, ...this.groupList.render(GROUP_COL)];
621
+ const rightLines = [rightHeader, ...this.nodeList.render(width - GROUP_COL - 1)];
622
+ const body = sideBySide({
623
+ left: leftLines,
624
+ right: rightLines,
625
+ leftWidth: GROUP_COL,
626
+ width,
627
+ height: Math.max(this.height, leftLines.length, rightLines.length)
628
+ });
629
+ if (this.filtering) body.push(pc.cyan(fitLine(`/ ${this.filterText}`, width)));
630
+ else if (offline) body.push(pc.dim(fitLine(" daemon 未运行:选择节点将预选,下次启动生效(S 启动)", width)));
631
+ return body;
632
+ }
633
+ invalidate() {
634
+ this.groupList.invalidate();
635
+ this.nodeList.invalidate();
636
+ }
637
+ setHeight(height) {
638
+ this.height = height;
639
+ }
640
+ };
641
+ //#endregion
642
+ //#region src/tui/widgets/table.ts
643
+ function renderTable(options) {
644
+ const { columns, rows, width } = options;
645
+ const headerColor = options.headerColor ?? ((s) => s);
646
+ const fixedWidth = columns.reduce((sum, c) => sum + (c.width ?? 0), 0);
647
+ const totalWeight = columns.reduce((sum, c) => sum + (c.width === void 0 ? c.weight ?? 1 : 0), 0);
648
+ const flexible = Math.max(0, width - fixedWidth);
649
+ const widths = columns.map((c) => {
650
+ if (c.width !== void 0) return c.width;
651
+ if (totalWeight === 0) return 0;
652
+ return Math.floor(flexible * (c.weight ?? 1) / totalWeight);
653
+ });
654
+ const padTo = (text, colWidth, align) => {
655
+ const pad = colWidth - visibleWidth(text);
656
+ if (pad <= 0) return text;
657
+ return align === "right" ? " ".repeat(pad) + text : text + " ".repeat(pad);
658
+ };
659
+ const renderCell = (text, colWidth, align) => {
660
+ return padTo(truncateToWidth(text, colWidth, "…", false), colWidth, align);
661
+ };
662
+ const lines = [];
663
+ let headerLine = "";
664
+ for (let i = 0; i < columns.length; i += 1) {
665
+ const col = columns[i];
666
+ const w = widths[i];
667
+ headerLine += headerColor(renderCell(col.header, w, "left"));
668
+ }
669
+ lines.push(truncateToWidth(headerLine, width, "…", true));
670
+ for (let r = 0; r < rows.length; r += 1) {
671
+ const row = rows[r];
672
+ let line = "";
673
+ for (let i = 0; i < columns.length; i += 1) {
674
+ const col = columns[i];
675
+ const w = widths[i];
676
+ let cell = renderCell(col.render(row), w, col.align);
677
+ if (col.color !== void 0) cell = col.color(cell);
678
+ if (options.selectedIndex === r && options.selectedColor !== void 0) cell = options.selectedColor(cell);
679
+ line += cell;
680
+ }
681
+ lines.push(truncateToWidth(line, width, "…", true));
682
+ }
683
+ return {
684
+ lines,
685
+ width
686
+ };
687
+ }
688
+ //#endregion
689
+ //#region src/tui/widgets/confirm.ts
690
+ var ConfirmDialog = class {
691
+ finish;
692
+ focused = true;
693
+ lines;
694
+ constructor(opts, finish) {
695
+ this.finish = finish;
696
+ this.lines = this.build(opts);
697
+ }
698
+ build(opts) {
699
+ const hint = opts.hint ?? "y 确认 / n 取消";
700
+ return [
701
+ pc.bold(pc.red(opts.title)),
702
+ "",
703
+ opts.message,
704
+ "",
705
+ pc.dim(`[${hint}]`)
706
+ ];
707
+ }
708
+ handleInput(data) {
709
+ if (matchesKey(data, Key.escape) || data === "n" || data === "N") {
710
+ this.finish(false);
711
+ return;
712
+ }
713
+ if (data === "y" || data === "Y") this.finish(true);
714
+ }
715
+ render(width) {
716
+ return this.lines.map((line) => fitLine(line, width));
717
+ }
718
+ invalidate() {}
719
+ contentWidth() {
720
+ return this.lines.reduce((max, line) => Math.max(max, visibleWidth(line)), 0);
721
+ }
722
+ lineCount() {
723
+ return this.lines.length;
724
+ }
725
+ };
726
+ /** 弹确认框,返回用户是否确认(y=true,Esc/n=false)。 */
727
+ function confirm(tui, opts) {
728
+ return new Promise((resolve) => {
729
+ let settled = false;
730
+ const dialog = new ConfirmDialog(opts, (ok) => {
731
+ if (settled) return;
732
+ settled = true;
733
+ handle.hide();
734
+ resolve(ok);
735
+ });
736
+ const width = opts.width ?? Math.min(60, Math.max(36, dialog.contentWidth() + 6));
737
+ const handle = tui.showOverlay(dialog, {
738
+ width,
739
+ maxHeight: dialog.lineCount() + 2,
740
+ anchor: "center"
741
+ });
742
+ handle.focus();
743
+ });
744
+ }
745
+ //#endregion
746
+ //#region src/tui/widgets/details-modal.ts
747
+ var ConnectionDetail = class ConnectionDetail {
748
+ conn;
749
+ onClose;
750
+ onKill;
751
+ focused = true;
752
+ lines;
753
+ constructor(conn, onClose, onKill) {
754
+ this.conn = conn;
755
+ this.onClose = onClose;
756
+ this.onKill = onKill;
757
+ this.lines = ConnectionDetail.build(conn);
758
+ }
759
+ static build(c) {
760
+ const field = (label, value) => ` ${pc.cyan(label.padEnd(8))} ${value}`;
761
+ const out = [];
762
+ out.push(pc.bold(pc.cyan("连接详情")));
763
+ out.push("");
764
+ out.push(field("Host", c.hostRaw));
765
+ if (c.network.length > 0 || c.type.length > 0) out.push(field("类型", [c.network, c.type].filter(Boolean).join(" / ")));
766
+ if (c.sourceIP.length > 0) out.push(field("源地址", `${c.sourceIP}:${c.sourcePort}`));
767
+ if (c.destinationIP.length > 0) out.push(field("目标", `${c.destinationIP}:${c.destinationPort}`));
768
+ if (c.processPath.length > 0) out.push(field("进程", c.processPath));
769
+ out.push(field("规则", c.rule));
770
+ out.push(field("代理链", c.chainsFull.join(" → ")));
771
+ out.push(field("流量", `↑ ${formatBytes(c.up)} ↓ ${formatBytes(c.down)}`));
772
+ out.push(field("时长", formatDuration(Date.now() - c.startedAt)));
773
+ if (c.dnsMode.length > 0) out.push(field("DNS", c.dnsMode));
774
+ out.push("");
775
+ out.push(pc.dim(" [d] 断开连接 [Esc/Enter] 关闭"));
776
+ return out;
777
+ }
778
+ handleInput(data) {
779
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.enter) || data === "q") {
780
+ this.onClose();
781
+ return;
782
+ }
783
+ if (data === "d" || data === "D") {
784
+ this.onKill(this.conn.id);
785
+ this.onClose();
786
+ }
787
+ }
788
+ render(width) {
789
+ return this.lines.map((line) => fitLine(line, width));
790
+ }
791
+ invalidate() {}
792
+ contentWidth() {
793
+ return this.lines.reduce((max, line) => Math.max(max, visibleWidth(line)), 0);
794
+ }
795
+ lineCount() {
796
+ return this.lines.length;
797
+ }
798
+ };
799
+ /** 打开连接详情浮层。onKill 在用户按 d 时回调(断开连接),浮层随后关闭。 */
800
+ function showConnectionDetail(tui, conn, onKill) {
801
+ return new Promise((resolve) => {
802
+ let settled = false;
803
+ const overlay = new ConnectionDetail(conn, () => {
804
+ if (settled) return;
805
+ settled = true;
806
+ handle.hide();
807
+ resolve();
808
+ }, onKill);
809
+ const width = Math.min(64, Math.max(40, overlay.contentWidth() + 4));
810
+ const handle = tui.showOverlay(overlay, {
811
+ width,
812
+ maxHeight: Math.min(24, overlay.lineCount() + 2),
813
+ anchor: "center"
814
+ });
815
+ handle.focus();
816
+ });
817
+ }
818
+ //#endregion
819
+ //#region src/tui/panels/connections-panel.ts
820
+ var ConnectionsPanel = class {
821
+ runtime;
822
+ filtering = false;
823
+ bodyHeight = 20;
824
+ constructor(runtime) {
825
+ this.runtime = runtime;
826
+ }
827
+ hints() {
828
+ return [
829
+ "[↑/↓] 滚动",
830
+ "[Enter] 详情",
831
+ "[d] 断开",
832
+ "[X] 全部断开",
833
+ "[s] 排序",
834
+ "[/] 过滤"
835
+ ];
836
+ }
837
+ get cursor() {
838
+ return this.runtime.state.connections.cursor;
839
+ }
840
+ set cursor(value) {
841
+ const rows = this.visible();
842
+ const max = Math.max(0, rows.length - 1);
843
+ const clamped = Math.max(0, Math.min(value, max));
844
+ const scroll = this.computeScroll(clamped, this.runtime.state.connections.scroll, this.pageRows, rows.length);
845
+ this.runtime.setConnectionsNav(scroll, clamped);
846
+ }
847
+ /** 摘要(2) + 表头(1) + 底部提示(1) 之外留给数据行的高度。 */
848
+ get pageRows() {
849
+ return Math.max(1, this.bodyHeight - 4);
850
+ }
851
+ computeScroll(cursor, scroll, page, total) {
852
+ if (cursor < scroll) return cursor;
853
+ if (cursor >= scroll + page) return cursor - page + 1;
854
+ if (scroll + page > total) return Math.max(0, total - page);
855
+ return scroll;
856
+ }
857
+ visible() {
858
+ return this.runtime.visibleConnections();
859
+ }
860
+ handleInput(data) {
861
+ if (this.filtering) {
862
+ this.handleFilterInput(data);
863
+ return;
864
+ }
865
+ if (matchesKey(data, Key.up) || matchesKey(data, "k")) {
866
+ this.cursor = this.cursor - 1;
867
+ return;
868
+ }
869
+ if (matchesKey(data, Key.down) || matchesKey(data, "j")) {
870
+ this.cursor = this.cursor + 1;
871
+ return;
872
+ }
873
+ if (matchesKey(data, Key.pageUp)) {
874
+ this.cursor = this.cursor - this.pageRows;
875
+ return;
876
+ }
877
+ if (matchesKey(data, Key.pageDown)) {
878
+ this.cursor = this.cursor + this.pageRows;
879
+ return;
880
+ }
881
+ if (matchesKey(data, Key.home) || data === "g") {
882
+ this.cursor = 0;
883
+ return;
884
+ }
885
+ if (matchesKey(data, Key.end) || data === "G") {
886
+ this.cursor = this.visible().length - 1;
887
+ return;
888
+ }
889
+ if (matchesKey(data, "/")) {
890
+ this.filtering = true;
891
+ this.runtime.setConnectionsFilter("");
892
+ return;
893
+ }
894
+ if (data === "s") {
895
+ this.runtime.toggleConnectionsSort();
896
+ return;
897
+ }
898
+ if (matchesKey(data, Key.enter)) {
899
+ const row = this.visible()[this.cursor];
900
+ if (row !== void 0) showConnectionDetail(this.runtime.tui, row, (id) => {
901
+ this.runtime.closeConnection(id);
902
+ });
903
+ return;
904
+ }
905
+ if (data === "d") {
906
+ const row = this.visible()[this.cursor];
907
+ if (row !== void 0) this.runtime.closeConnection(row.id);
908
+ return;
909
+ }
910
+ if (data === "X" && this.runtime.apiClient !== void 0) this.closeAllWithConfirm();
911
+ }
912
+ async closeAllWithConfirm() {
913
+ if (await confirm(this.runtime.tui, {
914
+ title: "断开全部连接?",
915
+ message: "将立即断开当前所有活跃连接,此操作不可撤销。",
916
+ hint: "y 断开 / n 取消"
917
+ })) await this.runtime.closeAllConnections();
918
+ }
919
+ handleFilterInput(data) {
920
+ let filter = this.runtime.state.connections.filter;
921
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.escape)) {
922
+ this.filtering = false;
923
+ this.runtime.scheduleRender();
924
+ return;
925
+ }
926
+ if (matchesKey(data, Key.backspace)) filter = filter.slice(0, -1);
927
+ else if (data.length === 1 && data >= " ") filter += data;
928
+ this.runtime.setConnectionsFilter(filter);
929
+ }
930
+ render(width) {
931
+ if (this.runtime.apiClient === void 0) return renderOfflineHint(width, this.bodyHeight, {
932
+ status: this.runtime.state.daemon,
933
+ secretMissing: this.runtime.state.secretMissing,
934
+ error: this.runtime.state.error
935
+ });
936
+ const rows = this.visible();
937
+ const state = this.runtime.state;
938
+ const ov = state.overview;
939
+ const out = [];
940
+ out.push(fitLine(pc.green(`↑ ${formatRate(state.upRate)} 总计 ${formatBytes(ov.uploadTotal)}`) + " " + pc.cyan(`↓ ${formatRate(state.downRate)} 总计 ${formatBytes(ov.downloadTotal)}`) + " " + pc.dim(`活跃连接 ${rows.length}`), width));
941
+ const sparkWidth = Math.max(10, width - 2);
942
+ out.push(fitLine(renderSparkline(state.traffic.down, sparkWidth, pc.cyan), width));
943
+ const start = state.connections.scroll;
944
+ const visibleSlice = rows.slice(start, start + this.pageRows);
945
+ const now = Date.now();
946
+ const { lines: tableLines } = renderTable({
947
+ columns: [
948
+ {
949
+ key: "host",
950
+ header: "Host",
951
+ render: (r) => r.host
952
+ },
953
+ {
954
+ key: "net",
955
+ header: "Net",
956
+ width: 5,
957
+ render: (r) => r.network
958
+ },
959
+ {
960
+ key: "rule",
961
+ header: "Rule",
962
+ width: 16,
963
+ render: (r) => r.rule
964
+ },
965
+ {
966
+ key: "chain",
967
+ header: "Chain",
968
+ width: 16,
969
+ render: (r) => r.chain
970
+ },
971
+ {
972
+ key: "up",
973
+ header: "↑",
974
+ width: 9,
975
+ align: "right",
976
+ render: (r) => formatBytes(r.up)
977
+ },
978
+ {
979
+ key: "down",
980
+ header: "↓",
981
+ width: 9,
982
+ align: "right",
983
+ render: (r) => formatBytes(r.down)
984
+ },
985
+ {
986
+ key: "time",
987
+ header: "Time",
988
+ width: 6,
989
+ align: "right",
990
+ render: (r) => formatDuration(now - r.startedAt)
991
+ }
992
+ ],
993
+ rows: visibleSlice,
994
+ width,
995
+ headerColor: theme.tableHeader,
996
+ selectedIndex: state.connections.cursor - start,
997
+ selectedColor: pc.inverse
998
+ });
999
+ for (const line of tableLines) out.push(line);
1000
+ if (this.filtering) out.push(pc.cyan(fitLine(`/ ${state.connections.filter}`, width)));
1001
+ else if (state.connections.filter.length > 0) out.push(pc.dim(fitLine(`过滤: ${state.connections.filter} (按 / 修改,Esc 清除)`, width)));
1002
+ else if (rows.length === 0) out.push(pc.dim(fitLine("无活跃连接", width)));
1003
+ else out.push("");
1004
+ return out;
1005
+ }
1006
+ invalidate() {}
1007
+ setBodyHeight(height) {
1008
+ this.bodyHeight = height;
1009
+ }
1010
+ };
1011
+ //#endregion
1012
+ //#region src/tui/panels/logs-panel.ts
1013
+ const TIME_COL = 9;
1014
+ const LV_COL = 6;
1015
+ const LEVEL_COLOR = {
1016
+ debug: pc.dim,
1017
+ info: pc.cyan,
1018
+ warning: pc.yellow,
1019
+ error: pc.red
1020
+ };
1021
+ const LEVEL_LABEL = {
1022
+ debug: "DEBUG",
1023
+ info: "INFO ",
1024
+ warning: "WARN ",
1025
+ error: "ERROR"
1026
+ };
1027
+ function formatTime(ms) {
1028
+ const d = new Date(ms);
1029
+ const p = (n) => String(n).padStart(2, "0");
1030
+ return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
1031
+ }
1032
+ var LogsPanel = class {
1033
+ runtime;
1034
+ filtering = false;
1035
+ bodyHeight = 20;
1036
+ constructor(runtime) {
1037
+ this.runtime = runtime;
1038
+ }
1039
+ hints() {
1040
+ return [
1041
+ "[↑/↓] 滚动",
1042
+ "[Space] 暂停",
1043
+ "[l] 级别",
1044
+ "[f] 跟随",
1045
+ "[c] 清屏",
1046
+ "[/] 过滤"
1047
+ ];
1048
+ }
1049
+ activate() {
1050
+ this.runtime.startLogs();
1051
+ }
1052
+ deactivate() {
1053
+ this.runtime.stopLogs();
1054
+ }
1055
+ /** 摘要(1) + 底部提示(1) 之外留给日志行的高度。 */
1056
+ get pageRows() {
1057
+ return Math.max(1, this.bodyHeight - 2);
1058
+ }
1059
+ handleInput(data) {
1060
+ if (this.filtering) {
1061
+ this.handleFilterInput(data);
1062
+ return;
1063
+ }
1064
+ if (matchesKey(data, Key.up) || data === "k") {
1065
+ this.scrollBy(-1);
1066
+ return;
1067
+ }
1068
+ if (matchesKey(data, Key.down) || data === "j") {
1069
+ this.scrollBy(1);
1070
+ return;
1071
+ }
1072
+ if (matchesKey(data, Key.pageUp)) {
1073
+ this.scrollBy(-this.pageRows);
1074
+ return;
1075
+ }
1076
+ if (matchesKey(data, Key.pageDown)) {
1077
+ this.scrollBy(this.pageRows);
1078
+ return;
1079
+ }
1080
+ if (matchesKey(data, Key.home) || data === "g") {
1081
+ this.jump(0);
1082
+ return;
1083
+ }
1084
+ if (matchesKey(data, Key.end) || data === "G") {
1085
+ this.jump(Number.MAX_SAFE_INTEGER);
1086
+ return;
1087
+ }
1088
+ if (data === " ") {
1089
+ this.runtime.toggleLogPause();
1090
+ return;
1091
+ }
1092
+ if (data === "l") {
1093
+ this.runtime.cycleLogLevel();
1094
+ return;
1095
+ }
1096
+ if (data === "f") {
1097
+ this.runtime.toggleLogFollow();
1098
+ return;
1099
+ }
1100
+ if (data === "c") {
1101
+ this.runtime.clearLogs();
1102
+ return;
1103
+ }
1104
+ if (data === "/") {
1105
+ this.filtering = true;
1106
+ this.runtime.setLogFilter("");
1107
+ }
1108
+ }
1109
+ handleFilterInput(data) {
1110
+ let filter = this.runtime.state.logs.filter;
1111
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.escape)) {
1112
+ this.filtering = false;
1113
+ this.runtime.scheduleRender();
1114
+ return;
1115
+ }
1116
+ if (matchesKey(data, Key.backspace)) filter = filter.slice(0, -1);
1117
+ else if (data.length === 1 && data >= " ") filter += data;
1118
+ this.runtime.setLogFilter(filter);
1119
+ }
1120
+ scrollBy(delta) {
1121
+ const rows = this.runtime.visibleLogs();
1122
+ const max = Math.max(0, rows.length - 1);
1123
+ const target = Math.max(0, Math.min(this.currentScroll(rows.length) + delta, max));
1124
+ this.commitScroll(target, rows.length);
1125
+ }
1126
+ jump(target) {
1127
+ const rows = this.runtime.visibleLogs();
1128
+ this.commitScroll(target === Number.MAX_SAFE_INTEGER ? Math.max(0, rows.length - 1) : target, rows.length);
1129
+ }
1130
+ /** 归一化 scroll:MAX_SAFE_INTEGER 表示跟随尾部,渲染前 clamp 到可见末尾。 */
1131
+ currentScroll(total) {
1132
+ const s = this.runtime.state.logs.scroll;
1133
+ if (s === Number.MAX_SAFE_INTEGER) return Math.max(0, total - 1);
1134
+ return Math.min(s, Math.max(0, total - 1));
1135
+ }
1136
+ commitScroll(target, total) {
1137
+ const atBottom = target >= total - 1;
1138
+ this.runtime.setLogScroll(atBottom ? Number.MAX_SAFE_INTEGER : target, atBottom);
1139
+ }
1140
+ render(width) {
1141
+ if (this.runtime.apiClient === void 0) return renderOfflineHint(width, this.bodyHeight, {
1142
+ status: this.runtime.state.daemon,
1143
+ secretMissing: this.runtime.state.secretMissing,
1144
+ error: this.runtime.state.error
1145
+ });
1146
+ const logs = this.runtime.state.logs;
1147
+ const out = [];
1148
+ const followMark = logs.follow ? pc.green("跟随 ●") : pc.dim("跟随 ○");
1149
+ const pauseMark = logs.paused ? pc.yellow("已暂停") : "";
1150
+ out.push(fitLine(` 级别: ${LEVEL_COLOR[logs.level](LEVEL_LABEL[logs.level].trim())} ${followMark}` + (pauseMark.length > 0 ? ` ${pauseMark}` : ""), width));
1151
+ const rows = this.runtime.visibleLogs();
1152
+ const msgWidth = Math.max(8, width - TIME_COL - LV_COL);
1153
+ const total = rows.length;
1154
+ const start = Math.max(0, Math.min(logs.scroll === Number.MAX_SAFE_INTEGER ? total - this.pageRows : logs.scroll, Math.max(0, total - this.pageRows)));
1155
+ const slice = rows.slice(start, start + this.pageRows);
1156
+ for (const e of slice) out.push(this.renderLine(e, msgWidth, width));
1157
+ while (out.length - 1 < this.pageRows) out.push("");
1158
+ if (this.filtering) out.push(pc.cyan(fitLine(`/ ${logs.filter}`, width)));
1159
+ else if (logs.filter.length > 0) out.push(pc.dim(fitLine(`过滤: ${logs.filter} (按 / 修改,Esc 清除)`, width)));
1160
+ else if (total === 0) out.push(pc.dim(fitLine("等待日志…(级别过低或无流量时可能为空)", width)));
1161
+ else out.push("");
1162
+ return out;
1163
+ }
1164
+ renderLine(e, msgWidth, width) {
1165
+ const time = pc.dim(formatTime(e.receivedAt).padEnd(TIME_COL - 1));
1166
+ const color = LEVEL_COLOR[e.level];
1167
+ return fitLine(`${time} ${color(LEVEL_LABEL[e.level])} ${fitLine(e.payload, msgWidth)}`, width);
1168
+ }
1169
+ invalidate() {}
1170
+ setBodyHeight(height) {
1171
+ this.bodyHeight = height;
1172
+ }
1173
+ };
1174
+ //#endregion
1175
+ //#region src/config/models.ts
1176
+ var ConfigError = class extends Error {
1177
+ constructor(message) {
1178
+ super(message);
1179
+ this.name = "ConfigError";
1180
+ }
1181
+ };
1182
+ /** 从 unknown 错误值中提取可读消息,替代散落各处的 instanceof 三元表达式。 */
1183
+ function errorMessage(error) {
1184
+ return error instanceof Error ? error.message : String(error);
1185
+ }
1186
+ //#endregion
1187
+ //#region src/config/profile-paths.ts
1188
+ /**
1189
+ * Lynx 主目录:~/.lynx-proxy/
1190
+ */
1191
+ function getLynxHome() {
1192
+ return join(homedir(), ".lynx-proxy");
1193
+ }
1194
+ /**
1195
+ * Profile 索引文件路径:~/.lynx-proxy/profiles.yaml
1196
+ */
1197
+ function getProfilesYamlPath() {
1198
+ return join(getLynxHome(), "profiles.yaml");
1199
+ }
1200
+ /**
1201
+ * mihomo 运行时配置文件路径:~/.lynx-proxy/config.yaml
1202
+ * 由 Lynx 在生成 Profile 后写入,mihomo 启动时读取。
1203
+ */
1204
+ function getMihomoConfigPath() {
1205
+ return join(getLynxHome(), "config.yaml");
1206
+ }
1207
+ //#endregion
1208
+ //#region src/config/profiles.ts
1209
+ /**
1210
+ * 加载 profiles.yaml。文件不存在时返回空配置。
1211
+ */
1212
+ function loadProfiles() {
1213
+ const path = getProfilesYamlPath();
1214
+ if (!existsSync(path)) return {};
1215
+ try {
1216
+ const parsed = load(readFileSync(path, "utf8"));
1217
+ if (parsed === void 0 || parsed === null) return {};
1218
+ if (typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("profiles.yaml root must be a mapping");
1219
+ return normalizeProfiles(parsed);
1220
+ } catch (error) {
1221
+ if (error instanceof ConfigError) throw error;
1222
+ throw new ConfigError(`Failed to load profiles.yaml: ${errorMessage(error)}`);
1223
+ }
1224
+ }
1225
+ /**
1226
+ * 写入 profiles.yaml。
1227
+ */
1228
+ function saveProfiles(config) {
1229
+ const path = getProfilesYamlPath();
1230
+ mkdirSync(dirname(path), { recursive: true });
1231
+ writeFileSync(path, `# Profiles Config for LynxProxy\n${dump(config, {
1232
+ indent: 2,
1233
+ lineWidth: 120,
1234
+ noRefs: true,
1235
+ sortKeys: false
1236
+ })}`, "utf8");
1237
+ }
1238
+ /**
1239
+ * 获取当前激活的 Profile。
1240
+ */
1241
+ function getCurrentProfile(config) {
1242
+ if (config.current === void 0) return void 0;
1243
+ return (config.items ?? []).find((item) => item.uid === config.current);
1244
+ }
1245
+ /**
1246
+ * 切换当前 Profile。
1247
+ */
1248
+ function setCurrentProfile(config, uid) {
1249
+ if (!(config.items ?? []).some((item) => item.uid === uid)) return false;
1250
+ config.current = uid;
1251
+ return true;
1252
+ }
1253
+ /**
1254
+ * 读取某 Profile 的代理组预选(返回空 map 表示无记录)。
1255
+ */
1256
+ function getProfileSelections(profile) {
1257
+ return profile?.selections ?? {};
1258
+ }
1259
+ /**
1260
+ * 设置(或删除)某 Profile 中某个组的预选节点。
1261
+ * 仅修改传入的 config 对象,调用方负责 saveProfiles() 落盘。
1262
+ *
1263
+ * @param node 节点名;传空串/undefined 表示删除该组的预选
1264
+ * @returns 是否发生了实际变更
1265
+ */
1266
+ function setProfileSelection(config, uid, group, node) {
1267
+ const item = (config.items ?? []).find((it) => it.uid === uid);
1268
+ if (item === void 0) return false;
1269
+ const current = item.selections?.[group];
1270
+ if (node === void 0 || node.length === 0) {
1271
+ if (current === void 0) return false;
1272
+ if (item.selections !== void 0) delete item.selections[group];
1273
+ return true;
1274
+ }
1275
+ if (current === node) return false;
1276
+ if (item.selections === void 0) item.selections = {};
1277
+ item.selections[group] = node;
1278
+ return true;
1279
+ }
1280
+ function normalizeProfiles(raw) {
1281
+ const result = {};
1282
+ if (typeof raw["current"] === "string") result.current = raw["current"];
1283
+ if (Array.isArray(raw["items"])) result.items = raw["items"].map((entry, index) => {
1284
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new ConfigError(`profiles.yaml items[${index}] must be a mapping`);
1285
+ return normalizeItem(entry);
1286
+ });
1287
+ return result;
1288
+ }
1289
+ function normalizeItem(raw) {
1290
+ const uid = raw["uid"];
1291
+ const type = raw["type"];
1292
+ const name = raw["name"];
1293
+ const file = raw["file"];
1294
+ if (typeof uid !== "string" || uid.length === 0) throw new ConfigError("profile item uid must be a non-empty string");
1295
+ if (type !== "remote" && type !== "local" && type !== "merge" && type !== "script" && type !== "decoder") throw new ConfigError(`profile item type must be remote|local|merge|script|decoder, got: ${String(type)}`);
1296
+ if (typeof name !== "string" || name.length === 0) throw new ConfigError("profile item name must be a non-empty string");
1297
+ if (typeof file !== "string" || file.length === 0) throw new ConfigError("profile item file must be a non-empty string");
1298
+ const item = {
1299
+ uid,
1300
+ type,
1301
+ name,
1302
+ file
1303
+ };
1304
+ if (typeof raw["url"] === "string") item.url = raw["url"];
1305
+ if (typeof raw["updated"] === "number") item.updated = raw["updated"];
1306
+ if (typeof raw["desc"] === "string") item.desc = raw["desc"];
1307
+ if (Array.isArray(raw["selected"])) item.selected = raw["selected"].map((s, i) => {
1308
+ if (typeof s !== "object" || s === null) throw new ConfigError(`selected[${i}] must be a mapping`);
1309
+ const obj = s;
1310
+ return {
1311
+ name: String(obj["name"] ?? ""),
1312
+ now: String(obj["now"] ?? "")
1313
+ };
1314
+ });
1315
+ if (typeof raw["selections"] === "object" && raw["selections"] !== null && !Array.isArray(raw["selections"])) {
1316
+ const map = raw["selections"];
1317
+ const selections = {};
1318
+ for (const [group, node] of Object.entries(map)) if (typeof node === "string" && node.length > 0) selections[group] = node;
1319
+ if (Object.keys(selections).length > 0) item.selections = selections;
1320
+ }
1321
+ if (typeof raw["extra"] === "object" && raw["extra"] !== null && !Array.isArray(raw["extra"])) {
1322
+ const e = raw["extra"];
1323
+ const extra = {};
1324
+ if (typeof e["upload"] === "number") extra.upload = e["upload"];
1325
+ if (typeof e["download"] === "number") extra.download = e["download"];
1326
+ if (typeof e["total"] === "number") extra.total = e["total"];
1327
+ if (typeof e["expire"] === "number") extra.expire = e["expire"];
1328
+ item.extra = extra;
1329
+ }
1330
+ if (typeof raw["option"] === "object" && raw["option"] !== null && !Array.isArray(raw["option"])) item.option = normalizeOption(raw["option"]);
1331
+ return item;
1332
+ }
1333
+ /** 是否已经打印过 decoder 字段弃用警告。同一进程只打一次。 */
1334
+ let decoderDeprecationWarned = false;
1335
+ function warnDecoderDeprecationOnce(legacy) {
1336
+ if (decoderDeprecationWarned) return;
1337
+ decoderDeprecationWarned = true;
1338
+ process.stderr.write(`[lynx] profile option.decoder="${legacy}" 已弃用,自动迁移到 decoder_plugin: D_xxyun。新写法:lynx profile add ... --decoder-plugin D_xxyun。
1339
+ `);
1340
+ }
1341
+ function normalizeOption(raw) {
1342
+ const opt = {};
1343
+ if (typeof raw["user_agent"] === "string") opt.user_agent = raw["user_agent"];
1344
+ if (typeof raw["with_proxy"] === "boolean") opt.with_proxy = raw["with_proxy"];
1345
+ if (typeof raw["self_proxy"] === "boolean") opt.self_proxy = raw["self_proxy"];
1346
+ if (typeof raw["update_interval"] === "number") opt.update_interval = raw["update_interval"];
1347
+ if (typeof raw["timeout_seconds"] === "number") opt.timeout_seconds = raw["timeout_seconds"];
1348
+ if (typeof raw["danger_accept_invalid_certs"] === "boolean") opt.danger_accept_invalid_certs = raw["danger_accept_invalid_certs"];
1349
+ if (typeof raw["allow_auto_update"] === "boolean") opt.allow_auto_update = raw["allow_auto_update"];
1350
+ if (typeof raw["merge"] === "string") opt.merge = raw["merge"];
1351
+ if (typeof raw["script"] === "string") opt.script = raw["script"];
1352
+ if (typeof raw["decoder"] === "string") {
1353
+ const legacy = raw["decoder"];
1354
+ if (legacy === "xxyun" || legacy === "D_xxyun") {
1355
+ opt.decoder_plugin = "D_xxyun";
1356
+ warnDecoderDeprecationOnce(legacy);
1357
+ } else throw new ConfigError(`Unknown legacy decoder: "${legacy}". xxyun has been migrated to plugin D_xxyun; for custom decoders, use "lynx profile decoder add".`);
1358
+ }
1359
+ if (typeof raw["decoder_plugin"] === "string") opt.decoder_plugin = raw["decoder_plugin"];
1360
+ if (typeof raw["decoder_key"] === "string") opt.decoder_key = raw["decoder_key"];
1361
+ return opt;
1362
+ }
1363
+ //#endregion
1364
+ //#region src/tui/widgets/input-modal.ts
1365
+ /**
1366
+ * 带标题的单行输入浮层:Enter 提交(通过 validate 后)、Esc 取消。
1367
+ * 类似 widgets/modal.ts 的 selectFromList,返回输入值;取消返回 undefined。
1368
+ */
1369
+ var PromptDialog = class {
1370
+ finish;
1371
+ focused = true;
1372
+ input;
1373
+ error;
1374
+ title;
1375
+ constructor(opts, finish) {
1376
+ this.finish = finish;
1377
+ this.title = opts.title;
1378
+ this.input = new Input();
1379
+ this.input.focused = true;
1380
+ if (opts.initial !== void 0) this.input.setValue(opts.initial);
1381
+ this.input.onSubmit = (value) => {
1382
+ const err = opts.validate?.(value);
1383
+ if (err !== void 0) {
1384
+ this.error = err;
1385
+ return;
1386
+ }
1387
+ this.finish(value);
1388
+ };
1389
+ this.input.onEscape = () => this.finish(void 0);
1390
+ }
1391
+ handleInput(data) {
1392
+ if (this.error !== void 0) this.error = void 0;
1393
+ this.input.handleInput(data);
1394
+ }
1395
+ render(width) {
1396
+ const out = [];
1397
+ out.push(pc.bold(pc.cyan(this.title)));
1398
+ out.push("");
1399
+ const inputLine = this.input.render(width - 2)[0] ?? "";
1400
+ out.push(` ${inputLine} `);
1401
+ if (this.error !== void 0) {
1402
+ out.push("");
1403
+ out.push(pc.red(` ${this.error}`));
1404
+ } else {
1405
+ out.push("");
1406
+ out.push(pc.dim(" Enter 确认 · Esc 取消"));
1407
+ }
1408
+ return out.map((line) => fitLine(line, width)).filter((line) => visibleWidth(line) <= width);
1409
+ }
1410
+ invalidate() {
1411
+ this.input.invalidate();
1412
+ }
1413
+ lineCount() {
1414
+ return this.error !== void 0 ? 7 : 6;
1415
+ }
1416
+ };
1417
+ function promptInput(tui, opts) {
1418
+ return new Promise((resolve) => {
1419
+ let settled = false;
1420
+ const dialog = new PromptDialog(opts, (value) => {
1421
+ if (settled) return;
1422
+ settled = true;
1423
+ handle.hide();
1424
+ resolve(value);
1425
+ });
1426
+ const width = opts.width ?? 48;
1427
+ const handle = tui.showOverlay(dialog, {
1428
+ width,
1429
+ maxHeight: dialog.lineCount(),
1430
+ anchor: "center"
1431
+ });
1432
+ handle.focus();
1433
+ });
1434
+ }
1435
+ //#endregion
1436
+ //#region src/tui/panels/settings-panel.ts
1437
+ const MODES$1 = [
1438
+ "rule",
1439
+ "global",
1440
+ "direct",
1441
+ "script"
1442
+ ];
1443
+ const MIHOMO_LOG_LEVELS = [
1444
+ "debug",
1445
+ "info",
1446
+ "warning",
1447
+ "error"
1448
+ ];
1449
+ const LYNX_LOG_LEVELS = [
1450
+ "debug",
1451
+ "info",
1452
+ "warn",
1453
+ "error"
1454
+ ];
1455
+ const IPV6_OPTIONS = [
1456
+ {
1457
+ value: "unset",
1458
+ label: "未设置(跟随订阅)"
1459
+ },
1460
+ {
1461
+ value: "true",
1462
+ label: "启用"
1463
+ },
1464
+ {
1465
+ value: "false",
1466
+ label: "禁用"
1467
+ }
1468
+ ];
1469
+ /** 校验 "host:port" 字符串。 */
1470
+ function validateListen(value) {
1471
+ const trimmed = value.trim();
1472
+ if (trimmed.length === 0) return "监听地址不能为空";
1473
+ const idx = trimmed.lastIndexOf(":");
1474
+ if (idx <= 0) return "格式应为 host:port(如 127.0.0.1:7890)";
1475
+ const port = Number.parseInt(trimmed.slice(idx + 1), 10);
1476
+ if (!Number.isFinite(port) || port < 1 || port > 65535) return "端口须为 1–65535";
1477
+ }
1478
+ /** 校验端口号字符串。 */
1479
+ function validatePort(value) {
1480
+ const port = Number.parseInt(value.trim(), 10);
1481
+ if (!Number.isFinite(port) || port < 1 || port > 65535) return "端口须为 1–65535";
1482
+ }
1483
+ var SettingsPanel = class {
1484
+ runtime;
1485
+ tui;
1486
+ cursor = 0;
1487
+ items = [];
1488
+ constructor(runtime, tui) {
1489
+ this.runtime = runtime;
1490
+ this.tui = tui;
1491
+ }
1492
+ hints() {
1493
+ return ["[↑/↓] 选择", "[Enter] 修改"];
1494
+ }
1495
+ activate() {
1496
+ this.cursor = 0;
1497
+ }
1498
+ get online() {
1499
+ return this.runtime.apiClient !== void 0;
1500
+ }
1501
+ selectableIndexes() {
1502
+ const out = [];
1503
+ this.items.forEach((item, i) => {
1504
+ if (item.kind === "row") out.push(i);
1505
+ });
1506
+ return out;
1507
+ }
1508
+ handleInput(data) {
1509
+ const selectable = this.selectableIndexes();
1510
+ if (selectable.length === 0) return;
1511
+ if (matchesKey(data, Key.up) || data === "k") {
1512
+ this.cursor = Math.max(0, this.cursor - 1);
1513
+ this.runtime.scheduleRender();
1514
+ return;
1515
+ }
1516
+ if (matchesKey(data, Key.down) || data === "j") {
1517
+ this.cursor = Math.min(selectable.length - 1, this.cursor + 1);
1518
+ this.runtime.scheduleRender();
1519
+ return;
1520
+ }
1521
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.space)) {
1522
+ const idx = selectable[this.cursor];
1523
+ if (idx === void 0) return;
1524
+ const item = this.items[idx];
1525
+ if (item === void 0 || item.kind !== "row") return;
1526
+ if (item.needsDaemon && !this.online) {
1527
+ this.runtime.flash(`需要运行中的 daemon 才能${item.label}。`);
1528
+ return;
1529
+ }
1530
+ item.activate();
1531
+ }
1532
+ }
1533
+ async pickMode() {
1534
+ const item = await selectFromList(this.tui, MODES$1.map((m) => ({
1535
+ value: m,
1536
+ label: m
1537
+ })), {
1538
+ width: 24,
1539
+ maxHeight: 6
1540
+ });
1541
+ if (item !== void 0) await this.runtime.setMode(item.value);
1542
+ }
1543
+ async pickMihomoLogLevel() {
1544
+ const item = await selectFromList(this.tui, MIHOMO_LOG_LEVELS.map((l) => ({
1545
+ value: l,
1546
+ label: l
1547
+ })), {
1548
+ width: 28,
1549
+ maxHeight: 6
1550
+ });
1551
+ if (item !== void 0) await this.runtime.setLogLevel(item.value);
1552
+ }
1553
+ async pickProfile() {
1554
+ let items;
1555
+ let currentUid;
1556
+ try {
1557
+ const profiles = loadProfiles();
1558
+ currentUid = getCurrentProfile(profiles)?.uid;
1559
+ items = (profiles.items ?? []).filter((p) => p.type === "remote" || p.type === "local").map((p) => ({
1560
+ value: p.uid,
1561
+ label: p.uid === currentUid ? `${p.name} (当前)` : p.name,
1562
+ description: `[${p.type}]`
1563
+ }));
1564
+ } catch (error) {
1565
+ this.runtime.flash(`读取 profiles.yaml 失败:${String(error)}`);
1566
+ return;
1567
+ }
1568
+ if (items.length === 0) {
1569
+ this.runtime.flash("没有可用的 Profile(先用 lynx profile add 添加)。");
1570
+ return;
1571
+ }
1572
+ const picked = await selectFromList(this.tui, items, {
1573
+ width: 44,
1574
+ maxHeight: 12
1575
+ });
1576
+ if (picked === void 0 || picked.value === currentUid) return;
1577
+ await this.runtime.switchProfile(picked.value);
1578
+ }
1579
+ async pickKernel() {
1580
+ const current = this.runtime.state.overview.kernelChannel;
1581
+ const picked = await selectFromList(this.tui, ["stable", "alpha"].map((c) => ({
1582
+ value: c,
1583
+ label: c === current ? `${c} (当前)` : c
1584
+ })), {
1585
+ width: 28,
1586
+ maxHeight: 5
1587
+ });
1588
+ if (picked === void 0) return;
1589
+ const channel = picked.value === "alpha" ? "alpha" : "stable";
1590
+ if (channel === current) return;
1591
+ if (this.online) {
1592
+ if (!await confirm(this.tui, {
1593
+ title: `切换到 ${channel} 内核?`,
1594
+ message: "将重启 daemon,所有连接断开。",
1595
+ hint: "y 切换 / n 取消"
1596
+ })) return;
1597
+ }
1598
+ await this.runtime.switchKernel(channel);
1599
+ }
1600
+ async editListen() {
1601
+ const initial = this.runtime.readLynxConfig()?.listen ?? "127.0.0.1:7890";
1602
+ const value = await promptInput(this.tui, {
1603
+ title: "Lynx 监听地址(host:port)",
1604
+ initial,
1605
+ validate: validateListen
1606
+ });
1607
+ if (value === void 0) return;
1608
+ await this.runtime.updateLynxConfig((config) => {
1609
+ config.listen = value.trim();
1610
+ }, "监听地址");
1611
+ }
1612
+ async editMixedPort() {
1613
+ const cfg = this.runtime.readLynxConfig();
1614
+ const initial = String(cfg?.mihomo["mixed-port"] ?? 7891);
1615
+ const value = await promptInput(this.tui, {
1616
+ title: "mihomo 混合端口(mixed-port)",
1617
+ initial,
1618
+ validate: validatePort
1619
+ });
1620
+ if (value === void 0) return;
1621
+ const port = Number.parseInt(value.trim(), 10);
1622
+ await this.runtime.updateLynxConfig((config) => {
1623
+ config.mihomo["mixed-port"] = port;
1624
+ }, "mihomo 端口");
1625
+ }
1626
+ async pickIpv6() {
1627
+ const current = this.runtime.readLynxConfig()?.mihomo.ipv6;
1628
+ const currentStr = current === void 0 ? "unset" : String(current);
1629
+ const picked = await selectFromList(this.tui, IPV6_OPTIONS.map((o) => ({
1630
+ value: o.value,
1631
+ label: o.value === currentStr ? `${o.label} (当前)` : o.label
1632
+ })), {
1633
+ width: 32,
1634
+ maxHeight: 5
1635
+ });
1636
+ if (picked === void 0) return;
1637
+ await this.runtime.updateLynxConfig((config) => {
1638
+ if (picked.value === "unset") delete config.mihomo.ipv6;
1639
+ else config.mihomo.ipv6 = picked.value === "true";
1640
+ }, "IPv6 出站");
1641
+ }
1642
+ async pickLynxLogLevel() {
1643
+ const current = this.runtime.readLynxConfig()?.log?.level ?? "info";
1644
+ const picked = await selectFromList(this.tui, LYNX_LOG_LEVELS.map((l) => ({
1645
+ value: l,
1646
+ label: l === current ? `${l} (当前)` : l
1647
+ })), {
1648
+ width: 24,
1649
+ maxHeight: 6
1650
+ });
1651
+ if (picked === void 0) return;
1652
+ await this.runtime.updateLynxConfig((config) => {
1653
+ config.log = {
1654
+ ...config.log ?? {},
1655
+ level: picked.value
1656
+ };
1657
+ }, "Lynx 日志级别");
1658
+ }
1659
+ async toggleAccessLog() {
1660
+ const current = this.runtime.readLynxConfig()?.log?.access ?? true;
1661
+ await this.runtime.updateLynxConfig((config) => {
1662
+ config.log = {
1663
+ ...config.log ?? {},
1664
+ access: !current
1665
+ };
1666
+ }, "访问日志");
1667
+ }
1668
+ buildItems() {
1669
+ const ov = this.runtime.state.overview;
1670
+ const cfg = this.runtime.readLynxConfig();
1671
+ const items = [];
1672
+ items.push({
1673
+ kind: "header",
1674
+ label: "运行"
1675
+ });
1676
+ items.push({
1677
+ kind: "row",
1678
+ label: "切换路由模式",
1679
+ value: () => ov.mode ?? "—",
1680
+ hint: this.online ? "Enter 切换: rule/global/direct/script" : "Enter 切换(离线写入,下次启动生效)",
1681
+ needsDaemon: false,
1682
+ activate: () => this.pickMode()
1683
+ });
1684
+ items.push({
1685
+ kind: "row",
1686
+ label: "切换系统代理",
1687
+ value: () => ov.systemProxy,
1688
+ hint: "Enter 切换",
1689
+ needsDaemon: false,
1690
+ activate: () => this.runtime.toggleSystemProxy()
1691
+ });
1692
+ items.push({
1693
+ kind: "row",
1694
+ label: "mihomo 日志级别",
1695
+ value: () => ov.logLevel ?? "—",
1696
+ hint: "Enter 切换(运行时,影响 daemon 日志)",
1697
+ needsDaemon: true,
1698
+ activate: () => this.pickMihomoLogLevel()
1699
+ });
1700
+ items.push({
1701
+ kind: "header",
1702
+ label: "订阅与内核"
1703
+ });
1704
+ items.push({
1705
+ kind: "row",
1706
+ label: "切换 Profile",
1707
+ value: () => ov.profileName ?? "—",
1708
+ hint: this.online ? "Enter 切换(立即生效)" : "Enter 切换(下次启动生效)",
1709
+ needsDaemon: false,
1710
+ activate: () => this.pickProfile()
1711
+ });
1712
+ items.push({
1713
+ kind: "row",
1714
+ label: "切换内核通道",
1715
+ value: () => ov.kernelChannel,
1716
+ hint: this.online ? "Enter 切换(重启 daemon)" : "Enter 切换(下次启动生效)",
1717
+ needsDaemon: false,
1718
+ activate: () => this.pickKernel()
1719
+ });
1720
+ items.push({
1721
+ kind: "text",
1722
+ render: () => {
1723
+ const ver = ov.version !== void 0 ? ov.version.version : ov.kernelVersion ?? "—";
1724
+ return ` ${pc.dim("内核版本")} mihomo ${ver}`;
1725
+ }
1726
+ });
1727
+ items.push({
1728
+ kind: "header",
1729
+ label: "配置文件(lynx.json,重启生效)"
1730
+ });
1731
+ items.push({
1732
+ kind: "row",
1733
+ label: "监听地址",
1734
+ value: () => cfg?.listen ?? "—",
1735
+ hint: "Enter 编辑 host:port",
1736
+ needsDaemon: false,
1737
+ activate: () => this.editListen()
1738
+ });
1739
+ items.push({
1740
+ kind: "row",
1741
+ label: "mihomo 端口",
1742
+ value: () => String(cfg?.mihomo["mixed-port"] ?? "—"),
1743
+ hint: "Enter 编辑 mixed-port",
1744
+ needsDaemon: false,
1745
+ activate: () => this.editMixedPort()
1746
+ });
1747
+ items.push({
1748
+ kind: "row",
1749
+ label: "IPv6 出站",
1750
+ value: () => {
1751
+ const v = cfg?.mihomo.ipv6;
1752
+ return v === void 0 ? "未设置" : v ? "启用" : "禁用";
1753
+ },
1754
+ hint: "Enter 切换",
1755
+ needsDaemon: false,
1756
+ activate: () => this.pickIpv6()
1757
+ });
1758
+ items.push({
1759
+ kind: "row",
1760
+ label: "Lynx 日志级别",
1761
+ value: () => cfg?.log?.level ?? "info",
1762
+ hint: "Enter 切换(写入配置文件)",
1763
+ needsDaemon: false,
1764
+ activate: () => this.pickLynxLogLevel()
1765
+ });
1766
+ items.push({
1767
+ kind: "row",
1768
+ label: "访问日志",
1769
+ value: () => cfg?.log?.access ?? true ? "开启" : "关闭",
1770
+ hint: "Enter 切换",
1771
+ needsDaemon: false,
1772
+ activate: () => this.toggleAccessLog()
1773
+ });
1774
+ items.push({
1775
+ kind: "header",
1776
+ label: "关于"
1777
+ });
1778
+ items.push({
1779
+ kind: "text",
1780
+ render: () => ` ${pc.dim("版本")} lynx ${lynxVersion()} · Node ${process.versions.node}`
1781
+ });
1782
+ items.push({
1783
+ kind: "text",
1784
+ render: () => ` ${pc.dim("配置目录")} ${getLynxHome()}`
1785
+ });
1786
+ return items;
1787
+ }
1788
+ render(width) {
1789
+ this.items = this.buildItems();
1790
+ const selectable = this.selectableIndexes();
1791
+ this.cursor = Math.min(this.cursor, Math.max(0, selectable.length - 1));
1792
+ const activeIdx = selectable[this.cursor];
1793
+ const out = [];
1794
+ const labelWidth = 16;
1795
+ for (let i = 0; i < this.items.length; i += 1) {
1796
+ const item = this.items[i];
1797
+ if (item.kind === "header") {
1798
+ if (out.length > 0) out.push("");
1799
+ out.push(pc.bold(pc.cyan(` ${item.label}`)));
1800
+ out.push(pc.dim(` ${"─".repeat(Math.max(0, Math.min(width - 2, 68)))}`));
1801
+ continue;
1802
+ }
1803
+ if (item.kind === "text") {
1804
+ out.push(item.render());
1805
+ continue;
1806
+ }
1807
+ const disabled = item.needsDaemon && !this.online;
1808
+ const line = `${` ${item.label.replace(/^(切换|设置)/, "").padEnd(labelWidth)} ${item.value()}`}${pc.dim(` ${item.hint}`)}`;
1809
+ if (i === activeIdx) out.push(pc.inverse(fitLine(line, width)));
1810
+ else if (disabled) out.push(pc.dim(line));
1811
+ else out.push(line);
1812
+ }
1813
+ if (!this.online) {
1814
+ out.push("");
1815
+ out.push(pc.dim(" daemon 未运行:配置修改写入文件,下次启动生效(S 启动)"));
1816
+ }
1817
+ return out.map((line) => fitLine(line, width));
1818
+ }
1819
+ invalidate() {}
1820
+ };
1821
+ /** 从 package.json 读取 lynx 版本(与 src/index.ts 的 printVersion 一致)。 */
1822
+ function lynxVersion() {
1823
+ try {
1824
+ const here = dirname(fileURLToPath(import.meta.url));
1825
+ return JSON.parse(readFileSync(resolve(here, "..", "package.json"), "utf8")).version ?? "unknown";
1826
+ } catch {
1827
+ return "unknown";
1828
+ }
1829
+ }
1830
+ //#endregion
1831
+ //#region src/tui/widgets/help-overlay.ts
1832
+ function panelLabel(panel) {
1833
+ return PANELS.find((p) => p.id === panel)?.label ?? panel;
1834
+ }
1835
+ function globalKeys() {
1836
+ return [
1837
+ [PANELS.map((p) => p.hotkey).join("…"), "切换面板"],
1838
+ ["R", "重载订阅"],
1839
+ ["S / s", "启停 daemon"],
1840
+ ["?", "帮助"],
1841
+ ["q / Ctrl+c", "退出"]
1842
+ ];
1843
+ }
1844
+ /**
1845
+ * 帮助浮层:分组展示全局键与当前面板键,替换旧版 ? 的一行 flash。
1846
+ * Esc / Enter / ? / q 关闭。宽度固定,按内容自适应高度。
1847
+ */
1848
+ var HelpOverlay = class HelpOverlay {
1849
+ finish;
1850
+ focused = true;
1851
+ lines;
1852
+ constructor(panel, panelHints, finish) {
1853
+ this.finish = finish;
1854
+ this.lines = HelpOverlay.buildLines(panel, panelHints);
1855
+ }
1856
+ static buildLines(panel, panelHints) {
1857
+ const label = panelLabel(panel);
1858
+ const out = [];
1859
+ out.push(pc.bold(pc.cyan("帮助")));
1860
+ out.push("");
1861
+ out.push(pc.bold("全局"));
1862
+ for (const [key, desc] of globalKeys()) out.push(` ${pc.yellow(key.padEnd(12))} ${desc}`);
1863
+ out.push("");
1864
+ out.push(pc.bold(`当前面板:${label}`));
1865
+ for (const hint of panelHints) out.push(` ${hint}`);
1866
+ out.push("");
1867
+ out.push(pc.dim("[Esc/Enter] 关闭"));
1868
+ return out;
1869
+ }
1870
+ handleInput(data) {
1871
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.enter) || data === "q" || data === "?") this.finish();
1872
+ }
1873
+ render(width) {
1874
+ return this.lines.map((line) => fitLine(line, width));
1875
+ }
1876
+ invalidate() {}
1877
+ contentWidth() {
1878
+ return this.lines.reduce((max, line) => Math.max(max, visibleWidth(line)), 0);
1879
+ }
1880
+ lineCount() {
1881
+ return this.lines.length;
1882
+ }
1883
+ };
1884
+ /** 打开帮助浮层,返回在用户关闭后 resolve 的 Promise。 */
1885
+ function showHelp(tui, panel, panelHints) {
1886
+ return new Promise((resolve) => {
1887
+ let settled = false;
1888
+ const overlay = new HelpOverlay(panel, panelHints, () => {
1889
+ if (settled) return;
1890
+ settled = true;
1891
+ handle.hide();
1892
+ resolve();
1893
+ });
1894
+ const width = Math.min(52, Math.max(36, overlay.contentWidth() + 4));
1895
+ const handle = tui.showOverlay(overlay, {
1896
+ width,
1897
+ maxHeight: Math.min(24, overlay.lineCount() + 2),
1898
+ anchor: "center"
1899
+ });
1900
+ handle.focus();
1901
+ });
1902
+ }
1903
+ //#endregion
1904
+ //#region src/tui/app.ts
1905
+ const SIDEBAR_WIDTH = 16;
1906
+ const MIN_WIDTH = 60;
1907
+ const MIN_HEIGHT = 16;
1908
+ var App = class {
1909
+ tui;
1910
+ runtime;
1911
+ quit;
1912
+ focused = true;
1913
+ panels;
1914
+ constructor(tui, runtime, quit = () => {}) {
1915
+ this.tui = tui;
1916
+ this.runtime = runtime;
1917
+ this.quit = quit;
1918
+ this.panels = {
1919
+ overview: new OverviewPanel(runtime, tui),
1920
+ proxies: new ProxiesPanel(runtime),
1921
+ connections: new ConnectionsPanel(runtime),
1922
+ logs: new LogsPanel(runtime),
1923
+ settings: new SettingsPanel(runtime, tui)
1924
+ };
1925
+ }
1926
+ get activePanel() {
1927
+ return this.panels[this.runtime.state.panel];
1928
+ }
1929
+ handleInput(data) {
1930
+ if (matchesKey(data, Key.ctrl("c")) || data === "q") {
1931
+ this.quit(0);
1932
+ return;
1933
+ }
1934
+ if (matchesKey(data, "?") || data === "?") {
1935
+ showHelp(this.tui, this.runtime.state.panel, this.activePanel.hints());
1936
+ return;
1937
+ }
1938
+ const target = PANELS.find((p) => p.hotkey === data);
1939
+ if (target !== void 0) {
1940
+ this.switchPanel(target.id);
1941
+ return;
1942
+ }
1943
+ if (data === "R") {
1944
+ this.runtime.reload();
1945
+ return;
1946
+ }
1947
+ if (data === "S" || data === "s") {
1948
+ if (this.runtime.state.daemon === "running") this.runtime.stopDaemon();
1949
+ else if (this.runtime.state.daemon === "stopped" || this.runtime.state.secretMissing) this.runtime.startDaemon();
1950
+ return;
1951
+ }
1952
+ this.activePanel.handleInput?.(data);
1953
+ }
1954
+ switchPanel(panel) {
1955
+ if (panel === this.runtime.state.panel) return;
1956
+ this.activePanel.deactivate?.();
1957
+ this.runtime.setPanel(panel);
1958
+ this.panels[panel].activate?.({
1959
+ runtime: this.runtime,
1960
+ tui: this.tui
1961
+ });
1962
+ }
1963
+ render(width) {
1964
+ const height = this.tui.terminal.rows;
1965
+ this.runtime.state.width = width;
1966
+ this.runtime.state.height = height;
1967
+ if (width < MIN_WIDTH || height < MIN_HEIGHT) return [fitLine(pc.yellow(`终端过小(至少 ${MIN_WIDTH}×${MIN_HEIGHT}),请放大窗口`), width)];
1968
+ const top = this.renderTopBar(width);
1969
+ const bottom = this.renderBottomBar(width);
1970
+ const bodyHeight = height - 2;
1971
+ const contentWidth = width - SIDEBAR_WIDTH - 1;
1972
+ const content = this.activePanel.render(contentWidth);
1973
+ if (this.runtime.state.panel === "proxies") this.panels.proxies.setHeight(bodyHeight);
1974
+ if (this.runtime.state.panel === "connections") this.panels.connections.setBodyHeight(bodyHeight);
1975
+ if (this.runtime.state.panel === "logs") this.panels.logs.setBodyHeight(bodyHeight);
1976
+ return [
1977
+ top,
1978
+ ...sideBySide({
1979
+ left: this.renderSidebar(bodyHeight),
1980
+ right: content,
1981
+ leftWidth: SIDEBAR_WIDTH,
1982
+ width,
1983
+ height: bodyHeight
1984
+ }),
1985
+ bottom
1986
+ ];
1987
+ }
1988
+ renderTopBar(width) {
1989
+ const s = this.runtime.state;
1990
+ const ov = s.overview;
1991
+ const profile = ov.profileName ?? "无 profile";
1992
+ const kernel = ov.version?.version ?? ov.kernelVersion ?? "-";
1993
+ const coloredStatus = statusColor(s.daemon)(s.daemon);
1994
+ const left = pc.black(` LynxProxy · ${profile} · ${kernel} · ${statusDot[s.daemon]} ${coloredStatus}`);
1995
+ const right = pc.black(` ↑${formatRate(s.upRate)} ↓${formatRate(s.downRate)} `);
1996
+ const gap = Math.max(1, width - visibleWidth(left) - visibleWidth(right));
1997
+ const content = left + " ".repeat(gap) + right;
1998
+ const line = pc.bgCyan(content);
1999
+ if (s.error !== void 0) return fitLine(pc.bgRed(pc.black(` ${s.error} `)), width);
2000
+ return fitLine(line, width);
2001
+ }
2002
+ renderSidebar(height) {
2003
+ const s = this.runtime.state;
2004
+ const lines = [];
2005
+ lines.push(theme.title(" LynxProxy"));
2006
+ lines.push("");
2007
+ for (const panel of PANELS) {
2008
+ const active = panel.id === s.panel;
2009
+ const label = `${panel.hotkey}. ${panel.label}`;
2010
+ lines.push(active ? theme.sidebarActive(label) : pc.dim(` ${label}`));
2011
+ }
2012
+ lines.push("");
2013
+ lines.push("");
2014
+ const daemonLine = ` ${statusDot[s.daemon]} ${s.daemon}`;
2015
+ lines.push(daemonLine);
2016
+ if (s.daemonState !== void 0) lines.push(pc.dim(` :${s.daemonState.port}`));
2017
+ lines.push("");
2018
+ lines.push(pc.dim(" R 重载"));
2019
+ lines.push(pc.dim(" S 启停"));
2020
+ lines.push(pc.dim(" ? 帮助"));
2021
+ lines.push(pc.dim(" q 退出"));
2022
+ while (lines.length < height) lines.push("");
2023
+ return lines.slice(0, height);
2024
+ }
2025
+ renderBottomBar(width) {
2026
+ const s = this.runtime.state;
2027
+ const hints = this.activePanel.hints();
2028
+ const flash = s.flash !== void 0 ? pc.yellow(s.flash) : "";
2029
+ const parts = flash.length > 0 ? [...hints, flash] : hints;
2030
+ return fitLine(pc.dim(` ${parts.join(" │ ")}`), width);
2031
+ }
2032
+ invalidate() {
2033
+ for (const panel of Object.values(this.panels)) panel.invalidate();
2034
+ }
2035
+ };
2036
+ //#endregion
2037
+ //#region src/config/lynx-config.ts
2038
+ /** lynx.json 完整路径。 */
2039
+ function getConfigPath() {
2040
+ return join(getLynxHome(), "lynx.json");
2041
+ }
2042
+ /** 加载 lynx.json。不存在时创建默认配置。 */
2043
+ function loadLynxConfig() {
2044
+ const path = getConfigPath();
2045
+ if (!existsSync(path)) {
2046
+ const config = getDefaultConfig();
2047
+ writeLynxConfig(config);
2048
+ return config;
2049
+ }
2050
+ try {
2051
+ const raw = readFileSync(path, "utf8");
2052
+ return applyDefaults(JSON.parse(raw));
2053
+ } catch (error) {
2054
+ throw new ConfigError(`Failed to load lynx.json: ${errorMessage(error)}`);
2055
+ }
2056
+ }
2057
+ /** 写入 lynx.json。 */
2058
+ function writeLynxConfig(config) {
2059
+ mkdirSync(getLynxHome(), { recursive: true });
2060
+ writeFileSync(getConfigPath(), `${JSON.stringify(config, null, 2)}\n`, "utf8");
2061
+ }
2062
+ /** 创建默认配置。 */
2063
+ function getDefaultConfig() {
2064
+ return {
2065
+ version: 1,
2066
+ listen: "127.0.0.1:7890",
2067
+ mihomo: {
2068
+ "mixed-port": 7891,
2069
+ "external-controller": "127.0.0.1:9090",
2070
+ "auto-update": true
2071
+ },
2072
+ "system-proxy": false,
2073
+ log: {
2074
+ level: "info",
2075
+ access: true
2076
+ }
2077
+ };
2078
+ }
2079
+ function applyDefaults(parsed) {
2080
+ const mihomo = parsed.mihomo ?? {};
2081
+ const subscriptionUa = parsed.subscription?.user_agent;
2082
+ const subscription = {};
2083
+ if (typeof subscriptionUa === "string") subscription.user_agent = subscriptionUa;
2084
+ return {
2085
+ version: 1,
2086
+ listen: parsed.listen ?? "127.0.0.1:7890",
2087
+ mihomo: {
2088
+ "mixed-port": mihomo["mixed-port"] ?? 7891,
2089
+ "external-controller": mihomo["external-controller"] ?? "127.0.0.1:9090",
2090
+ "auto-update": mihomo["auto-update"] ?? true,
2091
+ ...mihomo.secret !== void 0 ? { secret: mihomo.secret } : {},
2092
+ ...mihomo["bin-dir"] !== void 0 ? { "bin-dir": mihomo["bin-dir"] } : {},
2093
+ ...mihomo.kernel !== void 0 ? { kernel: mihomo.kernel } : {},
2094
+ ...typeof mihomo.ipv6 === "boolean" ? { ipv6: mihomo.ipv6 } : {},
2095
+ ...isMode(mihomo.mode) ? { mode: mihomo.mode } : {}
2096
+ },
2097
+ "system-proxy": parsed["system-proxy"] ?? false,
2098
+ log: parsed.log ?? {
2099
+ level: "info",
2100
+ access: true
2101
+ },
2102
+ ...Object.keys(subscription).length > 0 ? { subscription } : {}
2103
+ };
2104
+ }
2105
+ const MODES = [
2106
+ "rule",
2107
+ "global",
2108
+ "direct",
2109
+ "script"
2110
+ ];
2111
+ function isMode(value) {
2112
+ return typeof value === "string" && MODES.includes(value);
2113
+ }
2114
+ //#endregion
2115
+ //#region src/mihomo/mihomo-api.ts
2116
+ var MihomoApiError = class extends Error {
2117
+ status;
2118
+ data;
2119
+ constructor(message, status, data) {
2120
+ super(message);
2121
+ this.name = "MihomoApiError";
2122
+ this.status = status;
2123
+ this.data = data;
2124
+ }
2125
+ };
2126
+ /**
2127
+ * mihomo REST API 客户端。
2128
+ * 完整封装 mihomo 外部控制器 HTTP 端点,使用 Bearer token 认证。
2129
+ *
2130
+ * 所有公共方法返回具体类型,错误统一抛 {@link MihomoApiError}。
2131
+ *
2132
+ * WebSocket 端点(/traffic, /logs)不在此类中,需另行实现 WebSocket 连接。
2133
+ */
2134
+ var MihomoApiClient = class {
2135
+ baseUrl;
2136
+ secret;
2137
+ /** 默认请求超时(毫秒) */
2138
+ timeout;
2139
+ constructor(host, port, secret, timeout = 5e3) {
2140
+ this.baseUrl = `http://${host}:${port}`;
2141
+ this.secret = secret;
2142
+ this.timeout = timeout;
2143
+ }
2144
+ /** 健康检查:GET /version */
2145
+ async isReady() {
2146
+ try {
2147
+ await this.request("/version", "GET");
2148
+ return true;
2149
+ } catch {
2150
+ return false;
2151
+ }
2152
+ }
2153
+ /** 获取 mihomo 版本信息:GET /version */
2154
+ async getVersion() {
2155
+ return this.request("/version", "GET");
2156
+ }
2157
+ /** 重载配置:PUT /configs?force=true */
2158
+ async reloadConfig() {
2159
+ await this.request("/configs?force=true", "PUT", { path: "" });
2160
+ }
2161
+ /** 重启 mihomo:POST /restart */
2162
+ async restart() {
2163
+ await this.request("/restart", "POST");
2164
+ }
2165
+ /** 获取所有代理和组状态:GET /proxies */
2166
+ async getProxies() {
2167
+ return this.request("/proxies", "GET");
2168
+ }
2169
+ /** 获取单个代理或组详情:GET /proxies/{name} */
2170
+ async getProxy(name) {
2171
+ return this.request(`/proxies/${encodeURIComponent(name)}`, "GET");
2172
+ }
2173
+ /** 设置代理组选中的节点:PUT /proxies/{groupName} */
2174
+ async selectProxy(groupName, proxyName) {
2175
+ await this.request(`/proxies/${encodeURIComponent(groupName)}`, "PUT", { name: proxyName });
2176
+ }
2177
+ /** 测试节点延迟:GET /proxies/{name}/delay?url=...&timeout=... */
2178
+ async getProxyDelay(name, url = "http://www.gstatic.com/generate_204", timeout = 5e3) {
2179
+ const params = new URLSearchParams({
2180
+ url,
2181
+ timeout: String(timeout)
2182
+ });
2183
+ return this.request(`/proxies/${encodeURIComponent(name)}/delay?${params.toString()}`, "GET");
2184
+ }
2185
+ /**
2186
+ * 获取所有代理组详情:GET /groups
2187
+ *
2188
+ * 与 /proxies 不同,/groups 只返回代理组(Selector / URLTest / Fallback 等),
2189
+ * 不包含普通代理节点。
2190
+ */
2191
+ async getGroups() {
2192
+ return (await this.request("/groups", "GET")).groups;
2193
+ }
2194
+ /** 获取所有活跃连接及累计流量:GET /connections */
2195
+ async getConnections() {
2196
+ return this.request("/connections", "GET");
2197
+ }
2198
+ /** 断开所有连接:DELETE /connections */
2199
+ async closeConnections() {
2200
+ await this.request("/connections", "DELETE");
2201
+ }
2202
+ /** 断开指定连接:DELETE /connections/{id} */
2203
+ async closeConnection(id) {
2204
+ await this.request(`/connections/${encodeURIComponent(id)}`, "DELETE");
2205
+ }
2206
+ /** 获取当前运行配置:GET /configs */
2207
+ async getConfigs() {
2208
+ return this.request("/configs", "GET");
2209
+ }
2210
+ /** 更新运行配置(如 mode):PATCH /configs */
2211
+ async patchConfigs(patch) {
2212
+ await this.request("/configs", "PATCH", patch);
2213
+ }
2214
+ /** 获取规则匹配统计:GET /rules */
2215
+ async getRules() {
2216
+ return this.request("/rules", "GET");
2217
+ }
2218
+ /** 获取所有 proxy provider:GET /providers/proxies */
2219
+ async getProxyProviders() {
2220
+ return this.request("/providers/proxies", "GET");
2221
+ }
2222
+ /** 刷新单个 proxy provider:PUT /providers/proxies/{name} */
2223
+ async refreshProxyProvider(name) {
2224
+ await this.request(`/providers/proxies/${encodeURIComponent(name)}`, "PUT");
2225
+ }
2226
+ /** 获取所有 rule provider:GET /providers/rules */
2227
+ async getRuleProviders() {
2228
+ return this.request("/providers/rules", "GET");
2229
+ }
2230
+ /** 刷新单个 rule provider:PUT /providers/rules/{name} */
2231
+ async refreshRuleProvider(name) {
2232
+ await this.request(`/providers/rules/${encodeURIComponent(name)}`, "PUT");
2233
+ }
2234
+ /**
2235
+ * DNS 查询:GET /dns/query?name={name}&type={type}
2236
+ * @param name 要查询的域名
2237
+ * @param type 记录类型(如 "A", "AAAA", "TXT"),默认 "A"
2238
+ */
2239
+ async dnsQuery(name, type = "A") {
2240
+ const params = new URLSearchParams({
2241
+ name,
2242
+ type
2243
+ });
2244
+ return this.request(`/dns/query?${params.toString()}`, "GET");
2245
+ }
2246
+ /** 获取 FakeIP 缓存:GET /cache/fakeip */
2247
+ async getFakeIpCache() {
2248
+ return this.request("/cache/fakeip", "GET");
2249
+ }
2250
+ /** 清空 FakeIP 缓存:DELETE /cache/fakeip */
2251
+ async flushFakeIpCache() {
2252
+ await this.request("/cache/fakeip", "DELETE");
2253
+ }
2254
+ /** 获取当前日志级别:GET /logs/level */
2255
+ async getLogLevel() {
2256
+ return this.request("/logs/level", "GET");
2257
+ }
2258
+ /**
2259
+ * 设置日志级别:PATCH /logs/level
2260
+ * @param level 日志级别 "debug" | "info" | "warn" | "error"
2261
+ */
2262
+ async setLogLevel(level) {
2263
+ await this.request("/logs/level", "PATCH", { level });
2264
+ }
2265
+ /** 获取内存使用统计:GET /memory */
2266
+ async getMemory() {
2267
+ return this.request("/memory", "GET");
2268
+ }
2269
+ /** 升级 mihomo 内核:PUT /upgrade */
2270
+ async upgradeCore() {
2271
+ return this.request("/upgrade", "PUT");
2272
+ }
2273
+ /** 升级 Geo 数据库:PUT /upgrade/geo */
2274
+ async upgradeGeo() {
2275
+ return this.request("/upgrade/geo", "PUT");
2276
+ }
2277
+ /**
2278
+ * 获取 pprof 性能分析数据:GET /debug/pprof/{name}
2279
+ *
2280
+ * 返回原始二进制数据(ArrayBuffer),适用于:
2281
+ * - goroutine — 协程栈
2282
+ * - heap — 堆分配
2283
+ * - allocs — 分配统计
2284
+ * - threadcreate — 线程创建
2285
+ * - block — 阻塞分析
2286
+ * - mutex — 互斥锁
2287
+ * - profile — CPU 分析(配合 seconds 参数)
2288
+ * - trace — 执行追踪(配合 seconds 参数)
2289
+ *
2290
+ * @param name 分析类型名称,如 "heap", "goroutine", "profile"
2291
+ * @param seconds CPU profile / trace 的采样时长(秒)
2292
+ */
2293
+ async getPprof(name, seconds) {
2294
+ let path = `/debug/pprof/${encodeURIComponent(name)}`;
2295
+ if (seconds !== void 0) path += `?seconds=${seconds}`;
2296
+ const config = {
2297
+ method: "GET",
2298
+ url: `${this.baseUrl}${path}`,
2299
+ headers: { Authorization: `Bearer ${this.secret}` },
2300
+ timeout: (seconds ?? 30) * 1e3 + 5e3,
2301
+ responseType: "arraybuffer"
2302
+ };
2303
+ try {
2304
+ return (await axios(config)).data;
2305
+ } catch (error) {
2306
+ if (axios.isAxiosError(error)) {
2307
+ const status = error.response?.status;
2308
+ throw new MihomoApiError(`pprof error (${status ?? "unknown"}): ${error.message}`, status);
2309
+ }
2310
+ throw new MihomoApiError(`pprof request failed: ${String(error)}`);
2311
+ }
2312
+ }
2313
+ /**
2314
+ * 统一 HTTP 请求底层方法(JSON 响应)。
2315
+ * - 自动注入 Bearer token
2316
+ * - 错误统一抛 {@link MihomoApiError}
2317
+ * - 返回解析后的 JSON 响应体
2318
+ */
2319
+ async request(path, method, body) {
2320
+ const config = {
2321
+ method,
2322
+ url: `${this.baseUrl}${path}`,
2323
+ headers: { Authorization: `Bearer ${this.secret}` },
2324
+ timeout: this.timeout
2325
+ };
2326
+ if (body !== void 0) {
2327
+ config.headers = {
2328
+ ...config.headers,
2329
+ "Content-Type": "application/json"
2330
+ };
2331
+ config.data = body;
2332
+ }
2333
+ try {
2334
+ return (await axios(config)).data;
2335
+ } catch (error) {
2336
+ if (axios.isAxiosError(error)) {
2337
+ const status = error.response?.status;
2338
+ const data = error.response?.data;
2339
+ throw new MihomoApiError(`mihomo API error (${status ?? "unknown"}): ${data !== void 0 ? JSON.stringify(data) : error.message}`, status, data);
2340
+ }
2341
+ throw new MihomoApiError(`mihomo API request failed: ${String(error)}`);
2342
+ }
2343
+ }
2344
+ };
2345
+ //#endregion
2346
+ //#region src/utils/process.ts
2347
+ /**
2348
+ * 判断给定 PID 的进程是否存活。
2349
+ *
2350
+ * `process.kill(pid, 0)` 不发送真实信号,只做存在性与权限探测:
2351
+ * - 成功 → 进程存在
2352
+ * - `ESRCH` → 进程不存在
2353
+ * - `EPERM` → 进程**存在**,但当前用户无权向它发信号(如换用户后残留的 daemon)
2354
+ *
2355
+ * 因此 EPERM 必须视为"存活"。把它当成"已退出"会导致等待退出的逻辑立即返回,
2356
+ * 误判进程已结束。
2357
+ */
2358
+ function isPidAlive(pid) {
2359
+ try {
2360
+ process.kill(pid, 0);
2361
+ return true;
2362
+ } catch (error) {
2363
+ return (typeof error === "object" && error !== null ? error.code : void 0) === "EPERM";
2364
+ }
2365
+ }
2366
+ //#endregion
2367
+ //#region src/runtime/daemon-state.ts
2368
+ const LYNX_HOME = getLynxHome();
2369
+ function getProxyDaemonStatePath() {
2370
+ return join(LYNX_HOME, "runtime", "proxy-daemon.json");
2371
+ }
2372
+ function getProxyDaemonLogPath() {
2373
+ return join(LYNX_HOME, "runtime", "proxy-daemon.log");
2374
+ }
2375
+ function getControlSocketPath() {
2376
+ return join(LYNX_HOME, "runtime", "control.sock");
2377
+ }
2378
+ function loadProxyDaemonState(path = getProxyDaemonStatePath()) {
2379
+ if (!existsSync(path)) return;
2380
+ const raw = JSON.parse(readFileSync(path, "utf8"));
2381
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("proxy daemon state must be an object");
2382
+ const object = raw;
2383
+ if (object["version"] !== 1) throw new Error("proxy daemon state version must be 1");
2384
+ const pid = object["pid"];
2385
+ const host = object["host"];
2386
+ const port = object["port"];
2387
+ const startedAt = object["startedAt"];
2388
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) throw new Error("proxy daemon state pid must be a positive integer");
2389
+ if (typeof host !== "string" || host.length === 0) throw new Error("proxy daemon state host must be a non-empty string");
2390
+ if (typeof port !== "number" || !Number.isInteger(port) || port <= 0) throw new Error("proxy daemon state port must be a positive integer");
2391
+ if (typeof startedAt !== "string" || startedAt.length === 0) throw new Error("proxy daemon state startedAt must be a non-empty string");
2392
+ const state = {
2393
+ version: 1,
2394
+ pid,
2395
+ host,
2396
+ port,
2397
+ startedAt
2398
+ };
2399
+ if (typeof object["logFile"] === "string") state.logFile = object["logFile"];
2400
+ if (typeof object["profile"] === "string") state.profile = object["profile"];
2401
+ if (typeof object["profilePath"] === "string") state.profilePath = object["profilePath"];
2402
+ const hasExtHost = object["extHost"] !== void 0;
2403
+ const hasExtPort = object["extPort"] !== void 0;
2404
+ const hasSecret = object["secret"] !== void 0;
2405
+ if (hasExtHost || hasExtPort || hasSecret) {
2406
+ if (typeof object["extHost"] !== "string" || object["extHost"].length === 0) throw new Error("proxy daemon state extHost must be a non-empty string");
2407
+ if (typeof object["extPort"] !== "number" || !Number.isInteger(object["extPort"]) || object["extPort"] <= 0) throw new Error("proxy daemon state extPort must be a positive integer");
2408
+ if (typeof object["secret"] !== "string" || object["secret"].length === 0) throw new Error("proxy daemon state secret must be a non-empty string");
2409
+ state.extHost = object["extHost"];
2410
+ state.extPort = object["extPort"];
2411
+ state.secret = object["secret"];
2412
+ }
2413
+ return state;
2414
+ }
2415
+ function removeProxyDaemonState(path = getProxyDaemonStatePath()) {
2416
+ rmSync(path, { force: true });
2417
+ }
2418
+ function isProcessRunning(pid) {
2419
+ if (!isPidAlive(pid)) return false;
2420
+ if (process.platform === "linux") try {
2421
+ const cmdline = readFileSync(`/proc/${pid}/cmdline`, "utf8");
2422
+ return cmdline.includes("proxy") && cmdline.includes("run-daemon");
2423
+ } catch {
2424
+ return false;
2425
+ }
2426
+ return true;
2427
+ }
2428
+ //#endregion
2429
+ //#region src/runtime/control-client.ts
2430
+ /**
2431
+ * 向 daemon 控制通道发送一条命令并返回响应。
2432
+ *
2433
+ * 单次请求/单次响应:发送后收到第一行响应即关闭连接。
2434
+ * socket 文件不存在或连接被拒(daemon 未运行)时返回 undefined。
2435
+ */
2436
+ function sendControlCommand(command, socketPath = getControlSocketPath()) {
2437
+ if (!existsSync(socketPath)) return Promise.resolve(void 0);
2438
+ return new Promise((resolve, reject) => {
2439
+ const socket = createConnection(socketPath);
2440
+ let buffer = "";
2441
+ socket.setEncoding("utf8");
2442
+ socket.on("connect", () => {
2443
+ socket.write(`${JSON.stringify(command)}\n`);
2444
+ });
2445
+ socket.on("data", (chunk) => {
2446
+ buffer += chunk;
2447
+ const nl = buffer.indexOf("\n");
2448
+ if (nl !== -1) {
2449
+ socket.end();
2450
+ try {
2451
+ resolve(JSON.parse(buffer.slice(0, nl)));
2452
+ } catch {
2453
+ resolve(void 0);
2454
+ }
2455
+ }
2456
+ });
2457
+ socket.on("error", (error) => {
2458
+ if (error.code === "ECONNREFUSED" || error.code === "ENOENT") {
2459
+ resolve(void 0);
2460
+ return;
2461
+ }
2462
+ reject(error);
2463
+ });
2464
+ });
2465
+ }
2466
+ /** 检测控制 socket 是否有 daemon 在监听。Windows 上恒为 false(无 unix socket)。 */
2467
+ function isControlSocketReady(socketPath = getControlSocketPath()) {
2468
+ if (!existsSync(socketPath)) return Promise.resolve(false);
2469
+ return new Promise((resolve) => {
2470
+ const probe = createConnection(socketPath);
2471
+ const done = (ready) => {
2472
+ probe.destroy();
2473
+ resolve(ready);
2474
+ };
2475
+ probe.once("connect", () => done(true));
2476
+ probe.once("error", () => done(false));
2477
+ });
2478
+ }
2479
+ //#endregion
2480
+ //#region src/system-proxy/base.ts
2481
+ const execFile$1 = promisify(execFile);
2482
+ var SystemProxyError = class extends Error {
2483
+ controller;
2484
+ constructor(message, controller, options) {
2485
+ super(message, options);
2486
+ this.name = "SystemProxyError";
2487
+ this.controller = controller;
2488
+ }
2489
+ };
2490
+ /**
2491
+ * 执行一条命令并返回 stdout。非零退出码或命令不存在时抛 SystemProxyError,
2492
+ * 由调用方决定是降级(detect)还是上抛(enable/disable)。
2493
+ */
2494
+ async function runCommand(controller, file, args) {
2495
+ try {
2496
+ const { stdout } = await execFile$1(file, [...args]);
2497
+ return stdout;
2498
+ } catch (error) {
2499
+ const execError = error;
2500
+ const code = execError?.code ?? "unknown";
2501
+ const stderr = typeof execError?.stderr === "string" ? execError.stderr.trim() : "";
2502
+ const detail = stderr.length > 0 ? `: ${stderr}` : "";
2503
+ throw new SystemProxyError(`${controller}: \`${file} ${args.join(" ")}\` failed (${code})${detail}`, controller, { cause: error });
2504
+ }
2505
+ }
2506
+ //#endregion
2507
+ //#region src/system-proxy/linux.ts
2508
+ const GNOME_SCHEMA = "org.gnome.system.proxy";
2509
+ const GNOME_HTTP_SCHEMA = "org.gnome.system.proxy.http";
2510
+ /** GNOME 桌面:通过 gsettings 写 org.gnome.system.proxy。 */
2511
+ const gnomeController = {
2512
+ name: "gnome",
2513
+ async detect() {
2514
+ try {
2515
+ await runCommand("gnome", "gsettings", [
2516
+ "get",
2517
+ GNOME_SCHEMA,
2518
+ "mode"
2519
+ ]);
2520
+ return true;
2521
+ } catch {
2522
+ return false;
2523
+ }
2524
+ },
2525
+ async enable(host, port) {
2526
+ await runCommand("gnome", "gsettings", [
2527
+ "set",
2528
+ GNOME_SCHEMA,
2529
+ "mode",
2530
+ "manual"
2531
+ ]);
2532
+ await runCommand("gnome", "gsettings", [
2533
+ "set",
2534
+ GNOME_HTTP_SCHEMA,
2535
+ "host",
2536
+ host
2537
+ ]);
2538
+ await runCommand("gnome", "gsettings", [
2539
+ "set",
2540
+ GNOME_HTTP_SCHEMA,
2541
+ "port",
2542
+ String(port)
2543
+ ]);
2544
+ },
2545
+ async disable() {
2546
+ await runCommand("gnome", "gsettings", [
2547
+ "set",
2548
+ GNOME_SCHEMA,
2549
+ "mode",
2550
+ "none"
2551
+ ]);
2552
+ },
2553
+ async current() {
2554
+ try {
2555
+ if ((await runCommand("gnome", "gsettings", [
2556
+ "get",
2557
+ GNOME_SCHEMA,
2558
+ "mode"
2559
+ ])).trim() !== "'manual'") return;
2560
+ const host = stripGsettingsQuotes(await runCommand("gnome", "gsettings", [
2561
+ "get",
2562
+ GNOME_HTTP_SCHEMA,
2563
+ "host"
2564
+ ]));
2565
+ const port = Number.parseInt((await runCommand("gnome", "gsettings", [
2566
+ "get",
2567
+ GNOME_HTTP_SCHEMA,
2568
+ "port"
2569
+ ])).trim(), 10);
2570
+ if (host.length === 0 || !Number.isInteger(port)) return;
2571
+ return {
2572
+ host,
2573
+ port
2574
+ };
2575
+ } catch {
2576
+ return;
2577
+ }
2578
+ }
2579
+ };
2580
+ const KDE_FILE = "kioslaverc";
2581
+ const KDE_GROUP = "Proxy Settings";
2582
+ /** KDE Plasma 6:通过 kwriteconfig6 写 kioslaverc,并 dbus 通知重载。 */
2583
+ const kdeController = {
2584
+ name: "kde",
2585
+ async detect() {
2586
+ try {
2587
+ await runCommand("kde", "kwriteconfig6", ["--version"]);
2588
+ return true;
2589
+ } catch {
2590
+ return false;
2591
+ }
2592
+ },
2593
+ async enable(host, port) {
2594
+ const endpoint = `http://${host}:${port}`;
2595
+ await runCommand("kde", "kwriteconfig6", [
2596
+ "--file",
2597
+ KDE_FILE,
2598
+ "--group",
2599
+ KDE_GROUP,
2600
+ "--key",
2601
+ "ProxyType",
2602
+ "1"
2603
+ ]);
2604
+ await runCommand("kde", "kwriteconfig6", [
2605
+ "--file",
2606
+ KDE_FILE,
2607
+ "--group",
2608
+ KDE_GROUP,
2609
+ "--key",
2610
+ "httpProxy",
2611
+ endpoint
2612
+ ]);
2613
+ await runCommand("kde", "kwriteconfig6", [
2614
+ "--file",
2615
+ KDE_FILE,
2616
+ "--group",
2617
+ KDE_GROUP,
2618
+ "--key",
2619
+ "httpsProxy",
2620
+ endpoint
2621
+ ]);
2622
+ await notifyKde();
2623
+ },
2624
+ async disable() {
2625
+ await runCommand("kde", "kwriteconfig6", [
2626
+ "--file",
2627
+ KDE_FILE,
2628
+ "--group",
2629
+ KDE_GROUP,
2630
+ "--key",
2631
+ "ProxyType",
2632
+ "0"
2633
+ ]);
2634
+ await notifyKde();
2635
+ },
2636
+ async current() {
2637
+ try {
2638
+ if ((await runCommand("kde", "kreadconfig6", [
2639
+ "--file",
2640
+ KDE_FILE,
2641
+ "--group",
2642
+ KDE_GROUP,
2643
+ "--key",
2644
+ "ProxyType",
2645
+ "0"
2646
+ ])).trim() !== "1") return;
2647
+ return parseHttpEndpoint((await runCommand("kde", "kreadconfig6", [
2648
+ "--file",
2649
+ KDE_FILE,
2650
+ "--group",
2651
+ KDE_GROUP,
2652
+ "--key",
2653
+ "httpProxy"
2654
+ ])).trim());
2655
+ } catch {
2656
+ return;
2657
+ }
2658
+ }
2659
+ };
2660
+ /**
2661
+ * 通知 KDE 重载 kioslaverc。对已运行应用的即时性弱于 GNOME gsettings,
2662
+ * 部分应用需重启;通知失败不致命(写入已生效)。
2663
+ */
2664
+ async function notifyKde() {
2665
+ try {
2666
+ await runCommand("kde", "dbus-send", [
2667
+ "--session",
2668
+ "--type=signal",
2669
+ "/KIO/KTrader/knotify",
2670
+ "org.kde.KDirNotify.FilesChanged"
2671
+ ]);
2672
+ } catch {}
2673
+ }
2674
+ function stripGsettingsQuotes(raw) {
2675
+ const trimmed = raw.trim();
2676
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
2677
+ return trimmed;
2678
+ }
2679
+ function parseHttpEndpoint(raw) {
2680
+ const match = /^http:\/\/([^:/]+):(\d+)$/.exec(raw);
2681
+ if (match === null) return;
2682
+ const host = match[1];
2683
+ const port = Number.parseInt(match[2] ?? "", 10);
2684
+ if (host === void 0 || !Number.isInteger(port)) return;
2685
+ return {
2686
+ host,
2687
+ port
2688
+ };
2689
+ }
2690
+ //#endregion
2691
+ //#region src/system-proxy/macos.ts
2692
+ /** macOS:通过 networksetup 枚举所有网络服务逐个设置 HTTP/HTTPS 代理。 */
2693
+ const macosController = {
2694
+ name: "macos",
2695
+ async detect() {
2696
+ try {
2697
+ await runCommand("macos", "networksetup", ["-listallnetworkservices"]);
2698
+ return true;
2699
+ } catch {
2700
+ return false;
2701
+ }
2702
+ },
2703
+ async enable(host, port) {
2704
+ const services = await listNetworkServices();
2705
+ for (const service of services) {
2706
+ await runCommand("macos", "networksetup", [
2707
+ "-setwebproxy",
2708
+ service,
2709
+ host,
2710
+ String(port)
2711
+ ]);
2712
+ await runCommand("macos", "networksetup", [
2713
+ "-setsecurewebproxy",
2714
+ service,
2715
+ host,
2716
+ String(port)
2717
+ ]);
2718
+ }
2719
+ },
2720
+ async disable() {
2721
+ const services = await listNetworkServices();
2722
+ for (const service of services) {
2723
+ await runCommand("macos", "networksetup", [
2724
+ "-setwebproxystate",
2725
+ service,
2726
+ "off"
2727
+ ]);
2728
+ await runCommand("macos", "networksetup", [
2729
+ "-setsecurewebproxystate",
2730
+ service,
2731
+ "off"
2732
+ ]);
2733
+ }
2734
+ },
2735
+ async current() {
2736
+ const services = await listNetworkServices();
2737
+ for (const service of services) try {
2738
+ const endpoint = parseNetworksetupProxy(await runCommand("macos", "networksetup", ["-getwebproxy", service]));
2739
+ if (endpoint !== void 0) return endpoint;
2740
+ } catch {
2741
+ continue;
2742
+ }
2743
+ }
2744
+ };
2745
+ /**
2746
+ * 解析 `networksetup -listallnetworkservices` 输出:跳过首行标题与星标禁用项。
2747
+ */
2748
+ async function listNetworkServices() {
2749
+ return (await runCommand("macos", "networksetup", ["-listallnetworkservices"])).split("\n").slice(1).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("*"));
2750
+ }
2751
+ /**
2752
+ * 解析 `networksetup -getwebproxy <service>` 输出,仅在 Enabled: Yes 时返回端点。
2753
+ */
2754
+ function parseNetworksetupProxy(output) {
2755
+ if (!/Enabled:\s*Yes/i.test(output)) return;
2756
+ const host = /^Server:\s*(.+)$/m.exec(output)?.[1]?.trim();
2757
+ const portMatch = /^Port:\s*(\d+)$/m.exec(output)?.[1];
2758
+ const port = portMatch === void 0 ? NaN : Number.parseInt(portMatch, 10);
2759
+ if (host === void 0 || host.length === 0 || !Number.isInteger(port)) return;
2760
+ return {
2761
+ host,
2762
+ port
2763
+ };
2764
+ }
2765
+ //#endregion
2766
+ //#region src/system-proxy/windows.ts
2767
+ /**
2768
+ * Windows 系统代理层(注册表 InternetSettings + WM_SETTINGCHANGE)标记为 P2,
2769
+ * 本次仅占位。`detect()` 返回 false 使 daemon 跳过系统代理同步,由用户用
2770
+ * `lynx env on` 管理 CLI 入口。
2771
+ *
2772
+ * TODO(P2): 实现注册表 ProxyEnable/ProxyServer 写入与 WM_SETTINGCHANGE 广播。
2773
+ */
2774
+ const windowsController = {
2775
+ name: "windows",
2776
+ async detect() {
2777
+ return false;
2778
+ },
2779
+ async enable() {
2780
+ throw new SystemProxyError("Windows 系统代理层待实现,请用 `lynx env on`", "windows");
2781
+ },
2782
+ async disable() {},
2783
+ async current() {}
2784
+ };
2785
+ //#endregion
2786
+ //#region src/system-proxy/detect.ts
2787
+ /**
2788
+ * 按平台与可用工具选择首个 `detect()` 为 true 的系统代理控制器;都不支持时返回 undefined。
2789
+ */
2790
+ async function detectSystemProxyController() {
2791
+ for (const candidate of getCandidatesForPlatform()) try {
2792
+ if (await candidate.detect()) return candidate;
2793
+ } catch {
2794
+ continue;
2795
+ }
2796
+ }
2797
+ function getCandidatesForPlatform(platform = process.platform) {
2798
+ switch (platform) {
2799
+ case "linux": return [gnomeController, kdeController];
2800
+ case "darwin": return [macosController];
2801
+ case "win32": return [windowsController];
2802
+ default: return [];
2803
+ }
2804
+ }
2805
+ /**
2806
+ * 报告系统代理状态:enabled(指向某端点)/ disabled(无 manual 代理)/
2807
+ * not-supported(本机无可用系统代理 API)。
2808
+ */
2809
+ async function getSystemProxyStatus(controller) {
2810
+ if (controller === void 0) return "not-supported";
2811
+ try {
2812
+ if (await controller.current() !== void 0) return "enabled";
2813
+ return "disabled";
2814
+ } catch {
2815
+ return "disabled";
2816
+ }
2817
+ }
2818
+ //#endregion
2819
+ //#region src/runtime/daemon-lifecycle.ts
2820
+ const STOP_TIMEOUT_MS = 5e3;
2821
+ const SYSTEM_PROXY_ENV = "LYNX_SYSTEM_PROXY";
2822
+ const ALPHA_ENV = "LYNX_ALPHA";
2823
+ /**
2824
+ * 主 CLI 产物路径(dist/index.mjs)。
2825
+ *
2826
+ * 本模块会被主 CLI 与 TUI 两个 bundle 同时打包,但两者都位于 dist/ 下,
2827
+ * 因此相对本模块目录解析 index.mjs 在两种情况下都指向主 CLI。
2828
+ * 不能用 process.argv[1]——在 TUI 进程里它指向 tui.mjs,会导致递归自启。
2829
+ */
2830
+ const MAIN_CLI_ENTRY = resolve(dirname(fileURLToPath(import.meta.url)), "index.mjs");
2831
+ /**
2832
+ * 读取并校验 daemon state;state 文件损坏时清理并抛错(与原 CLI 行为一致)。
2833
+ */
2834
+ function readDaemonState() {
2835
+ try {
2836
+ return loadProxyDaemonState();
2837
+ } catch (error) {
2838
+ removeProxyDaemonState();
2839
+ throw new Error(`Invalid proxy daemon state removed: ${errorMessage(error)}`);
2840
+ }
2841
+ }
2842
+ /**
2843
+ * 以后台 detached 子进程启动 daemon(执行 `lynx proxy run-daemon`)。
2844
+ * 不打印任何内容;由调用方(CLI/TUI)决定如何呈现结果。
2845
+ */
2846
+ async function startDaemonDetached(options = {}) {
2847
+ const noSystemProxy = options.noSystemProxy ?? false;
2848
+ const alpha = options.alpha ?? false;
2849
+ const existing = readDaemonState();
2850
+ if (existing !== void 0) {
2851
+ if (isProcessRunning(existing.pid)) return {
2852
+ status: "already-running",
2853
+ pid: existing.pid,
2854
+ logFile: existing.logFile ?? getProxyDaemonLogPath(),
2855
+ listen: `${existing.host}:${existing.port}`,
2856
+ kernel: alpha ? "alpha" : "stable",
2857
+ systemProxySkipped: noSystemProxy
2858
+ };
2859
+ removeProxyDaemonState();
2860
+ }
2861
+ const lynxConfig = loadLynxConfig();
2862
+ const logFile = getProxyDaemonLogPath();
2863
+ mkdirSync(dirname(logFile), { recursive: true });
2864
+ const out = openSync(logFile, "a");
2865
+ const child = spawn(process.execPath, [
2866
+ MAIN_CLI_ENTRY,
2867
+ "proxy",
2868
+ "run-daemon"
2869
+ ], {
2870
+ detached: true,
2871
+ stdio: [
2872
+ "ignore",
2873
+ out,
2874
+ out
2875
+ ],
2876
+ windowsHide: true,
2877
+ env: {
2878
+ ...process.env,
2879
+ [SYSTEM_PROXY_ENV]: noSystemProxy ? "0" : "1",
2880
+ ...alpha ? { [ALPHA_ENV]: "1" } : {}
2881
+ }
2882
+ });
2883
+ child.unref();
2884
+ if (child.pid === void 0) throw new Error("Failed to start daemon: child process has no PID");
2885
+ return {
2886
+ status: "started",
2887
+ pid: child.pid,
2888
+ logFile,
2889
+ listen: lynxConfig.listen ?? "127.0.0.1:7890",
2890
+ kernel: alpha ? "alpha" : "stable",
2891
+ systemProxySkipped: noSystemProxy
2892
+ };
2893
+ }
2894
+ /**
2895
+ * 停止后台 daemon:SIGTERM 优雅退出,超时 SIGKILL,最后清理 state。
2896
+ * 默认在停止前清系统代理(除非 noSystemProxy)。
2897
+ */
2898
+ async function stopDaemon(options = {}) {
2899
+ const noSystemProxy = options.noSystemProxy ?? false;
2900
+ const state = readDaemonState();
2901
+ if (state === void 0) return { stopped: false };
2902
+ if (!isProcessRunning(state.pid)) {
2903
+ removeProxyDaemonState();
2904
+ return {
2905
+ stopped: false,
2906
+ staleRemoved: true,
2907
+ pid: state.pid
2908
+ };
2909
+ }
2910
+ if (!noSystemProxy) await clearSystemProxyEntry();
2911
+ process.kill(state.pid, "SIGTERM");
2912
+ let exited = await waitForExit(state.pid, STOP_TIMEOUT_MS);
2913
+ if (!exited) {
2914
+ try {
2915
+ process.kill(state.pid, "SIGKILL");
2916
+ } catch {}
2917
+ exited = await waitForExit(state.pid, STOP_TIMEOUT_MS);
2918
+ }
2919
+ removeProxyDaemonState();
2920
+ return {
2921
+ stopped: exited,
2922
+ pid: state.pid
2923
+ };
2924
+ }
2925
+ /**
2926
+ * 停止时清系统代理(best-effort,失败不抛错)。
2927
+ */
2928
+ async function clearSystemProxyEntry() {
2929
+ const controller = await detectSystemProxyController();
2930
+ if (controller === void 0) return;
2931
+ try {
2932
+ await controller.disable();
2933
+ } catch {}
2934
+ }
2935
+ function waitForExit(pid, timeoutMs) {
2936
+ return new Promise((resolve) => {
2937
+ const started = Date.now();
2938
+ const timer = setInterval(() => {
2939
+ if (!isProcessRunning(pid)) {
2940
+ clearInterval(timer);
2941
+ resolve(true);
2942
+ return;
2943
+ }
2944
+ if (Date.now() - started >= timeoutMs) {
2945
+ clearInterval(timer);
2946
+ resolve(false);
2947
+ }
2948
+ }, 100);
2949
+ });
2950
+ }
2951
+ /**
2952
+ * 轮询等待 daemon 就绪:state 已写入 extHost/extPort/secret 三字段,且 mihomo API 可连通。
2953
+ * Windows 不要求 control socket 就绪。
2954
+ */
2955
+ async function waitForDaemonReady(timeoutMs = 3e4, pollMs = 300) {
2956
+ const deadline = Date.now() + timeoutMs;
2957
+ let lastState;
2958
+ while (Date.now() < deadline) {
2959
+ const state = readDaemonState();
2960
+ if (state !== void 0 && isProcessRunning(state.pid)) {
2961
+ lastState = state;
2962
+ if (state.extHost !== void 0 && state.extPort !== void 0 && state.secret !== void 0) {
2963
+ if (await new MihomoApiClient(state.extHost, state.extPort, state.secret, 4e3).isReady()) if (process.platform !== "win32" && !await isControlSocketReady()) {} else return state;
2964
+ }
2965
+ }
2966
+ await new Promise((resolve) => {
2967
+ setTimeout(resolve, pollMs);
2968
+ });
2969
+ }
2970
+ throw new Error(lastState !== void 0 ? `Timed out waiting for daemon (PID ${lastState.pid}) to become ready` : "Timed out waiting for daemon to start (no state file written)");
2971
+ }
2972
+ /** 日志环形缓冲上限(暂停时新日志直接丢弃,故正常情况下不会暴涨)。 */
2973
+ const LOG_WINDOW = 1e3;
2974
+ /** 返回去掉某个可选键的 state 副本(用于 exactOptionalPropertyTypes 下清除字段)。 */
2975
+ function omitKey(state, key) {
2976
+ const next = { ...state };
2977
+ delete next[key];
2978
+ return next;
2979
+ }
2980
+ function createInitialState() {
2981
+ return {
2982
+ daemon: "stopped",
2983
+ secretMissing: false,
2984
+ panel: "overview",
2985
+ traffic: {
2986
+ up: [],
2987
+ down: []
2988
+ },
2989
+ upRate: 0,
2990
+ downRate: 0,
2991
+ overview: {
2992
+ uploadTotal: 0,
2993
+ downloadTotal: 0,
2994
+ systemProxy: "unknown",
2995
+ kernelChannel: "stable"
2996
+ },
2997
+ proxies: {
2998
+ groups: [],
2999
+ proxies: {},
3000
+ selectedGroup: "",
3001
+ delayOverrides: {},
3002
+ testing: false
3003
+ },
3004
+ connections: {
3005
+ rows: [],
3006
+ scroll: 0,
3007
+ cursor: 0,
3008
+ filter: "",
3009
+ sortBy: "down"
3010
+ },
3011
+ logs: {
3012
+ entries: [],
3013
+ level: "info",
3014
+ paused: false,
3015
+ follow: true,
3016
+ filter: "",
3017
+ scroll: 0
3018
+ },
3019
+ width: 80,
3020
+ height: 24
3021
+ };
3022
+ }
3023
+ function pushSample(arr, value) {
3024
+ const next = arr.length >= 60 ? arr.slice(arr.length - 60 + 1) : arr.slice();
3025
+ next.push(value);
3026
+ return next;
3027
+ }
3028
+ /** 追加一条日志到环形缓冲;暂停(paused)时丢弃新条目。 */
3029
+ function pushLog(entries, entry, paused) {
3030
+ if (paused) return entries;
3031
+ const next = entries.length >= 1e3 ? entries.slice(entries.length - LOG_WINDOW + 1) : entries.slice();
3032
+ next.push(entry);
3033
+ return next;
3034
+ }
3035
+ /**
3036
+ * 用新快照更新连接列表,按 id 合并并对累计字节做差分得到速率。
3037
+ * 消失的连接移除;新连接加入(速率从 0 起)。
3038
+ */
3039
+ function mergeConnections(previous, entries, elapsedMs) {
3040
+ const prevById = /* @__PURE__ */ new Map();
3041
+ for (const row of previous) prevById.set(row.id, row);
3042
+ const seconds = elapsedMs > 0 ? elapsedMs / 1e3 : 0;
3043
+ const next = [];
3044
+ for (const entry of entries) {
3045
+ const view = toConnectionView(entry);
3046
+ const prev = prevById.get(entry.id);
3047
+ if (prev !== void 0 && seconds > 0) {
3048
+ view.upRate = Math.max(0, (view.up - prev.up) / seconds);
3049
+ view.downRate = Math.max(0, (view.down - prev.down) / seconds);
3050
+ }
3051
+ next.push(view);
3052
+ }
3053
+ return next;
3054
+ }
3055
+ function reducer(state, action) {
3056
+ switch (action.type) {
3057
+ case "daemon": {
3058
+ const next = {
3059
+ ...state,
3060
+ daemon: action.status,
3061
+ ...action.secretMissing !== void 0 ? { secretMissing: action.secretMissing } : {},
3062
+ ...action.daemonState !== void 0 ? { daemonState: action.daemonState } : {},
3063
+ ...action.error !== void 0 ? { error: action.error } : {}
3064
+ };
3065
+ if (action.status === "stopped") {
3066
+ next.upRate = 0;
3067
+ next.downRate = 0;
3068
+ next.traffic = {
3069
+ up: [],
3070
+ down: []
3071
+ };
3072
+ next.connections = {
3073
+ ...state.connections,
3074
+ rows: []
3075
+ };
3076
+ if (action.error === void 0) delete next.error;
3077
+ }
3078
+ return next;
3079
+ }
3080
+ case "traffic": return {
3081
+ ...state,
3082
+ upRate: action.up,
3083
+ downRate: action.down,
3084
+ traffic: {
3085
+ up: pushSample(state.traffic.up, action.up),
3086
+ down: pushSample(state.traffic.down, action.down)
3087
+ }
3088
+ };
3089
+ case "connections": return {
3090
+ ...state,
3091
+ connections: {
3092
+ ...state.connections,
3093
+ rows: mergeConnections(state.connections.rows, action.entries, action.elapsedMs)
3094
+ },
3095
+ overview: {
3096
+ ...state.overview,
3097
+ uploadTotal: action.uploadTotal,
3098
+ downloadTotal: action.downloadTotal
3099
+ }
3100
+ };
3101
+ case "proxies": {
3102
+ const selectedGroup = action.groups.some((g) => g.name === state.proxies.selectedGroup) ? state.proxies.selectedGroup : action.groups[0]?.name ?? "";
3103
+ const proxiesView = {
3104
+ groups: action.groups,
3105
+ proxies: action.proxies,
3106
+ selectedGroup,
3107
+ delayOverrides: state.proxies.delayOverrides,
3108
+ testing: state.proxies.testing
3109
+ };
3110
+ return {
3111
+ ...state,
3112
+ proxies: proxiesView
3113
+ };
3114
+ }
3115
+ case "configs": return {
3116
+ ...state,
3117
+ overview: {
3118
+ ...state.overview,
3119
+ mode: action.mode,
3120
+ ...action.logLevel !== void 0 ? { logLevel: action.logLevel } : {}
3121
+ }
3122
+ };
3123
+ case "version": return {
3124
+ ...state,
3125
+ overview: {
3126
+ ...state.overview,
3127
+ version: action.version
3128
+ }
3129
+ };
3130
+ case "memory": return {
3131
+ ...state,
3132
+ overview: {
3133
+ ...state.overview,
3134
+ memory: action.memory
3135
+ }
3136
+ };
3137
+ case "overviewMeta": {
3138
+ const overview = {
3139
+ ...state.overview,
3140
+ kernelChannel: action.kernelChannel,
3141
+ systemProxy: action.systemProxy,
3142
+ ...action.profileName !== void 0 ? { profileName: action.profileName } : {},
3143
+ ...action.kernelVersion !== void 0 ? { kernelVersion: action.kernelVersion } : {}
3144
+ };
3145
+ return {
3146
+ ...state,
3147
+ overview
3148
+ };
3149
+ }
3150
+ case "panel": return {
3151
+ ...state,
3152
+ panel: action.panel
3153
+ };
3154
+ case "connectionsNav": return {
3155
+ ...state,
3156
+ connections: {
3157
+ ...state.connections,
3158
+ scroll: action.scroll,
3159
+ cursor: action.cursor
3160
+ }
3161
+ };
3162
+ case "connectionsFilter": return {
3163
+ ...state,
3164
+ connections: {
3165
+ ...state.connections,
3166
+ filter: action.filter,
3167
+ cursor: 0,
3168
+ scroll: 0
3169
+ }
3170
+ };
3171
+ case "connectionsSort": return {
3172
+ ...state,
3173
+ connections: {
3174
+ ...state.connections,
3175
+ sortBy: action.sortBy
3176
+ }
3177
+ };
3178
+ case "selectGroup": return {
3179
+ ...state,
3180
+ proxies: {
3181
+ ...state.proxies,
3182
+ selectedGroup: action.group
3183
+ }
3184
+ };
3185
+ case "delay": return {
3186
+ ...state,
3187
+ proxies: {
3188
+ ...state.proxies,
3189
+ delayOverrides: {
3190
+ ...state.proxies.delayOverrides,
3191
+ [action.name]: action.delay
3192
+ }
3193
+ }
3194
+ };
3195
+ case "testing": return {
3196
+ ...state,
3197
+ proxies: {
3198
+ ...state.proxies,
3199
+ testing: action.testing
3200
+ }
3201
+ };
3202
+ case "optimisticProxy": {
3203
+ const groups = state.proxies.groups.map((g) => g.name === action.group ? {
3204
+ ...g,
3205
+ now: action.now
3206
+ } : g);
3207
+ const proxies = { ...state.proxies.proxies };
3208
+ if (proxies[action.group] !== void 0) proxies[action.group] = {
3209
+ ...proxies[action.group],
3210
+ now: action.now
3211
+ };
3212
+ return {
3213
+ ...state,
3214
+ proxies: {
3215
+ ...state.proxies,
3216
+ groups,
3217
+ proxies
3218
+ }
3219
+ };
3220
+ }
3221
+ case "flash": return action.message !== void 0 ? {
3222
+ ...state,
3223
+ flash: action.message
3224
+ } : omitKey(state, "flash");
3225
+ case "error": return action.error !== void 0 ? {
3226
+ ...state,
3227
+ error: action.error
3228
+ } : omitKey(state, "error");
3229
+ case "size": return {
3230
+ ...state,
3231
+ width: action.width,
3232
+ height: action.height
3233
+ };
3234
+ case "logEntry": {
3235
+ const entries = pushLog(state.logs.entries, action.entry, state.logs.paused);
3236
+ if (entries === state.logs.entries) return state;
3237
+ const scroll = state.logs.follow ? Number.MAX_SAFE_INTEGER : state.logs.scroll;
3238
+ return {
3239
+ ...state,
3240
+ logs: {
3241
+ ...state.logs,
3242
+ entries,
3243
+ scroll
3244
+ }
3245
+ };
3246
+ }
3247
+ case "logClear": return {
3248
+ ...state,
3249
+ logs: {
3250
+ ...state.logs,
3251
+ entries: [],
3252
+ scroll: 0
3253
+ }
3254
+ };
3255
+ case "logTogglePause": return {
3256
+ ...state,
3257
+ logs: {
3258
+ ...state.logs,
3259
+ paused: !state.logs.paused
3260
+ }
3261
+ };
3262
+ case "logSetLevel": return {
3263
+ ...state,
3264
+ logs: {
3265
+ ...state.logs,
3266
+ level: action.level,
3267
+ scroll: 0
3268
+ }
3269
+ };
3270
+ case "logSetFilter": return {
3271
+ ...state,
3272
+ logs: {
3273
+ ...state.logs,
3274
+ filter: action.filter,
3275
+ scroll: 0
3276
+ }
3277
+ };
3278
+ case "logNav": return {
3279
+ ...state,
3280
+ logs: {
3281
+ ...state.logs,
3282
+ scroll: action.scroll,
3283
+ follow: action.follow
3284
+ }
3285
+ };
3286
+ case "logToggleFollow": return {
3287
+ ...state,
3288
+ logs: {
3289
+ ...state.logs,
3290
+ follow: !state.logs.follow,
3291
+ scroll: !state.logs.follow ? Number.MAX_SAFE_INTEGER : state.logs.scroll
3292
+ }
3293
+ };
3294
+ case "logReset": return {
3295
+ ...state,
3296
+ logs: {
3297
+ entries: [],
3298
+ level: state.logs.level,
3299
+ paused: false,
3300
+ follow: true,
3301
+ filter: "",
3302
+ scroll: 0
3303
+ }
3304
+ };
3305
+ default: return state;
3306
+ }
3307
+ }
3308
+ /** 选择器:当前连接表经过滤+排序后的可见行。纯函数,供面板与测试复用。 */
3309
+ function selectVisibleConnections(state) {
3310
+ const { rows, filter, sortBy } = state.connections;
3311
+ const q = filter.trim().toLowerCase();
3312
+ return (q.length === 0 ? rows : rows.filter((r) => r.host.toLowerCase().includes(q) || r.rule.toLowerCase().includes(q) || r.chain.toLowerCase().includes(q) || r.network.toLowerCase().includes(q))).slice().sort((a, b) => sortBy === "up" ? b.up - a.up : b.down - a.down);
3313
+ }
3314
+ /** 选择器:日志经过级别阈值 + payload 过滤后的可见条目(按时间正序)。纯函数。 */
3315
+ function selectVisibleLogs(state) {
3316
+ const { entries, level, filter } = state.logs;
3317
+ const threshold = LOG_LEVEL_ORDER[level];
3318
+ const q = filter.trim().toLowerCase();
3319
+ if (q.length === 0) return threshold === 0 ? entries : entries.filter((e) => LOG_LEVEL_ORDER[e.level] >= threshold);
3320
+ return entries.filter((e) => LOG_LEVEL_ORDER[e.level] >= threshold && e.payload.toLowerCase().includes(q));
3321
+ }
3322
+ //#endregion
3323
+ //#region src/tui/runtime/mihomo-connect.ts
3324
+ function openTrafficWebSocket(host, port, secret, handlers) {
3325
+ const baseDelay = 1e3;
3326
+ const maxDelay = 1e4;
3327
+ let attempt = 0;
3328
+ let stopped = false;
3329
+ let ws;
3330
+ let reconnectTimer;
3331
+ const connect = () => {
3332
+ if (stopped) return;
3333
+ const url = `ws://${host}:${port}/traffic?token=${encodeURIComponent(secret)}`;
3334
+ let socket;
3335
+ try {
3336
+ socket = new WebSocket(url);
3337
+ } catch {
3338
+ scheduleReconnect();
3339
+ return;
3340
+ }
3341
+ ws = socket;
3342
+ socket.onopen = () => {
3343
+ attempt = 0;
3344
+ handlers.onStatusChange?.(true);
3345
+ };
3346
+ socket.onmessage = (event) => {
3347
+ try {
3348
+ const data = JSON.parse(String(event.data));
3349
+ handlers.onTraffic(data.up ?? 0, data.down ?? 0);
3350
+ } catch {}
3351
+ };
3352
+ const onClosed = () => {
3353
+ handlers.onStatusChange?.(false);
3354
+ if (!stopped) scheduleReconnect();
3355
+ };
3356
+ socket.onerror = () => {
3357
+ try {
3358
+ socket.close();
3359
+ } catch {}
3360
+ };
3361
+ socket.onclose = onClosed;
3362
+ };
3363
+ const scheduleReconnect = () => {
3364
+ if (stopped) return;
3365
+ const delay = Math.min(maxDelay, baseDelay * 2 ** attempt) + Math.floor(Math.random() * 300);
3366
+ attempt += 1;
3367
+ reconnectTimer = setTimeout(connect, delay);
3368
+ };
3369
+ connect();
3370
+ return { stop() {
3371
+ stopped = true;
3372
+ if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
3373
+ if (ws !== void 0) try {
3374
+ ws.close();
3375
+ } catch {}
3376
+ } };
3377
+ }
3378
+ //#endregion
3379
+ //#region src/tui/runtime/mihomo-log-connect.ts
3380
+ const VALID_LEVELS = /* @__PURE__ */ new Set([
3381
+ "debug",
3382
+ "info",
3383
+ "warning",
3384
+ "error"
3385
+ ]);
3386
+ /**
3387
+ * 解析一帧 mihomo 日志消息为 LogEntryView。
3388
+ * 纯函数,导出供单测。无法解析或级别非法时返回 undefined。
3389
+ *
3390
+ * @param data WebSocket 帧数据
3391
+ * @param receivedAt 接收时刻毫秒时间戳(由调用方传入,避免测试依赖 Date.now)
3392
+ */
3393
+ function parseLogFrame(data, receivedAt) {
3394
+ let parsed;
3395
+ try {
3396
+ parsed = JSON.parse(typeof data === "string" ? data : String(data));
3397
+ } catch {
3398
+ return;
3399
+ }
3400
+ if (typeof parsed.type !== "string" || !VALID_LEVELS.has(parsed.type)) return;
3401
+ const payload = typeof parsed.payload === "string" ? parsed.payload : "";
3402
+ return {
3403
+ receivedAt,
3404
+ level: parsed.type,
3405
+ payload
3406
+ };
3407
+ }
3408
+ function openLogWebSocket(host, port, secret, initialLevel, handlers) {
3409
+ const baseDelay = 1e3;
3410
+ const maxDelay = 1e4;
3411
+ let attempt = 0;
3412
+ let stopped = false;
3413
+ let level = initialLevel;
3414
+ let ws;
3415
+ let reconnectTimer;
3416
+ const teardownSocket = () => {
3417
+ if (ws !== void 0) {
3418
+ const socket = ws;
3419
+ ws = void 0;
3420
+ socket.onopen = null;
3421
+ socket.onmessage = null;
3422
+ socket.onerror = null;
3423
+ socket.onclose = null;
3424
+ try {
3425
+ socket.close();
3426
+ } catch {}
3427
+ }
3428
+ };
3429
+ const connect = () => {
3430
+ if (stopped) return;
3431
+ const url = `ws://${host}:${port}/logs?level=${encodeURIComponent(level)}`;
3432
+ let socket;
3433
+ try {
3434
+ socket = new WebSocket(url, { headers: { Authorization: `Bearer ${secret}` } });
3435
+ } catch {
3436
+ scheduleReconnect();
3437
+ return;
3438
+ }
3439
+ ws = socket;
3440
+ socket.onopen = () => {
3441
+ attempt = 0;
3442
+ handlers.onStatusChange?.(true);
3443
+ };
3444
+ socket.onmessage = (event) => {
3445
+ const entry = parseLogFrame(event.data, Date.now());
3446
+ if (entry !== void 0) handlers.onLog(entry);
3447
+ };
3448
+ socket.onerror = () => {
3449
+ try {
3450
+ socket.close();
3451
+ } catch {}
3452
+ };
3453
+ socket.onclose = () => {
3454
+ if (ws === socket) ws = void 0;
3455
+ handlers.onStatusChange?.(false);
3456
+ if (!stopped) scheduleReconnect();
3457
+ };
3458
+ };
3459
+ const scheduleReconnect = () => {
3460
+ if (stopped) return;
3461
+ if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
3462
+ const delay = Math.min(maxDelay, baseDelay * 2 ** attempt) + Math.floor(Math.random() * 300);
3463
+ attempt += 1;
3464
+ reconnectTimer = setTimeout(connect, delay);
3465
+ };
3466
+ connect();
3467
+ return {
3468
+ setLevel(next) {
3469
+ if (next === level) return;
3470
+ level = next;
3471
+ if (stopped) return;
3472
+ if (reconnectTimer !== void 0) {
3473
+ clearTimeout(reconnectTimer);
3474
+ reconnectTimer = void 0;
3475
+ }
3476
+ attempt = 0;
3477
+ teardownSocket();
3478
+ connect();
3479
+ },
3480
+ stop() {
3481
+ stopped = true;
3482
+ if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
3483
+ reconnectTimer = void 0;
3484
+ teardownSocket();
3485
+ }
3486
+ };
3487
+ }
3488
+ //#endregion
3489
+ //#region src/tui/runtime/polling.ts
3490
+ function startPolling(intervalMs, task, options = {}) {
3491
+ let stopped = false;
3492
+ let inFlight = false;
3493
+ const tick = async () => {
3494
+ if (stopped || inFlight) return;
3495
+ inFlight = true;
3496
+ try {
3497
+ await task();
3498
+ } catch {} finally {
3499
+ inFlight = false;
3500
+ }
3501
+ };
3502
+ if (options.runImmediately) tick();
3503
+ const id = setInterval(() => {
3504
+ tick();
3505
+ }, intervalMs);
3506
+ if (typeof id.unref === "function") id.unref();
3507
+ return { stop() {
3508
+ stopped = true;
3509
+ clearInterval(id);
3510
+ } };
3511
+ }
3512
+ //#endregion
3513
+ //#region src/tui/runtime/offline-proxies.ts
3514
+ /**
3515
+ * 离线代理数据:从 mihomo config.yaml 解析出的代理组 + 节点,
3516
+ * 并用 profiles.yaml 里记录的 selections 填充每组当前选中(now)。
3517
+ *
3518
+ * daemon 未运行时没有 mihomo API,TUI 用它渲染代理页并允许预选节点。
3519
+ * 数据来源是上一次生成的 config.yaml(纯 YAML),不经过配置生成管线
3520
+ * (Merge/Script 在 vm 中执行,按构建边界禁止进入 TUI bundle)。
3521
+ */
3522
+ const GROUP_TYPE_MAP = {
3523
+ "select": "Selector",
3524
+ "url-test": "URLTest",
3525
+ "fallback": "Fallback",
3526
+ "load-balance": "LoadBalance",
3527
+ "relay": "Relay"
3528
+ };
3529
+ /**
3530
+ * 从已解析的 mihomo config 对象构建离线代理数据(纯函数,便于单测)。
3531
+ *
3532
+ * @param config mihomo config.yaml 的解析结果(mapping)
3533
+ * @param selections 组名→选中节点(来自当前 profile 的 selections)
3534
+ */
3535
+ function buildOfflineProxies(config, selections) {
3536
+ const groups = [];
3537
+ const proxies = {};
3538
+ const rawGroups = config?.["proxy-groups"];
3539
+ if (!Array.isArray(rawGroups)) return {
3540
+ groups,
3541
+ proxies
3542
+ };
3543
+ const groupNames = /* @__PURE__ */ new Set();
3544
+ for (const g of rawGroups) {
3545
+ if (typeof g !== "object" || g === null || Array.isArray(g)) continue;
3546
+ const raw = g;
3547
+ if (typeof raw.name !== "string" || raw.name.length === 0) continue;
3548
+ groupNames.add(raw.name);
3549
+ }
3550
+ for (const g of rawGroups) {
3551
+ if (typeof g !== "object" || g === null || Array.isArray(g)) continue;
3552
+ const raw = g;
3553
+ if (typeof raw.name !== "string" || raw.name.length === 0) continue;
3554
+ if (!Array.isArray(raw.proxies)) continue;
3555
+ const members = raw.proxies.filter((m) => typeof m === "string");
3556
+ const type = typeof raw.type === "string" ? GROUP_TYPE_MAP[raw.type] ?? "Selector" : "Selector";
3557
+ const selected = selections[raw.name];
3558
+ const now = selected !== void 0 && members.includes(selected) ? selected : type === "Selector" ? members[0] ?? "" : "";
3559
+ groups.push({
3560
+ name: raw.name,
3561
+ type,
3562
+ now,
3563
+ all: members
3564
+ });
3565
+ proxies[raw.name] = {
3566
+ name: raw.name,
3567
+ type,
3568
+ now,
3569
+ all: members,
3570
+ history: []
3571
+ };
3572
+ }
3573
+ for (const group of groups) for (const member of group.all) if (proxies[member] === void 0) proxies[member] = {
3574
+ name: member,
3575
+ type: "Unknown",
3576
+ now: "",
3577
+ all: [],
3578
+ history: []
3579
+ };
3580
+ return {
3581
+ groups,
3582
+ proxies
3583
+ };
3584
+ }
3585
+ /**
3586
+ * 读取磁盘上的 config.yaml 并结合 selections 构建离线代理数据。
3587
+ * 文件缺失/解析失败时返回空数据(调用方据此显示"无配置"占位)。
3588
+ */
3589
+ function loadOfflineProxies(selections) {
3590
+ try {
3591
+ return buildOfflineProxies(load(readFileSync(getMihomoConfigPath(), "utf8")), selections);
3592
+ } catch {
3593
+ return {
3594
+ groups: [],
3595
+ proxies: {}
3596
+ };
3597
+ }
3598
+ }
3599
+ //#endregion
3600
+ //#region src/tui/runtime/tui-runtime.ts
3601
+ const RENDER_THROTTLE_MS = 100;
3602
+ const FLASH_MS = 2500;
3603
+ const GROUP_TYPES = /* @__PURE__ */ new Set([
3604
+ "Selector",
3605
+ "URLTest",
3606
+ "Fallback",
3607
+ "LoadBalance",
3608
+ "Relay"
3609
+ ]);
3610
+ /**
3611
+ * TUI 运行时:持有集中状态、mihomo API 客户端、traffic WebSocket 与轮询器,
3612
+ * 并暴露面板可调用的动作。所有异步失败被捕获并写入 state.error,不抛到渲染循环。
3613
+ */
3614
+ var TuiRuntime = class {
3615
+ state;
3616
+ tui;
3617
+ apiClient;
3618
+ traffic;
3619
+ logs;
3620
+ pollers = [];
3621
+ systemProxyController;
3622
+ proxiesSerial = 0;
3623
+ renderTimer;
3624
+ flashTimer;
3625
+ stopping = false;
3626
+ lastConnectionsAt = 0;
3627
+ constructor(tui) {
3628
+ this.tui = tui;
3629
+ this.state = createInitialState();
3630
+ }
3631
+ async start() {
3632
+ await this.detectSystemProxy();
3633
+ this.loadStaticMeta();
3634
+ await this.bootstrap();
3635
+ if (this.apiClient === void 0) this.refreshOfflineProxies();
3636
+ }
3637
+ stop() {
3638
+ this.stopping = true;
3639
+ this.traffic?.stop();
3640
+ this.logs?.stop();
3641
+ this.logs = void 0;
3642
+ for (const poller of this.pollers) poller.stop();
3643
+ this.pollers = [];
3644
+ if (this.renderTimer !== void 0) clearTimeout(this.renderTimer);
3645
+ if (this.flashTimer !== void 0) clearTimeout(this.flashTimer);
3646
+ }
3647
+ dispatch(action) {
3648
+ this.state = reducer(this.state, action);
3649
+ this.scheduleRender();
3650
+ }
3651
+ scheduleRender() {
3652
+ if (this.renderTimer !== void 0) return;
3653
+ this.renderTimer = setTimeout(() => {
3654
+ this.renderTimer = void 0;
3655
+ if (!this.stopping) this.tui.requestRender();
3656
+ }, RENDER_THROTTLE_MS);
3657
+ }
3658
+ flash(message) {
3659
+ if (message !== void 0) this.dispatch({
3660
+ type: "flash",
3661
+ message
3662
+ });
3663
+ else this.clearFlash();
3664
+ if (this.flashTimer !== void 0) clearTimeout(this.flashTimer);
3665
+ if (message === void 0) return;
3666
+ this.flashTimer = setTimeout(() => {
3667
+ this.flashTimer = void 0;
3668
+ this.clearFlash();
3669
+ }, FLASH_MS);
3670
+ }
3671
+ clearFlash() {
3672
+ this.dispatch({ type: "flash" });
3673
+ }
3674
+ setError(error) {
3675
+ this.dispatch(error !== void 0 ? {
3676
+ type: "error",
3677
+ error
3678
+ } : { type: "error" });
3679
+ }
3680
+ /**
3681
+ * 需要运行中 daemon 的用户动作调用:离线时 flash 提示并返回 undefined。
3682
+ * 写配置文件类动作(切 Profile/内核)不要用这个守卫。
3683
+ */
3684
+ requireApi(action) {
3685
+ if (this.apiClient === void 0) {
3686
+ this.flash(`需要运行中的 daemon 才能${action}。`);
3687
+ return;
3688
+ }
3689
+ return this.apiClient;
3690
+ }
3691
+ setDaemon(status, extras = {}) {
3692
+ this.dispatch({
3693
+ type: "daemon",
3694
+ status,
3695
+ ...extras
3696
+ });
3697
+ }
3698
+ async bootstrap() {
3699
+ let state;
3700
+ try {
3701
+ state = loadProxyDaemonState();
3702
+ } catch {
3703
+ removeProxyDaemonState();
3704
+ state = void 0;
3705
+ }
3706
+ if (state === void 0 || !isProcessRunning(state.pid)) {
3707
+ if (state !== void 0) removeProxyDaemonState();
3708
+ this.setDaemon("stopped");
3709
+ return;
3710
+ }
3711
+ if (state.extHost === void 0 || state.extPort === void 0 || state.secret === void 0) {
3712
+ this.setDaemon("running", {
3713
+ secretMissing: true,
3714
+ daemonState: state,
3715
+ error: "旧 daemon 缺少外部控制器凭据,请重启 daemon。"
3716
+ });
3717
+ return;
3718
+ }
3719
+ await this.connect(state);
3720
+ }
3721
+ async connect(state) {
3722
+ if (state.extHost === void 0 || state.extPort === void 0 || state.secret === void 0) return;
3723
+ this.setDaemon("starting", {
3724
+ daemonState: state,
3725
+ secretMissing: false,
3726
+ error: void 0
3727
+ });
3728
+ const client = new MihomoApiClient(state.extHost, state.extPort, state.secret, 8e3);
3729
+ this.apiClient = client;
3730
+ if (!await client.isReady()) {
3731
+ this.setDaemon("reconnecting", {
3732
+ daemonState: state,
3733
+ error: "mihomo API 未就绪,重连中…"
3734
+ });
3735
+ setTimeout(() => {
3736
+ this.bootstrap();
3737
+ }, 1500);
3738
+ return;
3739
+ }
3740
+ this.setDaemon("running", {
3741
+ daemonState: state,
3742
+ error: void 0
3743
+ });
3744
+ this.loadStaticMeta();
3745
+ this.fetchOverview();
3746
+ this.fetchProxies();
3747
+ this.traffic = openTrafficWebSocket(state.extHost, state.extPort, state.secret, {
3748
+ onTraffic: (up, down) => {
3749
+ this.dispatch({
3750
+ type: "traffic",
3751
+ up,
3752
+ down
3753
+ });
3754
+ },
3755
+ onStatusChange: (connected) => {
3756
+ if (!connected && this.state.daemon === "running") this.setError("流量通道断开,重连中…");
3757
+ else if (connected) this.setError(void 0);
3758
+ }
3759
+ });
3760
+ this.pollers = [
3761
+ startPolling(1e3, () => this.fetchConnections(), { runImmediately: true }),
3762
+ startPolling(3e3, () => this.fetchOverview()),
3763
+ startPolling(4e3, () => this.fetchProxies())
3764
+ ];
3765
+ if (this.state.panel === "logs") this.startLogs();
3766
+ }
3767
+ resetToStopped(message) {
3768
+ this.traffic?.stop();
3769
+ this.traffic = void 0;
3770
+ this.stopLogs();
3771
+ for (const poller of this.pollers) poller.stop();
3772
+ this.pollers = [];
3773
+ this.apiClient = void 0;
3774
+ this.setDaemon("stopped", { error: message });
3775
+ this.refreshOfflineProxies();
3776
+ }
3777
+ /**
3778
+ * 离线时从 config.yaml 解析代理组/节点,并按当前 profile 的 selections 标记选中。
3779
+ * config.yaml 可能已被离线切 Profile 等操作"过期",但这是离线唯一可解析的来源;
3780
+ * 实际应用以 daemon 启动后的 config 为准(组名不存在会被 applyProfileSelections 跳过)。
3781
+ */
3782
+ refreshOfflineProxies() {
3783
+ if (this.apiClient !== void 0) return;
3784
+ try {
3785
+ const { groups, proxies } = loadOfflineProxies(getProfileSelections(getCurrentProfile(loadProfiles())));
3786
+ this.dispatch({
3787
+ type: "proxies",
3788
+ groups,
3789
+ proxies
3790
+ });
3791
+ } catch {}
3792
+ }
3793
+ loadStaticMeta() {
3794
+ try {
3795
+ const lynx = loadLynxConfig();
3796
+ const current = getCurrentProfile(loadProfiles());
3797
+ this.dispatch({
3798
+ type: "overviewMeta",
3799
+ profileName: current?.name,
3800
+ kernelChannel: lynx.mihomo.kernel ?? "stable",
3801
+ systemProxy: this.state.overview.systemProxy
3802
+ });
3803
+ if (lynx.mihomo.mode !== void 0 && this.apiClient === void 0) this.dispatch({
3804
+ type: "configs",
3805
+ mode: lynx.mihomo.mode
3806
+ });
3807
+ } catch {}
3808
+ }
3809
+ async fetchOverview() {
3810
+ const client = this.apiClient;
3811
+ if (client === void 0) return;
3812
+ try {
3813
+ const configs = await client.getConfigs();
3814
+ this.dispatch({
3815
+ type: "configs",
3816
+ mode: configs.mode,
3817
+ logLevel: configs["log-level"]
3818
+ });
3819
+ } catch {
3820
+ this.handleApiError();
3821
+ }
3822
+ try {
3823
+ const version = await client.getVersion();
3824
+ this.dispatch({
3825
+ type: "version",
3826
+ version
3827
+ });
3828
+ } catch {}
3829
+ try {
3830
+ const memory = await client.getMemory();
3831
+ this.dispatch({
3832
+ type: "memory",
3833
+ memory
3834
+ });
3835
+ } catch {}
3836
+ await this.refreshSystemProxyStatus();
3837
+ }
3838
+ async fetchProxies() {
3839
+ const client = this.apiClient;
3840
+ if (client === void 0) return;
3841
+ const serial = ++this.proxiesSerial;
3842
+ try {
3843
+ const proxiesResp = await client.getProxies();
3844
+ if (serial !== this.proxiesSerial) return;
3845
+ const proxies = {};
3846
+ const groups = [];
3847
+ for (const [name, info] of Object.entries(proxiesResp.proxies)) {
3848
+ proxies[name] = info;
3849
+ if (GROUP_TYPES.has(info.type)) groups.push({
3850
+ name,
3851
+ type: info.type,
3852
+ now: info.now,
3853
+ all: info.all
3854
+ });
3855
+ }
3856
+ this.dispatch({
3857
+ type: "proxies",
3858
+ groups,
3859
+ proxies
3860
+ });
3861
+ } catch {
3862
+ this.handleApiError();
3863
+ }
3864
+ }
3865
+ async fetchConnections() {
3866
+ const client = this.apiClient;
3867
+ if (client === void 0) return;
3868
+ const now = Date.now();
3869
+ const elapsed = this.lastConnectionsAt === 0 ? 0 : now - this.lastConnectionsAt;
3870
+ this.lastConnectionsAt = now;
3871
+ try {
3872
+ const resp = await client.getConnections();
3873
+ this.dispatch({
3874
+ type: "connections",
3875
+ entries: resp.connections ?? [],
3876
+ uploadTotal: resp.uploadTotal,
3877
+ downloadTotal: resp.downloadTotal,
3878
+ elapsedMs: elapsed
3879
+ });
3880
+ } catch {
3881
+ this.handleApiError();
3882
+ }
3883
+ }
3884
+ consecutiveFailures = 0;
3885
+ handleApiError() {
3886
+ this.consecutiveFailures += 1;
3887
+ if (this.consecutiveFailures >= 5) {
3888
+ this.consecutiveFailures = 0;
3889
+ const state = this.state.daemonState;
3890
+ if (state !== void 0 && !isProcessRunning(state.pid)) this.resetToStopped("daemon 已退出。");
3891
+ else this.setError("mihomo API 不可达,重连中…");
3892
+ }
3893
+ }
3894
+ async detectSystemProxy() {
3895
+ try {
3896
+ this.systemProxyController = await detectSystemProxyController();
3897
+ } catch {
3898
+ this.systemProxyController = void 0;
3899
+ }
3900
+ await this.refreshSystemProxyStatus();
3901
+ }
3902
+ async refreshSystemProxyStatus() {
3903
+ const status = await getSystemProxyStatus(this.systemProxyController);
3904
+ if (status !== this.state.overview.systemProxy) this.dispatch({
3905
+ type: "overviewMeta",
3906
+ profileName: this.state.overview.profileName,
3907
+ kernelChannel: this.state.overview.kernelChannel,
3908
+ kernelVersion: this.state.overview.kernelVersion,
3909
+ systemProxy: status
3910
+ });
3911
+ }
3912
+ setPanel(panel) {
3913
+ this.dispatch({
3914
+ type: "panel",
3915
+ panel
3916
+ });
3917
+ }
3918
+ /** 立即刷新概览数据(模式/版本/内存/系统代理)。 */
3919
+ refreshOverview() {
3920
+ return this.fetchOverview();
3921
+ }
3922
+ setConnectionsNav(scroll, cursor) {
3923
+ this.dispatch({
3924
+ type: "connectionsNav",
3925
+ scroll,
3926
+ cursor
3927
+ });
3928
+ }
3929
+ setConnectionsFilter(filter) {
3930
+ this.dispatch({
3931
+ type: "connectionsFilter",
3932
+ filter
3933
+ });
3934
+ }
3935
+ toggleConnectionsSort() {
3936
+ this.dispatch({
3937
+ type: "connectionsSort",
3938
+ sortBy: this.state.connections.sortBy === "down" ? "up" : "down"
3939
+ });
3940
+ }
3941
+ selectGroup(name) {
3942
+ this.dispatch({
3943
+ type: "selectGroup",
3944
+ group: name
3945
+ });
3946
+ }
3947
+ async setMode(mode) {
3948
+ if (this.apiClient === void 0) {
3949
+ await this.updateLynxConfig((config) => {
3950
+ config.mihomo.mode = mode;
3951
+ }, `路由模式(${mode})`);
3952
+ this.dispatch({
3953
+ type: "configs",
3954
+ mode
3955
+ });
3956
+ return;
3957
+ }
3958
+ try {
3959
+ await this.apiClient.patchConfigs({ mode });
3960
+ this.dispatch({
3961
+ type: "configs",
3962
+ mode
3963
+ });
3964
+ this.flash(`路由模式:${mode}`);
3965
+ } catch (error) {
3966
+ this.flash(`切换模式失败:${String(error)}`);
3967
+ }
3968
+ }
3969
+ async toggleSystemProxy() {
3970
+ const controller = this.systemProxyController;
3971
+ if (controller === void 0) {
3972
+ this.flash("当前平台不支持系统代理接管。");
3973
+ return;
3974
+ }
3975
+ const target = this.resolveProxyTarget();
3976
+ if (target === void 0) {
3977
+ this.flash("无法确定代理监听地址,请先启动一次 daemon。");
3978
+ return;
3979
+ }
3980
+ try {
3981
+ if (await getSystemProxyStatus(controller) === "enabled") {
3982
+ await controller.disable();
3983
+ this.flash("系统代理已关闭。");
3984
+ } else {
3985
+ await controller.enable(target.host, target.port);
3986
+ this.flash(this.apiClient === void 0 ? `系统代理已指向 ${target.host}:${target.port}(daemon 未运行,启动后生效)。` : `系统代理已指向 ${target.host}:${target.port}。`);
3987
+ }
3988
+ await this.refreshSystemProxyStatus();
3989
+ } catch (error) {
3990
+ this.flash(`系统代理操作失败:${String(error)}`);
3991
+ }
3992
+ }
3993
+ /** 系统代理要指向的地址:优先 daemon 实际监听,回落到 lynx.json 的 listen。 */
3994
+ resolveProxyTarget() {
3995
+ const state = this.state.daemonState;
3996
+ if (state !== void 0) return {
3997
+ host: state.host,
3998
+ port: state.port
3999
+ };
4000
+ try {
4001
+ return parseHostPort(loadLynxConfig().listen, "127.0.0.1", 7890);
4002
+ } catch {
4003
+ return;
4004
+ }
4005
+ }
4006
+ async selectProxy(group, proxy) {
4007
+ if (this.apiClient === void 0) {
4008
+ this.persistOfflineSelection(group, proxy);
4009
+ return;
4010
+ }
4011
+ try {
4012
+ await this.apiClient.selectProxy(group, proxy);
4013
+ this.dispatch({
4014
+ type: "optimisticProxy",
4015
+ group,
4016
+ now: proxy
4017
+ });
4018
+ this.flash(`已切换:${group} → ${proxy}`);
4019
+ this.fetchProxies();
4020
+ } catch (error) {
4021
+ this.flash(`切换节点失败:${String(error)}`);
4022
+ }
4023
+ }
4024
+ /** 离线预选:写入 profiles.yaml 当前 profile 的 selections 并刷新离线视图。 */
4025
+ persistOfflineSelection(group, proxy) {
4026
+ try {
4027
+ const profiles = loadProfiles();
4028
+ const current = getCurrentProfile(profiles);
4029
+ if (current === void 0) {
4030
+ this.flash("未选择 Profile,无法预选节点。");
4031
+ return;
4032
+ }
4033
+ if (!setProfileSelection(profiles, current.uid, group, proxy)) return;
4034
+ saveProfiles(profiles);
4035
+ this.dispatch({
4036
+ type: "optimisticProxy",
4037
+ group,
4038
+ now: proxy
4039
+ });
4040
+ this.flash(`已预选:${group} → ${proxy}(下次启动生效)`);
4041
+ } catch (error) {
4042
+ this.flash(`写入预选失败:${String(error)}`);
4043
+ }
4044
+ }
4045
+ /** 测试一个组内所有真实节点的延迟,逐个写入结果并刷新。 */
4046
+ async testGroupDelay(groupName) {
4047
+ const client = this.requireApi("测速");
4048
+ if (client === void 0) return;
4049
+ const group = this.state.proxies.groups.find((g) => g.name === groupName);
4050
+ if (group === void 0) return;
4051
+ this.dispatch({
4052
+ type: "testing",
4053
+ testing: true
4054
+ });
4055
+ const concurrency = 8;
4056
+ const nodes = group.all.filter((name) => {
4057
+ const info = this.state.proxies.proxies[name];
4058
+ return info !== void 0 && !GROUP_TYPES.has(info.type);
4059
+ });
4060
+ let index = 0;
4061
+ const workers = [];
4062
+ const runOne = async (name) => {
4063
+ try {
4064
+ const resp = await client.getProxyDelay(name, "https://www.gstatic.com/generate_204", 5e3);
4065
+ const delay = Object.values(resp).filter((v) => typeof v === "number")[0] ?? 0;
4066
+ this.dispatch({
4067
+ type: "delay",
4068
+ name,
4069
+ delay
4070
+ });
4071
+ } catch {
4072
+ this.dispatch({
4073
+ type: "delay",
4074
+ name,
4075
+ delay: 0
4076
+ });
4077
+ }
4078
+ };
4079
+ for (let w = 0; w < concurrency; w += 1) workers.push((async () => {
4080
+ while (index < nodes.length) {
4081
+ const current = index;
4082
+ index += 1;
4083
+ const name = nodes[current];
4084
+ if (name !== void 0) await runOne(name);
4085
+ }
4086
+ })());
4087
+ await Promise.all(workers);
4088
+ this.dispatch({
4089
+ type: "testing",
4090
+ testing: false
4091
+ });
4092
+ }
4093
+ async closeConnection(id) {
4094
+ const client = this.requireApi("断开连接");
4095
+ if (client === void 0) return;
4096
+ try {
4097
+ await client.closeConnection(id);
4098
+ this.state.connections.rows = this.state.connections.rows.filter((r) => r.id !== id);
4099
+ this.scheduleRender();
4100
+ } catch (error) {
4101
+ this.flash(`断开连接失败:${String(error)}`);
4102
+ }
4103
+ }
4104
+ async closeAllConnections() {
4105
+ const client = this.requireApi("断开全部连接");
4106
+ if (client === void 0) return;
4107
+ try {
4108
+ await client.closeConnections();
4109
+ this.state.connections.rows = [];
4110
+ this.scheduleRender();
4111
+ this.flash("已断开全部连接。");
4112
+ } catch (error) {
4113
+ this.flash(`断开全部连接失败:${String(error)}`);
4114
+ }
4115
+ }
4116
+ async reload() {
4117
+ if (process.platform === "win32") {
4118
+ this.flash("Windows 不支持 reload,请重启 daemon。");
4119
+ return;
4120
+ }
4121
+ try {
4122
+ const resp = await sendControlCommand({ cmd: "reload" });
4123
+ if (resp === void 0) this.flash("daemon 无响应。");
4124
+ else if (resp.ok) {
4125
+ this.flash("已刷新订阅与配置。");
4126
+ this.fetchProxies();
4127
+ } else this.flash(`刷新失败:${resp.error ?? "未知错误"}`);
4128
+ } catch (error) {
4129
+ this.flash(`刷新失败:${String(error)}`);
4130
+ }
4131
+ }
4132
+ /** 设置 mihomo 全局日志级别(影响 daemon 日志文件)。需要在线。 */
4133
+ async setLogLevel(level) {
4134
+ const client = this.requireApi("设置日志级别");
4135
+ if (client === void 0) return;
4136
+ try {
4137
+ await client.setLogLevel(level);
4138
+ this.flash(`日志级别已设为 ${level}。`);
4139
+ this.fetchOverview();
4140
+ } catch (error) {
4141
+ this.flash(`设置日志级别失败:${String(error)}`);
4142
+ }
4143
+ }
4144
+ /**
4145
+ * 切换当前 Profile。
4146
+ *
4147
+ * 在线:经控制通道发 useProfile,由 daemon 重新生成 config.yaml 并热重载(免重启)。
4148
+ * 离线:只写 profiles.yaml,下次启动 daemon 时生效。
4149
+ */
4150
+ async switchProfile(uid) {
4151
+ if (this.apiClient !== void 0 && process.platform !== "win32") {
4152
+ try {
4153
+ const resp = await sendControlCommand({
4154
+ cmd: "useProfile",
4155
+ uid
4156
+ });
4157
+ if (resp === void 0) {
4158
+ this.writeProfileSelection(uid, "daemon 无响应,已写入配置,重启后生效。");
4159
+ return;
4160
+ }
4161
+ if (resp.ok) {
4162
+ this.loadStaticMeta();
4163
+ this.flash("已切换 Profile。");
4164
+ this.fetchProxies();
4165
+ this.fetchOverview();
4166
+ } else this.flash(`切换 Profile 失败:${resp.error ?? "未知错误"}`);
4167
+ } catch (error) {
4168
+ this.flash(`切换 Profile 失败:${String(error)}`);
4169
+ }
4170
+ return;
4171
+ }
4172
+ this.writeProfileSelection(uid, process.platform === "win32" ? "已写入配置,重启 daemon 后生效。" : "已切换 Profile,下次启动生效。");
4173
+ }
4174
+ /** 把当前 Profile 选择写入 profiles.yaml(不依赖 daemon)。 */
4175
+ writeProfileSelection(uid, message) {
4176
+ try {
4177
+ const profiles = loadProfiles();
4178
+ if (!setCurrentProfile(profiles, uid)) {
4179
+ this.flash("切换失败:Profile 不存在。");
4180
+ return;
4181
+ }
4182
+ saveProfiles(profiles);
4183
+ this.loadStaticMeta();
4184
+ this.refreshOfflineProxies();
4185
+ this.flash(message);
4186
+ } catch (error) {
4187
+ this.flash(`写入 profiles.yaml 失败:${String(error)}`);
4188
+ }
4189
+ }
4190
+ /**
4191
+ * 修改并保存 lynx.json(离线可写)。mutator 在加载出的配置对象上原地修改,
4192
+ * 返回 false 表示中止(不写盘、不提示)。在线时提示重启 daemon 生效,不自动重启。
4193
+ * 这是设置页所有 lynx.json 编辑项的统一入口。
4194
+ *
4195
+ * @returns 是否成功写盘
4196
+ */
4197
+ async updateLynxConfig(mutator, description) {
4198
+ let config;
4199
+ try {
4200
+ config = loadLynxConfig();
4201
+ } catch (error) {
4202
+ this.flash(`读取 lynx.json 失败:${String(error)}`);
4203
+ return false;
4204
+ }
4205
+ if (mutator(config) === false) return false;
4206
+ try {
4207
+ writeLynxConfig(config);
4208
+ } catch (error) {
4209
+ this.flash(`写入 lynx.json 失败:${String(error)}`);
4210
+ return false;
4211
+ }
4212
+ this.loadStaticMeta();
4213
+ this.flash(this.apiClient === void 0 ? `${description}已保存,下次启动生效。` : `${description}已保存,重启 daemon 后生效(S)。`);
4214
+ return true;
4215
+ }
4216
+ /** 读取 lynx.json(设置页展示当前值用)。 */
4217
+ readLynxConfig() {
4218
+ try {
4219
+ return loadLynxConfig();
4220
+ } catch {
4221
+ return;
4222
+ }
4223
+ }
4224
+ /**
4225
+ * 切换 mihomo 内核通道(stable/alpha)。
4226
+ *
4227
+ * 一律先写 lynx.json(写失败即中止,避免停了 daemon 却起不来)。
4228
+ * 在线:停 daemon → 按新通道重新启动 → 重连。
4229
+ * 离线:只写配置,下次启动生效。
4230
+ *
4231
+ * 注意:不能用 mihomo API 的 restart()——它只 re-exec 当前同一个二进制,
4232
+ * 无法在 stable/alpha 之间切换,换通道必须重启 daemon 进程。
4233
+ */
4234
+ async switchKernel(channel) {
4235
+ if (this.state.overview.kernelChannel === channel) {
4236
+ this.flash(`已是 ${channel} 内核。`);
4237
+ return;
4238
+ }
4239
+ try {
4240
+ const lynx = loadLynxConfig();
4241
+ lynx.mihomo.kernel = channel;
4242
+ writeLynxConfig(lynx);
4243
+ } catch (error) {
4244
+ this.flash(`写入 lynx.json 失败:${String(error)}`);
4245
+ return;
4246
+ }
4247
+ this.loadStaticMeta();
4248
+ if (this.apiClient === void 0) {
4249
+ this.flash(`已选择 ${channel} 内核,下次启动生效。`);
4250
+ return;
4251
+ }
4252
+ this.flash(`正在切换到 ${channel} 内核…`);
4253
+ this.setDaemon("starting", { error: void 0 });
4254
+ try {
4255
+ await stopDaemon();
4256
+ } catch {}
4257
+ try {
4258
+ if ((await startDaemonDetached({ alpha: channel === "alpha" })).status === "already-running") {
4259
+ await this.bootstrap();
4260
+ return;
4261
+ }
4262
+ const state = await waitForDaemonReady(3e4, 300);
4263
+ await this.connect(state);
4264
+ this.flash(`已切换到 ${channel} 内核。`);
4265
+ } catch (error) {
4266
+ this.setDaemon("stopped", { error: `切换内核失败:${String(error)}(若未安装可执行 lynx mihomo install ${channel})` });
4267
+ }
4268
+ }
4269
+ async startDaemon() {
4270
+ if (this.state.daemon === "starting") return;
4271
+ this.setDaemon("starting", {
4272
+ error: void 0,
4273
+ secretMissing: false
4274
+ });
4275
+ try {
4276
+ if ((await startDaemonDetached()).status === "already-running") {
4277
+ await this.bootstrap();
4278
+ return;
4279
+ }
4280
+ const state = await waitForDaemonReady(3e4, 300);
4281
+ this.flash(void 0);
4282
+ await this.connect(state);
4283
+ } catch (error) {
4284
+ this.setDaemon("stopped", { error: `启动失败:${String(error)}` });
4285
+ }
4286
+ }
4287
+ async stopDaemon() {
4288
+ this.setDaemon("starting", { error: void 0 });
4289
+ try {
4290
+ await stopDaemon();
4291
+ } catch {}
4292
+ this.resetToStopped();
4293
+ }
4294
+ visibleConnections() {
4295
+ return selectVisibleConnections(this.state);
4296
+ }
4297
+ visibleLogs() {
4298
+ return selectVisibleLogs(this.state);
4299
+ }
4300
+ /** 打开日志 WebSocket(切到日志页时由 App 调用)。已连接/离线时安全 no-op。 */
4301
+ startLogs() {
4302
+ if (this.logs !== void 0) return;
4303
+ const state = this.state.daemonState;
4304
+ if (this.apiClient === void 0 || state?.extHost === void 0 || state.extPort === void 0 || state.secret === void 0) return;
4305
+ this.logs = openLogWebSocket(state.extHost, state.extPort, state.secret, this.state.logs.level, { onLog: (entry) => {
4306
+ this.dispatch({
4307
+ type: "logEntry",
4308
+ entry
4309
+ });
4310
+ } });
4311
+ }
4312
+ /** 关闭日志 WebSocket(切走日志页/停止时调用)。 */
4313
+ stopLogs() {
4314
+ this.logs?.stop();
4315
+ this.logs = void 0;
4316
+ }
4317
+ clearLogs() {
4318
+ this.dispatch({ type: "logClear" });
4319
+ }
4320
+ toggleLogPause() {
4321
+ this.dispatch({ type: "logTogglePause" });
4322
+ }
4323
+ setLogFilter(filter) {
4324
+ this.dispatch({
4325
+ type: "logSetFilter",
4326
+ filter
4327
+ });
4328
+ }
4329
+ /**
4330
+ * 设置滚动偏移。atBottom=true 表示视口已在末尾(自动开启跟随);
4331
+ * 用户上翻使 atBottom=false 时自动关闭跟随。
4332
+ */
4333
+ setLogScroll(scroll, atBottom) {
4334
+ this.dispatch({
4335
+ type: "logNav",
4336
+ scroll,
4337
+ follow: atBottom
4338
+ });
4339
+ }
4340
+ /** f 键:显式切换跟随;开启时把视口跳到末尾。 */
4341
+ toggleLogFollow() {
4342
+ this.dispatch({ type: "logToggleFollow" });
4343
+ }
4344
+ /** 切换级别并以新级别重连 WS(级别在 query 中指定,必须重连)。 */
4345
+ cycleLogLevel() {
4346
+ const order = [
4347
+ "debug",
4348
+ "info",
4349
+ "warning",
4350
+ "error"
4351
+ ];
4352
+ const next = order[(order.indexOf(this.state.logs.level) + 1) % order.length];
4353
+ this.dispatch({
4354
+ type: "logSetLevel",
4355
+ level: next
4356
+ });
4357
+ this.logs?.setLevel(next);
4358
+ this.flash(`日志级别:${next}`);
4359
+ }
4360
+ };
4361
+ //#endregion
4362
+ //#region src/tui/index.ts
4363
+ /**
4364
+ * LynxProxy TUI 控制台独立入口。
4365
+ *
4366
+ * 由 `lynx tui` 以独立子进程方式启动(见 src/cli/tui-cli.ts),
4367
+ * 不被主 CLI/daemon 产物 dist/index.mjs 引用。
4368
+ *
4369
+ * 与主进程的交互只发生在运行时:
4370
+ * - 读取 ~/.lynx-proxy/runtime/proxy-daemon.json 拿 daemon 状态与 mihomo 凭据
4371
+ * - HTTP 连 mihomo external-controller(MihomoApiClient)
4372
+ * - WebSocket 订阅 /traffic
4373
+ * - 经控制 socket 发送 reload 等命令
4374
+ * 不发生任何进程内调用。
4375
+ */
4376
+ /**
4377
+ * 启动 TUI 控制台。返回的 Promise 在 TUI 停止后 resolve。
4378
+ */
4379
+ async function runTui() {
4380
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
4381
+ console.error("lynx tui 需要一个交互式终端。");
4382
+ process.exitCode = 1;
4383
+ return;
4384
+ }
4385
+ const terminal = new ProcessTerminal();
4386
+ const tui = new TUI(terminal);
4387
+ const runtime = new TuiRuntime(tui);
4388
+ let stopping = false;
4389
+ const quit = (code = 0) => {
4390
+ if (stopping) return;
4391
+ stopping = true;
4392
+ runtime.stop();
4393
+ tui.stop();
4394
+ terminal.drainInput(500, 50).then(() => {
4395
+ process.exit(code);
4396
+ });
4397
+ };
4398
+ const app = new App(tui, runtime, quit);
4399
+ tui.addChild(app);
4400
+ tui.setFocus(app);
4401
+ process.once("SIGINT", () => quit(0));
4402
+ process.once("SIGTERM", () => quit(0));
4403
+ process.once("SIGHUP", () => quit(0));
4404
+ tui.start();
4405
+ runtime.start().catch(() => {});
4406
+ await new Promise(() => {});
4407
+ }
4408
+ if (process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href) runTui().catch((error) => {
4409
+ console.error(error);
4410
+ process.exit(1);
4411
+ });
4412
+ //#endregion
4413
+ export { runTui };
4414
+
4415
+ //# sourceMappingURL=tui.mjs.map