mihomo-cli 4.7.6 → 4.8.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 +86 -0
- package/README.md +48 -32
- package/dist/index.js +495 -692
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
+
// node_modules/compare-versions/lib/esm/utils.js
|
|
4
|
+
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
5
|
+
var validateAndParse = (version) => {
|
|
6
|
+
if (typeof version !== "string") {
|
|
7
|
+
throw new TypeError("Invalid argument expected string");
|
|
8
|
+
}
|
|
9
|
+
const match = version.match(semver);
|
|
10
|
+
if (!match) {
|
|
11
|
+
throw new Error(`Invalid argument not valid semver ('${version}' received)`);
|
|
12
|
+
}
|
|
13
|
+
match.shift();
|
|
14
|
+
return match;
|
|
15
|
+
};
|
|
16
|
+
var isWildcard = (s) => s === "*" || s === "x" || s === "X";
|
|
17
|
+
var tryParse = (v) => {
|
|
18
|
+
const n = parseInt(v, 10);
|
|
19
|
+
return isNaN(n) ? v : n;
|
|
20
|
+
};
|
|
21
|
+
var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
|
|
22
|
+
var compareStrings = (a, b) => {
|
|
23
|
+
if (isWildcard(a) || isWildcard(b))
|
|
24
|
+
return 0;
|
|
25
|
+
const [ap, bp] = forceType(tryParse(a), tryParse(b));
|
|
26
|
+
if (ap > bp)
|
|
27
|
+
return 1;
|
|
28
|
+
if (ap < bp)
|
|
29
|
+
return -1;
|
|
30
|
+
return 0;
|
|
31
|
+
};
|
|
32
|
+
var compareSegments = (a, b) => {
|
|
33
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
34
|
+
const r = compareStrings(a[i] || "0", b[i] || "0");
|
|
35
|
+
if (r !== 0)
|
|
36
|
+
return r;
|
|
37
|
+
}
|
|
38
|
+
return 0;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
42
|
+
var compareVersions = (v1, v2) => {
|
|
43
|
+
const n1 = validateAndParse(v1);
|
|
44
|
+
const n2 = validateAndParse(v2);
|
|
45
|
+
const p1 = n1.pop();
|
|
46
|
+
const p2 = n2.pop();
|
|
47
|
+
const r = compareSegments(n1, n2);
|
|
48
|
+
if (r !== 0)
|
|
49
|
+
return r;
|
|
50
|
+
if (p1 && p2) {
|
|
51
|
+
return compareSegments(p1.split("."), p2.split("."));
|
|
52
|
+
} else if (p1 || p2) {
|
|
53
|
+
return p1 ? -1 : 1;
|
|
54
|
+
}
|
|
55
|
+
return 0;
|
|
56
|
+
};
|
|
57
|
+
|
|
3
58
|
// src/colors.ts
|
|
4
59
|
var NO_COLOR = process.env.NO_COLOR !== void 0 || !process.stdout.isTTY;
|
|
5
60
|
function colorize(code, str) {
|
|
@@ -16,8 +71,10 @@ var colors = {
|
|
|
16
71
|
};
|
|
17
72
|
|
|
18
73
|
// src/config.ts
|
|
19
|
-
import { spawnSync } from "child_process";
|
|
74
|
+
import { execFile, spawnSync } from "child_process";
|
|
20
75
|
import fs4 from "fs";
|
|
76
|
+
import path4 from "path";
|
|
77
|
+
import { promisify } from "util";
|
|
21
78
|
|
|
22
79
|
// node_modules/js-yaml/dist/js-yaml.mjs
|
|
23
80
|
var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
|
|
@@ -3060,6 +3117,12 @@ var require2 = createRequire(import.meta.url);
|
|
|
3060
3117
|
var pkg = require2("../package.json");
|
|
3061
3118
|
var VERSION = pkg.version;
|
|
3062
3119
|
var PKG_NAME = pkg.name;
|
|
3120
|
+
var MIN_NODE_VERSION = (() => {
|
|
3121
|
+
const raw = pkg.engines?.node;
|
|
3122
|
+
if (typeof raw !== "string") return null;
|
|
3123
|
+
const m = raw.trim().match(/^>=\s*(\d+\.\d+\.\d+)$/);
|
|
3124
|
+
return m ? m[1] : null;
|
|
3125
|
+
})();
|
|
3063
3126
|
var MIRROR_HOST = "gh-proxy.org";
|
|
3064
3127
|
var MIRROR_ALIASES = {
|
|
3065
3128
|
v4: `https://v4.${MIRROR_HOST}/`,
|
|
@@ -3211,9 +3274,19 @@ var PATHS = {
|
|
|
3211
3274
|
settingsLock: path.join(USER_DATA_DIR, "settings.lock"),
|
|
3212
3275
|
subscriptionCacheLock: path.join(USER_DATA_DIR, "subscription-cache.lock"),
|
|
3213
3276
|
serviceLock: path.join(USER_DATA_DIR, "service.lock"),
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3277
|
+
/**
|
|
3278
|
+
* 「服务被要求停止」的单调计数(`service.ts` 的 `bumpStopEpoch`/`readStopEpoch`)。
|
|
3279
|
+
*
|
|
3280
|
+
* 为什么需要它:判断「本次 start 执行**期间**是否有人 stop 过」,launchd 自身给不出答案——
|
|
3281
|
+
* disable 位只有当前值,没有写入时间,而它又是**持久**的(上次 stop 留下的与刚刚新置的
|
|
3282
|
+
* 完全同形)。只比对 disable 位的前后快照,在「上次也 stop 过」时两边都是 true,
|
|
3283
|
+
* 并发 stop 就此隐形(v4.7.6 的残留缺口)。计数值变了则一定有人 stop 过,与位的当前值无关。
|
|
3284
|
+
*
|
|
3285
|
+
* 与锁同放 USER_DATA_DIR 根下,理由相同:`runtime/` 等目录会被 `rmrf`,
|
|
3286
|
+
* 文件消失即读作 0,会让「期间发生过 stop」丢失。命名**刻意不以 `Lock` 结尾**——
|
|
3287
|
+
* 它不是锁,不该进 `paths.spec.ts` 那条锁位置断言的枚举。
|
|
3288
|
+
*/
|
|
3289
|
+
serviceStopEpoch: path.join(USER_DATA_DIR, "service-stop-epoch"),
|
|
3217
3290
|
// 用户级 LaunchAgent(默认):gui/<uid> 域,全程免 sudo。随 homedir 走
|
|
3218
3291
|
userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`),
|
|
3219
3292
|
// 旧版本(v3.0–v4.0 的 daemon on)装的系统级 LaunchDaemon:root:wheel 拥有。
|
|
@@ -3320,35 +3393,20 @@ function sleepSyncMs(ms) {
|
|
|
3320
3393
|
// src/settings.ts
|
|
3321
3394
|
import fs2 from "fs";
|
|
3322
3395
|
import path2 from "path";
|
|
3323
|
-
var settingsCache = null;
|
|
3324
3396
|
function readSettings() {
|
|
3325
|
-
if (
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3331
|
-
} catch {
|
|
3332
|
-
return recoverCorruptedSettings();
|
|
3333
|
-
}
|
|
3334
|
-
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
3335
|
-
return recoverCorruptedSettings();
|
|
3336
|
-
}
|
|
3337
|
-
settingsCache = parsed;
|
|
3338
|
-
return settingsCache;
|
|
3397
|
+
if (!fs2.existsSync(PATHS.settingsFile)) return {};
|
|
3398
|
+
try {
|
|
3399
|
+
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3400
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
3401
|
+
} catch {
|
|
3339
3402
|
}
|
|
3340
|
-
settingsCache = {};
|
|
3341
|
-
return settingsCache;
|
|
3342
|
-
}
|
|
3343
|
-
function recoverCorruptedSettings() {
|
|
3344
3403
|
try {
|
|
3345
3404
|
fs2.copyFileSync(PATHS.settingsFile, `${PATHS.settingsFile}.bak`);
|
|
3346
3405
|
console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${PATHS.settingsFile}.bak\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
|
|
3347
3406
|
} catch {
|
|
3348
3407
|
console.warn("\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
|
|
3349
3408
|
}
|
|
3350
|
-
|
|
3351
|
-
return settingsCache;
|
|
3409
|
+
return {};
|
|
3352
3410
|
}
|
|
3353
3411
|
function isValidSettingsContent(content) {
|
|
3354
3412
|
try {
|
|
@@ -3359,31 +3417,22 @@ function isValidSettingsContent(content) {
|
|
|
3359
3417
|
}
|
|
3360
3418
|
}
|
|
3361
3419
|
function writeSettings(settings) {
|
|
3362
|
-
|
|
3363
|
-
return withFileLock(PATHS.settingsLock, () => writeSettingsUnlocked(settings));
|
|
3364
|
-
}
|
|
3365
|
-
function writeSettingsUnlocked(settings) {
|
|
3366
|
-
settingsCache = null;
|
|
3367
|
-
const existing = readSettings();
|
|
3368
|
-
const merged = { ...existing, ...settings };
|
|
3369
|
-
for (const key of Object.keys(settings)) {
|
|
3370
|
-
if (settings[key] === void 0) delete merged[key];
|
|
3371
|
-
}
|
|
3372
|
-
atomicWriteFileSync(PATHS.settingsFile, JSON.stringify(merged, null, 2), { mode: 384 });
|
|
3373
|
-
settingsCache = merged;
|
|
3374
|
-
return settingsCache;
|
|
3420
|
+
return updateSettings(() => settings);
|
|
3375
3421
|
}
|
|
3376
3422
|
function updateSettings(mutate) {
|
|
3377
3423
|
ensureDirs();
|
|
3378
3424
|
return withFileLock(PATHS.settingsLock, () => {
|
|
3379
|
-
settingsCache = null;
|
|
3380
3425
|
const current = readSettings();
|
|
3381
|
-
|
|
3426
|
+
const patch = mutate(current);
|
|
3427
|
+
if (Object.keys(patch).length === 0) return current;
|
|
3428
|
+
const merged = { ...current, ...patch };
|
|
3429
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
3430
|
+
if (value === void 0) delete merged[key];
|
|
3431
|
+
}
|
|
3432
|
+
atomicWriteFileSync(PATHS.settingsFile, JSON.stringify(merged, null, 2), { mode: 384 });
|
|
3433
|
+
return merged;
|
|
3382
3434
|
});
|
|
3383
3435
|
}
|
|
3384
|
-
function invalidateSettingsCache() {
|
|
3385
|
-
settingsCache = null;
|
|
3386
|
-
}
|
|
3387
3436
|
function validatePort(value, key) {
|
|
3388
3437
|
if (value === void 0) return void 0;
|
|
3389
3438
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535) {
|
|
@@ -3394,8 +3443,8 @@ function validatePort(value, key) {
|
|
|
3394
3443
|
}
|
|
3395
3444
|
return value;
|
|
3396
3445
|
}
|
|
3397
|
-
function getPorts() {
|
|
3398
|
-
const ports =
|
|
3446
|
+
function getPorts(settings = readSettings()) {
|
|
3447
|
+
const ports = settings.ports;
|
|
3399
3448
|
if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
|
|
3400
3449
|
if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
|
|
3401
3450
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
@@ -3499,8 +3548,8 @@ function deleteSubscriptionCache(subName) {
|
|
|
3499
3548
|
function isValidSubscription(s) {
|
|
3500
3549
|
return s != null && typeof s === "object" && typeof s.name === "string" && typeof s.url === "string";
|
|
3501
3550
|
}
|
|
3502
|
-
function getSubscriptions() {
|
|
3503
|
-
const list =
|
|
3551
|
+
function getSubscriptions(settings = readSettings()) {
|
|
3552
|
+
const list = settings.subscriptions;
|
|
3504
3553
|
if (!Array.isArray(list)) {
|
|
3505
3554
|
if (list !== void 0) {
|
|
3506
3555
|
console.warn("\u8B66\u544A: settings.json \u7684 subscriptions \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo sub add \u91CD\u65B0\u6DFB\u52A0\uFF09");
|
|
@@ -3525,29 +3574,22 @@ function validateSubscriptionName(name) {
|
|
|
3525
3574
|
}
|
|
3526
3575
|
function addSubscription(url, name = "default") {
|
|
3527
3576
|
validateSubscriptionName(name);
|
|
3528
|
-
let duplicate = false;
|
|
3529
3577
|
updateSettings((settings) => {
|
|
3530
|
-
const subs =
|
|
3578
|
+
const subs = getSubscriptions(settings);
|
|
3531
3579
|
if (subs.some((s) => s.name === name)) {
|
|
3532
|
-
|
|
3533
|
-
return {};
|
|
3580
|
+
throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
|
|
3534
3581
|
}
|
|
3535
3582
|
subs.push({ name, url });
|
|
3536
3583
|
const updates = { subscriptions: subs };
|
|
3537
|
-
if (!settings.active_subscription && subs.length === 1)
|
|
3538
|
-
updates.active_subscription = name;
|
|
3539
|
-
}
|
|
3584
|
+
if (!settings.active_subscription && subs.length === 1) updates.active_subscription = name;
|
|
3540
3585
|
return updates;
|
|
3541
3586
|
});
|
|
3542
|
-
if (duplicate) {
|
|
3543
|
-
throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
|
|
3544
|
-
}
|
|
3545
3587
|
}
|
|
3546
3588
|
function removeSubscription(name) {
|
|
3547
3589
|
let switchedTo = null;
|
|
3548
3590
|
let found = false;
|
|
3549
3591
|
updateSettings((settings) => {
|
|
3550
|
-
const subs =
|
|
3592
|
+
const subs = getSubscriptions(settings);
|
|
3551
3593
|
const idx = subs.findIndex((s) => s.name === name);
|
|
3552
3594
|
if (idx < 0) return {};
|
|
3553
3595
|
found = true;
|
|
@@ -3568,13 +3610,12 @@ function removeSubscription(name) {
|
|
|
3568
3610
|
return switchedTo;
|
|
3569
3611
|
}
|
|
3570
3612
|
function setDefaultSubscription(name) {
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
return true;
|
|
3613
|
+
let found = false;
|
|
3614
|
+
updateSettings((settings) => {
|
|
3615
|
+
found = getSubscriptions(settings).some((s) => s.name === name);
|
|
3616
|
+
return found ? { active_subscription: name } : {};
|
|
3617
|
+
});
|
|
3618
|
+
return found;
|
|
3578
3619
|
}
|
|
3579
3620
|
function getSubscriptionRawConfigPath(subName) {
|
|
3580
3621
|
if (!SAFE_NAME_RE.test(subName)) {
|
|
@@ -3825,14 +3866,9 @@ function loadOverwriteFile() {
|
|
|
3825
3866
|
}
|
|
3826
3867
|
return results;
|
|
3827
3868
|
}
|
|
3828
|
-
function applyOverwrite(baseConfig,
|
|
3829
|
-
if (!isOverwriteEnabled()) return { ...baseConfig };
|
|
3830
|
-
const overwriteFiles = preloadedFiles || loadOverwriteFile();
|
|
3831
|
-
if (overwriteFiles.length === 0) return { ...baseConfig };
|
|
3869
|
+
function applyOverwrite(baseConfig, files) {
|
|
3832
3870
|
let result = { ...baseConfig };
|
|
3833
|
-
for (const file of
|
|
3834
|
-
result = deepMergeWithOverrides(result, file.config);
|
|
3835
|
-
}
|
|
3871
|
+
for (const file of files) result = deepMergeWithOverrides(result, file.config);
|
|
3836
3872
|
return result;
|
|
3837
3873
|
}
|
|
3838
3874
|
function listOverwriteFile() {
|
|
@@ -3862,7 +3898,7 @@ var FLAGS = [
|
|
|
3862
3898
|
{ forms: ["-n", "--lines"], takesValue: true }
|
|
3863
3899
|
// 注意:`--mirror`(kernel)是可选值选项——`--mirror`、`--mirror=url`、`--mirror url`
|
|
3864
3900
|
// 三种形式都合法,只走 parseMirrorArg。故意不在此登记:登记了 getNonFlagArg 反而会
|
|
3865
|
-
//
|
|
3901
|
+
// 把它的值吞掉。它的解析与校验由 parseMirrorArg 自己负责。
|
|
3866
3902
|
];
|
|
3867
3903
|
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
3868
3904
|
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
@@ -3982,8 +4018,8 @@ function assertKnownFlags(args, known, command) {
|
|
|
3982
4018
|
if (!a.startsWith("-") || a === "-") continue;
|
|
3983
4019
|
if (knownSet.has(a)) continue;
|
|
3984
4020
|
const eqIdx = a.indexOf("=");
|
|
3985
|
-
if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx))) continue;
|
|
3986
|
-
if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2))) continue;
|
|
4021
|
+
if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx)) && (VALUE_FLAGS.has(a.slice(0, eqIdx)) || a.slice(0, eqIdx) === "--mirror")) continue;
|
|
4022
|
+
if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2)) && VALUE_FLAGS.has(a.slice(0, 2))) continue;
|
|
3987
4023
|
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
3988
4024
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
3989
4025
|
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
@@ -4018,17 +4054,6 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
4018
4054
|
}
|
|
4019
4055
|
return defaultValue;
|
|
4020
4056
|
}
|
|
4021
|
-
function assertNoRemovedSshFlag(args) {
|
|
4022
|
-
if (!args?.some((a) => a === "--no-ssh" || a.startsWith("--no-ssh="))) return;
|
|
4023
|
-
throw new CliError("--no-ssh \u5DF2\u79FB\u9664\uFF08v4.0.0\uFF09", {
|
|
4024
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4025
|
-
hint: [
|
|
4026
|
-
"ssh \u96A7\u9053\u529F\u80FD\u5DF2\u6574\u4F53\u79FB\u9664\uFF0C\u8BE5\u9009\u9879\u4E0D\u518D\u6709\u5BF9\u5E94\u884C\u4E3A\u3002",
|
|
4027
|
-
"\u5982\u4ECD\u9700\u5185\u7F51\u51FA\u53E3\uFF1A\u81EA\u884C\u8FD0\u884C ssh -D 127.0.0.1:<\u7AEF\u53E3> -N <\u4E3B\u673A>\uFF0C",
|
|
4028
|
-
"\u8282\u70B9\u4E0E\u5206\u6D41\u89C4\u5219\u5199\u5728 overwrite.yaml \u91CC\uFF08\u5199\u6CD5\u89C1 CHANGELOG \u7684 4.0.0 \u5347\u7EA7\u987B\u77E5\uFF09\u3002"
|
|
4029
|
-
]
|
|
4030
|
-
});
|
|
4031
|
-
}
|
|
4032
4057
|
function extractStartOptions(args) {
|
|
4033
4058
|
if (!args) return [];
|
|
4034
4059
|
const out = [];
|
|
@@ -4126,23 +4151,7 @@ function parseMirrorArg(args) {
|
|
|
4126
4151
|
if (!args || args.length < 2) {
|
|
4127
4152
|
return { mirror: null, isOverride: false };
|
|
4128
4153
|
}
|
|
4129
|
-
|
|
4130
|
-
throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
|
|
4131
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4132
|
-
hint: [
|
|
4133
|
-
"\u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7EDD\u4E0D\u7ECF\u8FC7\u955C\u50CF\uFF0C\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4EA7\u7269\u4E0B\u8F7D\u3002",
|
|
4134
|
-
"API \u82E5\u8D70\u955C\u50CF\uFF0C\u4E0B\u8F7D\u5730\u5740\u5C31\u7531\u955C\u50CF\u8BF4\u4E86\u7B97\uFF0C\u800C\u5185\u6838\u968F\u540E\u4EE5 root \u8FD0\u884C\u3002",
|
|
4135
|
-
"",
|
|
4136
|
-
"\u6539\u7528: mihomo kernel --mirror [\u955C\u50CF]"
|
|
4137
|
-
]
|
|
4138
|
-
});
|
|
4139
|
-
}
|
|
4140
|
-
if (args.includes("--no-mirror") || args.includes("--direct")) {
|
|
4141
|
-
throw new CliError("--no-mirror/--direct \u5DF2\u79FB\u9664\uFF08v4.7.0\uFF09", {
|
|
4142
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4143
|
-
hint: ["\u5F3A\u5236\u76F4\u8FDE\u6539\u7528: mihomo kernel --mirror direct", "\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE"]
|
|
4144
|
-
});
|
|
4145
|
-
}
|
|
4154
|
+
assertKnownFlags(args.slice(1), ["--mirror"], "kernel [--mirror [\u955C\u50CF]]");
|
|
4146
4155
|
const mirrorEq = args.find((a) => a.startsWith("--mirror="));
|
|
4147
4156
|
const mirrorIdx = args.indexOf("--mirror");
|
|
4148
4157
|
if (mirrorIdx >= 0 || mirrorEq) {
|
|
@@ -4181,64 +4190,6 @@ function parseConfigContent(content, errorMsg) {
|
|
|
4181
4190
|
function dumpYaml(obj) {
|
|
4182
4191
|
return dump(obj, { indent: 2, lineWidth: -1 });
|
|
4183
4192
|
}
|
|
4184
|
-
function collectOverwriteProxyNames(overwriteFiles, baseProxyNames) {
|
|
4185
|
-
const names = [];
|
|
4186
|
-
for (const file of overwriteFiles) {
|
|
4187
|
-
for (const [key, value] of Object.entries(file.config)) {
|
|
4188
|
-
if ((key === "+proxies" || key === "proxies+" || key === "~proxies") && Array.isArray(value)) {
|
|
4189
|
-
for (const proxy of value) {
|
|
4190
|
-
if (proxy && typeof proxy === "object" && "name" in proxy) {
|
|
4191
|
-
const name = proxy.name;
|
|
4192
|
-
if (typeof name !== "string" || name.length === 0) continue;
|
|
4193
|
-
if (key === "~proxies" && baseProxyNames.has(name)) continue;
|
|
4194
|
-
names.push(name);
|
|
4195
|
-
}
|
|
4196
|
-
}
|
|
4197
|
-
}
|
|
4198
|
-
}
|
|
4199
|
-
}
|
|
4200
|
-
return names;
|
|
4201
|
-
}
|
|
4202
|
-
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, baseProxyNames = /* @__PURE__ */ new Set()) {
|
|
4203
|
-
const injectedNames = collectOverwriteProxyNames(overwriteFiles, baseProxyNames);
|
|
4204
|
-
if (injectedNames.length === 0) return;
|
|
4205
|
-
const groups = config["proxy-groups"];
|
|
4206
|
-
if (!groups) return;
|
|
4207
|
-
const excludePattern = `^(?:${injectedNames.map((n) => escapeRegExp(n)).join("|")})$`;
|
|
4208
|
-
for (const group of groups) {
|
|
4209
|
-
if (!group["include-all"] && !group["include-all-proxies"]) continue;
|
|
4210
|
-
const existing = group["exclude-filter"];
|
|
4211
|
-
if (existing) {
|
|
4212
|
-
group["exclude-filter"] = `${existing}|${excludePattern}`;
|
|
4213
|
-
} else {
|
|
4214
|
-
group["exclude-filter"] = excludePattern;
|
|
4215
|
-
}
|
|
4216
|
-
}
|
|
4217
|
-
}
|
|
4218
|
-
var BUILTIN_PROXY_NAMES = /* @__PURE__ */ new Set(["DIRECT", "REJECT", "REJECT-DROP", "PASS", "COMPATIBLE"]);
|
|
4219
|
-
function deduplicateByName(items) {
|
|
4220
|
-
const names = /* @__PURE__ */ new Set();
|
|
4221
|
-
const duplicates = [];
|
|
4222
|
-
const result = items.filter((item) => {
|
|
4223
|
-
if (names.has(item.name)) {
|
|
4224
|
-
duplicates.push(item.name);
|
|
4225
|
-
return false;
|
|
4226
|
-
}
|
|
4227
|
-
names.add(item.name);
|
|
4228
|
-
return true;
|
|
4229
|
-
});
|
|
4230
|
-
return { result, names, duplicates };
|
|
4231
|
-
}
|
|
4232
|
-
var NON_TARGET_RULE_TYPES = /* @__PURE__ */ new Set(["SUB-RULE"]);
|
|
4233
|
-
function getRuleTarget(rule) {
|
|
4234
|
-
const parts = rule.split(",");
|
|
4235
|
-
if (parts.length < 2) return "";
|
|
4236
|
-
const last = parts[parts.length - 1].trim();
|
|
4237
|
-
if (last.toLowerCase() === "no-resolve" && parts.length >= 3) {
|
|
4238
|
-
return parts[parts.length - 2].trim();
|
|
4239
|
-
}
|
|
4240
|
-
return last;
|
|
4241
|
-
}
|
|
4242
4193
|
function assertDnsShape(dnsRaw) {
|
|
4243
4194
|
if (dnsRaw === void 0 || dnsRaw === null) return;
|
|
4244
4195
|
if (typeof dnsRaw !== "object" || Array.isArray(dnsRaw)) {
|
|
@@ -4299,109 +4250,12 @@ function assertConfigShape(config) {
|
|
|
4299
4250
|
}
|
|
4300
4251
|
}
|
|
4301
4252
|
}
|
|
4302
|
-
function validateConfig(config) {
|
|
4303
|
-
assertConfigShape(config);
|
|
4304
|
-
const warnings = [];
|
|
4305
|
-
const proxies = config.proxies || [];
|
|
4306
|
-
const groups = config["proxy-groups"] || [];
|
|
4307
|
-
const rules = config.rules || [];
|
|
4308
|
-
const proxyDedup = deduplicateByName(proxies);
|
|
4309
|
-
config.proxies = proxyDedup.result;
|
|
4310
|
-
if (proxyDedup.duplicates.length > 0) {
|
|
4311
|
-
const preview = proxyDedup.duplicates.slice(0, 3).map((n) => `"${n}"`).join(", ");
|
|
4312
|
-
warnings.push(`\u79FB\u9664\u4E86 ${proxyDedup.duplicates.length} \u4E2A\u91CD\u540D\u8282\u70B9: ${preview}${proxyDedup.duplicates.length > 3 ? " ..." : ""}`);
|
|
4313
|
-
}
|
|
4314
|
-
const groupDedup = deduplicateByName(groups);
|
|
4315
|
-
config["proxy-groups"] = groupDedup.result;
|
|
4316
|
-
if (groupDedup.duplicates.length > 0) {
|
|
4317
|
-
warnings.push(`\u79FB\u9664\u4E86 ${groupDedup.duplicates.length} \u4E2A\u91CD\u540D\u5206\u7EC4: ${groupDedup.duplicates.map((n) => `"${n}"`).join(", ")}`);
|
|
4318
|
-
}
|
|
4319
|
-
const validNames = /* @__PURE__ */ new Set([...BUILTIN_PROXY_NAMES, ...proxyDedup.names, ...groupDedup.names]);
|
|
4320
|
-
for (const name of groupDedup.names) {
|
|
4321
|
-
if (proxyDedup.names.has(name)) {
|
|
4322
|
-
warnings.push(`\u540D\u79F0\u51B2\u7A81: "${name}" \u540C\u65F6\u662F\u8282\u70B9\u548C\u5206\u7EC4\u540D\uFF0Cmihomo \u4F1A\u62D2\u7EDD\u52A0\u8F7D\uFF08\u8BF7\u91CD\u547D\u540D\u5176\u4E00\uFF09`);
|
|
4323
|
-
}
|
|
4324
|
-
}
|
|
4325
|
-
const providerNames = new Set(
|
|
4326
|
-
config["proxy-providers"] && typeof config["proxy-providers"] === "object" && !Array.isArray(config["proxy-providers"]) ? Object.keys(config["proxy-providers"]) : []
|
|
4327
|
-
);
|
|
4328
|
-
const activeGroups = groupDedup.result;
|
|
4329
|
-
const removedGroups = /* @__PURE__ */ new Set();
|
|
4330
|
-
let changed = true;
|
|
4331
|
-
while (changed) {
|
|
4332
|
-
changed = false;
|
|
4333
|
-
for (const group of activeGroups) {
|
|
4334
|
-
if (removedGroups.has(group.name)) continue;
|
|
4335
|
-
if (group.proxies !== void 0 && !Array.isArray(group.proxies)) {
|
|
4336
|
-
if (typeof group.proxies === "string") {
|
|
4337
|
-
warnings.push(`proxy-group "${group.name}": proxies \u5E94\u4E3A\u5217\u8868\uFF0C\u5DF2\u6309\u5355\u5143\u7D20\u5904\u7406\uFF08"${group.proxies}"\uFF09`);
|
|
4338
|
-
group.proxies = [group.proxies];
|
|
4339
|
-
} else {
|
|
4340
|
-
warnings.push(`proxy-group "${group.name}": proxies \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5B57\u6BB5`);
|
|
4341
|
-
group.proxies = [];
|
|
4342
|
-
}
|
|
4343
|
-
}
|
|
4344
|
-
if (!Array.isArray(group.proxies)) continue;
|
|
4345
|
-
if (Array.isArray(group.use)) {
|
|
4346
|
-
const ghosts = group.use.filter((u) => typeof u === "string" && !providerNames.has(u));
|
|
4347
|
-
if (ghosts.length > 0) {
|
|
4348
|
-
group.use = group.use.filter((u) => providerNames.has(u));
|
|
4349
|
-
warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684 provider \u5F15\u7528 ${ghosts.map((n) => `"${n}"`).join(", ")}`);
|
|
4350
|
-
}
|
|
4351
|
-
}
|
|
4352
|
-
const invalid = group.proxies.filter((name) => !validNames.has(name));
|
|
4353
|
-
if (invalid.length > 0) {
|
|
4354
|
-
group.proxies = group.proxies.filter((name) => validNames.has(name));
|
|
4355
|
-
warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684\u5F15\u7528 ${invalid.map((n) => `"${n}"`).join(", ")}`);
|
|
4356
|
-
}
|
|
4357
|
-
const hasUse = Array.isArray(group.use) ? group.use.length > 0 : Boolean(group.use);
|
|
4358
|
-
const includesAll = Boolean(group["include-all"] || group["include-all-proxies"]);
|
|
4359
|
-
const includeAllUsable = includesAll && proxyDedup.result.length > 0;
|
|
4360
|
-
const hasOtherSource = hasUse || includeAllUsable;
|
|
4361
|
-
if (group.proxies.length === 0 && !hasOtherSource) {
|
|
4362
|
-
removedGroups.add(group.name);
|
|
4363
|
-
validNames.delete(group.name);
|
|
4364
|
-
warnings.push(`proxy-group "${group.name}": \u5DF2\u79FB\u9664\uFF08\u65E0\u53EF\u7528\u8282\u70B9\uFF09`);
|
|
4365
|
-
changed = true;
|
|
4366
|
-
}
|
|
4367
|
-
}
|
|
4368
|
-
}
|
|
4369
|
-
if (removedGroups.size > 0) {
|
|
4370
|
-
config["proxy-groups"] = activeGroups.filter((g) => !removedGroups.has(g.name));
|
|
4371
|
-
}
|
|
4372
|
-
if (rules.length > 0) {
|
|
4373
|
-
const removedRules = [];
|
|
4374
|
-
config.rules = rules.filter((rule) => {
|
|
4375
|
-
const ruleType = rule.split(",")[0]?.trim().toUpperCase();
|
|
4376
|
-
if (NON_TARGET_RULE_TYPES.has(ruleType)) return true;
|
|
4377
|
-
const target = getRuleTarget(rule);
|
|
4378
|
-
if (!target || validNames.has(target)) return true;
|
|
4379
|
-
removedRules.push(rule);
|
|
4380
|
-
return false;
|
|
4381
|
-
});
|
|
4382
|
-
if (removedRules.length > 0) {
|
|
4383
|
-
warnings.push(`\u79FB\u9664\u4E86 ${removedRules.length} \u6761\u5F15\u7528\u4E0D\u5B58\u5728\u76EE\u6807\u7684\u89C4\u5219`);
|
|
4384
|
-
}
|
|
4385
|
-
}
|
|
4386
|
-
return warnings;
|
|
4387
|
-
}
|
|
4388
4253
|
function buildConfig(subRawContent, mode, scope) {
|
|
4389
4254
|
const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
}
|
|
4393
|
-
const overwriteEnabled = isOverwriteEnabled();
|
|
4394
|
-
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4255
|
+
const settings = readSettings();
|
|
4256
|
+
const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
|
|
4395
4257
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4396
|
-
const
|
|
4397
|
-
const withOverwrites = applyOverwrite(working, overwriteFiles);
|
|
4398
|
-
if (overwriteFiles.length > 0) {
|
|
4399
|
-
const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
|
|
4400
|
-
const baseProxyNames = new Set(
|
|
4401
|
-
baseProxies.filter((p) => p && typeof p === "object" && typeof p.name === "string").map((p) => p.name)
|
|
4402
|
-
);
|
|
4403
|
-
excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles, baseProxyNames);
|
|
4404
|
-
}
|
|
4258
|
+
const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4405
4259
|
const systemConfig = {};
|
|
4406
4260
|
const lockedWarnings = [];
|
|
4407
4261
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
@@ -4409,7 +4263,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4409
4263
|
systemConfig[key] = value;
|
|
4410
4264
|
}
|
|
4411
4265
|
}
|
|
4412
|
-
const ports = getPorts();
|
|
4266
|
+
const ports = getPorts(settings);
|
|
4413
4267
|
systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
|
|
4414
4268
|
systemConfig["mixed-port"] = ports.mixed;
|
|
4415
4269
|
delete withOverwrites["mixed-port"];
|
|
@@ -4419,7 +4273,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4419
4273
|
delete withOverwrites["external-ui-name"];
|
|
4420
4274
|
delete withOverwrites["external-ui-url"];
|
|
4421
4275
|
delete withOverwrites.secret;
|
|
4422
|
-
const controllerSecret =
|
|
4276
|
+
const controllerSecret = settings.controller_secret;
|
|
4423
4277
|
if (controllerSecret) {
|
|
4424
4278
|
systemConfig.secret = controllerSecret;
|
|
4425
4279
|
}
|
|
@@ -4455,24 +4309,39 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4455
4309
|
"skip-domain": ["+.push.apple.com"]
|
|
4456
4310
|
};
|
|
4457
4311
|
}
|
|
4458
|
-
|
|
4459
|
-
return { config: merged,
|
|
4312
|
+
assertConfigShape(merged);
|
|
4313
|
+
return { config: merged, warnings: lockedWarnings };
|
|
4460
4314
|
}
|
|
4461
4315
|
function writeMihomoConfig(configObj) {
|
|
4462
4316
|
ensureDirs();
|
|
4463
4317
|
const content = dumpYaml(configObj);
|
|
4464
4318
|
atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
|
|
4465
4319
|
}
|
|
4466
|
-
function
|
|
4320
|
+
async function validateConfigWithKernel(config) {
|
|
4321
|
+
if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4467
4322
|
ensureDirs();
|
|
4468
|
-
fs4.
|
|
4469
|
-
const
|
|
4470
|
-
|
|
4471
|
-
|
|
4323
|
+
const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
|
|
4324
|
+
const stageFile = path4.join(stageDir, "config.yaml");
|
|
4325
|
+
try {
|
|
4326
|
+
fs4.writeFileSync(stageFile, dumpYaml(config), { mode: 384 });
|
|
4327
|
+
try {
|
|
4328
|
+
await promisify(execFile)(PATHS.mihomoBinary, ["-t", "-d", DIRS.data, "-f", stageFile], {
|
|
4329
|
+
encoding: "utf8",
|
|
4330
|
+
timeout: 3e4,
|
|
4331
|
+
maxBuffer: 1024 * 1024
|
|
4332
|
+
});
|
|
4333
|
+
} catch (e) {
|
|
4334
|
+
const error = e;
|
|
4335
|
+
const detail = sanitizeTerminal(`${error.stdout || ""}
|
|
4336
|
+
${error.stderr || ""}`).trim();
|
|
4337
|
+
throw new CliError(error.killed ? "\u5185\u6838\u914D\u7F6E\u6821\u9A8C\u8D85\u65F6" : "\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
|
|
4338
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4339
|
+
hint: [detail || error.message, "", "\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002"]
|
|
4340
|
+
});
|
|
4341
|
+
}
|
|
4342
|
+
} finally {
|
|
4343
|
+
fs4.rmSync(stageDir, { recursive: true, force: true });
|
|
4472
4344
|
}
|
|
4473
|
-
const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
|
|
4474
|
-
fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
|
|
4475
|
-
fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
|
|
4476
4345
|
}
|
|
4477
4346
|
function hasConfig() {
|
|
4478
4347
|
return fs4.existsSync(PATHS.configFile);
|
|
@@ -4490,8 +4359,6 @@ function getConfigInfo() {
|
|
|
4490
4359
|
proxies: proxies ? proxies.length : 0,
|
|
4491
4360
|
proxyGroups: proxyGroups ? proxyGroups.length : 0,
|
|
4492
4361
|
mixedPort: cfg["mixed-port"] || null,
|
|
4493
|
-
httpPort: cfg.port || null,
|
|
4494
|
-
socksPort: cfg["socks-port"] || null,
|
|
4495
4362
|
tun: tun ? !!tun.enable : false
|
|
4496
4363
|
};
|
|
4497
4364
|
} catch {
|
|
@@ -4533,11 +4400,11 @@ function clearKernelVersionCache() {
|
|
|
4533
4400
|
// src/service.ts
|
|
4534
4401
|
import { spawnSync as spawnSync4 } from "child_process";
|
|
4535
4402
|
import fs8 from "fs";
|
|
4536
|
-
import
|
|
4403
|
+
import path7 from "path";
|
|
4537
4404
|
|
|
4538
4405
|
// src/log-files.ts
|
|
4539
4406
|
import fs5 from "fs";
|
|
4540
|
-
import
|
|
4407
|
+
import path5 from "path";
|
|
4541
4408
|
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
4542
4409
|
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
4543
4410
|
function isArchiveLogFilename(filename) {
|
|
@@ -4575,10 +4442,10 @@ function readLogTail(maxLines = 15) {
|
|
|
4575
4442
|
}
|
|
4576
4443
|
function allocateArchivePath() {
|
|
4577
4444
|
const timestamp = formatLocalTimestamp();
|
|
4578
|
-
let archivePath =
|
|
4445
|
+
let archivePath = path5.join(DIRS.logs, `mihomo.${timestamp}.log`);
|
|
4579
4446
|
let seq = 1;
|
|
4580
4447
|
while (fs5.existsSync(archivePath)) {
|
|
4581
|
-
archivePath =
|
|
4448
|
+
archivePath = path5.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
|
|
4582
4449
|
seq++;
|
|
4583
4450
|
}
|
|
4584
4451
|
return archivePath;
|
|
@@ -4603,7 +4470,7 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4603
4470
|
for (const file of files) {
|
|
4604
4471
|
if (!isArchiveLogFilename(file)) continue;
|
|
4605
4472
|
try {
|
|
4606
|
-
const filePath =
|
|
4473
|
+
const filePath = path5.join(logsDir, file);
|
|
4607
4474
|
const stat = fs5.statSync(filePath);
|
|
4608
4475
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
4609
4476
|
fs5.unlinkSync(filePath);
|
|
@@ -4633,7 +4500,7 @@ function listLogs() {
|
|
|
4633
4500
|
for (const file of files) {
|
|
4634
4501
|
if (!isArchiveLogFilename(file)) continue;
|
|
4635
4502
|
try {
|
|
4636
|
-
const filePath =
|
|
4503
|
+
const filePath = path5.join(logsDir, file);
|
|
4637
4504
|
const stat = fs5.statSync(filePath);
|
|
4638
4505
|
result.archives.push({
|
|
4639
4506
|
name: file,
|
|
@@ -4755,24 +4622,21 @@ function getStatus() {
|
|
|
4755
4622
|
return {
|
|
4756
4623
|
running,
|
|
4757
4624
|
pid: running ? pid : null,
|
|
4758
|
-
processInfo: running && pid ? getProcessInfo(pid) : null
|
|
4759
|
-
hasConfig: hasConfig(),
|
|
4760
|
-
hasKernel: hasKernel(),
|
|
4761
|
-
kernelVersion: getKernelVersion()
|
|
4625
|
+
processInfo: running && pid ? getProcessInfo(pid) : null
|
|
4762
4626
|
};
|
|
4763
4627
|
}
|
|
4764
4628
|
|
|
4765
4629
|
// src/sudo.ts
|
|
4766
4630
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
4767
4631
|
import fs7 from "fs";
|
|
4768
|
-
import
|
|
4632
|
+
import path6 from "path";
|
|
4769
4633
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
4770
4634
|
function runSudoScript(scriptBody, opts) {
|
|
4771
4635
|
if (!process.stdin.isTTY) {
|
|
4772
4636
|
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
4773
4637
|
}
|
|
4774
4638
|
ensureDirs();
|
|
4775
|
-
const scriptPath =
|
|
4639
|
+
const scriptPath = path6.join(DIRS.runtime, opts.file);
|
|
4776
4640
|
fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
4777
4641
|
fs7.chmodSync(scriptPath, 448);
|
|
4778
4642
|
try {
|
|
@@ -5029,11 +4893,12 @@ function killResidualKernels() {
|
|
|
5029
4893
|
}
|
|
5030
4894
|
if (rootPids.length > 0) cleanupRootResidue();
|
|
5031
4895
|
}
|
|
5032
|
-
async function installService(wasRunning) {
|
|
4896
|
+
async function installService(wasRunning, stopEpochBefore) {
|
|
5033
4897
|
assertServiceLabelSafe();
|
|
5034
4898
|
ensureDirs();
|
|
5035
4899
|
ensureServiceSymlink();
|
|
5036
|
-
|
|
4900
|
+
let restoreSkipped = false;
|
|
4901
|
+
const stagePath = path7.join(DIRS.runtime, "service.plist.stage");
|
|
5037
4902
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5038
4903
|
try {
|
|
5039
4904
|
const lint = spawnSync4("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
|
|
@@ -5044,11 +4909,15 @@ async function installService(wasRunning) {
|
|
|
5044
4909
|
}
|
|
5045
4910
|
bootoutService();
|
|
5046
4911
|
await waitUntilUnloaded();
|
|
5047
|
-
fs8.mkdirSync(
|
|
4912
|
+
fs8.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
5048
4913
|
fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
5049
4914
|
fs8.chmodSync(PATHS.userAgentPlist, 420);
|
|
5050
4915
|
if (wasRunning) {
|
|
5051
4916
|
withFileLock(PATHS.serviceLock, () => {
|
|
4917
|
+
if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
|
|
4918
|
+
restoreSkipped = true;
|
|
4919
|
+
return;
|
|
4920
|
+
}
|
|
5052
4921
|
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
5053
4922
|
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
|
|
5054
4923
|
});
|
|
@@ -5062,11 +4931,30 @@ async function installService(wasRunning) {
|
|
|
5062
4931
|
if (!wasRunning) {
|
|
5063
4932
|
disableServiceAutoStart();
|
|
5064
4933
|
}
|
|
4934
|
+
return { restoreSkipped };
|
|
4935
|
+
}
|
|
4936
|
+
function readStopEpoch() {
|
|
4937
|
+
try {
|
|
4938
|
+
const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
4939
|
+
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
4940
|
+
} catch {
|
|
4941
|
+
return 0;
|
|
4942
|
+
}
|
|
4943
|
+
}
|
|
4944
|
+
function bumpStopEpoch() {
|
|
4945
|
+
try {
|
|
4946
|
+
ensureDirs();
|
|
4947
|
+
atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
|
|
4948
|
+
} catch {
|
|
4949
|
+
}
|
|
4950
|
+
}
|
|
4951
|
+
function recordServiceStopped() {
|
|
4952
|
+
bumpStopEpoch();
|
|
5065
4953
|
}
|
|
5066
|
-
function shouldAbortStartOnDisable(
|
|
5067
|
-
return
|
|
4954
|
+
function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
|
|
4955
|
+
return stopEpochNow !== stopEpochBefore;
|
|
5068
4956
|
}
|
|
5069
|
-
async function startService(
|
|
4957
|
+
async function startService(stopEpochBefore) {
|
|
5070
4958
|
assertServiceLabelSafe();
|
|
5071
4959
|
ensureServiceSymlink();
|
|
5072
4960
|
if (!isServiceInstalled()) {
|
|
@@ -5092,7 +4980,7 @@ async function startService(disabledBefore) {
|
|
|
5092
4980
|
rotateAndCleanupLogs();
|
|
5093
4981
|
let started = true;
|
|
5094
4982
|
withFileLock(PATHS.serviceLock, () => {
|
|
5095
|
-
if (shouldAbortStartOnDisable(
|
|
4983
|
+
if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
|
|
5096
4984
|
started = false;
|
|
5097
4985
|
return;
|
|
5098
4986
|
}
|
|
@@ -5109,6 +4997,7 @@ function disableServiceAutoStart() {
|
|
|
5109
4997
|
hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
|
|
5110
4998
|
});
|
|
5111
4999
|
}
|
|
5000
|
+
bumpStopEpoch();
|
|
5112
5001
|
}
|
|
5113
5002
|
async function stopService() {
|
|
5114
5003
|
assertServiceLabelSafe();
|
|
@@ -5209,11 +5098,11 @@ async function tryHotReload() {
|
|
|
5209
5098
|
clearTimeout(timer);
|
|
5210
5099
|
}
|
|
5211
5100
|
}
|
|
5212
|
-
async function restartService() {
|
|
5101
|
+
async function restartService(stopEpochBefore) {
|
|
5213
5102
|
if (!isServiceInstalled()) {
|
|
5214
5103
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5215
5104
|
}
|
|
5216
|
-
if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
|
|
5105
|
+
if (!logOversized() && await tryHotReload()) return { hotReloaded: true, started: true };
|
|
5217
5106
|
if (logOversized()) {
|
|
5218
5107
|
const archiveFile = allocateArchivePath();
|
|
5219
5108
|
try {
|
|
@@ -5223,12 +5112,20 @@ async function restartService() {
|
|
|
5223
5112
|
}
|
|
5224
5113
|
}
|
|
5225
5114
|
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
5115
|
+
let started = true;
|
|
5226
5116
|
if (kick.status !== 0) {
|
|
5227
|
-
|
|
5228
|
-
|
|
5117
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
5118
|
+
if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
|
|
5119
|
+
started = false;
|
|
5120
|
+
return;
|
|
5121
|
+
}
|
|
5122
|
+
runLaunchctl(["enable", serviceTarget()]);
|
|
5123
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
|
|
5124
|
+
});
|
|
5125
|
+
if (!started) return { hotReloaded: false, started: false };
|
|
5229
5126
|
}
|
|
5230
5127
|
cleanupOldLogs();
|
|
5231
|
-
return { hotReloaded: false };
|
|
5128
|
+
return { hotReloaded: false, started: true };
|
|
5232
5129
|
}
|
|
5233
5130
|
|
|
5234
5131
|
// src/commands/help.ts
|
|
@@ -5317,7 +5214,7 @@ function printVersion() {
|
|
|
5317
5214
|
// src/commands/completion.ts
|
|
5318
5215
|
import fs10 from "fs";
|
|
5319
5216
|
import os3 from "os";
|
|
5320
|
-
import
|
|
5217
|
+
import path9 from "path";
|
|
5321
5218
|
|
|
5322
5219
|
// src/open.ts
|
|
5323
5220
|
import { spawn } from "child_process";
|
|
@@ -5502,25 +5399,37 @@ function getRunningState(serviceStatus) {
|
|
|
5502
5399
|
function isRestartNeededOnChange() {
|
|
5503
5400
|
return getRunningState().running;
|
|
5504
5401
|
}
|
|
5505
|
-
async function launchOrRestart(mode,
|
|
5402
|
+
async function launchOrRestart(mode, stopEpochBefore) {
|
|
5506
5403
|
if (mode === "tun") {
|
|
5507
5404
|
const result = await startTun();
|
|
5508
5405
|
return result.pid;
|
|
5509
5406
|
}
|
|
5510
5407
|
const status = getServiceStatus();
|
|
5408
|
+
let hotReloaded = false;
|
|
5409
|
+
let started;
|
|
5511
5410
|
if (status.running && !status.disabled) {
|
|
5512
|
-
|
|
5513
|
-
if (hotReloaded) return getServiceStatus().pid;
|
|
5411
|
+
({ hotReloaded, started } = await restartService(stopEpochBefore));
|
|
5514
5412
|
} else {
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5413
|
+
({ started } = await startService(stopEpochBefore));
|
|
5414
|
+
}
|
|
5415
|
+
if (!started) throw cancelledByConcurrentStop();
|
|
5416
|
+
if (hotReloaded) return getServiceStatus().pid;
|
|
5417
|
+
try {
|
|
5418
|
+
return await assertServiceHealthy();
|
|
5419
|
+
} catch (e) {
|
|
5420
|
+
if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) throw cancelledByConcurrentStop();
|
|
5421
|
+
throw e;
|
|
5522
5422
|
}
|
|
5523
|
-
|
|
5423
|
+
}
|
|
5424
|
+
function cancelledByConcurrentStop() {
|
|
5425
|
+
return new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C", {
|
|
5426
|
+
label: "\u542F\u52A8\u5931\u8D25",
|
|
5427
|
+
hint: [
|
|
5428
|
+
"\u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5728\u672C\u6B21\u542F\u52A8\u8FC7\u7A0B\u4E2D\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF08mihomo stop\uFF0C\u6216 tun / install \u7B49\u540C\u6837\u4F1A\u5173\u95ED\u81EA\u542F\u7684\u547D\u4EE4\uFF09\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62\u3002",
|
|
5429
|
+
"",
|
|
5430
|
+
"\u786E\u5B9E\u8981\u542F\u52A8: mihomo start"
|
|
5431
|
+
]
|
|
5432
|
+
});
|
|
5524
5433
|
}
|
|
5525
5434
|
async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
5526
5435
|
const health = await waitServiceHealthy();
|
|
@@ -5708,9 +5617,9 @@ function formatProxySummary(info) {
|
|
|
5708
5617
|
return parts.join(", ");
|
|
5709
5618
|
}
|
|
5710
5619
|
function getActiveSubscription() {
|
|
5711
|
-
const subs = getSubscriptions();
|
|
5712
|
-
if (subs.length === 0) return null;
|
|
5713
5620
|
const settings = readSettings();
|
|
5621
|
+
const subs = getSubscriptions(settings);
|
|
5622
|
+
if (subs.length === 0) return null;
|
|
5714
5623
|
const activeName = settings.active_subscription;
|
|
5715
5624
|
if (activeName) {
|
|
5716
5625
|
const found = subs.find((s) => s.name === activeName);
|
|
@@ -5795,7 +5704,6 @@ async function downloadSubscription(url, subName = "default", signal) {
|
|
|
5795
5704
|
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5796
5705
|
}
|
|
5797
5706
|
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5798
|
-
if (!parsed) throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5799
5707
|
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5800
5708
|
saveSubscriptionRawConfig(subName, content);
|
|
5801
5709
|
const meta = extractSubscriptionMeta(response.headers);
|
|
@@ -5811,13 +5719,14 @@ async function downloadSubscription(url, subName = "default", signal) {
|
|
|
5811
5719
|
username: meta.username
|
|
5812
5720
|
};
|
|
5813
5721
|
}
|
|
5814
|
-
function prepareConfigForStart(mode, subName = "default") {
|
|
5722
|
+
async function prepareConfigForStart(mode, subName = "default") {
|
|
5815
5723
|
const rawContent = readSubscriptionRawConfig(subName);
|
|
5816
5724
|
if (!rawContent) {
|
|
5817
5725
|
throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605\u914D\u7F6E "${subName}"\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605`);
|
|
5818
5726
|
}
|
|
5819
5727
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5820
5728
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5729
|
+
await validateConfigWithKernel(buildResult.config);
|
|
5821
5730
|
const proxies = buildResult.config.proxies;
|
|
5822
5731
|
const proxyGroups = buildResult.config["proxy-groups"];
|
|
5823
5732
|
return {
|
|
@@ -5832,12 +5741,11 @@ function commitPreparedConfig(prepared) {
|
|
|
5832
5741
|
const { buildResult } = prepared;
|
|
5833
5742
|
if (buildResult.warnings.length > 0) {
|
|
5834
5743
|
for (const warning of buildResult.warnings) {
|
|
5835
|
-
console.log(`${colors.yellow("\
|
|
5744
|
+
console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
|
|
5836
5745
|
}
|
|
5837
5746
|
console.log("");
|
|
5838
5747
|
}
|
|
5839
5748
|
writeMihomoConfig(buildResult.config);
|
|
5840
|
-
writeDebugConfig(buildResult);
|
|
5841
5749
|
return prepared.info;
|
|
5842
5750
|
}
|
|
5843
5751
|
function needsAutoUpdate(sub) {
|
|
@@ -5906,9 +5814,9 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
5906
5814
|
}
|
|
5907
5815
|
|
|
5908
5816
|
// src/proxy-probe.ts
|
|
5909
|
-
import { execFile } from "child_process";
|
|
5910
|
-
import { promisify } from "util";
|
|
5911
|
-
var execFileAsync =
|
|
5817
|
+
import { execFile as execFile2 } from "child_process";
|
|
5818
|
+
import { promisify as promisify2 } from "util";
|
|
5819
|
+
var execFileAsync = promisify2(execFile2);
|
|
5912
5820
|
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
5913
5821
|
function isProbeSuccessStatus(code) {
|
|
5914
5822
|
return code !== null && code >= 200 && code < 300;
|
|
@@ -5983,9 +5891,7 @@ function buildStatusJson(args) {
|
|
|
5983
5891
|
kernel: getKernelVersion(),
|
|
5984
5892
|
kernelInstalled: hasKernel(),
|
|
5985
5893
|
ports: args.info ? args.info.tun ? { tun: true, ...args.info.mixedPort ? { mixed: args.info.mixedPort } : {} } : {
|
|
5986
|
-
...args.info.mixedPort ? { mixed: args.info.mixedPort } : {}
|
|
5987
|
-
...args.info.httpPort ? { http: args.info.httpPort } : {},
|
|
5988
|
-
...args.info.socksPort ? { socks: args.info.socksPort } : {}
|
|
5894
|
+
...args.info.mixedPort ? { mixed: args.info.mixedPort } : {}
|
|
5989
5895
|
} : {},
|
|
5990
5896
|
subscription: args.activeSub ? {
|
|
5991
5897
|
name: args.activeSub.name,
|
|
@@ -6018,8 +5924,7 @@ async function printStatus(args = []) {
|
|
|
6018
5924
|
const service = getServiceStatus();
|
|
6019
5925
|
const state = getRunningState(service);
|
|
6020
5926
|
const info = getConfigInfo();
|
|
6021
|
-
const overwriteEnabled =
|
|
6022
|
-
const overwriteFiles = listOverwriteFile().files;
|
|
5927
|
+
const { enabled: overwriteEnabled, files: overwriteFiles } = listOverwriteFile();
|
|
6023
5928
|
const activeSub = getActiveSubscription();
|
|
6024
5929
|
const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
|
|
6025
5930
|
const legacy = detectLegacySystemInstall();
|
|
@@ -6092,10 +5997,7 @@ async function printStatus(args = []) {
|
|
|
6092
5997
|
} else if (info.mixedPort) {
|
|
6093
5998
|
console.log(`${colors.gray("\u7AEF\u53E3: ")}${info.mixedPort}`);
|
|
6094
5999
|
} else {
|
|
6095
|
-
|
|
6096
|
-
if (info.httpPort) ports.push(`HTTP:${info.httpPort}`);
|
|
6097
|
-
if (info.socksPort) ports.push(`SOCKS:${info.socksPort}`);
|
|
6098
|
-
console.log(`${colors.gray("\u7AEF\u53E3: ")}${ports.length > 0 ? ports.join(", ") : "\u672A\u77E5"}`);
|
|
6000
|
+
console.log(`${colors.gray("\u7AEF\u53E3: ")}\u672A\u77E5`);
|
|
6099
6001
|
}
|
|
6100
6002
|
}
|
|
6101
6003
|
if (activeSub) {
|
|
@@ -6171,6 +6073,7 @@ async function cmdStart(args) {
|
|
|
6171
6073
|
}
|
|
6172
6074
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6173
6075
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6076
|
+
const stopEpochBefore = readStopEpoch();
|
|
6174
6077
|
const serviceBefore = getServiceStatus();
|
|
6175
6078
|
if (targetMode === "tun") {
|
|
6176
6079
|
if (detectLegacySystemInstall()) {
|
|
@@ -6207,7 +6110,7 @@ async function cmdStart(args) {
|
|
|
6207
6110
|
}
|
|
6208
6111
|
let prepared;
|
|
6209
6112
|
try {
|
|
6210
|
-
prepared = prepareConfigForStart(targetMode, sub.name);
|
|
6113
|
+
prepared = await prepareConfigForStart(targetMode, sub.name);
|
|
6211
6114
|
} catch (e) {
|
|
6212
6115
|
if (e instanceof CliError) throw e;
|
|
6213
6116
|
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
@@ -6216,7 +6119,7 @@ async function cmdStart(args) {
|
|
|
6216
6119
|
const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
|
|
6217
6120
|
console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
6218
6121
|
try {
|
|
6219
|
-
const pid = await launchOrRestart(targetMode,
|
|
6122
|
+
const pid = await launchOrRestart(targetMode, stopEpochBefore);
|
|
6220
6123
|
console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
|
|
6221
6124
|
} catch (e) {
|
|
6222
6125
|
if (e instanceof CliError) throw e;
|
|
@@ -6236,7 +6139,7 @@ async function dispatchSubcommand(args, table, options) {
|
|
|
6236
6139
|
if (action) {
|
|
6237
6140
|
const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
|
|
6238
6141
|
if (cmd) return cmd.handler(args);
|
|
6239
|
-
|
|
6142
|
+
return options.onUnknown(action);
|
|
6240
6143
|
}
|
|
6241
6144
|
return options.fallback(args);
|
|
6242
6145
|
}
|
|
@@ -6306,6 +6209,7 @@ function printDirectoryInfo() {
|
|
|
6306
6209
|
}
|
|
6307
6210
|
var SUBCOMMANDS = [{ name: "open", description: "\u6253\u5F00\u76EE\u5F55", handler: openDirectory }];
|
|
6308
6211
|
async function cmdDirectory(args) {
|
|
6212
|
+
assertKnownFlags(args.slice(1), [], "dir");
|
|
6309
6213
|
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
6310
6214
|
fallback: printDirectoryInfo,
|
|
6311
6215
|
onUnknown: (action) => {
|
|
@@ -6319,7 +6223,7 @@ async function cmdDirectory(args) {
|
|
|
6319
6223
|
}
|
|
6320
6224
|
|
|
6321
6225
|
// src/commands/overwrite.ts
|
|
6322
|
-
import
|
|
6226
|
+
import path8 from "path";
|
|
6323
6227
|
function printOverwriteList() {
|
|
6324
6228
|
const info = listOverwriteFile();
|
|
6325
6229
|
const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
|
|
@@ -6329,8 +6233,8 @@ function printOverwriteList() {
|
|
|
6329
6233
|
if (info.files.length === 0) {
|
|
6330
6234
|
console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
|
|
6331
6235
|
console.log("");
|
|
6332
|
-
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${
|
|
6333
|
-
console.log(` \u6216 ${
|
|
6236
|
+
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
|
|
6237
|
+
console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
|
|
6334
6238
|
console.log("");
|
|
6335
6239
|
} else {
|
|
6336
6240
|
console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
|
|
@@ -6604,7 +6508,10 @@ async function cmdSubscription(args) {
|
|
|
6604
6508
|
|
|
6605
6509
|
// src/commands/completion.ts
|
|
6606
6510
|
function commandWords(commands) {
|
|
6607
|
-
return commands.
|
|
6511
|
+
return commands.flatMap((c) => [
|
|
6512
|
+
{ word: c.name, desc: c.usage[0]?.description ?? "" },
|
|
6513
|
+
...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))
|
|
6514
|
+
]);
|
|
6608
6515
|
}
|
|
6609
6516
|
function subWords(subs) {
|
|
6610
6517
|
return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
|
|
@@ -6679,8 +6586,8 @@ function buildZsh(commands, groups) {
|
|
|
6679
6586
|
" ;;",
|
|
6680
6587
|
" completion)",
|
|
6681
6588
|
" if (( CURRENT == 2 )); then",
|
|
6682
|
-
` _values 'action' install ${SHELLS.join(" ")}`,
|
|
6683
|
-
" elif (( CURRENT == 3 )) && [[ ${words[2]} == install ]]; then",
|
|
6589
|
+
` _values 'action' install uninstall ${SHELLS.join(" ")}`,
|
|
6590
|
+
" elif (( CURRENT == 3 )) && [[ ${words[2]} == (install|uninstall) ]]; then",
|
|
6684
6591
|
` _values 'shell' ${SHELLS.join(" ")}`,
|
|
6685
6592
|
" fi",
|
|
6686
6593
|
" ;;",
|
|
@@ -6745,8 +6652,8 @@ ${subCase}
|
|
|
6745
6652
|
;;
|
|
6746
6653
|
completion)
|
|
6747
6654
|
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
6748
|
-
COMPREPLY=( $(compgen -W "install ${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6749
|
-
elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install ]]; then
|
|
6655
|
+
COMPREPLY=( $(compgen -W "install uninstall ${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6656
|
+
elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install || "\${COMP_WORDS[2]}" == uninstall ]]; then
|
|
6750
6657
|
COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6751
6658
|
fi
|
|
6752
6659
|
;;
|
|
@@ -6772,8 +6679,8 @@ function buildFish(commands, groups) {
|
|
|
6772
6679
|
}
|
|
6773
6680
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
|
|
6774
6681
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
|
|
6775
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install ${SHELLS.join(" ")}' -d '\u5B89\u88C5\u8865\u5168
|
|
6776
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install" -a '${SHELLS.join(" ")}'`);
|
|
6682
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
|
|
6683
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
|
|
6777
6684
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
|
|
6778
6685
|
lines.push("end");
|
|
6779
6686
|
return lines.join("\n");
|
|
@@ -6801,11 +6708,11 @@ function completionInstallPath(shell) {
|
|
|
6801
6708
|
const home = os3.homedir();
|
|
6802
6709
|
switch (shell) {
|
|
6803
6710
|
case "zsh":
|
|
6804
|
-
return
|
|
6711
|
+
return path9.join(home, ".zsh", "completions", "_mihomo");
|
|
6805
6712
|
case "bash":
|
|
6806
|
-
return
|
|
6713
|
+
return path9.join(home, ".bash_completion");
|
|
6807
6714
|
case "fish":
|
|
6808
|
-
return
|
|
6715
|
+
return path9.join(home, ".config", "fish", "completions", "mihomo.fish");
|
|
6809
6716
|
default:
|
|
6810
6717
|
return null;
|
|
6811
6718
|
}
|
|
@@ -6828,7 +6735,7 @@ function installCompletion(shell, commands) {
|
|
|
6828
6735
|
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6829
6736
|
return;
|
|
6830
6737
|
}
|
|
6831
|
-
fs10.mkdirSync(
|
|
6738
|
+
fs10.mkdirSync(path9.dirname(target), { recursive: true });
|
|
6832
6739
|
fs10.appendFileSync(target, `
|
|
6833
6740
|
${BASH_MARKER}
|
|
6834
6741
|
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
@@ -6836,7 +6743,7 @@ ${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
|
6836
6743
|
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6837
6744
|
return;
|
|
6838
6745
|
}
|
|
6839
|
-
fs10.mkdirSync(
|
|
6746
|
+
fs10.mkdirSync(path9.dirname(target), { recursive: true });
|
|
6840
6747
|
fs10.writeFileSync(target, script, { mode: 420 });
|
|
6841
6748
|
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6842
6749
|
} catch (e) {
|
|
@@ -6849,17 +6756,78 @@ ${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
|
6849
6756
|
console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
|
|
6850
6757
|
}
|
|
6851
6758
|
}
|
|
6759
|
+
function uninstallCompletion(shell, commands) {
|
|
6760
|
+
if (!shell) {
|
|
6761
|
+
throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion uninstall <${SHELLS.join("|")}>`] });
|
|
6762
|
+
}
|
|
6763
|
+
const target = completionInstallPath(shell);
|
|
6764
|
+
if (!target) {
|
|
6765
|
+
buildCompletionScript(shell, commands);
|
|
6766
|
+
return;
|
|
6767
|
+
}
|
|
6768
|
+
if (!fs10.existsSync(target)) {
|
|
6769
|
+
console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
|
|
6770
|
+
return;
|
|
6771
|
+
}
|
|
6772
|
+
console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
|
|
6773
|
+
try {
|
|
6774
|
+
if (shell === "bash") {
|
|
6775
|
+
const existing2 = fs10.readFileSync(target, "utf8");
|
|
6776
|
+
const endMarker = BASH_MARKER.replace(">>>", "<<<");
|
|
6777
|
+
const start = existing2.indexOf(BASH_MARKER);
|
|
6778
|
+
const end = existing2.indexOf(endMarker);
|
|
6779
|
+
if (start === -1 || end === -1 || end < start) {
|
|
6780
|
+
console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
|
|
6781
|
+
console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
|
|
6782
|
+
return;
|
|
6783
|
+
}
|
|
6784
|
+
const before = existing2.slice(0, start).replace(/\n+$/, "\n");
|
|
6785
|
+
const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
|
|
6786
|
+
const rest = `${before}${after}`;
|
|
6787
|
+
if (rest.trim() === "") {
|
|
6788
|
+
fs10.rmSync(target);
|
|
6789
|
+
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"));
|
|
6790
|
+
return;
|
|
6791
|
+
}
|
|
6792
|
+
fs10.writeFileSync(target, rest);
|
|
6793
|
+
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"));
|
|
6794
|
+
return;
|
|
6795
|
+
}
|
|
6796
|
+
const existing = fs10.readFileSync(target, "utf8");
|
|
6797
|
+
const fingerprint = shell === "zsh" ? "#compdef mihomo" : "for cmd in mihomo";
|
|
6798
|
+
if (!existing.includes(fingerprint)) {
|
|
6799
|
+
throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
|
|
6800
|
+
label: "\u5378\u8F7D\u4E2D\u6B62",
|
|
6801
|
+
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}`]
|
|
6802
|
+
});
|
|
6803
|
+
}
|
|
6804
|
+
fs10.rmSync(target);
|
|
6805
|
+
console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6806
|
+
} catch (e) {
|
|
6807
|
+
if (e instanceof CliError) throw e;
|
|
6808
|
+
throw new CliError(`\u8865\u5168\u5378\u8F7D\u5931\u8D25: ${e.message}`, {
|
|
6809
|
+
label: "\u5378\u8F7D\u5931\u8D25",
|
|
6810
|
+
hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u6587\u4EF6\u7684\u6743\u9650\uFF0C\u6216\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
|
|
6811
|
+
});
|
|
6812
|
+
}
|
|
6813
|
+
}
|
|
6852
6814
|
function cmdCompletion(args, commands) {
|
|
6815
|
+
assertKnownFlags(args.slice(1), [], "completion");
|
|
6853
6816
|
if (args[1] === "install") {
|
|
6854
6817
|
installCompletion(args[2], commands);
|
|
6855
6818
|
return;
|
|
6856
6819
|
}
|
|
6820
|
+
if (args[1] === "uninstall") {
|
|
6821
|
+
uninstallCompletion(args[2], commands);
|
|
6822
|
+
return;
|
|
6823
|
+
}
|
|
6857
6824
|
const shell = args[1];
|
|
6858
6825
|
if (!shell) {
|
|
6859
6826
|
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
6860
6827
|
hint: [
|
|
6861
6828
|
`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`,
|
|
6862
6829
|
`\u5B89\u88C5\u5230\u9ED8\u8BA4\u4F4D\u7F6E: mihomo completion install <${SHELLS.join("|")}>`,
|
|
6830
|
+
`\u5378\u8F7D: mihomo completion uninstall <${SHELLS.join("|")}>`,
|
|
6863
6831
|
'\u4E34\u65F6\u542F\u7528: eval "$(mihomo completion zsh)"'
|
|
6864
6832
|
]
|
|
6865
6833
|
});
|
|
@@ -6867,69 +6835,47 @@ function cmdCompletion(args, commands) {
|
|
|
6867
6835
|
console.log(buildCompletionScript(shell, commands));
|
|
6868
6836
|
}
|
|
6869
6837
|
|
|
6870
|
-
// src/commands/
|
|
6871
|
-
|
|
6872
|
-
|
|
6873
|
-
|
|
6874
|
-
|
|
6875
|
-
|
|
6876
|
-
|
|
6877
|
-
if (typeof version !== "string") {
|
|
6878
|
-
throw new TypeError("Invalid argument expected string");
|
|
6838
|
+
// src/commands/config.ts
|
|
6839
|
+
function cmdConfig(args = []) {
|
|
6840
|
+
assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
|
|
6841
|
+
const asJson = hasFlag(args, "-j", "--json");
|
|
6842
|
+
const active = getActiveSubscription();
|
|
6843
|
+
if (!active) {
|
|
6844
|
+
throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url>" });
|
|
6879
6845
|
}
|
|
6880
|
-
const
|
|
6881
|
-
if (!
|
|
6882
|
-
throw new
|
|
6846
|
+
const rawContent = readSubscriptionRawConfig(active.name);
|
|
6847
|
+
if (!rawContent) {
|
|
6848
|
+
throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo sub update ${active.name}` });
|
|
6883
6849
|
}
|
|
6884
|
-
|
|
6885
|
-
|
|
6886
|
-
};
|
|
6887
|
-
|
|
6888
|
-
|
|
6889
|
-
|
|
6890
|
-
|
|
6891
|
-
};
|
|
6892
|
-
var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
|
|
6893
|
-
var compareStrings = (a, b) => {
|
|
6894
|
-
if (isWildcard(a) || isWildcard(b))
|
|
6895
|
-
return 0;
|
|
6896
|
-
const [ap, bp] = forceType(tryParse(a), tryParse(b));
|
|
6897
|
-
if (ap > bp)
|
|
6898
|
-
return 1;
|
|
6899
|
-
if (ap < bp)
|
|
6900
|
-
return -1;
|
|
6901
|
-
return 0;
|
|
6902
|
-
};
|
|
6903
|
-
var compareSegments = (a, b) => {
|
|
6904
|
-
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
6905
|
-
const r = compareStrings(a[i] || "0", b[i] || "0");
|
|
6906
|
-
if (r !== 0)
|
|
6907
|
-
return r;
|
|
6850
|
+
const mode = getConfigInfo()?.tun ? "tun" : "mixed";
|
|
6851
|
+
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
6852
|
+
const shown = { ...config };
|
|
6853
|
+
if (typeof shown.secret === "string" && shown.secret) shown.secret = "***";
|
|
6854
|
+
if (asJson) {
|
|
6855
|
+
console.log(JSON.stringify(shown, null, 2));
|
|
6856
|
+
return;
|
|
6908
6857
|
}
|
|
6909
|
-
|
|
6910
|
-
|
|
6911
|
-
|
|
6912
|
-
|
|
6913
|
-
var compareVersions = (v1, v2) => {
|
|
6914
|
-
const n1 = validateAndParse(v1);
|
|
6915
|
-
const n2 = validateAndParse(v2);
|
|
6916
|
-
const p1 = n1.pop();
|
|
6917
|
-
const p2 = n2.pop();
|
|
6918
|
-
const r = compareSegments(n1, n2);
|
|
6919
|
-
if (r !== 0)
|
|
6920
|
-
return r;
|
|
6921
|
-
if (p1 && p2) {
|
|
6922
|
-
return compareSegments(p1.split("."), p2.split("."));
|
|
6923
|
-
} else if (p1 || p2) {
|
|
6924
|
-
return p1 ? -1 : 1;
|
|
6858
|
+
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
6859
|
+
console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
|
|
6860
|
+
if (typeof config.secret === "string" && config.secret) {
|
|
6861
|
+
console.log(colors.gray("# secret \u5DF2\u8131\u654F\u663E\u793A"));
|
|
6925
6862
|
}
|
|
6926
|
-
|
|
6927
|
-
|
|
6863
|
+
console.log("");
|
|
6864
|
+
console.log(dumpYaml(shown).trimEnd());
|
|
6865
|
+
if (warnings.length > 0) {
|
|
6866
|
+
console.log("");
|
|
6867
|
+
for (const w of warnings) console.log(colors.yellow(`# ${w}`));
|
|
6868
|
+
}
|
|
6869
|
+
}
|
|
6870
|
+
|
|
6871
|
+
// src/commands/doctor.ts
|
|
6872
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6873
|
+
import fs11 from "fs";
|
|
6928
6874
|
|
|
6929
6875
|
// src/commands/update.ts
|
|
6930
|
-
import { execFile as
|
|
6931
|
-
import { promisify as
|
|
6932
|
-
var execFileAsync2 =
|
|
6876
|
+
import { execFile as execFile3, spawn as spawn2 } from "child_process";
|
|
6877
|
+
import { promisify as promisify3 } from "util";
|
|
6878
|
+
var execFileAsync2 = promisify3(execFile3);
|
|
6933
6879
|
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
6934
6880
|
async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
6935
6881
|
try {
|
|
@@ -6940,7 +6886,8 @@ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
|
6940
6886
|
return null;
|
|
6941
6887
|
}
|
|
6942
6888
|
}
|
|
6943
|
-
async function cmdUpdate() {
|
|
6889
|
+
async function cmdUpdate(args = []) {
|
|
6890
|
+
assertKnownFlags(args.slice(1), [], "update");
|
|
6944
6891
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6945
6892
|
console.log("");
|
|
6946
6893
|
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
@@ -7103,16 +7050,16 @@ async function collectChecks() {
|
|
|
7103
7050
|
} else {
|
|
7104
7051
|
push("\u7AEF\u53E3", "ok", `${mixedPort} \u7A7A\u95F2`);
|
|
7105
7052
|
}
|
|
7106
|
-
if (active) {
|
|
7053
|
+
if (active && hasKernel()) {
|
|
7107
7054
|
try {
|
|
7108
7055
|
const mode = info?.tun ? "tun" : "mixed";
|
|
7109
|
-
prepareConfigForStart(mode, active.name);
|
|
7110
|
-
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\
|
|
7056
|
+
await prepareConfigForStart(mode, active.name);
|
|
7057
|
+
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
|
|
7111
7058
|
} catch (e) {
|
|
7112
7059
|
push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start");
|
|
7113
7060
|
}
|
|
7114
7061
|
} else {
|
|
7115
|
-
push("\u914D\u7F6E\u6784\u5EFA", "
|
|
7062
|
+
push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
|
|
7116
7063
|
}
|
|
7117
7064
|
if (state.running && info?.mixedPort) {
|
|
7118
7065
|
const probe = await probeProxyConnectivity(info.mixedPort);
|
|
@@ -7134,7 +7081,8 @@ async function collectChecks() {
|
|
|
7134
7081
|
}
|
|
7135
7082
|
return checks;
|
|
7136
7083
|
}
|
|
7137
|
-
async function cmdDoctor() {
|
|
7084
|
+
async function cmdDoctor(args = []) {
|
|
7085
|
+
assertKnownFlags(args.slice(1), [], "doctor");
|
|
7138
7086
|
const checks = await collectChecks();
|
|
7139
7087
|
console.log("");
|
|
7140
7088
|
for (const c of checks) {
|
|
@@ -7162,7 +7110,7 @@ async function cmdDoctor() {
|
|
|
7162
7110
|
// src/kernel.ts
|
|
7163
7111
|
import { spawnSync as spawnSync7 } from "child_process";
|
|
7164
7112
|
import fs12 from "fs";
|
|
7165
|
-
import
|
|
7113
|
+
import path10 from "path";
|
|
7166
7114
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
7167
7115
|
var KERNEL_HTTP_TIMEOUT = 12e4;
|
|
7168
7116
|
var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
|
|
@@ -7301,7 +7249,7 @@ function findBinaryInDir(dir, maxDepth = 4) {
|
|
|
7301
7249
|
if (maxDepth <= 0) return null;
|
|
7302
7250
|
const files = fs12.readdirSync(dir);
|
|
7303
7251
|
for (const f of files) {
|
|
7304
|
-
const fullPath =
|
|
7252
|
+
const fullPath = path10.join(dir, f);
|
|
7305
7253
|
const stat = fs12.lstatSync(fullPath);
|
|
7306
7254
|
if (stat.isDirectory()) {
|
|
7307
7255
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
@@ -7354,8 +7302,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7354
7302
|
}
|
|
7355
7303
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7356
7304
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7357
|
-
const tempDir = fs12.mkdtempSync(
|
|
7358
|
-
const tempPath =
|
|
7305
|
+
const tempDir = fs12.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
|
|
7306
|
+
const tempPath = path10.join(tempDir, path10.basename(asset.name));
|
|
7359
7307
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7360
7308
|
try {
|
|
7361
7309
|
if (channel.kind === "mirror" && progressCallback) {
|
|
@@ -7365,7 +7313,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7365
7313
|
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
7366
7314
|
}
|
|
7367
7315
|
if (channel.kind === "gh") {
|
|
7368
|
-
if (/[*?[\]]/.test(asset.name) || asset.name !==
|
|
7316
|
+
if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
|
|
7369
7317
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7370
7318
|
}
|
|
7371
7319
|
const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
@@ -7447,8 +7395,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7447
7395
|
if (tarResult.error) throw tarResult.error;
|
|
7448
7396
|
if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
|
|
7449
7397
|
} else if (tempPath.endsWith(".gz")) {
|
|
7450
|
-
const baseName =
|
|
7451
|
-
const outputPath =
|
|
7398
|
+
const baseName = path10.basename(tempPath, ".gz");
|
|
7399
|
+
const outputPath = path10.join(tempDir, baseName);
|
|
7452
7400
|
const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7453
7401
|
if (gzipResult.error) throw gzipResult.error;
|
|
7454
7402
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
@@ -7492,27 +7440,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7492
7440
|
}
|
|
7493
7441
|
|
|
7494
7442
|
// src/commands/kernel.ts
|
|
7495
|
-
function assertKnownKernelFlags(args) {
|
|
7496
|
-
const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror"]);
|
|
7497
|
-
const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all=")).filter((a) => a !== "--no-mirror" && a !== "--direct");
|
|
7498
|
-
if (unknown.length > 0) {
|
|
7499
|
-
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
|
|
7500
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
7501
|
-
hint: [
|
|
7502
|
-
"",
|
|
7503
|
-
"\u53EF\u7528\u9009\u9879:",
|
|
7504
|
-
" --mirror [\u955C\u50CF] \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
|
|
7505
|
-
"",
|
|
7506
|
-
"\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
|
|
7507
|
-
"",
|
|
7508
|
-
`\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
|
|
7509
|
-
"\u77ED\u522B\u540D: --mirror cdn | v4 | v6 | axisnow"
|
|
7510
|
-
]
|
|
7511
|
-
});
|
|
7512
|
-
}
|
|
7513
|
-
}
|
|
7514
7443
|
async function cmdKernel(args) {
|
|
7515
|
-
assertKnownKernelFlags(args);
|
|
7516
7444
|
const mirrorInfo = parseMirrorArg(args);
|
|
7517
7445
|
const effectiveMirror = mirrorInfo.mirror;
|
|
7518
7446
|
const proxyRunning = getRunningState().running;
|
|
@@ -7580,7 +7508,7 @@ async function cmdKernel(args) {
|
|
|
7580
7508
|
label: "\u4E0B\u8F7D\u5931\u8D25",
|
|
7581
7509
|
hint: [
|
|
7582
7510
|
"",
|
|
7583
|
-
"\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \
|
|
7511
|
+
"\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
|
|
7584
7512
|
"\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09"
|
|
7585
7513
|
]
|
|
7586
7514
|
});
|
|
@@ -7664,13 +7592,6 @@ function cmdLogs(args) {
|
|
|
7664
7592
|
console.log("");
|
|
7665
7593
|
}
|
|
7666
7594
|
|
|
7667
|
-
// src/commands/removed.ts
|
|
7668
|
-
function removedCommand(name, version, hint) {
|
|
7669
|
-
return () => {
|
|
7670
|
-
throw new CliError(`${name} \u5DF2\u79FB\u9664\uFF08${version}\uFF09`, { label: "\u547D\u4EE4\u4E0D\u5B58\u5728", hint });
|
|
7671
|
-
};
|
|
7672
|
-
}
|
|
7673
|
-
|
|
7674
7595
|
// src/commands/reset.ts
|
|
7675
7596
|
import fs14 from "fs";
|
|
7676
7597
|
|
|
@@ -7784,235 +7705,125 @@ async function stop(forceSudo = false) {
|
|
|
7784
7705
|
|
|
7785
7706
|
// src/commands/reset.ts
|
|
7786
7707
|
var RESET_TARGETS = [
|
|
7787
|
-
{
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
paths: () => [DIRS.subscriptions],
|
|
7792
|
-
needsStop: true,
|
|
7793
|
-
onAfter: () => {
|
|
7794
|
-
writeSettings({ subscriptions: void 0, active_subscription: void 0 });
|
|
7795
|
-
}
|
|
7796
|
-
},
|
|
7797
|
-
{
|
|
7798
|
-
id: "logs",
|
|
7799
|
-
aliases: ["log", "logs"],
|
|
7800
|
-
label: "\u65E5\u5FD7",
|
|
7801
|
-
paths: () => [DIRS.logs],
|
|
7802
|
-
// 内核运行时持有日志 fd,删文件后内核继续写已删 inode,logs 0 会 tail 不存在的路径
|
|
7803
|
-
needsStop: true
|
|
7804
|
-
},
|
|
7805
|
-
{
|
|
7806
|
-
id: "data",
|
|
7807
|
-
aliases: ["data"],
|
|
7808
|
-
label: "\u8FD0\u884C\u6570\u636E",
|
|
7809
|
-
paths: () => [DIRS.data],
|
|
7810
|
-
needsStop: true
|
|
7811
|
-
},
|
|
7812
|
-
{
|
|
7813
|
-
id: "runtime",
|
|
7814
|
-
aliases: ["runtime"],
|
|
7815
|
-
label: "\u8FD0\u884C\u65F6",
|
|
7816
|
-
paths: () => [DIRS.runtime],
|
|
7817
|
-
needsStop: true
|
|
7818
|
-
},
|
|
7708
|
+
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
7709
|
+
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
7710
|
+
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
7711
|
+
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
7819
7712
|
{
|
|
7820
7713
|
id: "overwrites",
|
|
7821
7714
|
aliases: ["overwrite", "overwrites", "ow"],
|
|
7822
7715
|
label: "\u8986\u5199",
|
|
7823
|
-
paths: () => {
|
|
7824
|
-
const dir = USER_DATA_DIR;
|
|
7825
|
-
if (!fs14.existsSync(dir)) return [];
|
|
7826
|
-
return fs14.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
7827
|
-
},
|
|
7828
7716
|
needsStop: false,
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
}
|
|
7717
|
+
preserveOnBare: true,
|
|
7718
|
+
paths: () => fs14.existsSync(USER_DATA_DIR) ? fs14.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
7832
7719
|
},
|
|
7833
7720
|
{
|
|
7834
7721
|
id: "settings",
|
|
7835
7722
|
aliases: ["setting", "settings", "config"],
|
|
7836
7723
|
label: "\u8BBE\u7F6E",
|
|
7837
|
-
// 同时删 .bak:readSettings 遇格式损坏会备份原文件(settings.ts),里面含
|
|
7838
|
-
// controller_secret 与订阅 URL 的 token。只删主文件会让 "已重置: 设置" 名不副实,
|
|
7839
|
-
// 凭据仍明文留在数据目录(cache.json.bak 在 subscriptions/ 内,随整目录删除,无需单列)
|
|
7840
|
-
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`],
|
|
7841
|
-
needsStop: false
|
|
7842
|
-
},
|
|
7843
|
-
{
|
|
7844
|
-
id: "kernel",
|
|
7845
|
-
aliases: ["kernel", "core"],
|
|
7846
|
-
label: "\u5185\u6838",
|
|
7847
|
-
paths: () => [DIRS.kernel],
|
|
7848
7724
|
needsStop: false,
|
|
7849
|
-
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
warnIfRunning: true
|
|
7725
|
+
preserveOnBare: true,
|
|
7726
|
+
// 损坏备份也包含订阅凭据,需要一起删除
|
|
7727
|
+
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
7853
7728
|
},
|
|
7854
|
-
{
|
|
7855
|
-
|
|
7856
|
-
aliases: ["service", "daemon"],
|
|
7857
|
-
label: "\u670D\u52A1",
|
|
7858
|
-
// 卸载由确认后的 uninstallsService 段统一处理;此处 paths 返回空
|
|
7859
|
-
// (plist 不在数据目录里,且不应提前删破坏卸载),
|
|
7860
|
-
// onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
|
|
7861
|
-
paths: () => [],
|
|
7862
|
-
needsStop: false,
|
|
7863
|
-
onAfter: async () => {
|
|
7864
|
-
const st = getServiceStatus();
|
|
7865
|
-
if (st.installed || st.loaded) await uninstallService();
|
|
7866
|
-
if (detectLegacySystemInstall()) cleanupLegacyInstallOrThrow();
|
|
7867
|
-
},
|
|
7868
|
-
checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
|
|
7869
|
-
emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
|
|
7870
|
-
}
|
|
7729
|
+
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
7730
|
+
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
7871
7731
|
];
|
|
7872
|
-
var RESET_PRESERVED_ON_BARE = ["settings", "kernel", "overwrites", "service"];
|
|
7873
7732
|
function resolveResetTargets(names) {
|
|
7874
|
-
const matched =
|
|
7875
|
-
const unmatched = [];
|
|
7733
|
+
const matched = /* @__PURE__ */ new Set();
|
|
7876
7734
|
for (const name of names) {
|
|
7877
|
-
const
|
|
7878
|
-
if (
|
|
7879
|
-
|
|
7880
|
-
} else {
|
|
7881
|
-
unmatched.push(name);
|
|
7735
|
+
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
7736
|
+
if (!target) {
|
|
7737
|
+
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
7882
7738
|
}
|
|
7739
|
+
matched.add(target);
|
|
7883
7740
|
}
|
|
7884
|
-
matched
|
|
7885
|
-
return { matched, unmatched };
|
|
7741
|
+
return [...matched];
|
|
7886
7742
|
}
|
|
7887
7743
|
async function cmdReset(args) {
|
|
7888
|
-
|
|
7889
|
-
const names =
|
|
7890
|
-
const
|
|
7891
|
-
const
|
|
7892
|
-
|
|
7893
|
-
|
|
7894
|
-
|
|
7895
|
-
const
|
|
7896
|
-
const
|
|
7897
|
-
|
|
7898
|
-
if (
|
|
7899
|
-
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
if (unmatched.length > 0) {
|
|
7903
|
-
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${unmatched.join(", ")}`, {
|
|
7904
|
-
hint: [
|
|
7905
|
-
"",
|
|
7906
|
-
`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.aliases[0]).join(", ")}`,
|
|
7907
|
-
"",
|
|
7908
|
-
"\u793A\u4F8B:",
|
|
7909
|
-
" mihomo reset sub log # \u5220\u9664\u8BA2\u9605\u548C\u65E5\u5FD7",
|
|
7910
|
-
" mihomo reset kernel # \u53EA\u5220\u5185\u6838",
|
|
7911
|
-
" mihomo reset --full # \u5220\u9664\u5168\u90E8",
|
|
7912
|
-
" mihomo reset # \u5220\u9664\u5168\u90E8\uFF08\u4FDD\u7559\u8BBE\u7F6E\u3001\u5185\u6838\u3001\u8986\u5199\uFF09"
|
|
7913
|
-
]
|
|
7914
|
-
});
|
|
7744
|
+
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
7745
|
+
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
7746
|
+
const namedTargets = resolveResetTargets(names);
|
|
7747
|
+
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
7748
|
+
const ids = new Set(targets.map((t) => t.id));
|
|
7749
|
+
const needsStop = targets.some((t) => t.needsStop);
|
|
7750
|
+
const serviceTargeted = ids.has("service");
|
|
7751
|
+
const service = getServiceStatus();
|
|
7752
|
+
const serviceActive = service.installed || service.loaded;
|
|
7753
|
+
const legacy = detectLegacySystemInstall();
|
|
7754
|
+
if (targets.length === 1) {
|
|
7755
|
+
if (serviceTargeted && !serviceActive && !legacy) {
|
|
7756
|
+
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
7757
|
+
return;
|
|
7915
7758
|
}
|
|
7916
|
-
targets = matched;
|
|
7917
|
-
} else {
|
|
7918
|
-
targets = RESET_TARGETS.filter((t) => !RESET_PRESERVED_ON_BARE.includes(t.id));
|
|
7919
7759
|
}
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
if (targets.length === 1) {
|
|
7923
|
-
console.log(t.emptyMsg);
|
|
7924
|
-
return;
|
|
7925
|
-
}
|
|
7926
|
-
}
|
|
7760
|
+
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
7761
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
|
|
7927
7762
|
}
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
const serviceTargeted = targets.some((t) => t.id === "service");
|
|
7932
|
-
const uninstallsService = serviceTargeted;
|
|
7933
|
-
const stopsService = needsStop || kernelTargeted;
|
|
7934
|
-
const serviceStatus = getServiceStatus();
|
|
7935
|
-
const serviceActive = serviceStatus.installed || serviceStatus.loaded;
|
|
7936
|
-
const pids = needsStop || warnRunning ? getMihomoPids() : [];
|
|
7937
|
-
if (warnRunning && pids.length > 0) {
|
|
7938
|
-
console.log(colors.yellow(`\u8B66\u544A: mihomo \u6B63\u5728\u8FD0\u884C (PID ${pids.join(", ")})\uFF0C\u5220\u9664\u5185\u6838\u540E\u5C06\u65E0\u6CD5\u91CD\u65B0\u542F\u52A8`));
|
|
7939
|
-
}
|
|
7940
|
-
if (uninstallsService && serviceActive) {
|
|
7941
|
-
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08\u79FB\u9664\u767B\u5F55\u81EA\u542F\uFF0CMixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
7942
|
-
} else if (stopsService && serviceActive) {
|
|
7763
|
+
if (serviceTargeted && serviceActive) {
|
|
7764
|
+
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
7765
|
+
} else if (needsStop && serviceActive) {
|
|
7943
7766
|
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
7944
7767
|
}
|
|
7945
|
-
if (
|
|
7946
|
-
console.log(colors.yellow("\u5C06\u6E05\u7406\
|
|
7768
|
+
if ((needsStop || serviceTargeted) && legacy) {
|
|
7769
|
+
console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
7947
7770
|
}
|
|
7948
7771
|
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
7949
|
-
if (!
|
|
7950
|
-
|
|
7951
|
-
|
|
7952
|
-
|
|
7953
|
-
|
|
7954
|
-
|
|
7955
|
-
return;
|
|
7956
|
-
}
|
|
7772
|
+
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
7773
|
+
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
7774
|
+
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
7775
|
+
})) {
|
|
7776
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
7777
|
+
return;
|
|
7957
7778
|
}
|
|
7958
|
-
if ((
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
|
|
7962
|
-
} else {
|
|
7963
|
-
await stopService();
|
|
7964
|
-
}
|
|
7965
|
-
} catch (e) {
|
|
7966
|
-
if (e instanceof CliError) throw e;
|
|
7967
|
-
throw new CliError(e.message.split("\n")[0], { label: "\u670D\u52A1\u64CD\u4F5C\u5DF2\u53D6\u6D88\uFF0C\u91CD\u7F6E\u4E2D\u6B62" });
|
|
7968
|
-
}
|
|
7779
|
+
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
7780
|
+
if (serviceActive) {
|
|
7781
|
+
if (serviceTargeted) await uninstallService();
|
|
7782
|
+
else if (needsStop) await stopService();
|
|
7969
7783
|
}
|
|
7970
|
-
if (needsStop
|
|
7971
|
-
console.log("\u505C\u6B62\u8FDB\u7A0B...");
|
|
7784
|
+
if (needsStop) {
|
|
7972
7785
|
const cleanup = await cleanupAll();
|
|
7973
|
-
|
|
7974
|
-
|
|
7975
|
-
await new Promise((r) => setTimeout(r, PROCESS_WAIT_INTERVAL));
|
|
7976
|
-
}
|
|
7977
|
-
const remaining = getMihomoPids();
|
|
7978
|
-
if (remaining.length > 0) {
|
|
7979
|
-
throw new CliError(remaining.join(", "), {
|
|
7786
|
+
if (cleanup.remaining.length > 0) {
|
|
7787
|
+
throw new CliError(cleanup.remaining.join(", "), {
|
|
7980
7788
|
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
7981
|
-
hint: [
|
|
7982
|
-
`\u672A\u7EC8\u6B62\u7684\u8FDB\u7A0B: ${remaining.join(", ")}${cleanup.failed > 0 ? `\uFF08${cleanup.failed} \u4E2A\u7EC8\u6B62\u5931\u8D25\uFF09` : ""}`,
|
|
7983
|
-
"\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo",
|
|
7984
|
-
"\u5426\u5219\u6B8B\u7559\u8FDB\u7A0B\u4F1A\u7EE7\u7EED\u4F7F\u7528\u5373\u5C06\u5220\u9664\u7684\u914D\u7F6E\u3002"
|
|
7985
|
-
]
|
|
7789
|
+
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
7986
7790
|
});
|
|
7987
7791
|
}
|
|
7792
|
+
recordServiceStopped();
|
|
7988
7793
|
}
|
|
7989
|
-
const deleted =
|
|
7990
|
-
for (const
|
|
7991
|
-
let hadContent =
|
|
7992
|
-
for (const
|
|
7993
|
-
if (fs14.existsSync(
|
|
7994
|
-
|
|
7995
|
-
|
|
7996
|
-
|
|
7997
|
-
|
|
7998
|
-
console.warn(` \u8B66\u544A: \u65E0\u6CD5\u5220\u9664 ${p}: ${e.message}`);
|
|
7999
|
-
}
|
|
7794
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
7795
|
+
for (const target of targets) {
|
|
7796
|
+
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
7797
|
+
for (const filePath of target.paths()) {
|
|
7798
|
+
if (!fs14.existsSync(filePath)) continue;
|
|
7799
|
+
try {
|
|
7800
|
+
rmrf(filePath);
|
|
7801
|
+
} catch (e) {
|
|
7802
|
+
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
8000
7803
|
}
|
|
7804
|
+
hadContent = true;
|
|
8001
7805
|
}
|
|
8002
|
-
|
|
8003
|
-
if (hadContent || !t.checkEmpty) {
|
|
8004
|
-
deleted.push(t.label);
|
|
8005
|
-
}
|
|
7806
|
+
if (hadContent) deleted.add(target.id);
|
|
8006
7807
|
}
|
|
8007
|
-
|
|
8008
|
-
|
|
8009
|
-
|
|
8010
|
-
|
|
8011
|
-
|
|
8012
|
-
|
|
8013
|
-
|
|
8014
|
-
|
|
7808
|
+
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
7809
|
+
updateSettings((settings) => {
|
|
7810
|
+
const patch = {};
|
|
7811
|
+
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
7812
|
+
patch.subscriptions = void 0;
|
|
7813
|
+
patch.active_subscription = void 0;
|
|
7814
|
+
deleted.add("subs");
|
|
7815
|
+
}
|
|
7816
|
+
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
7817
|
+
patch.overwrite_enabled = void 0;
|
|
7818
|
+
deleted.add("overwrites");
|
|
7819
|
+
}
|
|
7820
|
+
return patch;
|
|
7821
|
+
});
|
|
8015
7822
|
}
|
|
7823
|
+
if (ids.has("kernel")) clearKernelVersionCache();
|
|
7824
|
+
ensureDirs();
|
|
7825
|
+
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
7826
|
+
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
8016
7827
|
}
|
|
8017
7828
|
|
|
8018
7829
|
// src/commands/service.ts
|
|
@@ -8027,22 +7838,38 @@ async function handleLegacyInstall() {
|
|
|
8027
7838
|
console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
|
|
8028
7839
|
console.log("");
|
|
8029
7840
|
}
|
|
8030
|
-
|
|
7841
|
+
function printRestoreSkipped() {
|
|
7842
|
+
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
7843
|
+
console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
|
|
7844
|
+
console.log(colors.gray(" \u542F\u52A8: mihomo start"));
|
|
7845
|
+
console.log("");
|
|
7846
|
+
}
|
|
7847
|
+
async function cmdInstall(args) {
|
|
7848
|
+
assertKnownFlags(args.slice(1), [], "install");
|
|
8031
7849
|
if (!hasKernel()) {
|
|
8032
7850
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
8033
7851
|
}
|
|
7852
|
+
const stopEpochBefore = readStopEpoch();
|
|
8034
7853
|
await handleLegacyInstall();
|
|
8035
7854
|
const wasRunning = getServiceStatus().running;
|
|
8036
|
-
await installService(wasRunning);
|
|
7855
|
+
const { restoreSkipped } = await installService(wasRunning, stopEpochBefore);
|
|
8037
7856
|
console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
|
|
8038
7857
|
console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
|
|
8039
7858
|
console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
|
|
8040
7859
|
console.log("");
|
|
7860
|
+
if (restoreSkipped) {
|
|
7861
|
+
printRestoreSkipped();
|
|
7862
|
+
return;
|
|
7863
|
+
}
|
|
8041
7864
|
if (wasRunning) {
|
|
8042
7865
|
try {
|
|
8043
7866
|
await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
|
|
8044
7867
|
} catch (e) {
|
|
8045
7868
|
if (!(e instanceof CliError)) throw e;
|
|
7869
|
+
if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
|
|
7870
|
+
printRestoreSkipped();
|
|
7871
|
+
return;
|
|
7872
|
+
}
|
|
8046
7873
|
throw new CliError(e.message, {
|
|
8047
7874
|
label: e.label,
|
|
8048
7875
|
hint: [...e.hint, "", "\u670D\u52A1\u5DF2\u5B89\u88C5\u6210\u529F\uFF0C\u4EC5\u6062\u590D\u8FD0\u884C\u5931\u8D25\uFF1B\u4FEE\u6B63\u914D\u7F6E\u540E\u53EF\u6267\u884C mihomo start \u91CD\u8BD5\u3002"]
|
|
@@ -8057,7 +7884,8 @@ async function cmdInstall(_args) {
|
|
|
8057
7884
|
}
|
|
8058
7885
|
console.log("");
|
|
8059
7886
|
}
|
|
8060
|
-
async function cmdUninstall(
|
|
7887
|
+
async function cmdUninstall(args) {
|
|
7888
|
+
assertKnownFlags(args.slice(1), [], "uninstall");
|
|
8061
7889
|
const status = getServiceStatus();
|
|
8062
7890
|
const legacy = detectLegacySystemInstall();
|
|
8063
7891
|
const residue = getMihomoPids();
|
|
@@ -8097,7 +7925,8 @@ function handleStopResult(result) {
|
|
|
8097
7925
|
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
|
|
8098
7926
|
}
|
|
8099
7927
|
}
|
|
8100
|
-
async function cmdStop(
|
|
7928
|
+
async function cmdStop(args) {
|
|
7929
|
+
assertKnownFlags(args.slice(1), [], "stop");
|
|
8101
7930
|
if (detectLegacySystemInstall()) {
|
|
8102
7931
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
|
|
8103
7932
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
@@ -8109,12 +7938,14 @@ async function cmdStop(_args) {
|
|
|
8109
7938
|
const pids = getMihomoPids();
|
|
8110
7939
|
const needsServiceWork = status.loaded || status.installed && !status.disabled;
|
|
8111
7940
|
if (!needsServiceWork && pids.length === 0) {
|
|
7941
|
+
recordServiceStopped();
|
|
8112
7942
|
console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
|
|
8113
7943
|
return;
|
|
8114
7944
|
}
|
|
8115
7945
|
if (!needsServiceWork) {
|
|
8116
7946
|
console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
|
|
8117
7947
|
handleStopResult(await stop());
|
|
7948
|
+
recordServiceStopped();
|
|
8118
7949
|
console.log(colors.green("\u5DF2\u505C\u6B62"));
|
|
8119
7950
|
return;
|
|
8120
7951
|
}
|
|
@@ -8139,6 +7970,7 @@ function copyToClipboard(text) {
|
|
|
8139
7970
|
}
|
|
8140
7971
|
}
|
|
8141
7972
|
function cmdUI(args) {
|
|
7973
|
+
assertKnownFlags(args.slice(1), [], "ui");
|
|
8142
7974
|
const uiName = args[1] || "zash";
|
|
8143
7975
|
if (!Object.hasOwn(UI_URLS, uiName)) {
|
|
8144
7976
|
throw new CliError(`\u672A\u77E5\u7684 UI "${uiName}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
|
|
@@ -8205,38 +8037,6 @@ var COMMANDS = [
|
|
|
8205
8037
|
group: "control",
|
|
8206
8038
|
usage: [{ signature: "status [-j|--json] [--no-probe]", description: "\u67E5\u770B\u72B6\u6001" }]
|
|
8207
8039
|
},
|
|
8208
|
-
// === 已移除(墓碑:显式报错指引迁移,不在帮助中列出) ===
|
|
8209
|
-
{
|
|
8210
|
-
name: "daemon",
|
|
8211
|
-
aliases: [],
|
|
8212
|
-
handler: removedCommand("daemon", "v4.1.0", [
|
|
8213
|
-
"\u4FDD\u6D3B\u5DF2\u6210\u4E3A Mixed \u6A21\u5F0F\u7684\u552F\u4E00\u8FD0\u884C\u65B9\u5F0F\uFF0C\u6539\u7528\u670D\u52A1\u547D\u4EE4\u65CF\uFF1A",
|
|
8214
|
-
" mihomo daemon on \u2192 mihomo install\uFF08\u4E00\u6B21\uFF09+ mihomo start",
|
|
8215
|
-
" mihomo daemon off \u2192 mihomo stop\uFF08\u505C\u6B62\u5E76\u5173\u95ED\u81EA\u542F\uFF09",
|
|
8216
|
-
" mihomo daemon \u2192 mihomo status",
|
|
8217
|
-
"",
|
|
8218
|
-
"\u5F7B\u5E95\u79FB\u9664\u670D\u52A1: mihomo uninstall"
|
|
8219
|
-
]),
|
|
8220
|
-
group: "meta",
|
|
8221
|
-
usage: [],
|
|
8222
|
-
hidden: true
|
|
8223
|
-
},
|
|
8224
|
-
{
|
|
8225
|
-
name: "up",
|
|
8226
|
-
aliases: [],
|
|
8227
|
-
handler: removedCommand("up", "v4.1.0", ["\u8BF7\u7528: mihomo start"]),
|
|
8228
|
-
group: "meta",
|
|
8229
|
-
usage: [],
|
|
8230
|
-
hidden: true
|
|
8231
|
-
},
|
|
8232
|
-
{
|
|
8233
|
-
name: "down",
|
|
8234
|
-
aliases: [],
|
|
8235
|
-
handler: removedCommand("down", "v4.1.0", ["\u8BF7\u7528: mihomo stop"]),
|
|
8236
|
-
group: "meta",
|
|
8237
|
-
usage: [],
|
|
8238
|
-
hidden: true
|
|
8239
|
-
},
|
|
8240
8040
|
// === 界面 ===
|
|
8241
8041
|
{
|
|
8242
8042
|
name: "ui",
|
|
@@ -8245,23 +8045,6 @@ var COMMANDS = [
|
|
|
8245
8045
|
group: "interface",
|
|
8246
8046
|
usage: [{ signature: "ui [zash|dash|yacd]", description: "\u6253\u5F00 Web UI\uFF08\u9ED8\u8BA4 zash\uFF09" }]
|
|
8247
8047
|
},
|
|
8248
|
-
{
|
|
8249
|
-
// 已并入 `logs -f`;保留为隐藏别名过渡,不在帮助中列出(usage 留空),也不进补全词表
|
|
8250
|
-
name: "log",
|
|
8251
|
-
aliases: [],
|
|
8252
|
-
handler: cmdLogs,
|
|
8253
|
-
// 隐藏别名:log = logs 0 -f。用户传了编号时尊重编号(log 1 = logs 1 -f),
|
|
8254
|
-
// 而非恒为 0——此前编号被 '0' 顶掉,log 1 跟随的是当前日志而非归档 1
|
|
8255
|
-
rewrite: (args) => {
|
|
8256
|
-
const hasNum = args[1] !== void 0 && /^\d+$/.test(args[1]);
|
|
8257
|
-
const num = hasNum ? args[1] : "0";
|
|
8258
|
-
const rest = hasNum ? args.slice(2) : args.slice(1);
|
|
8259
|
-
return ["logs", num, "-f", ...rest];
|
|
8260
|
-
},
|
|
8261
|
-
group: "interface",
|
|
8262
|
-
usage: [],
|
|
8263
|
-
hidden: true
|
|
8264
|
-
},
|
|
8265
8048
|
{
|
|
8266
8049
|
name: "logs",
|
|
8267
8050
|
aliases: [],
|
|
@@ -8293,6 +8076,13 @@ var COMMANDS = [
|
|
|
8293
8076
|
]
|
|
8294
8077
|
},
|
|
8295
8078
|
// === 配置 ===
|
|
8079
|
+
{
|
|
8080
|
+
name: "config",
|
|
8081
|
+
aliases: [],
|
|
8082
|
+
handler: cmdConfig,
|
|
8083
|
+
group: "config",
|
|
8084
|
+
usage: [{ signature: "config [--json]", description: "\u67E5\u770B\u5F53\u524D\u751F\u6548\u7684\u8FD0\u884C\u914D\u7F6E\uFF08\u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF09" }]
|
|
8085
|
+
},
|
|
8296
8086
|
{
|
|
8297
8087
|
name: "overwrite",
|
|
8298
8088
|
aliases: ["ow"],
|
|
@@ -8319,7 +8109,7 @@ var COMMANDS = [
|
|
|
8319
8109
|
aliases: [],
|
|
8320
8110
|
handler: cmdKernel,
|
|
8321
8111
|
group: "system",
|
|
8322
|
-
usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \
|
|
8112
|
+
usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE\uFF09" }]
|
|
8323
8113
|
},
|
|
8324
8114
|
{
|
|
8325
8115
|
name: "update",
|
|
@@ -8349,6 +8139,7 @@ var COMMANDS = [
|
|
|
8349
8139
|
group: "system",
|
|
8350
8140
|
usage: [
|
|
8351
8141
|
{ signature: "completion install <zsh|bash|fish>", description: "\u5B89\u88C5\u8865\u5168\u5230\u5BF9\u5E94 shell \u7684\u9ED8\u8BA4\u4F4D\u7F6E" },
|
|
8142
|
+
{ signature: "completion uninstall <zsh|bash|fish>", description: "\u79FB\u9664\u5DF2\u5B89\u88C5\u7684\u8865\u5168" },
|
|
8352
8143
|
{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA\u8865\u5168\u811A\u672C\uFF08\u91CD\u5B9A\u5411\u6216 eval \u4F7F\u7528\uFF09" }
|
|
8353
8144
|
]
|
|
8354
8145
|
},
|
|
@@ -8437,6 +8228,16 @@ function assertNotRoot(commandName) {
|
|
|
8437
8228
|
]
|
|
8438
8229
|
});
|
|
8439
8230
|
}
|
|
8231
|
+
function assertSupportedNodeVersion(commandName) {
|
|
8232
|
+
if (!MIN_NODE_VERSION) return;
|
|
8233
|
+
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
8234
|
+
const current = process.versions.node;
|
|
8235
|
+
if (compareVersions(current, MIN_NODE_VERSION) >= 0) return;
|
|
8236
|
+
throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 >= ${MIN_NODE_VERSION}\uFF09`, {
|
|
8237
|
+
label: "Node \u7248\u672C\u4E0D\u652F\u6301",
|
|
8238
|
+
hint: ["\u5347\u7EA7 Node \u540E\u91CD\u8BD5\uFF0C\u4F8B\u5982:", " brew upgrade node", " \u6216\u7528 nvm: nvm install --lts && nvm use --lts", "", `\u5F53\u524D\u89E3\u91CA\u5668: ${process.execPath}`]
|
|
8239
|
+
});
|
|
8240
|
+
}
|
|
8440
8241
|
function assertSupportedPlatform(commandName) {
|
|
8441
8242
|
if (process.platform === "darwin") return;
|
|
8442
8243
|
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
@@ -8454,6 +8255,7 @@ async function main() {
|
|
|
8454
8255
|
clearProxyEnv();
|
|
8455
8256
|
const args = process.argv.slice(2);
|
|
8456
8257
|
if (args.length === 0) {
|
|
8258
|
+
assertSupportedNodeVersion("status");
|
|
8457
8259
|
assertSupportedPlatform("status");
|
|
8458
8260
|
assertNotRoot("status");
|
|
8459
8261
|
ensureDirs();
|
|
@@ -8469,10 +8271,11 @@ async function main() {
|
|
|
8469
8271
|
hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo help" \u67E5\u770B\u5E2E\u52A9']
|
|
8470
8272
|
});
|
|
8471
8273
|
}
|
|
8274
|
+
assertSupportedNodeVersion(command.name);
|
|
8472
8275
|
assertSupportedPlatform(command.name);
|
|
8473
8276
|
assertNotRoot(command.name);
|
|
8474
8277
|
ensureDirs();
|
|
8475
|
-
|
|
8278
|
+
if (command.group === "meta") assertKnownFlags(args.slice(1), [], command.name);
|
|
8476
8279
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8477
8280
|
}
|
|
8478
8281
|
main().catch((e) => {
|