mihomo-cli 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3110,7 +3110,6 @@ var BASE_CONFIG = {
3110
3110
  }
3111
3111
  };
3112
3112
  var DEFAULT_UPDATE_INTERVAL_HOURS = 12;
3113
- var DEFAULT_UPDATE_INTERVAL_HOURS_GITHUB = 6;
3114
3113
  var DEFAULT_AUTO_UPDATE_TIMEOUT = 1e4;
3115
3114
 
3116
3115
  // src/errors.ts
@@ -3327,6 +3326,14 @@ function recoverCorruptedSettings() {
3327
3326
  settingsCache = {};
3328
3327
  return settingsCache;
3329
3328
  }
3329
+ function isValidSettingsContent(content) {
3330
+ try {
3331
+ const parsed = JSON.parse(content);
3332
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
3333
+ } catch {
3334
+ return false;
3335
+ }
3336
+ }
3330
3337
  function writeSettings(settings) {
3331
3338
  ensureDirs();
3332
3339
  return withFileLock(PATHS.settingsFile, () => writeSettingsUnlocked(settings));
@@ -5118,225 +5125,6 @@ function printVersion() {
5118
5125
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5119
5126
  }
5120
5127
 
5121
- // src/commands/completion.ts
5122
- var COMMAND_WORDS = [
5123
- { word: "install", desc: "\u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09" },
5124
- { word: "start", desc: "\u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F" },
5125
- { word: "stop", desc: "\u505C\u6B62\u4EE3\u7406\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F" },
5126
- { word: "uninstall", desc: "\u5378\u8F7D\u670D\u52A1" },
5127
- { word: "status", desc: "\u67E5\u770B\u72B6\u6001\uFF08--json \u673A\u5668\u53EF\u8BFB\uFF09" },
5128
- { word: "logs", desc: "\u65E5\u5FD7\u5217\u8868/\u67E5\u770B" },
5129
- { word: "ui", desc: "\u6253\u5F00 Web UI" },
5130
- { word: "subscription", desc: "\u8BA2\u9605\u7BA1\u7406" },
5131
- { word: "overwrite", desc: "\u8986\u5199\u914D\u7F6E" },
5132
- { word: "directory", desc: "\u6570\u636E\u76EE\u5F55" },
5133
- { word: "kernel", desc: "\u66F4\u65B0\u5185\u6838" },
5134
- { word: "update", desc: "\u66F4\u65B0 mihomo-cli" },
5135
- { word: "reset", desc: "\u91CD\u7F6E\u7528\u6237\u6570\u636E" },
5136
- { word: "doctor", desc: "\u4F53\u68C0\u8BCA\u65AD" },
5137
- { word: "completion", desc: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C" },
5138
- { word: "use", desc: "\u5207\u6362\u8BA2\u9605\uFF08subscription use \u5FEB\u6377\u65B9\u5F0F\uFF09" },
5139
- { word: "tun", desc: "\u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08= start tun\uFF09" },
5140
- { word: "help", desc: "\u663E\u793A\u5E2E\u52A9" },
5141
- { word: "version", desc: "\u663E\u793A\u7248\u672C" }
5142
- ];
5143
- var SUBCOMMANDS = {
5144
- subscription: [
5145
- { word: "use", desc: "\u5207\u6362\u8BA2\u9605" },
5146
- { word: "add", desc: "\u6DFB\u52A0\u8BA2\u9605" },
5147
- { word: "update", desc: "\u66F4\u65B0\u8BA2\u9605" },
5148
- { word: "remove", desc: "\u5220\u9664\u8BA2\u9605" },
5149
- { word: "rm", desc: "\u5220\u9664\u8BA2\u9605" },
5150
- { word: "delete", desc: "\u5220\u9664\u8BA2\u9605" }
5151
- ],
5152
- overwrite: [
5153
- { word: "on", desc: "\u542F\u7528\u8986\u5199" },
5154
- { word: "off", desc: "\u7981\u7528\u8986\u5199" },
5155
- { word: "enable", desc: "\u542F\u7528\u8986\u5199" },
5156
- { word: "disable", desc: "\u7981\u7528\u8986\u5199" }
5157
- ],
5158
- directory: [{ word: "open", desc: "\u6253\u5F00\u76EE\u5F55" }]
5159
- };
5160
- var DIR_TARGETS = ["root", "subs", "logs", "data", "runtime", "kernel"];
5161
- var UI_NAMES = ["zash", "dash", "yacd"];
5162
- var SHELLS = ["zsh", "bash", "fish"];
5163
- function buildZsh() {
5164
- const lines = [
5165
- "#compdef mihomo mhm mh mihomo-cli",
5166
- "",
5167
- '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: \u5199\u5165 ~/.zsh/completions/_mihomo \u6216 eval "$(mihomo completion zsh)"\uFF09',
5168
- "",
5169
- "_mihomo() {",
5170
- " local -a commands subcmds",
5171
- " commands=(",
5172
- ...COMMAND_WORDS.map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
5173
- " )",
5174
- "",
5175
- " _arguments -C \\",
5176
- " '1: :->cmd' \\",
5177
- " '*::arg:->args'",
5178
- "",
5179
- " case $state in",
5180
- " cmd)",
5181
- " _describe 'command' commands",
5182
- " ;;",
5183
- " args)",
5184
- " case ${words[1]} in"
5185
- ];
5186
- for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
5187
- const aliases = group === "subscription" ? "subscription|sub|subs|subscriptions" : group === "overwrite" ? "overwrite|ow" : "directory|dir|dirs|directories";
5188
- lines.push(` ${aliases})`);
5189
- lines.push(" subcmds=(");
5190
- for (const s of subs) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
5191
- lines.push(" )");
5192
- lines.push(" if (( CURRENT == 2 )); then");
5193
- lines.push(" _describe 'subcommand' subcmds");
5194
- lines.push(" else");
5195
- lines.push(" _files");
5196
- lines.push(" fi");
5197
- lines.push(" ;;");
5198
- }
5199
- lines.push(
5200
- " directory|dir|dirs|directories)",
5201
- " if (( CURRENT == 3 )); then",
5202
- ` _values 'target' ${DIR_TARGETS.join(" ")}`,
5203
- " fi",
5204
- " ;;",
5205
- " logs)",
5206
- " _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
5207
- " ;;",
5208
- " ui)",
5209
- ` _values 'ui' ${UI_NAMES.join(" ")}`,
5210
- " ;;",
5211
- " kernel)",
5212
- " _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:' '--no-mirror[\u76F4\u8FDE\u4E0B\u8F7D]'",
5213
- " ;;",
5214
- " reset)",
5215
- ` _values 'target' subs logs data runtime settings kernel overwrites service`,
5216
- " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
5217
- " ;;",
5218
- " completion)",
5219
- ` _values 'shell' ${SHELLS.join(" ")}`,
5220
- " ;;",
5221
- " *)",
5222
- " _files",
5223
- " ;;",
5224
- " esac",
5225
- " ;;",
5226
- " esac",
5227
- "}",
5228
- "",
5229
- '_mihomo "$@"'
5230
- );
5231
- return lines.join("\n");
5232
- }
5233
- function buildBash() {
5234
- const top = COMMAND_WORDS.map((c) => c.word).join(" ");
5235
- return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
5236
-
5237
- _mihomo_completions() {
5238
- local cur prev
5239
- COMPREPLY=()
5240
- cur="\${COMP_WORDS[COMP_CWORD]}"
5241
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
5242
-
5243
- if [[ \${COMP_CWORD} -eq 1 ]]; then
5244
- COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
5245
- return 0
5246
- fi
5247
-
5248
- case "\${COMP_WORDS[1]}" in
5249
- subscription|sub|subs|subscriptions)
5250
- if [[ \${COMP_CWORD} -eq 2 ]]; then
5251
- COMPREPLY=( $(compgen -W "use add update remove rm delete" -- "\${cur}") )
5252
- fi
5253
- ;;
5254
- overwrite|ow)
5255
- if [[ \${COMP_CWORD} -eq 2 ]]; then
5256
- COMPREPLY=( $(compgen -W "on off enable disable" -- "\${cur}") )
5257
- fi
5258
- ;;
5259
- directory|dir|dirs|directories)
5260
- if [[ \${COMP_CWORD} -eq 2 ]]; then
5261
- COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
5262
- elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
5263
- COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
5264
- fi
5265
- ;;
5266
- logs)
5267
- COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
5268
- ;;
5269
- ui)
5270
- COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
5271
- ;;
5272
- kernel)
5273
- COMPREPLY=( $(compgen -W "--mirror --no-mirror" -- "\${cur}") )
5274
- ;;
5275
- reset)
5276
- COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
5277
- ;;
5278
- completion)
5279
- COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
5280
- ;;
5281
- esac
5282
- }
5283
- complete -F _mihomo_completions mihomo mhm mh mihomo-cli
5284
- `;
5285
- }
5286
- function buildFish() {
5287
- const lines = [
5288
- "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
5289
- "",
5290
- "for cmd in mihomo mhm mh mihomo-cli"
5291
- ];
5292
- for (const c of COMMAND_WORDS) {
5293
- lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
5294
- }
5295
- const subAliases = {
5296
- subscription: "subscription sub subs subscriptions",
5297
- overwrite: "overwrite ow",
5298
- directory: "directory dir dirs directories"
5299
- };
5300
- for (const [group, subs] of Object.entries(SUBCOMMANDS)) {
5301
- for (const s of subs) {
5302
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${subAliases[group]}" -a '${s.word}' -d '${s.desc}'`);
5303
- }
5304
- }
5305
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
5306
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
5307
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
5308
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
5309
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
5310
- lines.push("end");
5311
- return lines.join("\n");
5312
- }
5313
- function buildCompletionScript(shell) {
5314
- switch (shell) {
5315
- case "zsh":
5316
- return buildZsh();
5317
- case "bash":
5318
- return buildBash();
5319
- case "fish":
5320
- return buildFish();
5321
- default: {
5322
- const suggestion = suggestSimilar(shell, [...SHELLS]);
5323
- throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
5324
- label: "\u53C2\u6570\u9519\u8BEF",
5325
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
5326
- });
5327
- }
5328
- }
5329
- }
5330
- function cmdCompletion(args) {
5331
- const shell = args[1];
5332
- if (!shell) {
5333
- throw new CliError("\u8BF7\u6307\u5B9A shell", {
5334
- hint: [`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`, '\u5B89\u88C5: eval "$(mihomo completion zsh)"\uFF0C\u6216\u5199\u5165\u5BF9\u5E94 shell \u7684\u8865\u5168\u76EE\u5F55']
5335
- });
5336
- }
5337
- console.log(buildCompletionScript(shell));
5338
- }
5339
-
5340
5128
  // src/open.ts
5341
5129
  import { spawn } from "child_process";
5342
5130
 
@@ -5507,8 +5295,8 @@ function getRuntimeMode() {
5507
5295
  if (isServiceInstalled()) return "mixed";
5508
5296
  return getConfigInfo()?.tun ? "tun" : "mixed";
5509
5297
  }
5510
- function getRunningState() {
5511
- const service = getServiceStatus();
5298
+ function getRunningState(serviceStatus) {
5299
+ const service = serviceStatus ?? getServiceStatus();
5512
5300
  if (service.running) {
5513
5301
  return { running: true, pid: service.pid, kind: "service", processInfo: null };
5514
5302
  }
@@ -5639,14 +5427,8 @@ async function withSpinner(label, fn) {
5639
5427
  }
5640
5428
 
5641
5429
  // src/subscription.ts
5642
- function isGithubUrl(url) {
5643
- return /github\.com|raw\.githubusercontent\.com/i.test(url);
5644
- }
5645
- function getDefaultUpdateInterval(url) {
5646
- return isGithubUrl(url) ? DEFAULT_UPDATE_INTERVAL_HOURS_GITHUB : DEFAULT_UPDATE_INTERVAL_HOURS;
5647
- }
5648
- function resolveUpdateInterval(url, cachedInterval) {
5649
- return cachedInterval && cachedInterval > 0 ? cachedInterval : getDefaultUpdateInterval(url);
5430
+ function resolveUpdateInterval(cachedInterval) {
5431
+ return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
5650
5432
  }
5651
5433
  var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
5652
5434
  function isValidHttpUrl(url) {
@@ -5850,7 +5632,7 @@ function needsAutoUpdate(sub) {
5850
5632
  const lastUpdate = new Date(sub.updated_at).getTime();
5851
5633
  if (Number.isNaN(lastUpdate)) return true;
5852
5634
  if (lastUpdate > Date.now()) return true;
5853
- const intervalHours = resolveUpdateInterval(sub.url, sub.update_interval);
5635
+ const intervalHours = resolveUpdateInterval(sub.update_interval);
5854
5636
  const intervalMs = intervalHours * 60 * 60 * 1e3;
5855
5637
  return Date.now() - lastUpdate > intervalMs;
5856
5638
  }
@@ -5877,7 +5659,7 @@ async function autoUpdateStaleSubscription(options = {}) {
5877
5659
  }
5878
5660
  if (staleSubs.length === 1) {
5879
5661
  const sub = staleSubs[0];
5880
- const interval = resolveUpdateInterval(sub.url, sub.update_interval);
5662
+ const interval = resolveUpdateInterval(sub.update_interval);
5881
5663
  console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
5882
5664
  } else {
5883
5665
  console.log(`\u68C0\u67E5\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
@@ -5918,7 +5700,7 @@ var PROBE_URL = "https://www.gstatic.com/generate_204";
5918
5700
  function isProbeSuccessStatus(code) {
5919
5701
  return code !== null && code >= 200 && code < 300;
5920
5702
  }
5921
- async function probeProxyConnectivity(port, timeoutMs = 5e3) {
5703
+ async function probeProxyConnectivity(port, timeoutMs = 2e3) {
5922
5704
  const start = Date.now();
5923
5705
  try {
5924
5706
  const { stdout } = await execFileAsync(
@@ -6015,8 +5797,9 @@ function buildStatusJson(args) {
6015
5797
  }
6016
5798
  async function printStatus(args = []) {
6017
5799
  const asJson = hasFlag(args, "-j", "--json");
6018
- const state = getRunningState();
5800
+ const skipProbe = hasFlag(args, "--no-probe");
6019
5801
  const service = getServiceStatus();
5802
+ const state = getRunningState(service);
6020
5803
  const info = getConfigInfo();
6021
5804
  const overwriteEnabled = isOverwriteEnabled();
6022
5805
  const overwriteFiles = listOverwriteFile().files;
@@ -6025,7 +5808,7 @@ async function printStatus(args = []) {
6025
5808
  const legacy = detectLegacySystemInstall();
6026
5809
  const { running, pid, kind } = state;
6027
5810
  let probe = null;
6028
- if (running && info?.mixedPort) {
5811
+ if (running && info?.mixedPort && !skipProbe) {
6029
5812
  probe = await probeProxyConnectivity(info.mixedPort);
6030
5813
  }
6031
5814
  if (asJson) {
@@ -6215,6 +5998,10 @@ async function cmdStart(args) {
6215
5998
  throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
6216
5999
  }
6217
6000
  await printStatus();
6001
+ if (targetMode === "mixed") {
6002
+ console.log(colors.gray("\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:7890\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09"));
6003
+ console.log("");
6004
+ }
6218
6005
  }
6219
6006
 
6220
6007
  // src/commands/shared.ts
@@ -6308,12 +6095,12 @@ function printDirectoryInfo() {
6308
6095
  console.log(colors.gray(" \u81EA\u5B9A\u4E49\u6839\u76EE\u5F55: \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR"));
6309
6096
  console.log("");
6310
6097
  }
6311
- var SUBCOMMANDS2 = [{ name: "open", handler: openDirectory }];
6098
+ var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
6312
6099
  async function cmdDirectory(args) {
6313
- await dispatchSubcommand(args, SUBCOMMANDS2, {
6100
+ await dispatchSubcommand(args, SUBCOMMANDS, {
6314
6101
  fallback: printDirectoryInfo,
6315
6102
  onUnknown: (action) => {
6316
- const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6103
+ const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
6317
6104
  const suggestion = suggestSimilar(action, names);
6318
6105
  throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
6319
6106
  hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo dir open <target>"]
@@ -6322,79 +6109,521 @@ async function cmdDirectory(args) {
6322
6109
  });
6323
6110
  }
6324
6111
 
6325
- // src/commands/doctor.ts
6326
- import { spawnSync as spawnSync5 } from "child_process";
6327
- import fs10 from "fs";
6328
- function isPortListening(port) {
6329
- try {
6330
- const r = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
6331
- return r.status === 0 && (r.stdout || "").trim().length > 0;
6332
- } catch {
6333
- return false;
6334
- }
6335
- }
6336
- function collectChecks() {
6337
- const checks = [];
6338
- const push = (name, status, detail, fix) => {
6339
- checks.push({ name, status, detail, fix });
6340
- };
6341
- if (!hasKernel()) {
6342
- push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
6343
- } else {
6344
- const v = getKernelVersion();
6345
- const r = spawnSync5(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
6346
- if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
6347
- push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
6348
- } else {
6349
- push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
6350
- }
6351
- }
6352
- try {
6353
- fs10.accessSync(USER_DATA_DIR, fs10.constants.W_OK);
6354
- push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
6355
- } catch {
6356
- push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
6357
- }
6358
- if (fs10.existsSync(PATHS.settingsFile)) {
6359
- try {
6360
- const parsed = JSON.parse(fs10.readFileSync(PATHS.settingsFile, "utf8"));
6361
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
6362
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
6363
- } else {
6364
- push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6365
- }
6366
- } catch {
6367
- push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "JSON \u635F\u574F\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6368
- }
6369
- } else {
6370
- push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
6371
- }
6372
- const subs = getSubscriptionsWithCache();
6373
- const active = getActiveSubscription();
6374
- if (subs.length === 0) {
6375
- push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
6112
+ // src/commands/overwrite.ts
6113
+ import path7 from "path";
6114
+ function printOverwriteList() {
6115
+ const info = listOverwriteFile();
6116
+ const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6117
+ console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6118
+ console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6119
+ console.log("");
6120
+ if (info.files.length === 0) {
6121
+ console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6122
+ console.log("");
6123
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path7.join(info.dir, "overwrite.yaml")}`);
6124
+ console.log(` \u6216 ${path7.join(info.dir, "overwrite.dns.yaml")}`);
6125
+ console.log("");
6376
6126
  } else {
6377
- push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
6378
- if (active) {
6379
- if (!readSubscriptionRawConfig(active.name)) {
6380
- push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
6381
- } else {
6382
- push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
6127
+ console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
6128
+ console.log("");
6129
+ info.files.forEach((f, i) => {
6130
+ const num = i < 10 ? ` ${i}` : `${i}`;
6131
+ console.log(` ${num}. ${f.name}`);
6132
+ if (f.scope) {
6133
+ console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6383
6134
  }
6384
- const cached = subs.find((s) => s.name === active.name);
6385
- if (cached?.updated_at) {
6386
- const rel = formatRelativeTime(cached.updated_at);
6387
- const intervalH = resolveUpdateInterval(cached.url, cached.update_interval);
6388
- const ageH = (Date.now() - new Date(cached.updated_at).getTime()) / 36e5;
6389
- if (ageH > intervalH) {
6390
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${intervalH} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
6391
- } else {
6392
- push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
6393
- }
6135
+ if (f.keys.length > 0) {
6136
+ console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6394
6137
  }
6395
- }
6138
+ });
6139
+ console.log("");
6396
6140
  }
6397
- const service = getServiceStatus();
6141
+ console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6142
+ console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6143
+ console.log("");
6144
+ }
6145
+ async function setOverwrite(enabled, args) {
6146
+ if (isOverwriteEnabled() === enabled) {
6147
+ console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
6148
+ console.log("");
6149
+ printOverwriteList();
6150
+ return;
6151
+ }
6152
+ setOverwriteEnabled(enabled);
6153
+ console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
6154
+ if (await restartToApply(args)) return;
6155
+ console.log("");
6156
+ printOverwriteList();
6157
+ }
6158
+ var SUBCOMMANDS2 = [
6159
+ { name: "on", aliases: ["enable"], description: "\u542F\u7528\u8986\u5199", handler: (args) => setOverwrite(true, args) },
6160
+ { name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
6161
+ ];
6162
+ async function cmdOverwrite(args) {
6163
+ await dispatchSubcommand(args, SUBCOMMANDS2, {
6164
+ // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6165
+ fallback: () => {
6166
+ console.log("");
6167
+ printOverwriteList();
6168
+ },
6169
+ onUnknown: (action) => {
6170
+ const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
6171
+ const suggestion = suggestSimilar(action, names);
6172
+ throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
6173
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
6174
+ });
6175
+ }
6176
+ });
6177
+ }
6178
+
6179
+ // src/commands/subscription.ts
6180
+ function printRestartHintIfRunning() {
6181
+ if (getRunningState().running) {
6182
+ console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C mihomo start \u4F7F\u66F4\u65B0\u751F\u6548"));
6183
+ console.log("");
6184
+ }
6185
+ }
6186
+ function printSubscriptionList() {
6187
+ const subs = getSubscriptionsWithCache();
6188
+ if (subs.length === 0) {
6189
+ console.log("\u6CA1\u6709\u8BA2\u9605");
6190
+ console.log("");
6191
+ console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
6192
+ console.log("");
6193
+ return;
6194
+ }
6195
+ const activeSub = getActiveSubscription();
6196
+ console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
6197
+ subs.forEach((s, i) => {
6198
+ const rel = formatRelativeTime(s.updated_at);
6199
+ const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
6200
+ const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
6201
+ const interval = resolveUpdateInterval(s.update_interval);
6202
+ console.log(` ${i + 1}. ${s.name}${defaultMark}`);
6203
+ console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
6204
+ if (s.username) {
6205
+ console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
6206
+ }
6207
+ const traffic = formatTraffic(s.upload, s.download, s.total);
6208
+ if (traffic) {
6209
+ console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
6210
+ }
6211
+ if (s.expire !== void 0) {
6212
+ console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
6213
+ }
6214
+ if (s.web_page_url) {
6215
+ console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
6216
+ }
6217
+ });
6218
+ console.log("");
6219
+ console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
6220
+ console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
6221
+ console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
6222
+ console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
6223
+ console.log("");
6224
+ }
6225
+ function assertNotFlagLike(name, usage) {
6226
+ if (name.startsWith("-")) {
6227
+ throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
6228
+ label: "\u53C2\u6570\u9519\u8BEF",
6229
+ hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
6230
+ });
6231
+ }
6232
+ }
6233
+ async function subAdd(args) {
6234
+ const url = args[2]?.trim();
6235
+ const name = args[3] || "default";
6236
+ if (!url) {
6237
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL");
6238
+ }
6239
+ if (!isValidHttpUrl(url)) {
6240
+ throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
6241
+ }
6242
+ assertNotFlagLike(name, "mihomo sub add <url> [name]");
6243
+ console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
6244
+ addSubscription(url, name);
6245
+ try {
6246
+ const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
6247
+ setDefaultSubscription(name);
6248
+ console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
6249
+ } catch (e) {
6250
+ removeSubscription(name);
6251
+ if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
6252
+ throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
6253
+ }
6254
+ console.log("");
6255
+ printSubscriptionList();
6256
+ }
6257
+ async function subUpdate(args) {
6258
+ const name = args[2];
6259
+ const subs = getSubscriptions();
6260
+ if (subs.length === 0) {
6261
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605");
6262
+ }
6263
+ if (!name) {
6264
+ console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
6265
+ const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
6266
+ let ok = 0;
6267
+ for (const r of results) {
6268
+ if (r.success) ok++;
6269
+ printUpdateResult(r);
6270
+ }
6271
+ if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
6272
+ console.log("");
6273
+ printRestartHintIfRunning();
6274
+ printSubscriptionList();
6275
+ return;
6276
+ }
6277
+ const target = resolveSubscription(subs, name);
6278
+ console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
6279
+ const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
6280
+ if (!result.success) {
6281
+ throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
6282
+ }
6283
+ console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
6284
+ console.log("");
6285
+ printRestartHintIfRunning();
6286
+ printSubscriptionList();
6287
+ }
6288
+ async function subUse(args) {
6289
+ const name = args[2];
6290
+ const subs = getSubscriptions();
6291
+ if (subs.length === 0) {
6292
+ throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
6293
+ }
6294
+ if (!name) {
6295
+ throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
6296
+ hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
6297
+ });
6298
+ }
6299
+ const target = resolveSubscription(subs, name);
6300
+ const currentDefault = getActiveSubscription();
6301
+ const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
6302
+ if (isAlreadyDefault) {
6303
+ console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
6304
+ console.log("");
6305
+ printSubscriptionList();
6306
+ return;
6307
+ }
6308
+ const success = setDefaultSubscription(target.name);
6309
+ if (!success) {
6310
+ throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
6311
+ }
6312
+ console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
6313
+ if (await restartToApply(args)) return;
6314
+ console.log("");
6315
+ printSubscriptionList();
6316
+ }
6317
+ async function subRemove(args) {
6318
+ const name = getNonFlagArg(args, 2);
6319
+ const subs = getSubscriptions();
6320
+ if (!name) {
6321
+ throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
6322
+ hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
6323
+ });
6324
+ }
6325
+ const target = resolveSubscription(subs, name);
6326
+ const isExact = target.name === name;
6327
+ const skipConfirm = hasFlag(args, "-y", "--yes");
6328
+ if (!isExact && !skipConfirm) {
6329
+ console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
6330
+ if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
6331
+ nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
6332
+ hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
6333
+ })) {
6334
+ console.log("\u5DF2\u53D6\u6D88");
6335
+ return;
6336
+ }
6337
+ }
6338
+ const switchedTo = removeSubscription(target.name);
6339
+ console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
6340
+ if (switchedTo) {
6341
+ console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
6342
+ }
6343
+ console.log("");
6344
+ printSubscriptionList();
6345
+ }
6346
+ var SUBCOMMANDS3 = [
6347
+ { name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: subAdd },
6348
+ { name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: subUpdate },
6349
+ { name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: subUse },
6350
+ { name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
6351
+ ];
6352
+ async function cmdSubscription(args) {
6353
+ await dispatchSubcommand(args, SUBCOMMANDS3, {
6354
+ // 无子命令 → 列表;未知子命令 → 报错
6355
+ fallback: printSubscriptionList,
6356
+ onUnknown: (action) => {
6357
+ const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
6358
+ const suggestion = suggestSimilar(action, names);
6359
+ throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
6360
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
6361
+ });
6362
+ }
6363
+ });
6364
+ }
6365
+
6366
+ // src/commands/completion.ts
6367
+ function commandWords(commands) {
6368
+ return commands.filter((c) => !c.hidden).map((c) => ({ word: c.name, desc: c.usage[0]?.description ?? "" }));
6369
+ }
6370
+ function subWords(subs) {
6371
+ return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
6372
+ }
6373
+ function subGroups(commands) {
6374
+ const groupOf = (name, subs) => {
6375
+ const cmd = commands.find((c) => c.name === name);
6376
+ return { tokens: cmd ? [cmd.name, ...cmd.aliases] : [name], words: subWords(subs) };
6377
+ };
6378
+ return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
6379
+ }
6380
+ var DIR_TARGETS = ["root", "subs", "logs", "data", "runtime", "kernel"];
6381
+ var UI_NAMES = ["zash", "dash", "yacd"];
6382
+ var SHELLS = ["zsh", "bash", "fish"];
6383
+ function buildZsh(commands, groups) {
6384
+ const lines = [
6385
+ "#compdef mihomo mhm mh mihomo-cli",
6386
+ "",
6387
+ '# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: \u5199\u5165 ~/.zsh/completions/_mihomo \u6216 eval "$(mihomo completion zsh)"\uFF09',
6388
+ "",
6389
+ "_mihomo() {",
6390
+ " local -a commands subcmds",
6391
+ " commands=(",
6392
+ ...commandWords(commands).map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
6393
+ " )",
6394
+ "",
6395
+ " _arguments -C \\",
6396
+ " '1: :->cmd' \\",
6397
+ " '*::arg:->args'",
6398
+ "",
6399
+ " case $state in",
6400
+ " cmd)",
6401
+ " _describe 'command' commands",
6402
+ " ;;",
6403
+ " args)",
6404
+ " case ${words[1]} in"
6405
+ ];
6406
+ for (const group of groups) {
6407
+ const aliases = group.tokens.join("|");
6408
+ lines.push(` ${aliases})`);
6409
+ lines.push(" subcmds=(");
6410
+ for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
6411
+ lines.push(" )");
6412
+ lines.push(" if (( CURRENT == 2 )); then");
6413
+ lines.push(" _describe 'subcommand' subcmds");
6414
+ lines.push(" else");
6415
+ lines.push(" _files");
6416
+ lines.push(" fi");
6417
+ lines.push(" ;;");
6418
+ }
6419
+ lines.push(
6420
+ " directory|dir|dirs|directories)",
6421
+ " if (( CURRENT == 3 )); then",
6422
+ ` _values 'target' ${DIR_TARGETS.join(" ")}`,
6423
+ " fi",
6424
+ " ;;",
6425
+ " logs)",
6426
+ " _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
6427
+ " ;;",
6428
+ " ui)",
6429
+ ` _values 'ui' ${UI_NAMES.join(" ")}`,
6430
+ " ;;",
6431
+ " kernel)",
6432
+ " _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:' '--no-mirror[\u76F4\u8FDE\u4E0B\u8F7D]'",
6433
+ " ;;",
6434
+ " reset)",
6435
+ ` _values 'target' subs logs data runtime settings kernel overwrites service`,
6436
+ " _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
6437
+ " ;;",
6438
+ " completion)",
6439
+ ` _values 'shell' ${SHELLS.join(" ")}`,
6440
+ " ;;",
6441
+ " *)",
6442
+ " _files",
6443
+ " ;;",
6444
+ " esac",
6445
+ " ;;",
6446
+ " esac",
6447
+ "}",
6448
+ "",
6449
+ '_mihomo "$@"'
6450
+ );
6451
+ return lines.join("\n");
6452
+ }
6453
+ function buildBash(commands, groups) {
6454
+ const top = commandWords(commands).map((c) => c.word).join(" ");
6455
+ const subCase = groups.map((group) => {
6456
+ const aliases = group.tokens.join("|");
6457
+ const words = group.words.map((w) => w.word).join(" ");
6458
+ if (group.tokens[0] === "directory") {
6459
+ return ` ${aliases})
6460
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
6461
+ COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
6462
+ elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
6463
+ COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
6464
+ fi
6465
+ ;;`;
6466
+ }
6467
+ return ` ${aliases})
6468
+ if [[ \${COMP_CWORD} -eq 2 ]]; then
6469
+ COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
6470
+ fi
6471
+ ;;`;
6472
+ }).join("\n");
6473
+ return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
6474
+
6475
+ _mihomo_completions() {
6476
+ local cur prev
6477
+ COMPREPLY=()
6478
+ cur="\${COMP_WORDS[COMP_CWORD]}"
6479
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
6480
+
6481
+ if [[ \${COMP_CWORD} -eq 1 ]]; then
6482
+ COMPREPLY=( $(compgen -W "${top}" -- "\${cur}") )
6483
+ return 0
6484
+ fi
6485
+
6486
+ case "\${COMP_WORDS[1]}" in
6487
+ ${subCase}
6488
+ logs)
6489
+ COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
6490
+ ;;
6491
+ ui)
6492
+ COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
6493
+ ;;
6494
+ kernel)
6495
+ COMPREPLY=( $(compgen -W "--mirror --no-mirror" -- "\${cur}") )
6496
+ ;;
6497
+ reset)
6498
+ COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
6499
+ ;;
6500
+ completion)
6501
+ COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
6502
+ ;;
6503
+ esac
6504
+ }
6505
+ complete -F _mihomo_completions mihomo mhm mh mihomo-cli
6506
+ `;
6507
+ }
6508
+ function buildFish(commands, groups) {
6509
+ const lines = [
6510
+ "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
6511
+ "",
6512
+ "for cmd in mihomo mhm mh mihomo-cli"
6513
+ ];
6514
+ for (const c of commandWords(commands)) {
6515
+ lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
6516
+ }
6517
+ for (const group of groups) {
6518
+ const seen = group.tokens.join(" ");
6519
+ for (const s of group.words) {
6520
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${seen}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
6521
+ }
6522
+ }
6523
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
6524
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
6525
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
6526
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
6527
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
6528
+ lines.push("end");
6529
+ return lines.join("\n");
6530
+ }
6531
+ function buildCompletionScript(shell, commands) {
6532
+ const groups = subGroups(commands);
6533
+ switch (shell) {
6534
+ case "zsh":
6535
+ return buildZsh(commands, groups);
6536
+ case "bash":
6537
+ return buildBash(commands, groups);
6538
+ case "fish":
6539
+ return buildFish(commands, groups);
6540
+ default: {
6541
+ const suggestion = suggestSimilar(shell, [...SHELLS]);
6542
+ throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
6543
+ label: "\u53C2\u6570\u9519\u8BEF",
6544
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
6545
+ });
6546
+ }
6547
+ }
6548
+ }
6549
+ function cmdCompletion(args, commands) {
6550
+ const shell = args[1];
6551
+ if (!shell) {
6552
+ throw new CliError("\u8BF7\u6307\u5B9A shell", {
6553
+ hint: [`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`, '\u5B89\u88C5: eval "$(mihomo completion zsh)"\uFF0C\u6216\u5199\u5165\u5BF9\u5E94 shell \u7684\u8865\u5168\u76EE\u5F55']
6554
+ });
6555
+ }
6556
+ console.log(buildCompletionScript(shell, commands));
6557
+ }
6558
+
6559
+ // src/commands/doctor.ts
6560
+ import { spawnSync as spawnSync5 } from "child_process";
6561
+ import fs10 from "fs";
6562
+ function isPortListening(port) {
6563
+ try {
6564
+ const r = spawnSync5("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
6565
+ return r.status === 0 && (r.stdout || "").trim().length > 0;
6566
+ } catch {
6567
+ return false;
6568
+ }
6569
+ }
6570
+ async function collectChecks() {
6571
+ const checks = [];
6572
+ const push = (name, status, detail, fix) => {
6573
+ checks.push({ name, status, detail, fix });
6574
+ };
6575
+ if (!hasKernel()) {
6576
+ push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
6577
+ } else {
6578
+ const v = getKernelVersion();
6579
+ const r = spawnSync5(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
6580
+ if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
6581
+ push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
6582
+ } else {
6583
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
6584
+ }
6585
+ }
6586
+ try {
6587
+ fs10.accessSync(USER_DATA_DIR, fs10.constants.W_OK);
6588
+ push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
6589
+ } catch {
6590
+ push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
6591
+ }
6592
+ if (fs10.existsSync(PATHS.settingsFile)) {
6593
+ if (isValidSettingsContent(fs10.readFileSync(PATHS.settingsFile, "utf8"))) {
6594
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
6595
+ } else {
6596
+ push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
6597
+ }
6598
+ } else {
6599
+ push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u672A\u521B\u5EFA\uFF08\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF09");
6600
+ }
6601
+ const subs = getSubscriptionsWithCache();
6602
+ const active = getActiveSubscription();
6603
+ if (subs.length === 0) {
6604
+ push("\u8BA2\u9605", "warn", "\u672A\u914D\u7F6E", "mihomo sub add <url>");
6605
+ } else {
6606
+ push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
6607
+ if (active) {
6608
+ if (!readSubscriptionRawConfig(active.name)) {
6609
+ push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo sub update ${active.name}`);
6610
+ } else {
6611
+ push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
6612
+ }
6613
+ const cached = subs.find((s) => s.name === active.name);
6614
+ if (cached?.updated_at) {
6615
+ const rel = formatRelativeTime(cached.updated_at);
6616
+ const intervalH = resolveUpdateInterval(cached.update_interval);
6617
+ const ageH = (Date.now() - new Date(cached.updated_at).getTime()) / 36e5;
6618
+ if (ageH > intervalH) {
6619
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${intervalH} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
6620
+ } else {
6621
+ push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
6622
+ }
6623
+ }
6624
+ }
6625
+ }
6626
+ const service = getServiceStatus();
6398
6627
  const legacy = detectLegacySystemInstall();
6399
6628
  if (legacy) {
6400
6629
  push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
@@ -6409,7 +6638,11 @@ function collectChecks() {
6409
6638
  push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0");
6410
6639
  }
6411
6640
  } else {
6412
- push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
6641
+ if (!service.disabled && service.lastExitCode !== null && service.lastExitCode !== 0) {
6642
+ push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${service.lastExitCode}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo stop \u505C\u6B62\u91CD\u8BD5");
6643
+ } else {
6644
+ push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${service.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
6645
+ }
6413
6646
  }
6414
6647
  const state = getRunningState();
6415
6648
  const info = getConfigInfo();
@@ -6436,62 +6669,34 @@ function collectChecks() {
6436
6669
  } else {
6437
6670
  push("\u914D\u7F6E\u6784\u5EFA", "warn", "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
6438
6671
  }
6439
- if (state.running && info?.mixedPort) {
6440
- const probe = probeProxyConnectivitySyncShim(info.mixedPort);
6441
- if (probe.ok) {
6442
- push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
6443
- } else {
6444
- push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
6445
- }
6446
- } else {
6447
- push("\u4EE3\u7406\u8FDE\u901A", "ok", "\u672A\u8FD0\u884C\uFF0C\u8DF3\u8FC7");
6448
- }
6449
- return checks;
6450
- }
6451
- function probeProxyConnectivitySyncShim(port) {
6452
- const start = Date.now();
6453
- try {
6454
- const r = spawnSync5(
6455
- "curl",
6456
- [
6457
- "-x",
6458
- `http://127.0.0.1:${port}`,
6459
- "-s",
6460
- "-o",
6461
- "/dev/null",
6462
- "-w",
6463
- "%{http_code}",
6464
- "--connect-timeout",
6465
- "3",
6466
- "--max-time",
6467
- "5",
6468
- "https://www.gstatic.com/generate_204"
6469
- ],
6470
- { encoding: "utf8", timeout: 8e3 }
6471
- );
6472
- const code = Number.parseInt((r.stdout || "").trim(), 10);
6473
- const statusCode = Number.isFinite(code) ? code : null;
6474
- const ok = statusCode !== null && statusCode >= 200 && statusCode < 300;
6475
- return { ok, statusCode, error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`, durationMs: Date.now() - start };
6476
- } catch (e) {
6477
- return { ok: false, statusCode: null, error: e.message, durationMs: Date.now() - start };
6672
+ if (state.running && info?.mixedPort) {
6673
+ const probe = await probeProxyConnectivity(info.mixedPort);
6674
+ if (probe.ok) {
6675
+ push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
6676
+ } else {
6677
+ push("\u4EE3\u7406\u8FDE\u901A", "warn", `\u4E0D\u901A: ${probe.error}`, "\u8282\u70B9\u53EF\u80FD\u5931\u6548\uFF0Cmihomo ui \u5207\u6362\u8282\u70B9");
6678
+ }
6679
+ } else {
6680
+ push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
6478
6681
  }
6682
+ return checks;
6479
6683
  }
6480
6684
  async function cmdDoctor() {
6481
- const checks = collectChecks();
6685
+ const checks = await collectChecks();
6482
6686
  console.log("");
6483
6687
  for (const c of checks) {
6484
- const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : colors.red("\u2717");
6688
+ const mark = c.status === "ok" ? colors.green("\u2713") : c.status === "warn" ? colors.yellow("!") : c.status === "fail" ? colors.red("\u2717") : colors.gray("\xB7");
6485
6689
  console.log(`${mark} ${colors.bold(c.name)}: ${c.detail}`);
6486
- if (c.status !== "ok" && c.fix) {
6690
+ if (c.status !== "ok" && c.status !== "skip" && c.fix) {
6487
6691
  console.log(colors.gray(` \u4FEE\u590D: ${c.fix}`));
6488
6692
  }
6489
6693
  }
6490
6694
  const ok = checks.filter((c) => c.status === "ok").length;
6491
6695
  const warn = checks.filter((c) => c.status === "warn").length;
6492
6696
  const fail = checks.filter((c) => c.status === "fail").length;
6697
+ const skip = checks.filter((c) => c.status === "skip").length;
6493
6698
  console.log("");
6494
- console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38`);
6699
+ console.log(`\u4F53\u68C0\u5B8C\u6210: ${ok} \u9879\u6B63\u5E38\uFF0C${warn} \u9879\u8B66\u544A\uFF0C${fail} \u9879\u5F02\u5E38${skip > 0 ? `\uFF0C${skip} \u9879\u8DF3\u8FC7` : ""}`);
6495
6700
  console.log("");
6496
6701
  if (fail > 0) {
6497
6702
  throw new CliError(`\u53D1\u73B0 ${fail} \u9879\u5F02\u5E38`, {
@@ -6504,7 +6709,7 @@ async function cmdDoctor() {
6504
6709
  // src/kernel.ts
6505
6710
  import { spawnSync as spawnSync6 } from "child_process";
6506
6711
  import fs11 from "fs";
6507
- import path7 from "path";
6712
+ import path8 from "path";
6508
6713
 
6509
6714
  // node_modules/compare-versions/lib/esm/utils.js
6510
6715
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
@@ -6644,7 +6849,7 @@ function findBinaryInDir(dir, maxDepth = 4) {
6644
6849
  if (maxDepth <= 0) return null;
6645
6850
  const files = fs11.readdirSync(dir);
6646
6851
  for (const f of files) {
6647
- const fullPath = path7.join(dir, f);
6852
+ const fullPath = path8.join(dir, f);
6648
6853
  const stat = fs11.lstatSync(fullPath);
6649
6854
  if (stat.isDirectory()) {
6650
6855
  const found = findBinaryInDir(fullPath, maxDepth - 1);
@@ -6673,7 +6878,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6673
6878
  }
6674
6879
  assertTrustedAssetUrl(asset.browser_download_url);
6675
6880
  const downloadUrl = withMirror(asset.browser_download_url, mirror);
6676
- const tempPath = path7.join(DIRS.kernel, path7.basename(asset.name));
6881
+ const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
6677
6882
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
6678
6883
  if (mirror && progressCallback) {
6679
6884
  progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
@@ -6763,8 +6968,8 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6763
6968
  if (tarResult.error) throw tarResult.error;
6764
6969
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
6765
6970
  } else if (tempPath.endsWith(".gz")) {
6766
- const baseName = path7.basename(tempPath, ".gz");
6767
- const outputPath = path7.join(extractPath, baseName);
6971
+ const baseName = path8.basename(tempPath, ".gz");
6972
+ const outputPath = path8.join(extractPath, baseName);
6768
6973
  const gzipResult = spawnSync6("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6769
6974
  if (gzipResult.error) throw gzipResult.error;
6770
6975
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
@@ -6964,73 +7169,6 @@ function cmdLogs(args) {
6964
7169
  console.log("");
6965
7170
  }
6966
7171
 
6967
- // src/commands/overwrite.ts
6968
- import path8 from "path";
6969
- function printOverwriteList() {
6970
- const info = listOverwriteFile();
6971
- const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
6972
- console.log(`${colors.gray("\u72B6\u6001: ")}${statusText}`);
6973
- console.log(`${colors.gray("\u4F4D\u7F6E: ")}${info.dir}`);
6974
- console.log("");
6975
- if (info.files.length === 0) {
6976
- console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6977
- console.log("");
6978
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6979
- console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
6980
- console.log("");
6981
- } else {
6982
- console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
6983
- console.log("");
6984
- info.files.forEach((f, i) => {
6985
- const num = i < 10 ? ` ${i}` : `${i}`;
6986
- console.log(` ${num}. ${f.name}`);
6987
- if (f.scope) {
6988
- console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
6989
- }
6990
- if (f.keys.length > 0) {
6991
- console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
6992
- }
6993
- });
6994
- console.log("");
6995
- }
6996
- console.log("\u542F\u7528\u8986\u5199: mihomo ow on");
6997
- console.log("\u7981\u7528\u8986\u5199: mihomo ow off");
6998
- console.log("");
6999
- }
7000
- async function setOverwrite(enabled, args) {
7001
- if (isOverwriteEnabled() === enabled) {
7002
- console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
7003
- console.log("");
7004
- printOverwriteList();
7005
- return;
7006
- }
7007
- setOverwriteEnabled(enabled);
7008
- console.log(`\u5DF2${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u8986\u5199\u914D\u7F6E`);
7009
- if (await restartToApply(args)) return;
7010
- console.log("");
7011
- printOverwriteList();
7012
- }
7013
- var SUBCOMMANDS3 = [
7014
- { name: "on", aliases: ["enable"], handler: (args) => setOverwrite(true, args) },
7015
- { name: "off", aliases: ["disable"], handler: (args) => setOverwrite(false, args) }
7016
- ];
7017
- async function cmdOverwrite(args) {
7018
- await dispatchSubcommand(args, SUBCOMMANDS3, {
7019
- // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
7020
- fallback: () => {
7021
- console.log("");
7022
- printOverwriteList();
7023
- },
7024
- onUnknown: (action) => {
7025
- const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
7026
- const suggestion = suggestSimilar(action, names);
7027
- throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
7028
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
7029
- });
7030
- }
7031
- });
7032
- }
7033
-
7034
7172
  // src/commands/removed.ts
7035
7173
  function removedCommand(name, version, hint) {
7036
7174
  return () => {
@@ -7480,193 +7618,6 @@ async function cmdStop(args) {
7480
7618
  console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
7481
7619
  }
7482
7620
 
7483
- // src/commands/subscription.ts
7484
- function printRestartHintIfRunning() {
7485
- if (getRunningState().running) {
7486
- console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C mihomo start \u4F7F\u66F4\u65B0\u751F\u6548"));
7487
- console.log("");
7488
- }
7489
- }
7490
- function printSubscriptionList() {
7491
- const subs = getSubscriptionsWithCache();
7492
- if (subs.length === 0) {
7493
- console.log("\u6CA1\u6709\u8BA2\u9605");
7494
- console.log("");
7495
- console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
7496
- console.log("");
7497
- return;
7498
- }
7499
- const activeSub = getActiveSubscription();
7500
- console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
7501
- subs.forEach((s, i) => {
7502
- const rel = formatRelativeTime(s.updated_at);
7503
- const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
7504
- const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
7505
- const interval = resolveUpdateInterval(s.url, s.update_interval);
7506
- console.log(` ${i + 1}. ${s.name}${defaultMark}`);
7507
- console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
7508
- if (s.username) {
7509
- console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
7510
- }
7511
- const traffic = formatTraffic(s.upload, s.download, s.total);
7512
- if (traffic) {
7513
- console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
7514
- }
7515
- if (s.expire !== void 0) {
7516
- console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
7517
- }
7518
- if (s.web_page_url) {
7519
- console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
7520
- }
7521
- });
7522
- console.log("");
7523
- console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
7524
- console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
7525
- console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
7526
- console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
7527
- console.log("");
7528
- }
7529
- function assertNotFlagLike(name, usage) {
7530
- if (name.startsWith("-")) {
7531
- throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
7532
- label: "\u53C2\u6570\u9519\u8BEF",
7533
- hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
7534
- });
7535
- }
7536
- }
7537
- async function subAdd(args) {
7538
- const url = args[2]?.trim();
7539
- const name = args[3] || "default";
7540
- if (!url) {
7541
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL");
7542
- }
7543
- if (!isValidHttpUrl(url)) {
7544
- throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
7545
- }
7546
- assertNotFlagLike(name, "mihomo sub add <url> [name]");
7547
- console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
7548
- addSubscription(url, name);
7549
- try {
7550
- const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
7551
- setDefaultSubscription(name);
7552
- console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
7553
- } catch (e) {
7554
- removeSubscription(name);
7555
- if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
7556
- throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
7557
- }
7558
- console.log("");
7559
- printSubscriptionList();
7560
- }
7561
- async function subUpdate(args) {
7562
- const name = args[2];
7563
- const subs = getSubscriptions();
7564
- if (subs.length === 0) {
7565
- throw new CliError("\u6CA1\u6709\u8BA2\u9605");
7566
- }
7567
- if (!name) {
7568
- console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
7569
- const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
7570
- let ok = 0;
7571
- for (const r of results) {
7572
- if (r.success) ok++;
7573
- printUpdateResult(r);
7574
- }
7575
- if (ok === 0) throw new CliError("\u5168\u90E8\u8BA2\u9605\u66F4\u65B0\u5931\u8D25");
7576
- console.log("");
7577
- printRestartHintIfRunning();
7578
- printSubscriptionList();
7579
- return;
7580
- }
7581
- const target = resolveSubscription(subs, name);
7582
- console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
7583
- const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
7584
- if (!result.success) {
7585
- throw new CliError((result.error || "").split("\n")[0], { label: "\u66F4\u65B0\u5931\u8D25" });
7586
- }
7587
- console.log(`\u5DF2\u66F4\u65B0 (${formatProxySummary(result)})`);
7588
- console.log("");
7589
- printRestartHintIfRunning();
7590
- printSubscriptionList();
7591
- }
7592
- async function subUse(args) {
7593
- const name = args[2];
7594
- const subs = getSubscriptions();
7595
- if (subs.length === 0) {
7596
- throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
7597
- }
7598
- if (!name) {
7599
- throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", {
7600
- hint: ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)]
7601
- });
7602
- }
7603
- const target = resolveSubscription(subs, name);
7604
- const currentDefault = getActiveSubscription();
7605
- const isAlreadyDefault = currentDefault && currentDefault.name === target.name;
7606
- if (isAlreadyDefault) {
7607
- console.log(`"${target.name}" \u5DF2\u662F\u5F53\u524D\u4F7F\u7528\u7684\u8BA2\u9605`);
7608
- console.log("");
7609
- printSubscriptionList();
7610
- return;
7611
- }
7612
- const success = setDefaultSubscription(target.name);
7613
- if (!success) {
7614
- throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605 "${name}"`);
7615
- }
7616
- console.log(`\u5DF2\u5207\u6362\u5230 "${target.name}"`);
7617
- if (await restartToApply(args)) return;
7618
- console.log("");
7619
- printSubscriptionList();
7620
- }
7621
- async function subRemove(args) {
7622
- const name = getNonFlagArg(args, 2);
7623
- const subs = getSubscriptions();
7624
- if (!name) {
7625
- throw new CliError("\u8BF7\u6307\u5B9A\u8981\u5220\u9664\u7684\u8BA2\u9605\u540D\u79F0", {
7626
- hint: subs.length > 0 ? ["", "\u53EF\u7528\u8BA2\u9605:", ...subs.map((s) => ` ${s.name}`)] : void 0
7627
- });
7628
- }
7629
- const target = resolveSubscription(subs, name);
7630
- const isExact = target.name === name;
7631
- const skipConfirm = hasFlag(args, "-y", "--yes");
7632
- if (!isExact && !skipConfirm) {
7633
- console.log(`\u5C06\u5220\u9664\u8BA2\u9605 "${target.name}" (\u6A21\u7CCA\u5339\u914D "${name}")`);
7634
- if (!await confirmOrThrow("\u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D\uFF0C\u786E\u8BA4?", {
7635
- nonTtyMessage: `\u6A21\u7CCA\u5339\u914D\u5230 "${target.name}"\uFF0C\u975E\u4EA4\u4E92\u73AF\u5883\u9700\u786E\u8BA4`,
7636
- hint: [`\u8BF7\u7528\u5B8C\u6574\u540D\u79F0: mihomo sub remove ${target.name}`, `\u6216\u8DF3\u8FC7\u786E\u8BA4: mihomo sub remove ${name} -y`]
7637
- })) {
7638
- console.log("\u5DF2\u53D6\u6D88");
7639
- return;
7640
- }
7641
- }
7642
- const switchedTo = removeSubscription(target.name);
7643
- console.log(`\u5DF2\u5220\u9664\u8BA2\u9605 "${target.name}"`);
7644
- if (switchedTo) {
7645
- console.log(`\u5DF2\u81EA\u52A8\u5207\u6362\u5230 "${switchedTo}"`);
7646
- }
7647
- console.log("");
7648
- printSubscriptionList();
7649
- }
7650
- var SUBCOMMANDS4 = [
7651
- { name: "add", handler: subAdd },
7652
- { name: "update", handler: subUpdate },
7653
- { name: "use", handler: subUse },
7654
- { name: "remove", aliases: ["rm", "delete"], handler: subRemove }
7655
- ];
7656
- async function cmdSubscription(args) {
7657
- await dispatchSubcommand(args, SUBCOMMANDS4, {
7658
- // 无子命令 → 列表;未知子命令 → 报错
7659
- fallback: printSubscriptionList,
7660
- onUnknown: (action) => {
7661
- const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7662
- const suggestion = suggestSimilar(action, names);
7663
- throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7664
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
7665
- });
7666
- }
7667
- });
7668
- }
7669
-
7670
7621
  // src/commands/ui.ts
7671
7622
  import { spawnSync as spawnSync8 } from "child_process";
7672
7623
  function copyToClipboard(text) {
@@ -7736,12 +7687,12 @@ async function cmdUpdate() {
7736
7687
  if (code === 0) {
7737
7688
  resolve();
7738
7689
  } else {
7739
- reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u53EF\u5C1D\u8BD5: sudo npm install -g mihomo-cli", { exitCode: code || 1 }));
7690
+ reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
7740
7691
  }
7741
7692
  });
7742
7693
  npm.on("error", (e) => {
7743
7694
  const perm = e.message.includes("EACCES") || e.message.includes("permission");
7744
- reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF0C\u53EF\u5C1D\u8BD5: sudo npm install -g mihomo-cli") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7695
+ reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
7745
7696
  });
7746
7697
  });
7747
7698
  try {
@@ -7804,7 +7755,7 @@ var COMMANDS = [
7804
7755
  aliases: [],
7805
7756
  handler: printStatus,
7806
7757
  group: "control",
7807
- usage: [{ signature: "status", description: "\u67E5\u770B\u72B6\u6001" }]
7758
+ usage: [{ signature: "status [-j|--json] [--no-probe]", description: "\u67E5\u770B\u72B6\u6001" }]
7808
7759
  },
7809
7760
  // === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
7810
7761
  {
@@ -7819,21 +7770,24 @@ var COMMANDS = [
7819
7770
  "\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
7820
7771
  ]),
7821
7772
  group: "meta",
7822
- usage: []
7773
+ usage: [],
7774
+ hidden: true
7823
7775
  },
7824
7776
  {
7825
7777
  name: "up",
7826
7778
  aliases: [],
7827
7779
  handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
7828
7780
  group: "meta",
7829
- usage: []
7781
+ usage: [],
7782
+ hidden: true
7830
7783
  },
7831
7784
  {
7832
7785
  name: "down",
7833
7786
  aliases: [],
7834
7787
  handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
7835
7788
  group: "meta",
7836
- usage: []
7789
+ usage: [],
7790
+ hidden: true
7837
7791
  },
7838
7792
  // === 界面 ===
7839
7793
  {
@@ -7844,13 +7798,14 @@ var COMMANDS = [
7844
7798
  usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
7845
7799
  },
7846
7800
  {
7847
- // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空)
7801
+ // 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空),也不进补全词表
7848
7802
  name: "log",
7849
7803
  aliases: [],
7850
7804
  handler: cmdLogs,
7851
7805
  rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
7852
7806
  group: "interface",
7853
- usage: []
7807
+ usage: [],
7808
+ hidden: true
7854
7809
  },
7855
7810
  {
7856
7811
  name: "logs",
@@ -7935,7 +7890,7 @@ var COMMANDS = [
7935
7890
  {
7936
7891
  name: "completion",
7937
7892
  aliases: [],
7938
- handler: cmdCompletion,
7893
+ handler: (args) => cmdCompletion(args, COMMANDS),
7939
7894
  group: "system",
7940
7895
  usage: [{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA shell \u8865\u5168\u811A\u672C\uFF08eval \u6216\u5199\u5165\u8865\u5168\u76EE\u5F55\uFF09" }]
7941
7896
  },