mihomo-cli 4.10.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,50 @@
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
+
32
+ ## [4.11.0] - 2026-09-13
33
+
34
+ 一处展示层误导的修复:`status` 此前会把「不适用于当前订阅」的覆写文件与真正生效的并排列出。单测 657(+8)。
35
+
36
+ ### 变更
37
+
38
+ - **`status` 的覆写行区分「生效」与「不适用」**:此前括号里列的是「目录里没被 `enabled: false` 停用的文件」,不按 `match` 过滤——只对别的订阅生效的文件会和真正生效的混在一行里,长得一模一样。用户拿它解释自己看到的行为(「我明明覆写了」),排查方向整个跑偏。现主行只列本次真正参与合并的文件,未命中的每个展开一行说明原因:`glados 不适用于当前订阅 mini1(作用域 name=edu*)`——文件名、当前订阅、作用域三者凑齐才看得出为什么没命中。两类失效分开计数而不合并成一个数字:「不适用」要改 `match` 或切订阅,「已禁用」要改文件里的 `enabled`,原因与改法都不同。status 判得了 match 是因为它知道当前活跃订阅,而 `mihomo ow` 列表不绑定某条订阅、判不了也不该判,那里维持原样(`listOverwriteFile` 不传 scope 时 `matched` 为 undefined = 未判定,与「未命中」区分)。判据仍是 `matchesScope` 本身,合并闸门也仍只有 `selectActiveOverwriteFiles`——新增的 `matched` 只供展示。反向验证:让 status 不传 scope,5 条新用例转红,另 2 条(`ow` 列表不判 match、全命中时无补充行)按设计恒绿
39
+
40
+ ### 新增
41
+
42
+ - **`status --json` 新增 `overwrite.applied`**:本次真正参与合并的覆写文件清单,三道过滤与 `buildConfig` 对齐(全局开关 → 文件级 `enabled` → 当前订阅的 `match`)。`overwrite.files` 保持旧契约不变(只滤文件级 `enabled`,不按 match、不随全局开关变空),两者并存以免破坏既有脚本
43
+
44
+ ### 修复
45
+
46
+ - **`applied` 漏了全局开关这道过滤**:上一条提交自引入,复查时实跑发现。`ow off` 之后同一份 JSON 里 `enabled` 是 `false`、`applied` 却列着文件,而人读形态此时只说「已禁用」、一个文件都不列——两种形态对不上,也与 `buildConfig` 的实际行为不符(全局关闭时它压根不加载任何覆写文件)。根因是契约注释先写错、实现照着错契约写,现三道过滤对齐并补回归用例
47
+
3
48
  ## [4.10.0] - 2026-09-13
4
49
 
5
50
  覆写作用域与单文件开关两项增强,并堵上三个相邻的静默失效。单测 649(+46)。
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
 
@@ -491,6 +494,15 @@ hosts:
491
494
 
492
495
  > `url-domain` 命中该域名下的**所有**订阅。同一机场的多条订阅(如 `edu1`、`mini1`)URL 往往同域名,用 `url-domain` 会一并生效;要在同机场内按套餐区分,用 `name` 通配(如 `name: edu*`)。若只是担心某条订阅没有要改的分组,用 `~?key` 就够了(它会自动跳过),不必为此改作用域;`match` 应当按「这份覆写在语义上属于哪些订阅」来写。
493
496
 
497
+ `mihomo status` 会按当前活跃订阅区分「生效」与「不适用」,括号里只列本次真正参与合并的文件:
498
+
499
+ ```text
500
+ 覆写: 已启用 (seal,1 个不适用,1 个已禁用)
501
+ glados 不适用于当前订阅 mini1(作用域 name=edu*)
502
+ ```
503
+
504
+ 「不适用」指文件本身是启用的,只是 `match` 没命中当前订阅——切到命中的订阅(`sub use`)或改 `match` 才会生效,与 `enabled: false` 的「已禁用」是两回事。`mihomo ow` 列表不做这个判断(它不绑定某条订阅),那里的作用域一栏只说明该文件管哪些订阅。`--json` 形态下 `overwrite.applied` 是生效清单(`ow off` 全局关闭时为空数组),`overwrite.files` 仍是「未被 `enabled: false` 停用」的全部文件
505
+
494
506
  ### 单个文件的开关(enabled)
495
507
 
496
508
  在覆写文件顶部写 `enabled: false`,可**只停用这一个文件**,其余覆写照常生效:
@@ -679,7 +691,7 @@ sudo pkill -9 mihomo
679
691
  - **URL 脱敏**:订阅 URL 中的 token、key、password 等敏感参数(含 query、userinfo 及路径型令牌)自动替换为 `***`。按整条 URL 处理、不按逗号切分——逗号在 query 中合法,切开会让 `?nodes=us,hk&token=xxx` 的 token 参数识别不出而明文输出
680
692
  - **文件权限**:配置文件使用 `0o600` 权限(仅所有者可读可写),目录使用 `0o700` 权限
681
693
  - **入站默认关闭**:订阅/覆写未指定时 `allow-lan` 默认 `false`;如需局域网设备连入代理端口,可在订阅或覆写中显式开启
682
- - **入站与控制面由本工具独占**:订阅与覆写里的入站端口(`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 实例,不通过订阅投递
683
695
  - **信号处理**:优雅处理 SIGINT/SIGTERM 信号
684
696
  - **异常捕获**:全局 uncaughtException 和 unhandledRejection 处理
685
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 {
@@ -4051,7 +4055,7 @@ function applyOverwrite(baseConfig, files) {
4051
4055
  }
4052
4056
  return { config: result, skipped, operatorShapedKeys };
4053
4057
  }
4054
- function listOverwriteFile() {
4058
+ function listOverwriteFile(scope) {
4055
4059
  const files = loadOverwriteFile();
4056
4060
  const enabled = isOverwriteEnabled();
4057
4061
  return {
@@ -4062,7 +4066,8 @@ function listOverwriteFile() {
4062
4066
  path: f.path,
4063
4067
  keys: Object.keys(f.config || {}),
4064
4068
  scope: summarizeMatch(f.match),
4065
- enabled: f.enabled !== false
4069
+ enabled: f.enabled !== false,
4070
+ ...scope ? { matched: matchesScope(f.match, scope) } : {}
4066
4071
  }))
4067
4072
  };
4068
4073
  }
@@ -4221,9 +4226,11 @@ function assertKnownFlags(args, known, command) {
4221
4226
  const match = matchValueFlagToken(a);
4222
4227
  if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
4223
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`] : [];
4224
4231
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
4225
4232
  label: "\u53C2\u6570\u9519\u8BEF",
4226
- 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}`]
4227
4234
  });
4228
4235
  }
4229
4236
  }
@@ -4381,7 +4388,10 @@ function parseMirrorArg(args) {
4381
4388
  if (mirrorCount > 1) {
4382
4389
  throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
4383
4390
  label: "\u53C2\u6570\u9519\u8BEF",
4384
- 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"]
4385
4395
  });
4386
4396
  }
4387
4397
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
@@ -4426,7 +4436,17 @@ var LOCKED_CONFIG_KEYS = [
4426
4436
  // bind-address 都管不到它们(那两个只作用于 HTTP/Socks/Redir/TProxy/Mixed)。
4427
4437
  // 即订阅里一行 `ss-config: ss://aes-128-gcm:pass@0.0.0.0:8388` 就是全网卡开放代理
4428
4438
  "ss-config",
4429
- "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"
4430
4450
  ];
4431
4451
  function loadYamlSafe(content) {
4432
4452
  return load(content, SAFE_YAML_LOAD_OPTIONS);
@@ -6307,7 +6327,13 @@ function buildStatusJson(args) {
6307
6327
  stale: args.cached ? isSubscriptionStale(args.cached) : false,
6308
6328
  urgency
6309
6329
  } : null,
6310
- overwrite: { enabled: args.overwriteEnabled, files: args.overwriteFiles },
6330
+ overwrite: {
6331
+ enabled: args.overwriteEnabled,
6332
+ files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6333
+ // 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
6334
+ // 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
6335
+ applied: args.overwriteEnabled ? args.overwriteFiles.filter((f) => f.enabled && f.matched !== false).map((f) => f.name) : []
6336
+ },
6311
6337
  service: {
6312
6338
  installed: args.service.installed,
6313
6339
  loaded: args.service.loaded,
@@ -6327,8 +6353,8 @@ async function printStatus(args = []) {
6327
6353
  const service = getServiceStatus();
6328
6354
  const state = getRunningState(service);
6329
6355
  const info = getConfigInfo();
6330
- const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile();
6331
6356
  const activeSub = getActiveSubscription();
6357
+ const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
6332
6358
  const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
6333
6359
  const legacy = detectLegacySystemInstall();
6334
6360
  const { running, pid, kind } = state;
@@ -6348,11 +6374,9 @@ async function printStatus(args = []) {
6348
6374
  activeSub,
6349
6375
  cached,
6350
6376
  overwriteEnabled,
6351
- // 只滤掉被 `enabled: false` 停用的文件。**不是**「当前生效的覆写」——这里拿不到
6352
- // 活跃订阅的 scope(listOverwriteFile 不做 match 过滤),也不受同级 enabled 字段
6353
- // (全局开关)影响:全局 off 时本数组照样列出文件。真·生效清单只有 buildConfig
6354
- // 侧的 overwriteSummaries(已按 match 与全局开关过滤)。契约仍是 string[]
6355
- overwriteFiles: overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
6377
+ // 两个数组在 buildStatusJson 里分出来:files 仍是旧契约(只滤文件级 enabled,
6378
+ // 不按 match、不随全局开关变空),applied 才是本次真正参与合并的
6379
+ overwriteFiles,
6356
6380
  service,
6357
6381
  legacy
6358
6382
  }),
@@ -6431,20 +6455,35 @@ async function printStatus(args = []) {
6431
6455
  } else {
6432
6456
  console.log(`${colors.gray("\u8BA2\u9605: ")}\u672A\u914D\u7F6E ${colors.gray("(\u6DFB\u52A0: mihomo sub add <url>)")}`);
6433
6457
  }
6434
- const activeOverwriteFiles = overwriteFiles.filter((f) => f.enabled);
6435
- const disabledOverwriteCount = overwriteFiles.length - activeOverwriteFiles.length;
6436
- const disabledSuffix = disabledOverwriteCount > 0 ? `\uFF0C${disabledOverwriteCount} \u4E2A\u5DF2\u7981\u7528` : "";
6437
- if (overwriteEnabled && activeOverwriteFiles.length > 0) {
6438
- const names = activeOverwriteFiles.map((f) => f.name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6").join(", ");
6439
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${names}${disabledSuffix})`);
6440
- } else if (overwriteEnabled) {
6441
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${disabledOverwriteCount > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${disabledSuffix}` : "\u65E0\u6587\u4EF6"})`);
6442
- } else {
6443
- console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
6444
- }
6458
+ printOverwriteLines(overwriteEnabled, overwriteFiles, activeSub);
6445
6459
  printServiceLines(service, legacy);
6446
6460
  console.log("");
6447
6461
  }
6462
+ function shortOverwriteName(name) {
6463
+ return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6464
+ }
6465
+ function printOverwriteLines(enabled, files, activeSub) {
6466
+ if (!enabled) {
6467
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
6468
+ return;
6469
+ }
6470
+ const active = files.filter((f) => f.enabled && f.matched !== false);
6471
+ const unmatched = files.filter((f) => f.enabled && f.matched === false);
6472
+ const disabledCount = files.filter((f) => !f.enabled).length;
6473
+ const suffixes = [];
6474
+ if (unmatched.length > 0) suffixes.push(`${unmatched.length} \u4E2A\u4E0D\u9002\u7528`);
6475
+ if (disabledCount > 0) suffixes.push(`${disabledCount} \u4E2A\u5DF2\u7981\u7528`);
6476
+ const suffix = suffixes.length > 0 ? `\uFF0C${suffixes.join("\uFF0C")}` : "";
6477
+ if (active.length > 0) {
6478
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${active.map((f) => shortOverwriteName(f.name)).join(", ")}${suffix})`);
6479
+ } else {
6480
+ console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
6481
+ }
6482
+ for (const f of unmatched) {
6483
+ const scope = f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
6484
+ console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${scope}\uFF09`));
6485
+ }
6486
+ }
6448
6487
  function printServiceLines(service, legacy) {
6449
6488
  if (!service.installed && !service.loaded) {
6450
6489
  console.log(`${colors.gray("\u670D\u52A1: ")}${colors.yellow("\u672A\u5B89\u88C5")} ${colors.gray("(mihomo install \u5B89\u88C5\u540E\u53EF\u7528 Mixed \u6A21\u5F0F)")}`);
@@ -7231,6 +7270,9 @@ var UI_NAMES = Object.keys(UI_URLS);
7231
7270
  var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
7232
7271
  var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
7233
7272
  var SHELLS = ["zsh", "bash", "fish"];
7273
+ function zshSingleQuote(s) {
7274
+ return s.replace(/'/g, "'\\''");
7275
+ }
7234
7276
  function buildZsh(commands, groups) {
7235
7277
  const lines = [
7236
7278
  "#compdef mihomo mhm mh mihomo-cli",
@@ -7240,7 +7282,7 @@ function buildZsh(commands, groups) {
7240
7282
  "_mihomo() {",
7241
7283
  " local -a commands subcmds",
7242
7284
  " commands=(",
7243
- ...commandWords(commands).map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
7285
+ ...commandWords(commands).map((c) => ` '${c.word}:${zshSingleQuote(c.desc)}'`),
7244
7286
  " )",
7245
7287
  "",
7246
7288
  " _arguments -C \\",
@@ -7259,7 +7301,7 @@ function buildZsh(commands, groups) {
7259
7301
  const isDirectory = group.tokens.includes("directory");
7260
7302
  lines.push(` ${aliases})`);
7261
7303
  lines.push(" subcmds=(");
7262
- 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)}'`);
7263
7305
  lines.push(" )");
7264
7306
  lines.push(" if (( CURRENT == 2 )); then");
7265
7307
  lines.push(" _describe 'subcommand' subcmds");
@@ -7304,7 +7346,19 @@ function buildZsh(commands, groups) {
7304
7346
  " esac",
7305
7347
  "}",
7306
7348
  "",
7307
- '_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"
7308
7362
  );
7309
7363
  return lines.join("\n");
7310
7364
  }
@@ -7316,7 +7370,7 @@ function buildBash(commands, groups) {
7316
7370
  if (group.tokens[0] === "directory") {
7317
7371
  return ` ${aliases})
7318
7372
  if [[ \${COMP_CWORD} -eq 2 ]]; then
7319
- COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
7373
+ COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7320
7374
  elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
7321
7375
  COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
7322
7376
  fi
@@ -7371,6 +7425,9 @@ ${subCase}
7371
7425
  complete -F _mihomo_completions mihomo mhm mh mihomo-cli
7372
7426
  `;
7373
7427
  }
7428
+ function fishSingleQuote(s) {
7429
+ return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
7430
+ }
7374
7431
  function buildFish(commands, groups) {
7375
7432
  const lines = [
7376
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",
@@ -7378,18 +7435,17 @@ function buildFish(commands, groups) {
7378
7435
  "for cmd in mihomo mhm mh mihomo-cli"
7379
7436
  ];
7380
7437
  for (const c of commandWords(commands)) {
7381
- 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)}'`);
7382
7439
  }
7383
7440
  for (const group of groups) {
7384
7441
  const seen = group.tokens.join(" ");
7385
7442
  const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
7386
7443
  for (const s of group.words) {
7387
- 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)}'`);
7388
7445
  }
7389
7446
  }
7390
- lines.push(
7391
- ` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
7392
- );
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(" ")}'`);
7393
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(" ")}'`);
7394
7450
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
7395
7451
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
@@ -7400,7 +7456,7 @@ function buildFish(commands, groups) {
7400
7456
  lines.push("end");
7401
7457
  return lines.join("\n");
7402
7458
  }
7403
- function buildCompletionScript(shell, commands) {
7459
+ function buildCompletionScript(shell, commands, usageVerb = "") {
7404
7460
  const groups = subGroups(commands);
7405
7461
  switch (shell) {
7406
7462
  case "zsh":
@@ -7411,14 +7467,26 @@ function buildCompletionScript(shell, commands) {
7411
7467
  return buildFish(commands, groups);
7412
7468
  default: {
7413
7469
  const suggestion = suggestSimilar(shell, [...SHELLS]);
7470
+ const usage = `\u7528\u6CD5: mihomo completion ${usageVerb ? `${usageVerb} ` : ""}<${SHELLS.join("|")}>`;
7414
7471
  throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
7415
7472
  label: "\u53C2\u6570\u9519\u8BEF",
7416
- 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]
7417
7474
  });
7418
7475
  }
7419
7476
  }
7420
7477
  }
7421
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
+ }
7422
7490
  function completionInstallPath(shell) {
7423
7491
  const home = os3.homedir();
7424
7492
  switch (shell) {
@@ -7440,7 +7508,7 @@ function installCompletion(shell, commands) {
7440
7508
  }
7441
7509
  const target = completionInstallPath(shell);
7442
7510
  if (!target) {
7443
- buildCompletionScript(shell, commands);
7511
+ buildCompletionScript(shell, commands, "install");
7444
7512
  return;
7445
7513
  }
7446
7514
  const script = buildCompletionScript(shell, commands);
@@ -7448,18 +7516,36 @@ function installCompletion(shell, commands) {
7448
7516
  try {
7449
7517
  if (shell === "bash") {
7450
7518
  const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
7451
- if (existing.includes(BASH_MARKER)) {
7519
+ if (hasBashMarkerBlock(existing)) {
7452
7520
  console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
7453
7521
  return;
7454
7522
  }
7455
7523
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7456
7524
  fs12.appendFileSync(target, `
7457
7525
  ${BASH_MARKER}
7458
- ${script}${BASH_MARKER.replace(">>>", "<<<")}
7526
+ ${script}${BASH_END_MARKER}
7459
7527
  `);
7460
7528
  console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7461
7529
  return;
7462
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
+ }
7463
7549
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7464
7550
  fs12.writeFileSync(target, script, { mode: 420 });
7465
7551
  console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
@@ -7479,7 +7565,7 @@ function uninstallCompletion(shell, commands) {
7479
7565
  }
7480
7566
  const target = completionInstallPath(shell);
7481
7567
  if (!target) {
7482
- buildCompletionScript(shell, commands);
7568
+ buildCompletionScript(shell, commands, "uninstall");
7483
7569
  return;
7484
7570
  }
7485
7571
  if (!fs12.existsSync(target)) {
@@ -7490,29 +7576,36 @@ function uninstallCompletion(shell, commands) {
7490
7576
  try {
7491
7577
  if (shell === "bash") {
7492
7578
  const existing2 = fs12.readFileSync(target, "utf8");
7493
- const endMarker = BASH_MARKER.replace(">>>", "<<<");
7494
- const start = existing2.indexOf(BASH_MARKER);
7495
- const end = existing2.indexOf(endMarker);
7496
- if (start === -1 || end === -1 || end < start) {
7579
+ if (!hasBashMarkerBlock(existing2)) {
7497
7580
  console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
7498
7581
  console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
7499
7582
  return;
7500
7583
  }
7501
- const before = existing2.slice(0, start).replace(/\n+$/, "\n");
7502
- const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
7503
- 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
+ }
7504
7594
  if (rest.trim() === "") {
7505
7595
  fs12.rmSync(target);
7506
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"));
7507
7597
  return;
7508
7598
  }
7509
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
+ }
7510
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"));
7511
7604
  return;
7512
7605
  }
7513
7606
  const existing = fs12.readFileSync(target, "utf8");
7514
- const fingerprint = shell === "zsh" ? "#compdef mihomo mhm mh mihomo-cli" : "for cmd in mihomo mhm mh mihomo-cli";
7515
- if (!existing.includes(fingerprint)) {
7607
+ const fingerprint = productFingerprint(shell);
7608
+ if (!fingerprint || !existing.includes(fingerprint)) {
7516
7609
  throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
7517
7610
  label: "\u5378\u8F7D\u4E2D\u6B62",
7518
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}`]
@@ -7678,6 +7771,7 @@ async function collectChecks() {
7678
7771
  const push = (name, status, detail, fix, notes) => {
7679
7772
  checks.push({ name, status, detail, fix, notes });
7680
7773
  };
7774
+ const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7681
7775
  if (!hasKernel()) {
7682
7776
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7683
7777
  } else {
@@ -7805,7 +7899,7 @@ async function collectChecks() {
7805
7899
  } else {
7806
7900
  push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
7807
7901
  }
7808
- const latest = await getLatestNpmVersion(4e3);
7902
+ const latest = await latestVersionPromise;
7809
7903
  if (latest === null) {
7810
7904
  push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7811
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.10.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": {