mihomo-cli 4.11.0 → 4.12.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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.12.0] - 2026-09-13
4
+
5
+ 全仓复审修出的十一项:两项入站/文件安全边界、六项修复、两处词表与文案收口、一项性能。单测 689(+32)。
6
+
7
+ ### 安全
8
+
9
+ - **订阅/覆写里的 `listeners` 与 `tunnels` 不再进运行配置**:两者自带监听地址、不受 `allow-lan` 约束,远端订阅一条 `listeners: [{type: socks, listen: 0.0.0.0, port: 18080}]` 即可在全网卡开出无鉴权 SOCKS 入站。判据与已锁的 `ss-config`/`vmess-config`/`tuic-server` 完全相同,此前因被记作「未定的产品决策」而放行了三个版本。确需额外入站请在本机另起实例;`iptables` 仍保留(Linux 专用、非监听)
10
+ - **`completion install zsh|fish` 不再覆盖非本工具生成的同名文件**:此前是无条件写入,用户手写或第三方分发的 `~/.zsh/completions/_mihomo` 会被静默销毁且无备份。判据与 `uninstall` 的删除守卫收口为同一条——此前卸载侧严格把关、安装侧直接覆盖,守的那道形同虚设(覆盖之后指纹就匹配了,卸载反而删得干干净净)
11
+
12
+ ### 修复
13
+
14
+ - **`status` 把主覆写文件显示成 `yaml`**:剥前缀与剥扩展名的顺序写反,`overwrite.yaml` 剩下 `yaml`、「主文件」兜底永不触发。只有一个主文件是最常见的配置形态,该行现显示 `覆写: 已启用 (主文件)`
15
+ - **`--mirror` 重复时的提示指向一个会报错的命令**:原提示「可用镜像见 `mihomo kernel --help`」,而命令级 `--help` 并不存在(只是顶层 help 的别名),照做会得到「未知的选项」。改为直接列出可用镜像
16
+ - **`eval "$(mihomo completion zsh)"` 实际不注册补全**:脚本结尾是裸调用 `_mihomo "$@"`,eval 下 `#compdef` 只是注释,裸调用则在补全上下文之外执行 `_arguments` 并报错,而 `eval` 仍返回 0——用户照 README 做了却发现补全不工作。改为 `compdef` 注册,两条安装路径(fpath 文件 / eval)现在都生效
17
+ - **bash 半截标记块导致 install 与 uninstall 互相甩锅**:`~/.bash_completion` 只剩起始标记时(手工编辑或上次写入中断),install 报「已安装过」、uninstall 报「未找到标记」,双双退出 0 且都不改文件,用户没有 CLI 路径可修。install 的幂等判据改为要求成对标记,可自愈
18
+ - **zsh 补全描述里的撇号被静默吞掉**:转义用了 `''`,而该写法仅在 `RC_QUOTES` 选项下才是转义(默认关闭),默认下是字符串拼接。改用 `'\''`。当前注册表无此类描述,属预防性修复
19
+ - **fish 补全描述以反斜杠结尾会让脚本语法错误**:只转义了撇号、未转义反斜杠,`-d 'desc\'` 的末尾 `\'` 被读作转义撇号。同为预防性修复
20
+ - **`settings.json` 内容是 JSON 合法的非对象时被静默丢弃**:`[1,2,3]`、`"str"`、`42`、`null` 这几种形态此前既不备份也不告警,而下一次写设置会把文件整个覆盖成默认内容——用户原件无声无息地没了。现与「JSON 解析失败」同样备份到 `.bak` 并告警
21
+ - **bash 补全有重复标记块时需卸载两次**:`uninstall` 只切第一对标记就报「已移除」,文件里仍留着一份生效的 `_mihomo_completions` 定义。现循环剥离到一个不剩,多份时如实告知移除了几份
22
+
23
+ ### 变更
24
+
25
+ - 补全的两处硬编码词表改为从单一真相源派生:bash 的 `dir` 分支不再写死 `open`(改用 `DIRECTORY_SUBCOMMANDS`),fish 的目录目标行不再写死四个 `directory` 别名(改从注册表取)。此前给 `directory` 加别名或子命令时,相邻的派生分支会跟上而这两处不会
26
+ - 不接受任何选项的命令(`completion`/`dir`/`stop` 等)在选项报错时不再打印空的「可用选项: 」,改说「该命令不接受任何选项」;`-h`/`--help` 额外点明它只在顶层可用。`completion install|uninstall <shell>` 的 shell 名报错也带上自己的动词,照提示改不会丢掉 `install` 这一步
27
+
28
+ ### 性能
29
+
30
+ - **`doctor` 的 npm 版本查询改为与本地检查并行**:该查询是纯网络往返(约 780ms),原先串在全部检查之后,而它不依赖任何前序结果。装了内核时体检从约 1070ms 降到约 837ms(省 22%);未装内核时本地检查太短,耗时下界即 npm 查询本身
31
+
3
32
  ## [4.11.0] - 2026-09-13
4
33
 
5
34
  一处展示层误导的修复:`status` 此前会把「不适用于当前订阅」的覆写文件与真正生效的并排列出。单测 657(+8)。
package/README.md CHANGED
@@ -196,6 +196,9 @@ mihomo completion fish | source
196
196
  mihomo completion uninstall zsh # bash 只剥掉自己那段,保留 ~/.bash_completion 中你自己的内容
197
197
  ```
198
198
 
199
+ > zsh/fish 的目标文件名由本工具独占,但**安装前会先确认那是不是自己生成的**:目标已存在且不像本工具的产物时报错退出、不覆盖(你手写或第三方分发的同名补全不会被销毁)。
200
+ > 确认无用后手动 `rm` 再装,或用 `mihomo completion <shell> > <自选路径>` 输出到别处。
201
+
199
202
  > zsh 的 `~/.zsh/completions` 不在默认 `fpath` 里(oh-my-zsh 默认已包含):
200
203
  > 补全不生效时在 `~/.zshrc` 加一行 `fpath=(~/.zsh/completions $fpath)`,重新打开终端。
201
204
 
@@ -688,7 +691,7 @@ sudo pkill -9 mihomo
688
691
  - **URL 脱敏**:订阅 URL 中的 token、key、password 等敏感参数(含 query、userinfo 及路径型令牌)自动替换为 `***`。按整条 URL 处理、不按逗号切分——逗号在 query 中合法,切开会让 `?nodes=us,hk&token=xxx` 的 token 参数识别不出而明文输出
689
692
  - **文件权限**:配置文件使用 `0o600` 权限(仅所有者可读可写),目录使用 `0o700` 权限
690
693
  - **入站默认关闭**:订阅/覆写未指定时 `allow-lan` 默认 `false`;如需局域网设备连入代理端口,可在订阅或覆写中显式开启
691
- - **入站与控制面由本工具独占**:订阅与覆写里的入站端口(`mixed-port`/`port`/`socks-port`/`redir-port`/`tproxy-port`)、独立入站服务端(`tuic-server`/`ss-config`/`vmess-config`)、外部控制器全家桶(`external-controller*`、`external-doh-server`、`secret`、`external-ui*`)与控制器证书段(`tls`)一律剥除,不进运行配置。这些键自带监听地址、不受 `allow-lan` 约束,远端订阅若能投递即可在全网卡开出无鉴权控制器或开放代理;端口与密钥只认 `settings.json`。覆写文件里写了会有提示,订阅侧静默剥除
694
+ - **入站与控制面由本工具独占**:订阅与覆写里的入站端口(`mixed-port`/`port`/`socks-port`/`redir-port`/`tproxy-port`)、独立入站服务端(`tuic-server`/`ss-config`/`vmess-config`)、通用入站声明(`listeners`/`tunnels`)、外部控制器全家桶(`external-controller*`、`external-doh-server`、`secret`、`external-ui*`)与控制器证书段(`tls`)一律剥除,不进运行配置。这些键自带监听地址、不受 `allow-lan` 约束,远端订阅若能投递即可在全网卡开出无鉴权控制器或开放代理;端口与密钥只认 `settings.json`。覆写文件里写了会有提示,订阅侧静默剥除。确需额外入站的场景请在本机另起一个 mihomo 实例,不通过订阅投递
692
695
  - **信号处理**:优雅处理 SIGINT/SIGTERM 信号
693
696
  - **异常捕获**:全局 uncaughtException 和 unhandledRejection 处理
694
697
 
package/dist/index.js CHANGED
@@ -3407,25 +3407,29 @@ function sleepSyncMs(ms) {
3407
3407
  // src/settings.ts
3408
3408
  import fs2 from "fs";
3409
3409
  import path2 from "path";
3410
+ function backupCorruptSettings(reason) {
3411
+ const backup = `${PATHS.settingsFile}.bak`;
3412
+ try {
3413
+ if (fs2.existsSync(backup)) {
3414
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3415
+ } else {
3416
+ fs2.copyFileSync(PATHS.settingsFile, backup);
3417
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3418
+ }
3419
+ } catch {
3420
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3421
+ }
3422
+ return {};
3423
+ }
3410
3424
  function readSettings() {
3411
3425
  if (!fs2.existsSync(PATHS.settingsFile)) return {};
3412
3426
  try {
3413
3427
  const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3414
3428
  if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3429
+ return backupCorruptSettings(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3415
3430
  } catch {
3416
- const backup = `${PATHS.settingsFile}.bak`;
3417
- try {
3418
- if (fs2.existsSync(backup)) {
3419
- console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3420
- } else {
3421
- fs2.copyFileSync(PATHS.settingsFile, backup);
3422
- console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3423
- }
3424
- } catch {
3425
- console.warn("\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
3426
- }
3431
+ return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
3427
3432
  }
3428
- return {};
3429
3433
  }
3430
3434
  function isValidSettingsContent(content) {
3431
3435
  try {
@@ -4222,9 +4226,11 @@ function assertKnownFlags(args, known, command) {
4222
4226
  const match = matchValueFlagToken(a);
4223
4227
  if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
4224
4228
  if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
4229
+ const isHelpFlag = a === "-h" || a === "--help";
4230
+ const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo help`] : [];
4225
4231
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
4226
4232
  label: "\u53C2\u6570\u9519\u8BEF",
4227
- hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
4233
+ hint: [known.length > 0 ? `\u53EF\u7528\u9009\u9879: ${known.join(", ")}` : "\u8BE5\u547D\u4EE4\u4E0D\u63A5\u53D7\u4EFB\u4F55\u9009\u9879", ...helpNote, "", `\u7528\u6CD5: mihomo ${command}`]
4228
4234
  });
4229
4235
  }
4230
4236
  }
@@ -4382,7 +4388,10 @@ function parseMirrorArg(args) {
4382
4388
  if (mirrorCount > 1) {
4383
4389
  throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
4384
4390
  label: "\u53C2\u6570\u9519\u8BEF",
4385
- hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", "\u53EF\u7528\u955C\u50CF\u89C1: mihomo kernel --help"]
4391
+ // 直接列出镜像,不说「见 mihomo kernel --help」:命令级 `--help` 并不存在
4392
+ // (`--help` 只是顶层 help 的别名,`kernel --help` 会撞 assertKnownFlags 报
4393
+ // 「未知的选项」),把用户指向一个必定报错的命令比不给提示更糟
4394
+ hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo kernel --mirror direct"]
4386
4395
  });
4387
4396
  }
4388
4397
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
@@ -4427,7 +4436,17 @@ var LOCKED_CONFIG_KEYS = [
4427
4436
  // bind-address 都管不到它们(那两个只作用于 HTTP/Socks/Redir/TProxy/Mixed)。
4428
4437
  // 即订阅里一行 `ss-config: ss://aes-128-gcm:pass@0.0.0.0:8388` 就是全网卡开放代理
4429
4438
  "ss-config",
4430
- "vmess-config"
4439
+ "vmess-config",
4440
+ // 通用入站声明:`listeners` 每个元素自带 type + listen,一条
4441
+ // `{type: socks, listen: 0.0.0.0, port: 18080}` 即在全网卡开出无鉴权 SOCKS 入站;
4442
+ // `tunnels` 声明本地端口到目标地址的直通转发,同样自带监听地址。两者与上面三个
4443
+ // 入站服务端满足完全相同的判据(订阅可指定监听地址、不经 genAddr、allow-lan 管不到),
4444
+ // 只因在上游是 RawConfig 顶层字段而非 Inbound 结构体成员,此前被记成「未定的产品决策」
4445
+ // 挂了三个版本——而「待定」在实现上等于放行:实测订阅里写 listeners 会原样进运行配置,
4446
+ // 与 README「入站默认关闭 / 入站与控制面由本工具独占」的承诺直接冲突。
4447
+ // 需要额外入站的用户改由本机另起实例,不接受远端订阅投递
4448
+ "listeners",
4449
+ "tunnels"
4431
4450
  ];
4432
4451
  function loadYamlSafe(content) {
4433
4452
  return load(content, SAFE_YAML_LOAD_OPTIONS);
@@ -6441,7 +6460,7 @@ async function printStatus(args = []) {
6441
6460
  console.log("");
6442
6461
  }
6443
6462
  function shortOverwriteName(name) {
6444
- return name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6";
6463
+ return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6445
6464
  }
6446
6465
  function printOverwriteLines(enabled, files, activeSub) {
6447
6466
  if (!enabled) {
@@ -7251,6 +7270,9 @@ var UI_NAMES = Object.keys(UI_URLS);
7251
7270
  var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
7252
7271
  var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
7253
7272
  var SHELLS = ["zsh", "bash", "fish"];
7273
+ function zshSingleQuote(s) {
7274
+ return s.replace(/'/g, "'\\''");
7275
+ }
7254
7276
  function buildZsh(commands, groups) {
7255
7277
  const lines = [
7256
7278
  "#compdef mihomo mhm mh mihomo-cli",
@@ -7260,7 +7282,7 @@ function buildZsh(commands, groups) {
7260
7282
  "_mihomo() {",
7261
7283
  " local -a commands subcmds",
7262
7284
  " commands=(",
7263
- ...commandWords(commands).map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
7285
+ ...commandWords(commands).map((c) => ` '${c.word}:${zshSingleQuote(c.desc)}'`),
7264
7286
  " )",
7265
7287
  "",
7266
7288
  " _arguments -C \\",
@@ -7279,7 +7301,7 @@ function buildZsh(commands, groups) {
7279
7301
  const isDirectory = group.tokens.includes("directory");
7280
7302
  lines.push(` ${aliases})`);
7281
7303
  lines.push(" subcmds=(");
7282
- for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
7304
+ for (const s of group.words) lines.push(` '${s.word}:${zshSingleQuote(s.desc)}'`);
7283
7305
  lines.push(" )");
7284
7306
  lines.push(" if (( CURRENT == 2 )); then");
7285
7307
  lines.push(" _describe 'subcommand' subcmds");
@@ -7324,7 +7346,19 @@ function buildZsh(commands, groups) {
7324
7346
  " esac",
7325
7347
  "}",
7326
7348
  "",
7327
- '_mihomo "$@"'
7349
+ // 结尾必须是 compdef 注册,**不能是裸调用 `_mihomo "$@"`**。
7350
+ //
7351
+ // 两条安装路径对结尾行的要求不同,而裸调用只满足其中一条:
7352
+ // - 放进 fpath(`completion install zsh`):compinit 按 `#compdef` 首行自动注册,
7353
+ // 函数体被 autoload,结尾写什么都行——两种写法实测都能注册全部四个别名
7354
+ // - `eval "$(mihomo completion zsh)"`(README 与下方 CLI 提示都推荐):`#compdef`
7355
+ // 只是条注释、不起作用,而裸调用会在补全上下文之外执行 `_arguments`,实测报
7356
+ // `_arguments:comparguments:327: can only be called from completion function`,
7357
+ // 且 `_comps[mihomo]` 前后都是 0 —— 补全完全没注册,eval 却返回 0。
7358
+ // 用户照文档做了、看到没报错(错误在 stderr 一闪而过)、补全就是不工作。
7359
+ //
7360
+ // compdef 同时满足两条:实测 eval 后四个别名 `_comps` 全部为 1,fpath 安装不受影响。
7361
+ "compdef _mihomo mihomo mhm mh mihomo-cli"
7328
7362
  );
7329
7363
  return lines.join("\n");
7330
7364
  }
@@ -7336,7 +7370,7 @@ function buildBash(commands, groups) {
7336
7370
  if (group.tokens[0] === "directory") {
7337
7371
  return ` ${aliases})
7338
7372
  if [[ \${COMP_CWORD} -eq 2 ]]; then
7339
- COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
7373
+ COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7340
7374
  elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
7341
7375
  COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
7342
7376
  fi
@@ -7391,6 +7425,9 @@ ${subCase}
7391
7425
  complete -F _mihomo_completions mihomo mhm mh mihomo-cli
7392
7426
  `;
7393
7427
  }
7428
+ function fishSingleQuote(s) {
7429
+ return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
7430
+ }
7394
7431
  function buildFish(commands, groups) {
7395
7432
  const lines = [
7396
7433
  "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install fish\uFF0C\u6216 mihomo completion fish | source\uFF09",
@@ -7398,18 +7435,17 @@ function buildFish(commands, groups) {
7398
7435
  "for cmd in mihomo mhm mh mihomo-cli"
7399
7436
  ];
7400
7437
  for (const c of commandWords(commands)) {
7401
- lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
7438
+ lines.push(` complete -c $cmd -f -a '${c.word}' -d '${fishSingleQuote(c.desc)}'`);
7402
7439
  }
7403
7440
  for (const group of groups) {
7404
7441
  const seen = group.tokens.join(" ");
7405
7442
  const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
7406
7443
  for (const s of group.words) {
7407
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
7444
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${fishSingleQuote(s.desc)}'`);
7408
7445
  }
7409
7446
  }
7410
- lines.push(
7411
- ` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
7412
- );
7447
+ const directoryTokens = groups.find((g) => g.tokens.includes("directory"))?.tokens.join(" ") ?? "directory";
7448
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${directoryTokens}; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`);
7413
7449
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
7414
7450
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
7415
7451
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
@@ -7420,7 +7456,7 @@ function buildFish(commands, groups) {
7420
7456
  lines.push("end");
7421
7457
  return lines.join("\n");
7422
7458
  }
7423
- function buildCompletionScript(shell, commands) {
7459
+ function buildCompletionScript(shell, commands, usageVerb = "") {
7424
7460
  const groups = subGroups(commands);
7425
7461
  switch (shell) {
7426
7462
  case "zsh":
@@ -7431,14 +7467,26 @@ function buildCompletionScript(shell, commands) {
7431
7467
  return buildFish(commands, groups);
7432
7468
  default: {
7433
7469
  const suggestion = suggestSimilar(shell, [...SHELLS]);
7470
+ const usage = `\u7528\u6CD5: mihomo completion ${usageVerb ? `${usageVerb} ` : ""}<${SHELLS.join("|")}>`;
7434
7471
  throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
7435
7472
  label: "\u53C2\u6570\u9519\u8BEF",
7436
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
7473
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], usage]
7437
7474
  });
7438
7475
  }
7439
7476
  }
7440
7477
  }
7441
7478
  var BASH_MARKER = "# >>> mihomo-cli completion (append)";
7479
+ var BASH_END_MARKER = BASH_MARKER.replace(">>>", "<<<");
7480
+ function hasBashMarkerBlock(content) {
7481
+ const start = content.indexOf(BASH_MARKER);
7482
+ const end = content.indexOf(BASH_END_MARKER);
7483
+ return start !== -1 && end !== -1 && end > start;
7484
+ }
7485
+ function productFingerprint(shell) {
7486
+ if (shell === "zsh") return "#compdef mihomo mhm mh mihomo-cli";
7487
+ if (shell === "fish") return "for cmd in mihomo mhm mh mihomo-cli";
7488
+ return null;
7489
+ }
7442
7490
  function completionInstallPath(shell) {
7443
7491
  const home = os3.homedir();
7444
7492
  switch (shell) {
@@ -7460,7 +7508,7 @@ function installCompletion(shell, commands) {
7460
7508
  }
7461
7509
  const target = completionInstallPath(shell);
7462
7510
  if (!target) {
7463
- buildCompletionScript(shell, commands);
7511
+ buildCompletionScript(shell, commands, "install");
7464
7512
  return;
7465
7513
  }
7466
7514
  const script = buildCompletionScript(shell, commands);
@@ -7468,18 +7516,36 @@ function installCompletion(shell, commands) {
7468
7516
  try {
7469
7517
  if (shell === "bash") {
7470
7518
  const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
7471
- if (existing.includes(BASH_MARKER)) {
7519
+ if (hasBashMarkerBlock(existing)) {
7472
7520
  console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
7473
7521
  return;
7474
7522
  }
7475
7523
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7476
7524
  fs12.appendFileSync(target, `
7477
7525
  ${BASH_MARKER}
7478
- ${script}${BASH_MARKER.replace(">>>", "<<<")}
7526
+ ${script}${BASH_END_MARKER}
7479
7527
  `);
7480
7528
  console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7481
7529
  return;
7482
7530
  }
7531
+ const fingerprint = productFingerprint(shell);
7532
+ if (fingerprint && fs12.existsSync(target)) {
7533
+ const existing = fs12.readFileSync(target, "utf8");
7534
+ if (!existing.includes(fingerprint)) {
7535
+ throw new CliError(`${target} \u5DF2\u5B58\u5728\u4E14\u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5B89\u88C5`, {
7536
+ label: "\u5B89\u88C5\u4E2D\u6B62",
7537
+ hint: [
7538
+ "\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\uFF0C\u8986\u76D6\u4F1A\u9020\u6210\u4E0D\u53EF\u6062\u590D\u7684\u4E22\u5931\u3002",
7539
+ "\u786E\u8BA4\u65E0\u7528\u540E\u5148\u624B\u52A8\u5220\u9664\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:",
7540
+ ` rm ${target}`,
7541
+ ` mihomo completion install ${shell}`,
7542
+ "",
7543
+ "\u6216\u6539\u4E3A\u624B\u52A8\u8F93\u51FA\u5230\u522B\u5904:",
7544
+ ` mihomo completion ${shell} > <\u4F60\u9009\u62E9\u7684\u8DEF\u5F84>`
7545
+ ]
7546
+ });
7547
+ }
7548
+ }
7483
7549
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7484
7550
  fs12.writeFileSync(target, script, { mode: 420 });
7485
7551
  console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
@@ -7499,7 +7565,7 @@ function uninstallCompletion(shell, commands) {
7499
7565
  }
7500
7566
  const target = completionInstallPath(shell);
7501
7567
  if (!target) {
7502
- buildCompletionScript(shell, commands);
7568
+ buildCompletionScript(shell, commands, "uninstall");
7503
7569
  return;
7504
7570
  }
7505
7571
  if (!fs12.existsSync(target)) {
@@ -7510,29 +7576,36 @@ function uninstallCompletion(shell, commands) {
7510
7576
  try {
7511
7577
  if (shell === "bash") {
7512
7578
  const existing2 = fs12.readFileSync(target, "utf8");
7513
- const endMarker = BASH_MARKER.replace(">>>", "<<<");
7514
- const start = existing2.indexOf(BASH_MARKER);
7515
- const end = existing2.indexOf(endMarker);
7516
- if (start === -1 || end === -1 || end < start) {
7579
+ if (!hasBashMarkerBlock(existing2)) {
7517
7580
  console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
7518
7581
  console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
7519
7582
  return;
7520
7583
  }
7521
- const before = existing2.slice(0, start).replace(/\n+$/, "\n");
7522
- const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
7523
- const rest = `${before}${after}`;
7584
+ let rest = existing2;
7585
+ let removed = 0;
7586
+ while (hasBashMarkerBlock(rest)) {
7587
+ const start = rest.indexOf(BASH_MARKER);
7588
+ const end = rest.indexOf(BASH_END_MARKER);
7589
+ const before = rest.slice(0, start).replace(/\n+$/, "\n");
7590
+ const after = rest.slice(end + BASH_END_MARKER.length).replace(/^\n/, "");
7591
+ rest = `${before}${after}`;
7592
+ removed++;
7593
+ }
7524
7594
  if (rest.trim() === "") {
7525
7595
  fs12.rmSync(target);
7526
7596
  console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7527
7597
  return;
7528
7598
  }
7529
7599
  fs12.writeFileSync(target, rest);
7600
+ if (removed > 1) {
7601
+ console.log(colors.gray(` \u53D1\u73B0\u5E76\u79FB\u9664\u4E86 ${removed} \u4EFD\u91CD\u590D\u7684\u8865\u5168\u6BB5`));
7602
+ }
7530
7603
  console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7531
7604
  return;
7532
7605
  }
7533
7606
  const existing = fs12.readFileSync(target, "utf8");
7534
- const fingerprint = shell === "zsh" ? "#compdef mihomo mhm mh mihomo-cli" : "for cmd in mihomo mhm mh mihomo-cli";
7535
- if (!existing.includes(fingerprint)) {
7607
+ const fingerprint = productFingerprint(shell);
7608
+ if (!fingerprint || !existing.includes(fingerprint)) {
7536
7609
  throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
7537
7610
  label: "\u5378\u8F7D\u4E2D\u6B62",
7538
7611
  hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
@@ -7698,6 +7771,7 @@ async function collectChecks() {
7698
7771
  const push = (name, status, detail, fix, notes) => {
7699
7772
  checks.push({ name, status, detail, fix, notes });
7700
7773
  };
7774
+ const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7701
7775
  if (!hasKernel()) {
7702
7776
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7703
7777
  } else {
@@ -7825,7 +7899,7 @@ async function collectChecks() {
7825
7899
  } else {
7826
7900
  push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
7827
7901
  }
7828
- const latest = await getLatestNpmVersion(4e3);
7902
+ const latest = await latestVersionPromise;
7829
7903
  if (latest === null) {
7830
7904
  push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7831
7905
  } else if (compareVersions(latest, VERSION) > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.11.0",
3
+ "version": "4.12.0",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {