mihomo-cli 4.8.1 → 4.9.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 +41 -0
- package/README.md +19 -5
- package/dist/index.js +822 -524
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -56,19 +56,22 @@ var compareVersions = (v1, v2) => {
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
// src/colors.ts
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
};
|
|
59
|
+
function colorEnabled(noColor, isTTY) {
|
|
60
|
+
return !(noColor !== void 0 && noColor !== "") && isTTY === true;
|
|
61
|
+
}
|
|
62
|
+
function createColors(enabled) {
|
|
63
|
+
const colorize = (code, str) => enabled ? `${code + String(str)}\x1B[0m` : String(str);
|
|
64
|
+
return {
|
|
65
|
+
bold: (s) => colorize("\x1B[1m", s),
|
|
66
|
+
red: (s) => colorize("\x1B[31m", s),
|
|
67
|
+
green: (s) => colorize("\x1B[32m", s),
|
|
68
|
+
yellow: (s) => colorize("\x1B[33m", s),
|
|
69
|
+
cyan: (s) => colorize("\x1B[36m", s),
|
|
70
|
+
gray: (s) => colorize("\x1B[90m", s)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
var colors = createColors(colorEnabled(process.env.NO_COLOR, process.stdout.isTTY));
|
|
74
|
+
var stderrColors = createColors(colorEnabled(process.env.NO_COLOR, process.stderr.isTTY));
|
|
72
75
|
|
|
73
76
|
// src/config.ts
|
|
74
77
|
import { execFile, spawnSync } from "child_process";
|
|
@@ -3200,6 +3203,9 @@ var CliError = class extends Error {
|
|
|
3200
3203
|
this.exitCode = options.exitCode ?? 1;
|
|
3201
3204
|
}
|
|
3202
3205
|
};
|
|
3206
|
+
function errorMessage(e) {
|
|
3207
|
+
return e instanceof Error ? e.message : String(e);
|
|
3208
|
+
}
|
|
3203
3209
|
function withTimeout(promise, ms) {
|
|
3204
3210
|
return new Promise((resolve, reject) => {
|
|
3205
3211
|
const timer = setTimeout(() => reject(new TimeoutError()), ms);
|
|
@@ -3327,8 +3333,9 @@ function rmrf(dir) {
|
|
|
3327
3333
|
}
|
|
3328
3334
|
var LOCK_STALE_MS = 1e4;
|
|
3329
3335
|
var LOCK_RETRY_MS = 20;
|
|
3330
|
-
function withFileLock(lockPath, fn) {
|
|
3331
|
-
const
|
|
3336
|
+
function withFileLock(lockPath, fn, opts) {
|
|
3337
|
+
const staleMs = opts?.staleMs ?? LOCK_STALE_MS;
|
|
3338
|
+
const deadline = Date.now() + (opts?.deadlineMs ?? LOCK_STALE_MS);
|
|
3332
3339
|
const token = `${process.pid}-${process.hrtime.bigint()}`;
|
|
3333
3340
|
let fd = null;
|
|
3334
3341
|
while (fd === null) {
|
|
@@ -3351,7 +3358,7 @@ function withFileLock(lockPath, fn) {
|
|
|
3351
3358
|
if (e.code !== "EEXIST") throw e;
|
|
3352
3359
|
let stale = false;
|
|
3353
3360
|
try {
|
|
3354
|
-
stale = Date.now() - fs.statSync(lockPath).mtimeMs >
|
|
3361
|
+
stale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3355
3362
|
} catch {
|
|
3356
3363
|
}
|
|
3357
3364
|
if (stale) {
|
|
@@ -3362,11 +3369,18 @@ function withFileLock(lockPath, fn) {
|
|
|
3362
3369
|
continue;
|
|
3363
3370
|
}
|
|
3364
3371
|
if (Date.now() > deadline) {
|
|
3372
|
+
let deadlineStale = false;
|
|
3365
3373
|
try {
|
|
3366
|
-
fs.
|
|
3374
|
+
deadlineStale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3367
3375
|
} catch {
|
|
3368
3376
|
}
|
|
3369
|
-
|
|
3377
|
+
if (deadlineStale) {
|
|
3378
|
+
try {
|
|
3379
|
+
fs.rmSync(lockPath, { force: true });
|
|
3380
|
+
} catch {
|
|
3381
|
+
}
|
|
3382
|
+
continue;
|
|
3383
|
+
}
|
|
3370
3384
|
}
|
|
3371
3385
|
sleepSyncMs(LOCK_RETRY_MS);
|
|
3372
3386
|
}
|
|
@@ -3449,15 +3463,19 @@ function getPorts(settings = readSettings()) {
|
|
|
3449
3463
|
if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
|
|
3450
3464
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3451
3465
|
}
|
|
3452
|
-
const
|
|
3453
|
-
const
|
|
3454
|
-
|
|
3455
|
-
|
|
3466
|
+
const configuredMixed = validatePort(ports.mixed, "ports.mixed");
|
|
3467
|
+
const configuredController = validatePort(ports.controller, "ports.controller");
|
|
3468
|
+
const mixed = configuredMixed ?? DEFAULT_MIXED_PORT;
|
|
3469
|
+
const controller = configuredController ?? CONTROLLER_PORT;
|
|
3470
|
+
if (mixed === controller) {
|
|
3471
|
+
const defaultedKey = configuredMixed === void 0 ? "ports.mixed" : configuredController === void 0 ? "ports.controller" : null;
|
|
3472
|
+
const source = defaultedKey ? `\uFF1A${defaultedKey} \u672A\u914D\u7F6E\uFF0C\u53D6\u9ED8\u8BA4 ${mixed}` : "";
|
|
3473
|
+
throw new CliError(`ports.mixed \u4E0E ports.controller \u4E0D\u80FD\u76F8\u540C\uFF08\u5F53\u524D\u5747\u4E3A ${mixed}${source}\uFF09`, {
|
|
3456
3474
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3457
3475
|
hint: ["\u6DF7\u5408\u7AEF\u53E3\u4E0E\u63A7\u5236\u5668\u7AEF\u53E3\u5404\u9700\u72EC\u7ACB\u7AEF\u53E3\uFF0C\u76F8\u540C\u4F1A\u5BFC\u81F4\u5185\u6838\u542F\u52A8\u5931\u8D25"]
|
|
3458
3476
|
});
|
|
3459
3477
|
}
|
|
3460
|
-
return { mixed
|
|
3478
|
+
return { mixed, controller };
|
|
3461
3479
|
}
|
|
3462
3480
|
function maskSingleUrl(url) {
|
|
3463
3481
|
try {
|
|
@@ -3669,6 +3687,9 @@ function parseOverrideKey(key) {
|
|
|
3669
3687
|
arrayMergeOnly = true;
|
|
3670
3688
|
actualKey = actualKey.slice(1);
|
|
3671
3689
|
}
|
|
3690
|
+
if (/^<[^>]+>$/.test(actualKey)) {
|
|
3691
|
+
actualKey = actualKey.slice(1, -1);
|
|
3692
|
+
}
|
|
3672
3693
|
} else {
|
|
3673
3694
|
if (actualKey.startsWith("+")) {
|
|
3674
3695
|
arrayPrepend = true;
|
|
@@ -3681,7 +3702,7 @@ function parseOverrideKey(key) {
|
|
|
3681
3702
|
}
|
|
3682
3703
|
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly };
|
|
3683
3704
|
}
|
|
3684
|
-
function
|
|
3705
|
+
function mergeConfigLevel(target, override, collectors, parseOperators) {
|
|
3685
3706
|
let t = target;
|
|
3686
3707
|
if (t === null || t === void 0) {
|
|
3687
3708
|
t = Array.isArray(override) ? [] : {};
|
|
@@ -3697,7 +3718,17 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3697
3718
|
}
|
|
3698
3719
|
const result = { ...t };
|
|
3699
3720
|
for (const [rawKey, value] of Object.entries(override)) {
|
|
3700
|
-
|
|
3721
|
+
let key = rawKey;
|
|
3722
|
+
let forceOverwrite = false;
|
|
3723
|
+
let arrayPrepend = false;
|
|
3724
|
+
let arrayAppend = false;
|
|
3725
|
+
let arrayMergeByName = false;
|
|
3726
|
+
let arrayMergeOnly = false;
|
|
3727
|
+
if (parseOperators) {
|
|
3728
|
+
({ key, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly } = parseOverrideKey(rawKey));
|
|
3729
|
+
} else if (isOperatorShapedNestedKey(rawKey)) {
|
|
3730
|
+
noteOperatorShapedKey(collectors, rawKey);
|
|
3731
|
+
}
|
|
3701
3732
|
const existingValue = result[key];
|
|
3702
3733
|
if (arrayMergeByName) {
|
|
3703
3734
|
if (existingValue !== void 0 && !Array.isArray(existingValue)) {
|
|
@@ -3719,9 +3750,9 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3719
3750
|
const name = item && typeof item === "object" && !Array.isArray(item) ? item.name : void 0;
|
|
3720
3751
|
const idx = name != null ? merged.findIndex((e) => e && typeof e === "object" && e.name === name) : -1;
|
|
3721
3752
|
if (idx >= 0) {
|
|
3722
|
-
merged[idx] =
|
|
3753
|
+
merged[idx] = mergeConfigLevel(merged[idx], item, collectors, false);
|
|
3723
3754
|
} else if (arrayMergeOnly) {
|
|
3724
|
-
skipped
|
|
3755
|
+
collectors.skipped.push({ key, name: name == null ? "(\u65E0 name)" : String(name) });
|
|
3725
3756
|
} else {
|
|
3726
3757
|
merged.push(item);
|
|
3727
3758
|
}
|
|
@@ -3753,13 +3784,21 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3753
3784
|
continue;
|
|
3754
3785
|
}
|
|
3755
3786
|
if (value !== null && typeof value === "object" && !Array.isArray(value) && existingValue !== null && typeof existingValue === "object" && !Array.isArray(existingValue)) {
|
|
3756
|
-
result[key] =
|
|
3787
|
+
result[key] = mergeConfigLevel(existingValue, value, collectors, false);
|
|
3757
3788
|
continue;
|
|
3758
3789
|
}
|
|
3759
3790
|
result[key] = value;
|
|
3760
3791
|
}
|
|
3761
3792
|
return result;
|
|
3762
3793
|
}
|
|
3794
|
+
function isOperatorShapedNestedKey(key) {
|
|
3795
|
+
if (key.startsWith("+.")) return false;
|
|
3796
|
+
return key.startsWith("~") || key.startsWith("+") || key.endsWith("!") || key.endsWith("+") || /^<[^>]+>$/.test(key);
|
|
3797
|
+
}
|
|
3798
|
+
function noteOperatorShapedKey(collectors, key) {
|
|
3799
|
+
if (collectors.operatorShapedKeys.some((note) => note.key === key)) return;
|
|
3800
|
+
collectors.operatorShapedKeys.push({ key });
|
|
3801
|
+
}
|
|
3763
3802
|
function isOverwriteEnabled() {
|
|
3764
3803
|
const settings = readSettings();
|
|
3765
3804
|
return settings.overwrite_enabled !== false;
|
|
@@ -3770,6 +3809,11 @@ function setOverwriteEnabled(enabled) {
|
|
|
3770
3809
|
function isOverwriteFilename(filename) {
|
|
3771
3810
|
return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
|
|
3772
3811
|
}
|
|
3812
|
+
function isOverwriteFilenameTypo(filename) {
|
|
3813
|
+
if (isOverwriteFilename(filename)) return false;
|
|
3814
|
+
const lower = filename.toLowerCase();
|
|
3815
|
+
return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower);
|
|
3816
|
+
}
|
|
3773
3817
|
var MATCH_KEYS = /* @__PURE__ */ new Set(["subscription", "url-domain"]);
|
|
3774
3818
|
function normalizeMatch(raw, fileName) {
|
|
3775
3819
|
if (raw == null) return void 0;
|
|
@@ -3852,11 +3896,17 @@ function filterOverwriteFilesByScope(files, scope) {
|
|
|
3852
3896
|
function loadOverwriteFile() {
|
|
3853
3897
|
const dir = USER_DATA_DIR;
|
|
3854
3898
|
if (!fs3.existsSync(dir)) return [];
|
|
3855
|
-
const
|
|
3899
|
+
const entries = fs3.readdirSync(dir);
|
|
3900
|
+
const files = entries.filter(isOverwriteFilename).sort((a, b) => {
|
|
3856
3901
|
if (a === "overwrite.yaml") return -1;
|
|
3857
3902
|
if (b === "overwrite.yaml") return 1;
|
|
3858
3903
|
return a.localeCompare(b);
|
|
3859
3904
|
});
|
|
3905
|
+
for (const typo of entries.filter((e) => isOverwriteFilenameTypo(e))) {
|
|
3906
|
+
console.warn(
|
|
3907
|
+
`\u8B66\u544A: "${typo}" \u4E0D\u4F1A\u88AB\u5F53\u4F5C\u8986\u5199\u6587\u4EF6\u52A0\u8F7D\uFF08\u5408\u6CD5\u6587\u4EF6\u540D: overwrite.yaml \u4E3B\u6587\u4EF6\u3001overwrite.*.yaml / overwrite.*.yml \u6269\u5C55\u6587\u4EF6\uFF1B\u4E3B\u6587\u4EF6\u4E0D\u652F\u6301 .yml\uFF09\uFF1B\u82E5\u662F\u7B14\u8BEF\u8BF7\u6539\u540D`
|
|
3908
|
+
);
|
|
3909
|
+
}
|
|
3860
3910
|
const results = [];
|
|
3861
3911
|
for (const file of files) {
|
|
3862
3912
|
const filePath = path3.join(dir, file);
|
|
@@ -3879,12 +3929,14 @@ function loadOverwriteFile() {
|
|
|
3879
3929
|
function applyOverwrite(baseConfig, files) {
|
|
3880
3930
|
let result = { ...baseConfig };
|
|
3881
3931
|
const skipped = [];
|
|
3932
|
+
const operatorShapedKeys = [];
|
|
3882
3933
|
for (const file of files) {
|
|
3883
|
-
const
|
|
3884
|
-
result =
|
|
3885
|
-
for (const s of
|
|
3934
|
+
const collectors = { skipped: [], operatorShapedKeys: [] };
|
|
3935
|
+
result = mergeConfigLevel(result, file.config, collectors, true);
|
|
3936
|
+
for (const s of collectors.skipped) skipped.push({ ...s, file: file.name });
|
|
3937
|
+
for (const k of collectors.operatorShapedKeys) operatorShapedKeys.push({ ...k, file: file.name });
|
|
3886
3938
|
}
|
|
3887
|
-
return { config: result, skipped };
|
|
3939
|
+
return { config: result, skipped, operatorShapedKeys };
|
|
3888
3940
|
}
|
|
3889
3941
|
function listOverwriteFile() {
|
|
3890
3942
|
const files = loadOverwriteFile();
|
|
@@ -3917,6 +3969,26 @@ var FLAGS = [
|
|
|
3917
3969
|
];
|
|
3918
3970
|
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
3919
3971
|
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
3972
|
+
function matchValueFlagToken(token) {
|
|
3973
|
+
const byForm = (form) => FLAGS.find((f) => f.takesValue && f.forms.includes(form));
|
|
3974
|
+
const exact = byForm(token);
|
|
3975
|
+
if (exact) return { spec: exact, baseForm: token, form: "exact", inlineValue: null };
|
|
3976
|
+
if (token.startsWith("--")) {
|
|
3977
|
+
const eqIdx = token.indexOf("=");
|
|
3978
|
+
if (eqIdx > 2) {
|
|
3979
|
+
const base = token.slice(0, eqIdx);
|
|
3980
|
+
const spec = byForm(base);
|
|
3981
|
+
if (spec) return { spec, baseForm: base, form: "long-eq", inlineValue: token.slice(eqIdx + 1) };
|
|
3982
|
+
}
|
|
3983
|
+
return null;
|
|
3984
|
+
}
|
|
3985
|
+
if (token.length > 2 && token.startsWith("-")) {
|
|
3986
|
+
const base = token.slice(0, 2);
|
|
3987
|
+
const spec = byForm(base);
|
|
3988
|
+
if (spec) return { spec, baseForm: base, form: "attached-short", inlineValue: token.slice(2) };
|
|
3989
|
+
}
|
|
3990
|
+
return null;
|
|
3991
|
+
}
|
|
3920
3992
|
|
|
3921
3993
|
// src/utils.ts
|
|
3922
3994
|
function sleep(ms) {
|
|
@@ -4032,15 +4104,33 @@ function assertKnownFlags(args, known, command) {
|
|
|
4032
4104
|
for (const a of args) {
|
|
4033
4105
|
if (!a.startsWith("-") || a === "-") continue;
|
|
4034
4106
|
if (knownSet.has(a)) continue;
|
|
4035
|
-
const
|
|
4036
|
-
if (
|
|
4037
|
-
if (a.
|
|
4107
|
+
const match = matchValueFlagToken(a);
|
|
4108
|
+
if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
|
|
4109
|
+
if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
|
|
4038
4110
|
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
4039
4111
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4040
4112
|
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
4041
4113
|
});
|
|
4042
4114
|
}
|
|
4043
4115
|
}
|
|
4116
|
+
function assertPositionalCount(args, max, startIdx, usage, valueFlags = VALUE_FLAGS) {
|
|
4117
|
+
if (!args) return;
|
|
4118
|
+
let count = 0;
|
|
4119
|
+
for (let i = startIdx; i < args.length; i++) {
|
|
4120
|
+
const a = args[i];
|
|
4121
|
+
if (a.startsWith("-")) {
|
|
4122
|
+
if (valueFlags.has(a)) i++;
|
|
4123
|
+
continue;
|
|
4124
|
+
}
|
|
4125
|
+
count++;
|
|
4126
|
+
if (count > max) {
|
|
4127
|
+
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
|
|
4128
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4129
|
+
hint: [`\u7528\u6CD5: ${usage}`]
|
|
4130
|
+
});
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4044
4134
|
function parseIntArg(args, short, long, defaultValue) {
|
|
4045
4135
|
if (!args) return defaultValue;
|
|
4046
4136
|
const parse = (raw, flag) => {
|
|
@@ -4060,11 +4150,9 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
4060
4150
|
}
|
|
4061
4151
|
throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
|
|
4062
4152
|
}
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
|
|
4067
|
-
return parse(args[i].slice(short.length), short);
|
|
4153
|
+
const match = matchValueFlagToken(args[i]);
|
|
4154
|
+
if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
|
|
4155
|
+
return parse(match.inlineValue ?? "", match.baseForm);
|
|
4068
4156
|
}
|
|
4069
4157
|
}
|
|
4070
4158
|
return defaultValue;
|
|
@@ -4073,12 +4161,16 @@ function extractStartOptions(args) {
|
|
|
4073
4161
|
if (!args) return [];
|
|
4074
4162
|
const out = [];
|
|
4075
4163
|
for (let i = 0; i < args.length; i++) {
|
|
4076
|
-
const
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4164
|
+
const token = args[i];
|
|
4165
|
+
if (START_RESTART_FLAGS.some((f) => !f.takesValue && f.forms.includes(token))) {
|
|
4166
|
+
out.push(token);
|
|
4167
|
+
continue;
|
|
4168
|
+
}
|
|
4169
|
+
const match = matchValueFlagToken(token);
|
|
4170
|
+
if (!match?.spec.passthroughToRestart) continue;
|
|
4171
|
+
out.push(token);
|
|
4172
|
+
if (match.form === "exact" && i + 1 < args.length) {
|
|
4173
|
+
out.push(args[++i]);
|
|
4082
4174
|
}
|
|
4083
4175
|
}
|
|
4084
4176
|
return out;
|
|
@@ -4270,13 +4362,18 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4270
4362
|
const settings = readSettings();
|
|
4271
4363
|
const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
|
|
4272
4364
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4273
|
-
const { config: withOverwrites, skipped: skippedMerges } = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4365
|
+
const { config: withOverwrites, skipped: skippedMerges, operatorShapedKeys } = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4274
4366
|
const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
|
|
4275
4367
|
const systemConfig = {};
|
|
4276
4368
|
const lockedWarnings = [];
|
|
4277
4369
|
for (const s of skippedMerges) {
|
|
4278
4370
|
lockedWarnings.push(`\u8986\u5199 ~?${s.key} \u7684\u8865\u4E01 "${s.name}" \u672A\u5339\u914D\u5230\u5F53\u524D\u8BA2\u9605\u4E2D\u7684\u540C\u540D\u5143\u7D20\uFF0C\u5DF2\u8DF3\u8FC7${s.file ? `\uFF08${s.file}\uFF09` : ""}`);
|
|
4279
4371
|
}
|
|
4372
|
+
for (const n of operatorShapedKeys) {
|
|
4373
|
+
lockedWarnings.push(
|
|
4374
|
+
`\u8986\u5199${n.file ? `\u6587\u4EF6 ${n.file} \u7684` : ""}\u5D4C\u5957\u952E "${n.key}" \u5F62\u4F3C\u64CD\u4F5C\u7B26\uFF0C\u5DF2\u6309\u5B57\u9762\u952E\u540D\u4FDD\u7559\uFF1B\u64CD\u4F5C\u7B26\u53EA\u5728\u8986\u5199\u6587\u4EF6\u9876\u5C42\u751F\u6548\uFF0C\u82E5\u8FD9\u662F mihomo \u539F\u751F\u952E\u53EF\u5FFD\u7565\u672C\u63D0\u793A`
|
|
4375
|
+
);
|
|
4376
|
+
}
|
|
4280
4377
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4281
4378
|
if (!(key in withOverwrites)) {
|
|
4282
4379
|
systemConfig[key] = value;
|
|
@@ -4288,6 +4385,8 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4288
4385
|
delete withOverwrites["mixed-port"];
|
|
4289
4386
|
delete withOverwrites.port;
|
|
4290
4387
|
delete withOverwrites["socks-port"];
|
|
4388
|
+
delete withOverwrites["redir-port"];
|
|
4389
|
+
delete withOverwrites["tproxy-port"];
|
|
4291
4390
|
delete withOverwrites["external-ui"];
|
|
4292
4391
|
delete withOverwrites["external-ui-name"];
|
|
4293
4392
|
delete withOverwrites["external-ui-url"];
|
|
@@ -4347,7 +4446,7 @@ function buildKernelRejectHint(detail, overwriteSummaries) {
|
|
|
4347
4446
|
hint.push("", `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
|
|
4348
4447
|
return hint;
|
|
4349
4448
|
}
|
|
4350
|
-
async function validateConfigWithKernel(config, overwriteSummaries
|
|
4449
|
+
async function validateConfigWithKernel(config, overwriteSummaries) {
|
|
4351
4450
|
if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4352
4451
|
ensureDirs();
|
|
4353
4452
|
const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
|
|
@@ -4476,23 +4575,51 @@ function readLogTail(maxLines = 15) {
|
|
|
4476
4575
|
}
|
|
4477
4576
|
}
|
|
4478
4577
|
}
|
|
4578
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
4479
4579
|
function allocateArchivePath() {
|
|
4480
4580
|
const timestamp = formatLocalTimestamp();
|
|
4481
|
-
let
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4581
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
4582
|
+
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
4583
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
4584
|
+
let fd = null;
|
|
4585
|
+
try {
|
|
4586
|
+
fd = fs5.openSync(archivePath, "wx");
|
|
4587
|
+
} catch (e) {
|
|
4588
|
+
if (e.code === "EEXIST") continue;
|
|
4589
|
+
throw e;
|
|
4590
|
+
}
|
|
4591
|
+
try {
|
|
4592
|
+
fs5.closeSync(fd);
|
|
4593
|
+
} catch {
|
|
4594
|
+
}
|
|
4595
|
+
return archivePath;
|
|
4486
4596
|
}
|
|
4487
|
-
|
|
4597
|
+
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
4598
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
4599
|
+
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
4600
|
+
});
|
|
4488
4601
|
}
|
|
4489
4602
|
function rotateLog() {
|
|
4490
4603
|
const logFile = PATHS.logFile;
|
|
4491
|
-
|
|
4492
|
-
|
|
4604
|
+
let stat;
|
|
4605
|
+
try {
|
|
4606
|
+
stat = fs5.statSync(logFile);
|
|
4607
|
+
} catch (e) {
|
|
4608
|
+
if (e.code === "ENOENT") return null;
|
|
4609
|
+
throw e;
|
|
4610
|
+
}
|
|
4493
4611
|
if (stat.size === 0) return null;
|
|
4494
4612
|
const rotatedPath = allocateArchivePath();
|
|
4495
|
-
|
|
4613
|
+
try {
|
|
4614
|
+
fs5.renameSync(logFile, rotatedPath);
|
|
4615
|
+
} catch (e) {
|
|
4616
|
+
try {
|
|
4617
|
+
fs5.unlinkSync(rotatedPath);
|
|
4618
|
+
} catch {
|
|
4619
|
+
}
|
|
4620
|
+
if (e.code === "ENOENT") return null;
|
|
4621
|
+
throw e;
|
|
4622
|
+
}
|
|
4496
4623
|
return rotatedPath;
|
|
4497
4624
|
}
|
|
4498
4625
|
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
@@ -4667,6 +4794,18 @@ import { spawnSync as spawnSync3 } from "child_process";
|
|
|
4667
4794
|
import fs7 from "fs";
|
|
4668
4795
|
import path6 from "path";
|
|
4669
4796
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
4797
|
+
var SudoAuthError = class extends Error {
|
|
4798
|
+
constructor() {
|
|
4799
|
+
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4800
|
+
this.name = "SudoAuthError";
|
|
4801
|
+
}
|
|
4802
|
+
};
|
|
4803
|
+
function sudoExitToError(action, status, codeMessages) {
|
|
4804
|
+
if (status === 1) return new SudoAuthError();
|
|
4805
|
+
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4806
|
+
const custom = codeMessages?.[status];
|
|
4807
|
+
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
4808
|
+
}
|
|
4670
4809
|
function runSudoScript(scriptBody, opts) {
|
|
4671
4810
|
if (!process.stdin.isTTY) {
|
|
4672
4811
|
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");
|
|
@@ -4678,16 +4817,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
4678
4817
|
try {
|
|
4679
4818
|
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
4680
4819
|
if (result.error) throw result.error;
|
|
4681
|
-
if (result.status !== 0)
|
|
4682
|
-
if (result.status === 1) {
|
|
4683
|
-
throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4684
|
-
}
|
|
4685
|
-
if (result.status == null) {
|
|
4686
|
-
throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4687
|
-
}
|
|
4688
|
-
const custom = opts.codeMessages?.[result.status];
|
|
4689
|
-
throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
|
|
4690
|
-
}
|
|
4820
|
+
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
4691
4821
|
} finally {
|
|
4692
4822
|
try {
|
|
4693
4823
|
fs7.unlinkSync(scriptPath);
|
|
@@ -4711,6 +4841,7 @@ var SERVICE_OBSERVE_MS = 1200;
|
|
|
4711
4841
|
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
4712
4842
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4713
4843
|
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
4844
|
+
var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
|
|
4714
4845
|
function serviceTarget() {
|
|
4715
4846
|
return `${bootstrapDomain()}/${SERVICE_LABEL}`;
|
|
4716
4847
|
}
|
|
@@ -4759,8 +4890,8 @@ function assertLaunchctlQueryOk(status, what) {
|
|
|
4759
4890
|
hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
|
|
4760
4891
|
});
|
|
4761
4892
|
}
|
|
4762
|
-
function isServiceDisabledInLaunchd() {
|
|
4763
|
-
const out = runLaunchctl(["print-disabled", bootstrapDomain()]);
|
|
4893
|
+
function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
4894
|
+
const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
|
|
4764
4895
|
assertLaunchctlQueryOk(out.status, "print-disabled");
|
|
4765
4896
|
return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
|
|
4766
4897
|
}
|
|
@@ -4867,16 +4998,16 @@ function ensureServiceSymlink() {
|
|
|
4867
4998
|
}
|
|
4868
4999
|
fs8.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
4869
5000
|
}
|
|
4870
|
-
function runLaunchctlOrThrow(args, what) {
|
|
4871
|
-
const result = runLaunchctl(args);
|
|
5001
|
+
function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5002
|
+
const result = runLaunchctl(args, timeoutMs);
|
|
4872
5003
|
if (result.status === 0) return;
|
|
4873
5004
|
const detail = result.stderr.trim();
|
|
4874
5005
|
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4875
5006
|
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
|
|
4876
5007
|
});
|
|
4877
5008
|
}
|
|
4878
|
-
function bootoutService() {
|
|
4879
|
-
const result = runLaunchctl(["bootout", serviceTarget()]);
|
|
5009
|
+
function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5010
|
+
const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
|
|
4880
5011
|
if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
4881
5012
|
const detail = result.stderr.trim();
|
|
4882
5013
|
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
@@ -4916,7 +5047,36 @@ function cleanupRootResidue() {
|
|
|
4916
5047
|
].join("\n");
|
|
4917
5048
|
runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh", codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" } });
|
|
4918
5049
|
}
|
|
4919
|
-
function
|
|
5050
|
+
function buildRootResidueCleanupError(e, ctx, rootPids) {
|
|
5051
|
+
const cancelled = e instanceof SudoAuthError;
|
|
5052
|
+
const hasKernelResidue = rootPids.length > 0;
|
|
5053
|
+
const hint = [
|
|
5054
|
+
ctx.mainOutcome,
|
|
5055
|
+
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u88AB\u6E05\u7406: ${PATHS.pidFile}`,
|
|
5056
|
+
`\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`
|
|
5057
|
+
];
|
|
5058
|
+
hint.push(hasKernelResidue ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5059
|
+
if (cancelled) {
|
|
5060
|
+
return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
|
|
5061
|
+
}
|
|
5062
|
+
return new CliError(e.message, { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5063
|
+
}
|
|
5064
|
+
function currentRootResiduePids() {
|
|
5065
|
+
try {
|
|
5066
|
+
return getMihomoPids().filter(isProcessRoot);
|
|
5067
|
+
} catch {
|
|
5068
|
+
return [];
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
function cleanupRootResidueOrThrow(ctx) {
|
|
5072
|
+
try {
|
|
5073
|
+
cleanupRootResidue();
|
|
5074
|
+
} catch (e) {
|
|
5075
|
+
if (e instanceof CliError) throw e;
|
|
5076
|
+
throw buildRootResidueCleanupError(e, ctx, currentRootResiduePids());
|
|
5077
|
+
}
|
|
5078
|
+
}
|
|
5079
|
+
function killResidualKernels(ctx) {
|
|
4920
5080
|
const pids = getMihomoPids();
|
|
4921
5081
|
if (pids.length === 0) return;
|
|
4922
5082
|
const rootPids = pids.filter(isProcessRoot);
|
|
@@ -4927,7 +5087,7 @@ function killResidualKernels() {
|
|
|
4927
5087
|
} catch {
|
|
4928
5088
|
}
|
|
4929
5089
|
}
|
|
4930
|
-
if (rootPids.length > 0)
|
|
5090
|
+
if (rootPids.length > 0) cleanupRootResidueOrThrow(ctx);
|
|
4931
5091
|
}
|
|
4932
5092
|
async function installService(wasRunning, stopEpochBefore) {
|
|
4933
5093
|
assertServiceLabelSafe();
|
|
@@ -5010,7 +5170,7 @@ async function startService(stopEpochBefore) {
|
|
|
5010
5170
|
]
|
|
5011
5171
|
});
|
|
5012
5172
|
}
|
|
5013
|
-
|
|
5173
|
+
cleanupRootResidueOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
|
|
5014
5174
|
bootoutService();
|
|
5015
5175
|
await waitUntilUnloaded();
|
|
5016
5176
|
rotateAndCleanupLogs();
|
|
@@ -5025,10 +5185,10 @@ async function startService(stopEpochBefore) {
|
|
|
5025
5185
|
});
|
|
5026
5186
|
return { started };
|
|
5027
5187
|
}
|
|
5028
|
-
function disableServiceAutoStart() {
|
|
5188
|
+
function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5029
5189
|
assertServiceLabelSafe();
|
|
5030
|
-
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F");
|
|
5031
|
-
if (!isServiceDisabledInLaunchd()) {
|
|
5190
|
+
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
|
|
5191
|
+
if (!isServiceDisabledInLaunchd(timeoutMs)) {
|
|
5032
5192
|
throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
|
|
5033
5193
|
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"]
|
|
5034
5194
|
});
|
|
@@ -5038,17 +5198,17 @@ function disableServiceAutoStart() {
|
|
|
5038
5198
|
async function stopService() {
|
|
5039
5199
|
assertServiceLabelSafe();
|
|
5040
5200
|
withFileLock(PATHS.serviceLock, () => {
|
|
5041
|
-
bootoutService();
|
|
5042
|
-
disableServiceAutoStart();
|
|
5201
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5202
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5043
5203
|
});
|
|
5044
5204
|
await waitUntilUnloaded();
|
|
5045
|
-
killResidualKernels();
|
|
5205
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
|
|
5046
5206
|
}
|
|
5047
5207
|
async function uninstallService() {
|
|
5048
5208
|
assertServiceLabelSafe();
|
|
5049
5209
|
withFileLock(PATHS.serviceLock, () => {
|
|
5050
|
-
bootoutService();
|
|
5051
|
-
disableServiceAutoStart();
|
|
5210
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5211
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5052
5212
|
});
|
|
5053
5213
|
await waitUntilUnloaded();
|
|
5054
5214
|
try {
|
|
@@ -5057,15 +5217,14 @@ async function uninstallService() {
|
|
|
5057
5217
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5058
5218
|
}
|
|
5059
5219
|
disableServiceAutoStart();
|
|
5060
|
-
killResidualKernels();
|
|
5220
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5061
5221
|
try {
|
|
5062
5222
|
fs8.rmSync(PATHS.serviceBinary, { force: true });
|
|
5063
5223
|
} catch {
|
|
5064
5224
|
}
|
|
5065
5225
|
}
|
|
5066
|
-
function
|
|
5067
|
-
|
|
5068
|
-
const script = [
|
|
5226
|
+
function buildLegacyCleanupScript() {
|
|
5227
|
+
return [
|
|
5069
5228
|
"#!/bin/bash",
|
|
5070
5229
|
// bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
|
|
5071
5230
|
// 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
|
|
@@ -5073,7 +5232,7 @@ function cleanupLegacySystemInstall() {
|
|
|
5073
5232
|
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
|
|
5074
5233
|
`if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
|
|
5075
5234
|
` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
|
|
5076
|
-
` exit
|
|
5235
|
+
` exit 3`,
|
|
5077
5236
|
`fi`,
|
|
5078
5237
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5079
5238
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
@@ -5082,7 +5241,16 @@ function cleanupLegacySystemInstall() {
|
|
|
5082
5241
|
"exit 0",
|
|
5083
5242
|
""
|
|
5084
5243
|
].join("\n");
|
|
5085
|
-
|
|
5244
|
+
}
|
|
5245
|
+
function cleanupLegacySystemInstall() {
|
|
5246
|
+
assertServiceLabelSafe();
|
|
5247
|
+
runSudoScript(buildLegacyCleanupScript(), {
|
|
5248
|
+
action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
|
|
5249
|
+
file: "legacy-cleanup.sh",
|
|
5250
|
+
// 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
|
|
5251
|
+
// 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
|
|
5252
|
+
codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
|
|
5253
|
+
});
|
|
5086
5254
|
}
|
|
5087
5255
|
function cleanupLegacyInstallOrThrow() {
|
|
5088
5256
|
try {
|
|
@@ -5134,11 +5302,16 @@ async function tryHotReload() {
|
|
|
5134
5302
|
clearTimeout(timer);
|
|
5135
5303
|
}
|
|
5136
5304
|
}
|
|
5305
|
+
function concludeHotReload(stopEpochBefore, stopEpochNow) {
|
|
5306
|
+
return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
|
|
5307
|
+
}
|
|
5137
5308
|
async function restartService(stopEpochBefore) {
|
|
5138
5309
|
if (!isServiceInstalled()) {
|
|
5139
5310
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5140
5311
|
}
|
|
5141
|
-
if (!logOversized() && await tryHotReload())
|
|
5312
|
+
if (!logOversized() && await tryHotReload()) {
|
|
5313
|
+
return concludeHotReload(stopEpochBefore, readStopEpoch());
|
|
5314
|
+
}
|
|
5142
5315
|
if (logOversized()) {
|
|
5143
5316
|
const archiveFile = allocateArchivePath();
|
|
5144
5317
|
try {
|
|
@@ -5248,7 +5421,7 @@ function printVersion() {
|
|
|
5248
5421
|
}
|
|
5249
5422
|
|
|
5250
5423
|
// src/commands/completion.ts
|
|
5251
|
-
import
|
|
5424
|
+
import fs12 from "fs";
|
|
5252
5425
|
import os3 from "os";
|
|
5253
5426
|
import path9 from "path";
|
|
5254
5427
|
|
|
@@ -5295,7 +5468,7 @@ function viewLogWithTail(logPath, options) {
|
|
|
5295
5468
|
tailArgs.push(logPath);
|
|
5296
5469
|
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5297
5470
|
if (follow) setSilentSigint(true);
|
|
5298
|
-
tail.on("close", (code
|
|
5471
|
+
tail.on("close", (code) => process.exit(code ?? 0));
|
|
5299
5472
|
tail.on("error", (e) => {
|
|
5300
5473
|
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5301
5474
|
process.exit(1);
|
|
@@ -5432,8 +5605,12 @@ function getRunningState(serviceStatus) {
|
|
|
5432
5605
|
}
|
|
5433
5606
|
return { running: false, pid: null, kind: null, processInfo: null };
|
|
5434
5607
|
}
|
|
5435
|
-
function
|
|
5436
|
-
return
|
|
5608
|
+
function restartModeFor(state, fallbackMode) {
|
|
5609
|
+
return state.kind === "tun" ? "tun" : fallbackMode;
|
|
5610
|
+
}
|
|
5611
|
+
function restartModeOnChange() {
|
|
5612
|
+
const state = getRunningState();
|
|
5613
|
+
return state.running ? restartModeFor(state, getRuntimeMode()) : null;
|
|
5437
5614
|
}
|
|
5438
5615
|
async function launchOrRestart(mode, stopEpochBefore) {
|
|
5439
5616
|
if (mode === "tun") {
|
|
@@ -5487,6 +5664,22 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
5487
5664
|
// src/http.ts
|
|
5488
5665
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5489
5666
|
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5667
|
+
function isHttpsUrl(url) {
|
|
5668
|
+
try {
|
|
5669
|
+
return new URL(url).protocol === "https:";
|
|
5670
|
+
} catch {
|
|
5671
|
+
return false;
|
|
5672
|
+
}
|
|
5673
|
+
}
|
|
5674
|
+
function createHttpError(status, bodyText) {
|
|
5675
|
+
const error = new Error(`HTTP ${status}`);
|
|
5676
|
+
error.response = { status };
|
|
5677
|
+
try {
|
|
5678
|
+
error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
|
|
5679
|
+
} catch {
|
|
5680
|
+
}
|
|
5681
|
+
return error;
|
|
5682
|
+
}
|
|
5490
5683
|
function createHttpClient(options = {}) {
|
|
5491
5684
|
const { timeout = 6e4 } = options;
|
|
5492
5685
|
return {
|
|
@@ -5499,18 +5692,16 @@ function createHttpClient(options = {}) {
|
|
|
5499
5692
|
signal,
|
|
5500
5693
|
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5501
5694
|
});
|
|
5502
|
-
if (url
|
|
5695
|
+
if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
|
|
5503
5696
|
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5504
5697
|
}
|
|
5505
5698
|
if (!response.ok) {
|
|
5506
|
-
|
|
5507
|
-
error.response = { status: response.status };
|
|
5699
|
+
let text2 = "";
|
|
5508
5700
|
try {
|
|
5509
|
-
|
|
5510
|
-
error.response.data = JSON.parse(text2);
|
|
5701
|
+
text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
|
|
5511
5702
|
} catch {
|
|
5512
5703
|
}
|
|
5513
|
-
throw
|
|
5704
|
+
throw createHttpError(response.status, text2);
|
|
5514
5705
|
}
|
|
5515
5706
|
const declaredLen = Number(response.headers.get("content-length"));
|
|
5516
5707
|
if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
|
|
@@ -5955,6 +6146,7 @@ function buildStatusJson(args) {
|
|
|
5955
6146
|
}
|
|
5956
6147
|
async function printStatus(args = []) {
|
|
5957
6148
|
assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
|
|
6149
|
+
assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
|
|
5958
6150
|
const asJson = hasFlag(args, "-j", "--json");
|
|
5959
6151
|
const skipProbe = hasFlag(args, "--no-probe");
|
|
5960
6152
|
const service = getServiceStatus();
|
|
@@ -6103,6 +6295,7 @@ function resolveStartMode(args) {
|
|
|
6103
6295
|
}
|
|
6104
6296
|
async function cmdStart(args) {
|
|
6105
6297
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
6298
|
+
assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
|
|
6106
6299
|
const targetMode = resolveStartMode(args);
|
|
6107
6300
|
if (!hasKernel()) {
|
|
6108
6301
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
@@ -6170,7 +6363,23 @@ async function cmdStart(args) {
|
|
|
6170
6363
|
}
|
|
6171
6364
|
|
|
6172
6365
|
// src/commands/shared.ts
|
|
6366
|
+
var validatedTables = /* @__PURE__ */ new WeakSet();
|
|
6367
|
+
function assertUniqueTokens(table) {
|
|
6368
|
+
if (validatedTables.has(table)) return;
|
|
6369
|
+
const owner = /* @__PURE__ */ new Map();
|
|
6370
|
+
for (const cmd of table) {
|
|
6371
|
+
for (const token of [cmd.name, ...cmd.aliases ?? []]) {
|
|
6372
|
+
const prev = owner.get(token);
|
|
6373
|
+
if (prev !== void 0) {
|
|
6374
|
+
throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
|
|
6375
|
+
}
|
|
6376
|
+
owner.set(token, cmd.name);
|
|
6377
|
+
}
|
|
6378
|
+
}
|
|
6379
|
+
validatedTables.add(table);
|
|
6380
|
+
}
|
|
6173
6381
|
async function dispatchSubcommand(args, table, options) {
|
|
6382
|
+
assertUniqueTokens(table);
|
|
6174
6383
|
const action = args[1];
|
|
6175
6384
|
if (action) {
|
|
6176
6385
|
const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
|
|
@@ -6197,8 +6406,8 @@ async function confirmOrThrow(question, opts) {
|
|
|
6197
6406
|
return confirmPrompt(question);
|
|
6198
6407
|
}
|
|
6199
6408
|
async function restartToApply(args) {
|
|
6200
|
-
|
|
6201
|
-
|
|
6409
|
+
const currentMode = restartModeOnChange();
|
|
6410
|
+
if (!currentMode) return false;
|
|
6202
6411
|
console.log("");
|
|
6203
6412
|
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
6204
6413
|
return true;
|
|
@@ -6206,6 +6415,7 @@ async function restartToApply(args) {
|
|
|
6206
6415
|
|
|
6207
6416
|
// src/commands/directory.ts
|
|
6208
6417
|
function openDirectory(args) {
|
|
6418
|
+
assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
|
|
6209
6419
|
const target = args[2];
|
|
6210
6420
|
if (!target || target === "root") {
|
|
6211
6421
|
console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
|
|
@@ -6292,6 +6502,7 @@ function printOverwriteList() {
|
|
|
6292
6502
|
console.log("");
|
|
6293
6503
|
}
|
|
6294
6504
|
async function setOverwrite(enabled, args) {
|
|
6505
|
+
assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
|
|
6295
6506
|
if (isOverwriteEnabled() === enabled) {
|
|
6296
6507
|
console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
|
|
6297
6508
|
console.log("");
|
|
@@ -6326,104 +6537,341 @@ async function cmdOverwrite(args) {
|
|
|
6326
6537
|
});
|
|
6327
6538
|
}
|
|
6328
6539
|
|
|
6329
|
-
// src/commands/
|
|
6540
|
+
// src/commands/reset.ts
|
|
6541
|
+
import fs11 from "fs";
|
|
6542
|
+
|
|
6543
|
+
// src/process-stop.ts
|
|
6330
6544
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6545
|
+
import fs10 from "fs";
|
|
6546
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6547
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
6548
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
6549
|
+
function clearRuntime() {
|
|
6550
|
+
if (fs10.existsSync(DIRS.runtime)) {
|
|
6551
|
+
rmrf(DIRS.runtime);
|
|
6335
6552
|
}
|
|
6553
|
+
ensureDirs();
|
|
6336
6554
|
}
|
|
6337
|
-
function
|
|
6338
|
-
|
|
6339
|
-
if (
|
|
6340
|
-
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
console.log("");
|
|
6344
|
-
return;
|
|
6345
|
-
}
|
|
6346
|
-
const activeSub = getActiveSubscription();
|
|
6347
|
-
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6348
|
-
subs.forEach((s, i) => {
|
|
6349
|
-
const rel = formatRelativeTime(s.updated_at);
|
|
6350
|
-
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6351
|
-
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6352
|
-
const interval = resolveUpdateInterval(s.update_interval);
|
|
6353
|
-
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6354
|
-
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6355
|
-
if (s.username) {
|
|
6356
|
-
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6357
|
-
}
|
|
6358
|
-
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6359
|
-
if (traffic) {
|
|
6360
|
-
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6361
|
-
}
|
|
6362
|
-
if (s.expire !== void 0) {
|
|
6363
|
-
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6555
|
+
function clearPid() {
|
|
6556
|
+
if (!fs10.existsSync(PATHS.pidFile)) return;
|
|
6557
|
+
if (isPidFileOwnedByRoot()) {
|
|
6558
|
+
try {
|
|
6559
|
+
spawnSync5("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
6560
|
+
} catch {
|
|
6364
6561
|
}
|
|
6365
|
-
|
|
6366
|
-
|
|
6562
|
+
} else {
|
|
6563
|
+
try {
|
|
6564
|
+
fs10.unlinkSync(PATHS.pidFile);
|
|
6565
|
+
} catch {
|
|
6367
6566
|
}
|
|
6368
|
-
}
|
|
6369
|
-
console.log("");
|
|
6370
|
-
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6371
|
-
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6372
|
-
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6373
|
-
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6374
|
-
console.log("");
|
|
6567
|
+
}
|
|
6375
6568
|
}
|
|
6376
|
-
function
|
|
6377
|
-
|
|
6378
|
-
|
|
6379
|
-
|
|
6380
|
-
|
|
6381
|
-
|
|
6569
|
+
function killProcess(pid) {
|
|
6570
|
+
try {
|
|
6571
|
+
process.kill(pid, "SIGKILL");
|
|
6572
|
+
return true;
|
|
6573
|
+
} catch {
|
|
6574
|
+
return false;
|
|
6382
6575
|
}
|
|
6383
6576
|
}
|
|
6384
|
-
function
|
|
6385
|
-
|
|
6577
|
+
function killAllMihomo(forceSudo = false) {
|
|
6578
|
+
const pattern = MAIN_INSTANCE_PATTERN;
|
|
6579
|
+
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
6580
|
+
const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
|
|
6386
6581
|
try {
|
|
6387
|
-
const
|
|
6388
|
-
if (
|
|
6389
|
-
|
|
6390
|
-
return isValidHttpUrl(text) ? text : null;
|
|
6582
|
+
const result = spawnSync5(argv[0], argv[1], options);
|
|
6583
|
+
if (result.error) return false;
|
|
6584
|
+
return result.status === 0 || result.status === 1;
|
|
6391
6585
|
} catch {
|
|
6392
|
-
return
|
|
6586
|
+
return false;
|
|
6393
6587
|
}
|
|
6394
6588
|
}
|
|
6395
|
-
async function
|
|
6396
|
-
|
|
6397
|
-
|
|
6398
|
-
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6404
|
-
|
|
6405
|
-
|
|
6589
|
+
async function cleanupAll(forceSudo = false) {
|
|
6590
|
+
const pids = getMihomoPids();
|
|
6591
|
+
if (pids.length === 0) {
|
|
6592
|
+
clearPid();
|
|
6593
|
+
return { killed: 0, failed: 0, remaining: [] };
|
|
6594
|
+
}
|
|
6595
|
+
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
6596
|
+
const needsSudo = forceSudo || hasRootProcess;
|
|
6597
|
+
let killedCount = 0;
|
|
6598
|
+
const failedPids = [];
|
|
6599
|
+
if (needsSudo) {
|
|
6600
|
+
const success = killAllMihomo(true);
|
|
6601
|
+
if (success) {
|
|
6602
|
+
killedCount = pids.length;
|
|
6603
|
+
} else {
|
|
6604
|
+
failedPids.push(...pids);
|
|
6605
|
+
}
|
|
6606
|
+
} else {
|
|
6607
|
+
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
6608
|
+
if (killAllMihomo(false)) {
|
|
6609
|
+
killedCount = pids.length;
|
|
6610
|
+
} else {
|
|
6611
|
+
failedPids.push(...pids);
|
|
6406
6612
|
}
|
|
6407
|
-
url = clipped;
|
|
6408
|
-
} else if (process.stdin.isTTY) {
|
|
6409
|
-
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6410
|
-
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6411
|
-
});
|
|
6412
6613
|
} else {
|
|
6413
|
-
|
|
6614
|
+
for (const pid of pids) {
|
|
6615
|
+
if (killProcess(pid)) {
|
|
6616
|
+
killedCount++;
|
|
6617
|
+
} else {
|
|
6618
|
+
failedPids.push(pid);
|
|
6619
|
+
}
|
|
6620
|
+
}
|
|
6414
6621
|
}
|
|
6415
6622
|
}
|
|
6416
|
-
|
|
6417
|
-
|
|
6623
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6624
|
+
if (getMihomoPids().length === 0) break;
|
|
6625
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
6418
6626
|
}
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
|
|
6425
|
-
|
|
6426
|
-
|
|
6627
|
+
clearPid();
|
|
6628
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
6629
|
+
}
|
|
6630
|
+
async function stop(forceSudo = false) {
|
|
6631
|
+
const allPids = getMihomoPids();
|
|
6632
|
+
if (allPids.length === 0) {
|
|
6633
|
+
clearPid();
|
|
6634
|
+
clearRuntime();
|
|
6635
|
+
return { success: true, notRunning: true };
|
|
6636
|
+
}
|
|
6637
|
+
const result = await cleanupAll(forceSudo);
|
|
6638
|
+
const remaining = getMihomoPids();
|
|
6639
|
+
if (remaining.length > 0) {
|
|
6640
|
+
console.log("");
|
|
6641
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
6642
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
6643
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
6644
|
+
console.log("");
|
|
6645
|
+
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
6646
|
+
}
|
|
6647
|
+
clearRuntime();
|
|
6648
|
+
return { success: true, killed: result.killed };
|
|
6649
|
+
}
|
|
6650
|
+
|
|
6651
|
+
// src/commands/reset.ts
|
|
6652
|
+
var RESET_TARGETS = [
|
|
6653
|
+
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
6654
|
+
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
6655
|
+
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
6656
|
+
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
6657
|
+
{
|
|
6658
|
+
id: "overwrites",
|
|
6659
|
+
aliases: ["overwrite", "overwrites", "ow"],
|
|
6660
|
+
label: "\u8986\u5199",
|
|
6661
|
+
needsStop: false,
|
|
6662
|
+
preserveOnBare: true,
|
|
6663
|
+
paths: () => fs11.existsSync(USER_DATA_DIR) ? fs11.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
6664
|
+
},
|
|
6665
|
+
{
|
|
6666
|
+
id: "settings",
|
|
6667
|
+
aliases: ["setting", "settings", "config"],
|
|
6668
|
+
label: "\u8BBE\u7F6E",
|
|
6669
|
+
needsStop: false,
|
|
6670
|
+
preserveOnBare: true,
|
|
6671
|
+
// 损坏备份也包含订阅凭据,需要一起删除
|
|
6672
|
+
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
6673
|
+
},
|
|
6674
|
+
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
6675
|
+
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
6676
|
+
];
|
|
6677
|
+
function resolveResetTargets(names) {
|
|
6678
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6679
|
+
for (const name of names) {
|
|
6680
|
+
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
6681
|
+
if (!target) {
|
|
6682
|
+
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
6683
|
+
}
|
|
6684
|
+
matched.add(target);
|
|
6685
|
+
}
|
|
6686
|
+
return [...matched];
|
|
6687
|
+
}
|
|
6688
|
+
async function cmdReset(args) {
|
|
6689
|
+
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
6690
|
+
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
6691
|
+
const namedTargets = resolveResetTargets(names);
|
|
6692
|
+
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
6693
|
+
const ids = new Set(targets.map((t) => t.id));
|
|
6694
|
+
const needsStop = targets.some((t) => t.needsStop);
|
|
6695
|
+
const serviceTargeted = ids.has("service");
|
|
6696
|
+
const service = getServiceStatus();
|
|
6697
|
+
const serviceActive = service.installed || service.loaded;
|
|
6698
|
+
const legacy = detectLegacySystemInstall();
|
|
6699
|
+
if (targets.length === 1) {
|
|
6700
|
+
if (serviceTargeted && !serviceActive && !legacy) {
|
|
6701
|
+
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
6702
|
+
return;
|
|
6703
|
+
}
|
|
6704
|
+
}
|
|
6705
|
+
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
6706
|
+
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"));
|
|
6707
|
+
}
|
|
6708
|
+
if (serviceTargeted && serviceActive) {
|
|
6709
|
+
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
6710
|
+
} else if (needsStop && serviceActive) {
|
|
6711
|
+
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"));
|
|
6712
|
+
}
|
|
6713
|
+
if ((needsStop || serviceTargeted) && legacy) {
|
|
6714
|
+
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"));
|
|
6715
|
+
}
|
|
6716
|
+
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
6717
|
+
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
6718
|
+
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
6719
|
+
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
6720
|
+
})) {
|
|
6721
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6722
|
+
return;
|
|
6723
|
+
}
|
|
6724
|
+
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
6725
|
+
if (serviceActive) {
|
|
6726
|
+
if (serviceTargeted) await uninstallService();
|
|
6727
|
+
else if (needsStop) await stopService();
|
|
6728
|
+
}
|
|
6729
|
+
if (needsStop) {
|
|
6730
|
+
const cleanup = await cleanupAll();
|
|
6731
|
+
if (cleanup.remaining.length > 0) {
|
|
6732
|
+
throw new CliError(cleanup.remaining.join(", "), {
|
|
6733
|
+
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
6734
|
+
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
6735
|
+
});
|
|
6736
|
+
}
|
|
6737
|
+
recordServiceStopped();
|
|
6738
|
+
}
|
|
6739
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
6740
|
+
for (const target of targets) {
|
|
6741
|
+
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
6742
|
+
for (const filePath of target.paths()) {
|
|
6743
|
+
if (!fs11.existsSync(filePath)) continue;
|
|
6744
|
+
try {
|
|
6745
|
+
rmrf(filePath);
|
|
6746
|
+
} catch (e) {
|
|
6747
|
+
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
6748
|
+
}
|
|
6749
|
+
hadContent = true;
|
|
6750
|
+
}
|
|
6751
|
+
if (hadContent) deleted.add(target.id);
|
|
6752
|
+
}
|
|
6753
|
+
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
6754
|
+
updateSettings((settings) => {
|
|
6755
|
+
const patch = {};
|
|
6756
|
+
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
6757
|
+
patch.subscriptions = void 0;
|
|
6758
|
+
patch.active_subscription = void 0;
|
|
6759
|
+
deleted.add("subs");
|
|
6760
|
+
}
|
|
6761
|
+
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
6762
|
+
patch.overwrite_enabled = void 0;
|
|
6763
|
+
deleted.add("overwrites");
|
|
6764
|
+
}
|
|
6765
|
+
return patch;
|
|
6766
|
+
});
|
|
6767
|
+
}
|
|
6768
|
+
if (ids.has("kernel")) clearKernelVersionCache();
|
|
6769
|
+
ensureDirs();
|
|
6770
|
+
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
6771
|
+
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
6772
|
+
}
|
|
6773
|
+
|
|
6774
|
+
// src/commands/subscription.ts
|
|
6775
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6776
|
+
function printRestartHintIfRunning() {
|
|
6777
|
+
const state = getRunningState();
|
|
6778
|
+
if (state.running) {
|
|
6779
|
+
const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
|
|
6780
|
+
console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`));
|
|
6781
|
+
console.log("");
|
|
6782
|
+
}
|
|
6783
|
+
}
|
|
6784
|
+
function printSubscriptionList() {
|
|
6785
|
+
const subs = getSubscriptionsWithCache();
|
|
6786
|
+
if (subs.length === 0) {
|
|
6787
|
+
console.log("\u6CA1\u6709\u8BA2\u9605");
|
|
6788
|
+
console.log("");
|
|
6789
|
+
console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6790
|
+
console.log("");
|
|
6791
|
+
return;
|
|
6792
|
+
}
|
|
6793
|
+
const activeSub = getActiveSubscription();
|
|
6794
|
+
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6795
|
+
subs.forEach((s, i) => {
|
|
6796
|
+
const rel = formatRelativeTime(s.updated_at);
|
|
6797
|
+
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6798
|
+
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6799
|
+
const interval = resolveUpdateInterval(s.update_interval);
|
|
6800
|
+
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6801
|
+
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6802
|
+
if (s.username) {
|
|
6803
|
+
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6804
|
+
}
|
|
6805
|
+
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6806
|
+
if (traffic) {
|
|
6807
|
+
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6808
|
+
}
|
|
6809
|
+
if (s.expire !== void 0) {
|
|
6810
|
+
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6811
|
+
}
|
|
6812
|
+
if (s.web_page_url) {
|
|
6813
|
+
console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
|
|
6814
|
+
}
|
|
6815
|
+
});
|
|
6816
|
+
console.log("");
|
|
6817
|
+
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6818
|
+
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6819
|
+
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6820
|
+
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6821
|
+
console.log("");
|
|
6822
|
+
}
|
|
6823
|
+
function assertNotFlagLike(name, usage) {
|
|
6824
|
+
if (name.startsWith("-")) {
|
|
6825
|
+
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
6826
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6827
|
+
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
6828
|
+
});
|
|
6829
|
+
}
|
|
6830
|
+
}
|
|
6831
|
+
function readUrlFromClipboard() {
|
|
6832
|
+
if (!process.stdin.isTTY) return null;
|
|
6833
|
+
try {
|
|
6834
|
+
const r = spawnSync6("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
6835
|
+
if (r.status !== 0) return null;
|
|
6836
|
+
const text = (r.stdout || "").trim();
|
|
6837
|
+
return isValidHttpUrl(text) ? text : null;
|
|
6838
|
+
} catch {
|
|
6839
|
+
return null;
|
|
6840
|
+
}
|
|
6841
|
+
}
|
|
6842
|
+
async function subAdd(args) {
|
|
6843
|
+
assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
|
|
6844
|
+
let url = args[2]?.trim();
|
|
6845
|
+
const name = args[3] || "default";
|
|
6846
|
+
if (!url) {
|
|
6847
|
+
const clipped = readUrlFromClipboard();
|
|
6848
|
+
if (clipped) {
|
|
6849
|
+
console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
|
|
6850
|
+
console.log(` ${maskUrl(clipped)}`);
|
|
6851
|
+
if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
|
|
6852
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6853
|
+
return;
|
|
6854
|
+
}
|
|
6855
|
+
url = clipped;
|
|
6856
|
+
} else if (process.stdin.isTTY) {
|
|
6857
|
+
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6858
|
+
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6859
|
+
});
|
|
6860
|
+
} else {
|
|
6861
|
+
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
|
|
6862
|
+
}
|
|
6863
|
+
}
|
|
6864
|
+
if (!isValidHttpUrl(url)) {
|
|
6865
|
+
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
6866
|
+
}
|
|
6867
|
+
assertNotFlagLike(name, "mihomo sub add <url> [name]");
|
|
6868
|
+
console.log(`\u6DFB\u52A0\u8BA2\u9605: ${name}`);
|
|
6869
|
+
addSubscription(url, name);
|
|
6870
|
+
try {
|
|
6871
|
+
const info = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => downloadSubscription(url, name));
|
|
6872
|
+
setDefaultSubscription(name);
|
|
6873
|
+
console.log(`\u5DF2\u6DFB\u52A0\u5E76\u5207\u6362\u5230 "${name}" (${formatProxySummary(info)})`);
|
|
6874
|
+
} catch (e) {
|
|
6427
6875
|
removeSubscription(name);
|
|
6428
6876
|
if (e instanceof CliError) throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25", hint: e.hint });
|
|
6429
6877
|
throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
|
|
@@ -6433,6 +6881,7 @@ async function subAdd(args) {
|
|
|
6433
6881
|
printSubscriptionList();
|
|
6434
6882
|
}
|
|
6435
6883
|
async function subUpdate(args) {
|
|
6884
|
+
assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
|
|
6436
6885
|
const name = getNonFlagArg(args, 2);
|
|
6437
6886
|
const subs = getSubscriptions();
|
|
6438
6887
|
if (subs.length === 0) {
|
|
@@ -6464,6 +6913,7 @@ async function subUpdate(args) {
|
|
|
6464
6913
|
printSubscriptionList();
|
|
6465
6914
|
}
|
|
6466
6915
|
async function subUse(args) {
|
|
6916
|
+
assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
|
|
6467
6917
|
const name = getNonFlagArg(args, 2);
|
|
6468
6918
|
const subs = getSubscriptions();
|
|
6469
6919
|
if (subs.length === 0) {
|
|
@@ -6493,6 +6943,7 @@ async function subUse(args) {
|
|
|
6493
6943
|
printSubscriptionList();
|
|
6494
6944
|
}
|
|
6495
6945
|
async function subRemove(args) {
|
|
6946
|
+
assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
|
|
6496
6947
|
const name = getNonFlagArg(args, 2);
|
|
6497
6948
|
const subs = getSubscriptions();
|
|
6498
6949
|
if (!name) {
|
|
@@ -6521,18 +6972,31 @@ async function subRemove(args) {
|
|
|
6521
6972
|
console.log("");
|
|
6522
6973
|
printSubscriptionList();
|
|
6523
6974
|
}
|
|
6975
|
+
var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
|
|
6976
|
+
var REMOVE_FLAGS = ["-y", "--yes"];
|
|
6977
|
+
function withKnownFlags(usage, known, handler) {
|
|
6978
|
+
return async (args) => {
|
|
6979
|
+
assertKnownFlags(args, known, usage);
|
|
6980
|
+
await handler(args);
|
|
6981
|
+
};
|
|
6982
|
+
}
|
|
6524
6983
|
var SUBCOMMANDS3 = [
|
|
6525
|
-
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: subAdd },
|
|
6526
|
-
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: subUpdate },
|
|
6527
|
-
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: subUse },
|
|
6528
|
-
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
|
|
6984
|
+
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
|
|
6985
|
+
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: withKnownFlags("sub update [name]", [], subUpdate) },
|
|
6986
|
+
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
|
|
6987
|
+
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
|
|
6529
6988
|
];
|
|
6530
6989
|
async function cmdSubscription(args) {
|
|
6531
|
-
assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
|
|
6532
6990
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6533
6991
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6534
6992
|
fallback: printSubscriptionList,
|
|
6535
6993
|
onUnknown: (action) => {
|
|
6994
|
+
if (action.startsWith("-")) {
|
|
6995
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
|
|
6996
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6997
|
+
hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
6998
|
+
});
|
|
6999
|
+
}
|
|
6536
7000
|
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6537
7001
|
const suggestion = suggestSimilar(action, names);
|
|
6538
7002
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
@@ -6559,8 +7023,10 @@ function subGroups(commands) {
|
|
|
6559
7023
|
};
|
|
6560
7024
|
return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
|
|
6561
7025
|
}
|
|
6562
|
-
var DIR_TARGETS =
|
|
6563
|
-
var UI_NAMES =
|
|
7026
|
+
var DIR_TARGETS = Object.keys(DIRECTORY_TARGETS);
|
|
7027
|
+
var UI_NAMES = Object.keys(UI_URLS);
|
|
7028
|
+
var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
|
|
7029
|
+
var RESET_TARGET_NAMES = RESET_TARGETS.map((t) => t.id);
|
|
6564
7030
|
var SHELLS = ["zsh", "bash", "fish"];
|
|
6565
7031
|
function buildZsh(commands, groups) {
|
|
6566
7032
|
const lines = [
|
|
@@ -6614,10 +7080,10 @@ function buildZsh(commands, groups) {
|
|
|
6614
7080
|
` _values 'ui' ${UI_NAMES.join(" ")}`,
|
|
6615
7081
|
" ;;",
|
|
6616
7082
|
" kernel)",
|
|
6617
|
-
|
|
7083
|
+
` _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(${MIRROR_NAMES.join(" ")})'`,
|
|
6618
7084
|
" ;;",
|
|
6619
7085
|
" reset)",
|
|
6620
|
-
` _values 'target'
|
|
7086
|
+
` _values 'target' ${RESET_TARGET_NAMES.join(" ")}`,
|
|
6621
7087
|
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
6622
7088
|
" ;;",
|
|
6623
7089
|
" completion)",
|
|
@@ -6681,10 +7147,14 @@ ${subCase}
|
|
|
6681
7147
|
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
6682
7148
|
;;
|
|
6683
7149
|
kernel)
|
|
6684
|
-
|
|
7150
|
+
if [[ "\${prev}" == "--mirror" ]]; then
|
|
7151
|
+
COMPREPLY=( $(compgen -W "${MIRROR_NAMES.join(" ")}" -- "\${cur}") )
|
|
7152
|
+
else
|
|
7153
|
+
COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
|
|
7154
|
+
fi
|
|
6685
7155
|
;;
|
|
6686
7156
|
reset)
|
|
6687
|
-
COMPREPLY=( $(compgen -W "
|
|
7157
|
+
COMPREPLY=( $(compgen -W "${RESET_TARGET_NAMES.join(" ")} --full -y" -- "\${cur}") )
|
|
6688
7158
|
;;
|
|
6689
7159
|
completion)
|
|
6690
7160
|
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
@@ -6709,15 +7179,20 @@ function buildFish(commands, groups) {
|
|
|
6709
7179
|
}
|
|
6710
7180
|
for (const group of groups) {
|
|
6711
7181
|
const seen = group.tokens.join(" ");
|
|
7182
|
+
const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
|
|
6712
7183
|
for (const s of group.words) {
|
|
6713
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${
|
|
7184
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
|
|
6714
7185
|
}
|
|
6715
7186
|
}
|
|
6716
|
-
lines.push(
|
|
6717
|
-
|
|
7187
|
+
lines.push(
|
|
7188
|
+
` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
|
|
7189
|
+
);
|
|
7190
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
|
|
6718
7191
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
|
|
6719
7192
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
|
|
6720
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -
|
|
7193
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -l mirror -d '\u8D70\u955C\u50CF\u4E0B\u8F7D' -a '${MIRROR_NAMES.join(" ")}'`);
|
|
7194
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -a '${RESET_TARGET_NAMES.join(" ")}'`);
|
|
7195
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -s y -l full -d '\u8DF3\u8FC7\u786E\u8BA4 / \u5220\u5168\u90E8'`);
|
|
6721
7196
|
lines.push("end");
|
|
6722
7197
|
return lines.join("\n");
|
|
6723
7198
|
}
|
|
@@ -6766,21 +7241,21 @@ function installCompletion(shell, commands) {
|
|
|
6766
7241
|
console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
|
|
6767
7242
|
try {
|
|
6768
7243
|
if (shell === "bash") {
|
|
6769
|
-
const existing =
|
|
7244
|
+
const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
|
|
6770
7245
|
if (existing.includes(BASH_MARKER)) {
|
|
6771
7246
|
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6772
7247
|
return;
|
|
6773
7248
|
}
|
|
6774
|
-
|
|
6775
|
-
|
|
7249
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7250
|
+
fs12.appendFileSync(target, `
|
|
6776
7251
|
${BASH_MARKER}
|
|
6777
7252
|
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
6778
7253
|
`);
|
|
6779
7254
|
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6780
7255
|
return;
|
|
6781
7256
|
}
|
|
6782
|
-
|
|
6783
|
-
|
|
7257
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7258
|
+
fs12.writeFileSync(target, script, { mode: 420 });
|
|
6784
7259
|
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6785
7260
|
} catch (e) {
|
|
6786
7261
|
throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
|
|
@@ -6801,14 +7276,14 @@ function uninstallCompletion(shell, commands) {
|
|
|
6801
7276
|
buildCompletionScript(shell, commands);
|
|
6802
7277
|
return;
|
|
6803
7278
|
}
|
|
6804
|
-
if (!
|
|
7279
|
+
if (!fs12.existsSync(target)) {
|
|
6805
7280
|
console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
|
|
6806
7281
|
return;
|
|
6807
7282
|
}
|
|
6808
7283
|
console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
|
|
6809
7284
|
try {
|
|
6810
7285
|
if (shell === "bash") {
|
|
6811
|
-
const existing2 =
|
|
7286
|
+
const existing2 = fs12.readFileSync(target, "utf8");
|
|
6812
7287
|
const endMarker = BASH_MARKER.replace(">>>", "<<<");
|
|
6813
7288
|
const start = existing2.indexOf(BASH_MARKER);
|
|
6814
7289
|
const end = existing2.indexOf(endMarker);
|
|
@@ -6821,15 +7296,15 @@ function uninstallCompletion(shell, commands) {
|
|
|
6821
7296
|
const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
|
|
6822
7297
|
const rest = `${before}${after}`;
|
|
6823
7298
|
if (rest.trim() === "") {
|
|
6824
|
-
|
|
7299
|
+
fs12.rmSync(target);
|
|
6825
7300
|
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"));
|
|
6826
7301
|
return;
|
|
6827
7302
|
}
|
|
6828
|
-
|
|
7303
|
+
fs12.writeFileSync(target, rest);
|
|
6829
7304
|
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"));
|
|
6830
7305
|
return;
|
|
6831
7306
|
}
|
|
6832
|
-
const existing =
|
|
7307
|
+
const existing = fs12.readFileSync(target, "utf8");
|
|
6833
7308
|
const fingerprint = shell === "zsh" ? "#compdef mihomo" : "for cmd in mihomo";
|
|
6834
7309
|
if (!existing.includes(fingerprint)) {
|
|
6835
7310
|
throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
|
|
@@ -6837,7 +7312,7 @@ function uninstallCompletion(shell, commands) {
|
|
|
6837
7312
|
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}`]
|
|
6838
7313
|
});
|
|
6839
7314
|
}
|
|
6840
|
-
|
|
7315
|
+
fs12.rmSync(target);
|
|
6841
7316
|
console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6842
7317
|
} catch (e) {
|
|
6843
7318
|
if (e instanceof CliError) throw e;
|
|
@@ -6850,13 +7325,16 @@ function uninstallCompletion(shell, commands) {
|
|
|
6850
7325
|
function cmdCompletion(args, commands) {
|
|
6851
7326
|
assertKnownFlags(args.slice(1), [], "completion");
|
|
6852
7327
|
if (args[1] === "install") {
|
|
7328
|
+
assertPositionalCount(args, 1, 2, `mihomo completion install <${SHELLS.join("|")}>`);
|
|
6853
7329
|
installCompletion(args[2], commands);
|
|
6854
7330
|
return;
|
|
6855
7331
|
}
|
|
6856
7332
|
if (args[1] === "uninstall") {
|
|
7333
|
+
assertPositionalCount(args, 1, 2, `mihomo completion uninstall <${SHELLS.join("|")}>`);
|
|
6857
7334
|
uninstallCompletion(args[2], commands);
|
|
6858
7335
|
return;
|
|
6859
7336
|
}
|
|
7337
|
+
assertPositionalCount(args, 1, 1, `mihomo completion <${SHELLS.join("|")}>`);
|
|
6860
7338
|
const shell = args[1];
|
|
6861
7339
|
if (!shell) {
|
|
6862
7340
|
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
@@ -6874,6 +7352,7 @@ function cmdCompletion(args, commands) {
|
|
|
6874
7352
|
// src/commands/config.ts
|
|
6875
7353
|
function cmdConfig(args = []) {
|
|
6876
7354
|
assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
|
|
7355
|
+
assertPositionalCount(args, 0, 1, "mihomo config [--json]");
|
|
6877
7356
|
const asJson = hasFlag(args, "-j", "--json");
|
|
6878
7357
|
const active = getActiveSubscription();
|
|
6879
7358
|
if (!active) {
|
|
@@ -6888,7 +7367,7 @@ function cmdConfig(args = []) {
|
|
|
6888
7367
|
const shown = { ...config };
|
|
6889
7368
|
if (typeof shown.secret === "string" && shown.secret) shown.secret = "***";
|
|
6890
7369
|
if (asJson) {
|
|
6891
|
-
console.log(JSON.stringify(shown, null, 2));
|
|
7370
|
+
console.log(JSON.stringify({ ...shown, warnings }, null, 2));
|
|
6892
7371
|
return;
|
|
6893
7372
|
}
|
|
6894
7373
|
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
@@ -6905,8 +7384,8 @@ function cmdConfig(args = []) {
|
|
|
6905
7384
|
}
|
|
6906
7385
|
|
|
6907
7386
|
// src/commands/doctor.ts
|
|
6908
|
-
import { spawnSync as
|
|
6909
|
-
import
|
|
7387
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7388
|
+
import fs13 from "fs";
|
|
6910
7389
|
|
|
6911
7390
|
// src/commands/update.ts
|
|
6912
7391
|
import { execFile as execFile3, spawn as spawn2 } from "child_process";
|
|
@@ -6924,6 +7403,7 @@ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
|
6924
7403
|
}
|
|
6925
7404
|
async function cmdUpdate(args = []) {
|
|
6926
7405
|
assertKnownFlags(args.slice(1), [], "update");
|
|
7406
|
+
assertPositionalCount(args, 0, 1, "mihomo update");
|
|
6927
7407
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6928
7408
|
console.log("");
|
|
6929
7409
|
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
@@ -6981,7 +7461,7 @@ async function cmdUpdate(args = []) {
|
|
|
6981
7461
|
// src/commands/doctor.ts
|
|
6982
7462
|
function isPortListening(port) {
|
|
6983
7463
|
try {
|
|
6984
|
-
const r =
|
|
7464
|
+
const r = spawnSync7("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
6985
7465
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
6986
7466
|
} catch {
|
|
6987
7467
|
return false;
|
|
@@ -6996,7 +7476,7 @@ async function collectChecks() {
|
|
|
6996
7476
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
6997
7477
|
} else {
|
|
6998
7478
|
const v = getKernelVersion();
|
|
6999
|
-
const r =
|
|
7479
|
+
const r = spawnSync7(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7000
7480
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
7001
7481
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
7002
7482
|
} else if (r.error) {
|
|
@@ -7006,13 +7486,13 @@ async function collectChecks() {
|
|
|
7006
7486
|
}
|
|
7007
7487
|
}
|
|
7008
7488
|
try {
|
|
7009
|
-
|
|
7489
|
+
fs13.accessSync(USER_DATA_DIR, fs13.constants.W_OK);
|
|
7010
7490
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
7011
7491
|
} catch {
|
|
7012
7492
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
7013
7493
|
}
|
|
7014
|
-
if (
|
|
7015
|
-
if (isValidSettingsContent(
|
|
7494
|
+
if (fs13.existsSync(PATHS.settingsFile)) {
|
|
7495
|
+
if (isValidSettingsContent(fs13.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
7016
7496
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
7017
7497
|
} else {
|
|
7018
7498
|
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
@@ -7089,8 +7569,19 @@ async function collectChecks() {
|
|
|
7089
7569
|
if (active && hasKernel()) {
|
|
7090
7570
|
try {
|
|
7091
7571
|
const mode = info?.tun ? "tun" : "mixed";
|
|
7092
|
-
await prepareConfigForStart(mode, active.name);
|
|
7093
|
-
|
|
7572
|
+
const prepared = await prepareConfigForStart(mode, active.name);
|
|
7573
|
+
const warnings = prepared.buildResult.warnings;
|
|
7574
|
+
if (warnings.length > 0) {
|
|
7575
|
+
push(
|
|
7576
|
+
"\u914D\u7F6E\u6784\u5EFA",
|
|
7577
|
+
"warn",
|
|
7578
|
+
`\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
|
|
7579
|
+
void 0,
|
|
7580
|
+
warnings.map((w) => ` ${w}`)
|
|
7581
|
+
);
|
|
7582
|
+
} else {
|
|
7583
|
+
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
|
|
7584
|
+
}
|
|
7094
7585
|
} catch (e) {
|
|
7095
7586
|
const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
|
|
7096
7587
|
push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
|
|
@@ -7120,6 +7611,7 @@ async function collectChecks() {
|
|
|
7120
7611
|
}
|
|
7121
7612
|
async function cmdDoctor(args = []) {
|
|
7122
7613
|
assertKnownFlags(args.slice(1), [], "doctor");
|
|
7614
|
+
assertPositionalCount(args, 0, 1, "mihomo doctor");
|
|
7123
7615
|
const checks = await collectChecks();
|
|
7124
7616
|
console.log("");
|
|
7125
7617
|
for (const c of checks) {
|
|
@@ -7146,13 +7638,15 @@ async function cmdDoctor(args = []) {
|
|
|
7146
7638
|
}
|
|
7147
7639
|
|
|
7148
7640
|
// src/kernel.ts
|
|
7149
|
-
import { spawnSync as
|
|
7150
|
-
import
|
|
7641
|
+
import { execFile as execFile4, spawnSync as spawnSync8 } from "child_process";
|
|
7642
|
+
import fs14 from "fs";
|
|
7151
7643
|
import path10 from "path";
|
|
7644
|
+
import { promisify as promisify4 } from "util";
|
|
7152
7645
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
7153
7646
|
var KERNEL_HTTP_TIMEOUT = 12e4;
|
|
7154
7647
|
var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
|
|
7155
7648
|
var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
|
|
7649
|
+
var execFileAsync3 = promisify4(execFile4);
|
|
7156
7650
|
function withMirror(url, mirror) {
|
|
7157
7651
|
if (mirror && url.startsWith("https://github.com/")) {
|
|
7158
7652
|
return mirror + url;
|
|
@@ -7184,7 +7678,7 @@ function resolveDownloadChannel(input) {
|
|
|
7184
7678
|
return { kind: "direct" };
|
|
7185
7679
|
}
|
|
7186
7680
|
function hasGh() {
|
|
7187
|
-
const result =
|
|
7681
|
+
const result = spawnSync8("gh", ["--version"], { stdio: "ignore" });
|
|
7188
7682
|
return !result.error && result.status === 0;
|
|
7189
7683
|
}
|
|
7190
7684
|
function getArch() {
|
|
@@ -7207,51 +7701,81 @@ function pickLatestRelease(releases) {
|
|
|
7207
7701
|
if (!Array.isArray(releases) || releases.length === 0) {
|
|
7208
7702
|
throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
|
|
7209
7703
|
}
|
|
7210
|
-
const stableReleases = releases.filter(
|
|
7211
|
-
(r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
|
|
7212
|
-
);
|
|
7213
|
-
if (stableReleases.length === 0) {
|
|
7214
|
-
throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
|
|
7704
|
+
const stableReleases = releases.filter(
|
|
7705
|
+
(r) => !r.prerelease && !r.tag_name.toLowerCase().includes("alpha") && !r.tag_name.toLowerCase().includes("beta") && !r.tag_name.toLowerCase().includes("prerelease")
|
|
7706
|
+
);
|
|
7707
|
+
if (stableReleases.length === 0) {
|
|
7708
|
+
throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
|
|
7709
|
+
}
|
|
7710
|
+
return stableReleases[0];
|
|
7711
|
+
}
|
|
7712
|
+
function buildReleaseApiCurlArgs(proxyPort, url) {
|
|
7713
|
+
return [
|
|
7714
|
+
"-s",
|
|
7715
|
+
"-x",
|
|
7716
|
+
`http://127.0.0.1:${proxyPort}`,
|
|
7717
|
+
"--proto",
|
|
7718
|
+
"=https",
|
|
7719
|
+
"--proto-redir",
|
|
7720
|
+
"=https",
|
|
7721
|
+
"--fail-with-body",
|
|
7722
|
+
"-w",
|
|
7723
|
+
"\n%{http_code}",
|
|
7724
|
+
"--connect-timeout",
|
|
7725
|
+
"10",
|
|
7726
|
+
"--max-time",
|
|
7727
|
+
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7728
|
+
"-H",
|
|
7729
|
+
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7730
|
+
url
|
|
7731
|
+
];
|
|
7732
|
+
}
|
|
7733
|
+
function parseCurlStatusOutput(stdout) {
|
|
7734
|
+
const newlineIdx = stdout.lastIndexOf("\n");
|
|
7735
|
+
if (newlineIdx === -1) return { body: stdout, statusCode: null };
|
|
7736
|
+
const code = Number.parseInt(stdout.slice(newlineIdx + 1).trim(), 10);
|
|
7737
|
+
return { body: stdout.slice(0, newlineIdx), statusCode: Number.isFinite(code) && code > 0 ? code : null };
|
|
7738
|
+
}
|
|
7739
|
+
function translateReleaseApiCurlError(e) {
|
|
7740
|
+
const err = e;
|
|
7741
|
+
if (typeof err.code === "string") {
|
|
7742
|
+
if (err.code === "ENOENT") {
|
|
7743
|
+
return new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7744
|
+
}
|
|
7745
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${err.message ?? err.code}`);
|
|
7746
|
+
}
|
|
7747
|
+
const { body, statusCode } = parseCurlStatusOutput(typeof err.stdout === "string" ? err.stdout : "");
|
|
7748
|
+
if (statusCode !== null && statusCode >= 400) {
|
|
7749
|
+
return createHttpError(statusCode, body);
|
|
7215
7750
|
}
|
|
7216
|
-
|
|
7751
|
+
if (err.killed) {
|
|
7752
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: curl ${Math.floor((KERNEL_HTTP_TIMEOUT + 1e4) / 1e3)}s \u672A\u5B8C\u6210\uFF0C\u5DF2\u7EC8\u6B62${err.signal ? `\uFF08${err.signal}\uFF09` : ""}`);
|
|
7753
|
+
}
|
|
7754
|
+
const stderr = (err.stderr || "").trim();
|
|
7755
|
+
const lastLine = stderr ? stderr.split("\n").pop()?.replace(/^curl: \(\d+\)\s*/, "") : void 0;
|
|
7756
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7217
7757
|
}
|
|
7218
7758
|
async function getLatestRelease(repo, proxyPort) {
|
|
7219
7759
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7220
7760
|
if (proxyPort) {
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
"
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
"--connect-timeout",
|
|
7232
|
-
"10",
|
|
7233
|
-
"--max-time",
|
|
7234
|
-
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7235
|
-
"-H",
|
|
7236
|
-
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7237
|
-
url
|
|
7238
|
-
],
|
|
7239
|
-
{ encoding: "utf8", maxBuffer: 50 * 1024 * 1024, timeout: KERNEL_HTTP_TIMEOUT + 1e4 }
|
|
7240
|
-
);
|
|
7241
|
-
if (result.error) {
|
|
7242
|
-
if (result.error.code === "ENOENT") {
|
|
7243
|
-
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7244
|
-
}
|
|
7245
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${result.error.message}`);
|
|
7761
|
+
let stdout;
|
|
7762
|
+
try {
|
|
7763
|
+
const result = await execFileAsync3("curl", buildReleaseApiCurlArgs(proxyPort, url), {
|
|
7764
|
+
encoding: "utf8",
|
|
7765
|
+
maxBuffer: 50 * 1024 * 1024,
|
|
7766
|
+
timeout: KERNEL_HTTP_TIMEOUT + 1e4
|
|
7767
|
+
});
|
|
7768
|
+
stdout = result.stdout;
|
|
7769
|
+
} catch (e) {
|
|
7770
|
+
throw translateReleaseApiCurlError(e);
|
|
7246
7771
|
}
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${result.status}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7772
|
+
const { body, statusCode } = parseCurlStatusOutput(stdout);
|
|
7773
|
+
if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
|
|
7774
|
+
throw createHttpError(statusCode, body);
|
|
7251
7775
|
}
|
|
7252
7776
|
let releases;
|
|
7253
7777
|
try {
|
|
7254
|
-
releases = JSON.parse(
|
|
7778
|
+
releases = JSON.parse(body);
|
|
7255
7779
|
} catch {
|
|
7256
7780
|
throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
|
|
7257
7781
|
}
|
|
@@ -7285,10 +7809,10 @@ async function checkUpdate(proxyPort) {
|
|
|
7285
7809
|
}
|
|
7286
7810
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
7287
7811
|
if (maxDepth <= 0) return null;
|
|
7288
|
-
const files =
|
|
7812
|
+
const files = fs14.readdirSync(dir);
|
|
7289
7813
|
for (const f of files) {
|
|
7290
7814
|
const fullPath = path10.join(dir, f);
|
|
7291
|
-
const stat =
|
|
7815
|
+
const stat = fs14.lstatSync(fullPath);
|
|
7292
7816
|
if (stat.isDirectory()) {
|
|
7293
7817
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
7294
7818
|
if (found) return found;
|
|
@@ -7340,7 +7864,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7340
7864
|
}
|
|
7341
7865
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7342
7866
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7343
|
-
const tempDir =
|
|
7867
|
+
const tempDir = fs14.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
|
|
7344
7868
|
const tempPath = path10.join(tempDir, path10.basename(asset.name));
|
|
7345
7869
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7346
7870
|
try {
|
|
@@ -7354,7 +7878,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7354
7878
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
|
|
7355
7879
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7356
7880
|
}
|
|
7357
|
-
const ghResult =
|
|
7881
|
+
const ghResult = spawnSync8("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7358
7882
|
stdio: "inherit",
|
|
7359
7883
|
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7360
7884
|
});
|
|
@@ -7372,7 +7896,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7372
7896
|
}
|
|
7373
7897
|
} else {
|
|
7374
7898
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7375
|
-
const curlResult =
|
|
7899
|
+
const curlResult = spawnSync8(
|
|
7376
7900
|
"curl",
|
|
7377
7901
|
buildKernelCurlArgs({
|
|
7378
7902
|
url: downloadUrl,
|
|
@@ -7392,11 +7916,11 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7392
7916
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7393
7917
|
}
|
|
7394
7918
|
}
|
|
7395
|
-
if (!
|
|
7919
|
+
if (!fs14.existsSync(tempPath)) {
|
|
7396
7920
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7397
7921
|
}
|
|
7398
7922
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7399
|
-
const actual =
|
|
7923
|
+
const actual = fs14.statSync(tempPath).size;
|
|
7400
7924
|
if (actual !== asset.size) {
|
|
7401
7925
|
throw new Error(
|
|
7402
7926
|
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
@@ -7409,7 +7933,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7409
7933
|
}
|
|
7410
7934
|
let extractedBinary = null;
|
|
7411
7935
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
7412
|
-
const listResult =
|
|
7936
|
+
const listResult = spawnSync8("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7413
7937
|
if (listResult.error) throw listResult.error;
|
|
7414
7938
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
7415
7939
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -7417,7 +7941,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7417
7941
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
7418
7942
|
}
|
|
7419
7943
|
}
|
|
7420
|
-
const typeResult =
|
|
7944
|
+
const typeResult = spawnSync8("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7421
7945
|
if (typeResult.error) throw typeResult.error;
|
|
7422
7946
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
7423
7947
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -7426,7 +7950,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7426
7950
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
7427
7951
|
}
|
|
7428
7952
|
}
|
|
7429
|
-
const tarResult =
|
|
7953
|
+
const tarResult = spawnSync8("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
|
|
7430
7954
|
stdio: ["ignore", "ignore", "inherit"],
|
|
7431
7955
|
timeout: 6e4
|
|
7432
7956
|
});
|
|
@@ -7435,10 +7959,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7435
7959
|
} else if (tempPath.endsWith(".gz")) {
|
|
7436
7960
|
const baseName = path10.basename(tempPath, ".gz");
|
|
7437
7961
|
const outputPath = path10.join(tempDir, baseName);
|
|
7438
|
-
const gzipResult =
|
|
7962
|
+
const gzipResult = spawnSync8("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7439
7963
|
if (gzipResult.error) throw gzipResult.error;
|
|
7440
7964
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7441
|
-
|
|
7965
|
+
fs14.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7442
7966
|
extractedBinary = outputPath;
|
|
7443
7967
|
}
|
|
7444
7968
|
const foundBinary = extractedBinary || findBinaryInDir(tempDir);
|
|
@@ -7448,8 +7972,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7448
7972
|
if (progressCallback) {
|
|
7449
7973
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7450
7974
|
}
|
|
7451
|
-
|
|
7452
|
-
const check =
|
|
7975
|
+
fs14.chmodSync(foundBinary, 493);
|
|
7976
|
+
const check = spawnSync8(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7453
7977
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7454
7978
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7455
7979
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
|
|
@@ -7465,21 +7989,23 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7465
7989
|
}
|
|
7466
7990
|
}
|
|
7467
7991
|
const targetPath = PATHS.mihomoBinary;
|
|
7468
|
-
|
|
7469
|
-
|
|
7992
|
+
fs14.renameSync(foundBinary, targetPath);
|
|
7993
|
+
fs14.chmodSync(targetPath, 493);
|
|
7470
7994
|
clearKernelVersionCache();
|
|
7471
7995
|
return { version: latest.tag_name, path: targetPath };
|
|
7472
7996
|
} finally {
|
|
7473
7997
|
try {
|
|
7474
|
-
|
|
7998
|
+
fs14.rmSync(tempDir, { recursive: true, force: true });
|
|
7475
7999
|
} catch {
|
|
7476
8000
|
}
|
|
7477
8001
|
}
|
|
7478
8002
|
}
|
|
7479
8003
|
|
|
7480
8004
|
// src/commands/kernel.ts
|
|
8005
|
+
var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
|
|
7481
8006
|
async function cmdKernel(args) {
|
|
7482
8007
|
const mirrorInfo = parseMirrorArg(args);
|
|
8008
|
+
assertPositionalCount(args, 0, 1, "mihomo kernel [--mirror [\u955C\u50CF]]", KERNEL_VALUE_FLAGS);
|
|
7483
8009
|
const effectiveMirror = mirrorInfo.mirror;
|
|
7484
8010
|
const proxyRunning = getRunningState().running;
|
|
7485
8011
|
const proxyPort = proxyRunning ? getPorts().mixed : null;
|
|
@@ -7562,12 +8088,11 @@ async function cmdKernel(args) {
|
|
|
7562
8088
|
// src/commands/log.ts
|
|
7563
8089
|
function cmdLogs(args) {
|
|
7564
8090
|
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8091
|
+
assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
|
|
7565
8092
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
7566
8093
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
7567
8094
|
const follow = hasFlag(args, "-f", "--follow");
|
|
7568
|
-
const hasLinesFlag = args.some(
|
|
7569
|
-
(a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
|
|
7570
|
-
);
|
|
8095
|
+
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
7571
8096
|
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
7572
8097
|
if (targetName) {
|
|
7573
8098
|
let logPath;
|
|
@@ -7630,240 +8155,6 @@ function cmdLogs(args) {
|
|
|
7630
8155
|
console.log("");
|
|
7631
8156
|
}
|
|
7632
8157
|
|
|
7633
|
-
// src/commands/reset.ts
|
|
7634
|
-
import fs14 from "fs";
|
|
7635
|
-
|
|
7636
|
-
// src/process-stop.ts
|
|
7637
|
-
import { spawnSync as spawnSync8 } from "child_process";
|
|
7638
|
-
import fs13 from "fs";
|
|
7639
|
-
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
7640
|
-
var PROCESS_WAIT_INTERVAL = 100;
|
|
7641
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
7642
|
-
function clearRuntime() {
|
|
7643
|
-
if (fs13.existsSync(DIRS.runtime)) {
|
|
7644
|
-
rmrf(DIRS.runtime);
|
|
7645
|
-
}
|
|
7646
|
-
ensureDirs();
|
|
7647
|
-
}
|
|
7648
|
-
function clearPid() {
|
|
7649
|
-
if (!fs13.existsSync(PATHS.pidFile)) return;
|
|
7650
|
-
if (isPidFileOwnedByRoot()) {
|
|
7651
|
-
try {
|
|
7652
|
-
spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
7653
|
-
} catch {
|
|
7654
|
-
}
|
|
7655
|
-
} else {
|
|
7656
|
-
try {
|
|
7657
|
-
fs13.unlinkSync(PATHS.pidFile);
|
|
7658
|
-
} catch {
|
|
7659
|
-
}
|
|
7660
|
-
}
|
|
7661
|
-
}
|
|
7662
|
-
function killProcess(pid) {
|
|
7663
|
-
try {
|
|
7664
|
-
process.kill(pid, "SIGKILL");
|
|
7665
|
-
return true;
|
|
7666
|
-
} catch {
|
|
7667
|
-
return false;
|
|
7668
|
-
}
|
|
7669
|
-
}
|
|
7670
|
-
function killAllMihomo(forceSudo = false) {
|
|
7671
|
-
const pattern = MAIN_INSTANCE_PATTERN;
|
|
7672
|
-
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
7673
|
-
const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
|
|
7674
|
-
try {
|
|
7675
|
-
const result = spawnSync8(argv[0], argv[1], options);
|
|
7676
|
-
if (result.error) return false;
|
|
7677
|
-
return result.status === 0 || result.status === 1;
|
|
7678
|
-
} catch {
|
|
7679
|
-
return false;
|
|
7680
|
-
}
|
|
7681
|
-
}
|
|
7682
|
-
async function cleanupAll(forceSudo = false) {
|
|
7683
|
-
const pids = getMihomoPids();
|
|
7684
|
-
if (pids.length === 0) {
|
|
7685
|
-
clearPid();
|
|
7686
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
7687
|
-
}
|
|
7688
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
7689
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
7690
|
-
let killedCount = 0;
|
|
7691
|
-
const failedPids = [];
|
|
7692
|
-
if (needsSudo) {
|
|
7693
|
-
const success = killAllMihomo(true);
|
|
7694
|
-
if (success) {
|
|
7695
|
-
killedCount = pids.length;
|
|
7696
|
-
} else {
|
|
7697
|
-
failedPids.push(...pids);
|
|
7698
|
-
}
|
|
7699
|
-
} else {
|
|
7700
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
7701
|
-
if (killAllMihomo(false)) {
|
|
7702
|
-
killedCount = pids.length;
|
|
7703
|
-
} else {
|
|
7704
|
-
failedPids.push(...pids);
|
|
7705
|
-
}
|
|
7706
|
-
} else {
|
|
7707
|
-
for (const pid of pids) {
|
|
7708
|
-
if (killProcess(pid)) {
|
|
7709
|
-
killedCount++;
|
|
7710
|
-
} else {
|
|
7711
|
-
failedPids.push(pid);
|
|
7712
|
-
}
|
|
7713
|
-
}
|
|
7714
|
-
}
|
|
7715
|
-
}
|
|
7716
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
7717
|
-
if (getMihomoPids().length === 0) break;
|
|
7718
|
-
await sleep(PROCESS_WAIT_INTERVAL);
|
|
7719
|
-
}
|
|
7720
|
-
clearPid();
|
|
7721
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
7722
|
-
}
|
|
7723
|
-
async function stop(forceSudo = false) {
|
|
7724
|
-
const allPids = getMihomoPids();
|
|
7725
|
-
if (allPids.length === 0) {
|
|
7726
|
-
clearPid();
|
|
7727
|
-
clearRuntime();
|
|
7728
|
-
return { success: true, notRunning: true };
|
|
7729
|
-
}
|
|
7730
|
-
const result = await cleanupAll(forceSudo);
|
|
7731
|
-
const remaining = getMihomoPids();
|
|
7732
|
-
if (remaining.length > 0) {
|
|
7733
|
-
console.log("");
|
|
7734
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
7735
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
7736
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
7737
|
-
console.log("");
|
|
7738
|
-
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
7739
|
-
}
|
|
7740
|
-
clearRuntime();
|
|
7741
|
-
return { success: true, killed: result.killed };
|
|
7742
|
-
}
|
|
7743
|
-
|
|
7744
|
-
// src/commands/reset.ts
|
|
7745
|
-
var RESET_TARGETS = [
|
|
7746
|
-
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
7747
|
-
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
7748
|
-
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
7749
|
-
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
7750
|
-
{
|
|
7751
|
-
id: "overwrites",
|
|
7752
|
-
aliases: ["overwrite", "overwrites", "ow"],
|
|
7753
|
-
label: "\u8986\u5199",
|
|
7754
|
-
needsStop: false,
|
|
7755
|
-
preserveOnBare: true,
|
|
7756
|
-
paths: () => fs14.existsSync(USER_DATA_DIR) ? fs14.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
7757
|
-
},
|
|
7758
|
-
{
|
|
7759
|
-
id: "settings",
|
|
7760
|
-
aliases: ["setting", "settings", "config"],
|
|
7761
|
-
label: "\u8BBE\u7F6E",
|
|
7762
|
-
needsStop: false,
|
|
7763
|
-
preserveOnBare: true,
|
|
7764
|
-
// 损坏备份也包含订阅凭据,需要一起删除
|
|
7765
|
-
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
7766
|
-
},
|
|
7767
|
-
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
7768
|
-
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
7769
|
-
];
|
|
7770
|
-
function resolveResetTargets(names) {
|
|
7771
|
-
const matched = /* @__PURE__ */ new Set();
|
|
7772
|
-
for (const name of names) {
|
|
7773
|
-
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
7774
|
-
if (!target) {
|
|
7775
|
-
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
7776
|
-
}
|
|
7777
|
-
matched.add(target);
|
|
7778
|
-
}
|
|
7779
|
-
return [...matched];
|
|
7780
|
-
}
|
|
7781
|
-
async function cmdReset(args) {
|
|
7782
|
-
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
7783
|
-
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
7784
|
-
const namedTargets = resolveResetTargets(names);
|
|
7785
|
-
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
7786
|
-
const ids = new Set(targets.map((t) => t.id));
|
|
7787
|
-
const needsStop = targets.some((t) => t.needsStop);
|
|
7788
|
-
const serviceTargeted = ids.has("service");
|
|
7789
|
-
const service = getServiceStatus();
|
|
7790
|
-
const serviceActive = service.installed || service.loaded;
|
|
7791
|
-
const legacy = detectLegacySystemInstall();
|
|
7792
|
-
if (targets.length === 1) {
|
|
7793
|
-
if (serviceTargeted && !serviceActive && !legacy) {
|
|
7794
|
-
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
7795
|
-
return;
|
|
7796
|
-
}
|
|
7797
|
-
}
|
|
7798
|
-
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
7799
|
-
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"));
|
|
7800
|
-
}
|
|
7801
|
-
if (serviceTargeted && serviceActive) {
|
|
7802
|
-
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
7803
|
-
} else if (needsStop && serviceActive) {
|
|
7804
|
-
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"));
|
|
7805
|
-
}
|
|
7806
|
-
if ((needsStop || serviceTargeted) && legacy) {
|
|
7807
|
-
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"));
|
|
7808
|
-
}
|
|
7809
|
-
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
7810
|
-
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
7811
|
-
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
7812
|
-
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
7813
|
-
})) {
|
|
7814
|
-
console.log("\u5DF2\u53D6\u6D88");
|
|
7815
|
-
return;
|
|
7816
|
-
}
|
|
7817
|
-
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
7818
|
-
if (serviceActive) {
|
|
7819
|
-
if (serviceTargeted) await uninstallService();
|
|
7820
|
-
else if (needsStop) await stopService();
|
|
7821
|
-
}
|
|
7822
|
-
if (needsStop) {
|
|
7823
|
-
const cleanup = await cleanupAll();
|
|
7824
|
-
if (cleanup.remaining.length > 0) {
|
|
7825
|
-
throw new CliError(cleanup.remaining.join(", "), {
|
|
7826
|
-
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
7827
|
-
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
7828
|
-
});
|
|
7829
|
-
}
|
|
7830
|
-
recordServiceStopped();
|
|
7831
|
-
}
|
|
7832
|
-
const deleted = /* @__PURE__ */ new Set();
|
|
7833
|
-
for (const target of targets) {
|
|
7834
|
-
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
7835
|
-
for (const filePath of target.paths()) {
|
|
7836
|
-
if (!fs14.existsSync(filePath)) continue;
|
|
7837
|
-
try {
|
|
7838
|
-
rmrf(filePath);
|
|
7839
|
-
} catch (e) {
|
|
7840
|
-
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
7841
|
-
}
|
|
7842
|
-
hadContent = true;
|
|
7843
|
-
}
|
|
7844
|
-
if (hadContent) deleted.add(target.id);
|
|
7845
|
-
}
|
|
7846
|
-
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
7847
|
-
updateSettings((settings) => {
|
|
7848
|
-
const patch = {};
|
|
7849
|
-
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
7850
|
-
patch.subscriptions = void 0;
|
|
7851
|
-
patch.active_subscription = void 0;
|
|
7852
|
-
deleted.add("subs");
|
|
7853
|
-
}
|
|
7854
|
-
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
7855
|
-
patch.overwrite_enabled = void 0;
|
|
7856
|
-
deleted.add("overwrites");
|
|
7857
|
-
}
|
|
7858
|
-
return patch;
|
|
7859
|
-
});
|
|
7860
|
-
}
|
|
7861
|
-
if (ids.has("kernel")) clearKernelVersionCache();
|
|
7862
|
-
ensureDirs();
|
|
7863
|
-
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
7864
|
-
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
7865
|
-
}
|
|
7866
|
-
|
|
7867
8158
|
// src/commands/service.ts
|
|
7868
8159
|
import fs15 from "fs";
|
|
7869
8160
|
async function handleLegacyInstall() {
|
|
@@ -7884,6 +8175,7 @@ function printRestoreSkipped() {
|
|
|
7884
8175
|
}
|
|
7885
8176
|
async function cmdInstall(args) {
|
|
7886
8177
|
assertKnownFlags(args.slice(1), [], "install");
|
|
8178
|
+
assertPositionalCount(args, 0, 1, "mihomo install");
|
|
7887
8179
|
if (!hasKernel()) {
|
|
7888
8180
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
7889
8181
|
}
|
|
@@ -7924,6 +8216,7 @@ async function cmdInstall(args) {
|
|
|
7924
8216
|
}
|
|
7925
8217
|
async function cmdUninstall(args) {
|
|
7926
8218
|
assertKnownFlags(args.slice(1), [], "uninstall");
|
|
8219
|
+
assertPositionalCount(args, 0, 1, "mihomo uninstall");
|
|
7927
8220
|
const status = getServiceStatus();
|
|
7928
8221
|
const legacy = detectLegacySystemInstall();
|
|
7929
8222
|
const residue = getMihomoPids();
|
|
@@ -7965,6 +8258,7 @@ function handleStopResult(result) {
|
|
|
7965
8258
|
}
|
|
7966
8259
|
async function cmdStop(args) {
|
|
7967
8260
|
assertKnownFlags(args.slice(1), [], "stop");
|
|
8261
|
+
assertPositionalCount(args, 0, 1, "mihomo stop");
|
|
7968
8262
|
if (detectLegacySystemInstall()) {
|
|
7969
8263
|
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"));
|
|
7970
8264
|
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"));
|
|
@@ -8009,6 +8303,7 @@ function copyToClipboard(text) {
|
|
|
8009
8303
|
}
|
|
8010
8304
|
function cmdUI(args) {
|
|
8011
8305
|
assertKnownFlags(args.slice(1), [], "ui");
|
|
8306
|
+
assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd]");
|
|
8012
8307
|
const uiName = args[1] || "zash";
|
|
8013
8308
|
if (!Object.hasOwn(UI_URLS, uiName)) {
|
|
8014
8309
|
throw new CliError(`\u672A\u77E5\u7684 UI "${uiName}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
|
|
@@ -8228,16 +8523,15 @@ process.on("SIGTERM", () => {
|
|
|
8228
8523
|
});
|
|
8229
8524
|
process.on("uncaughtException", (e) => {
|
|
8230
8525
|
console.error(`
|
|
8231
|
-
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${e
|
|
8232
|
-
if (e.stack) {
|
|
8526
|
+
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${errorMessage(e)}`);
|
|
8527
|
+
if (e instanceof Error && e.stack) {
|
|
8233
8528
|
console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8234
8529
|
}
|
|
8235
8530
|
process.exit(1);
|
|
8236
8531
|
});
|
|
8237
8532
|
process.on("unhandledRejection", (reason) => {
|
|
8238
|
-
const msg = reason instanceof Error ? reason.message : String(reason);
|
|
8239
8533
|
console.error(`
|
|
8240
|
-
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${
|
|
8534
|
+
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
|
|
8241
8535
|
process.exit(1);
|
|
8242
8536
|
});
|
|
8243
8537
|
function clearProxyEnv() {
|
|
@@ -8312,19 +8606,23 @@ async function main() {
|
|
|
8312
8606
|
assertSupportedNodeVersion(command.name);
|
|
8313
8607
|
assertSupportedPlatform(command.name);
|
|
8314
8608
|
assertNotRoot(command.name);
|
|
8315
|
-
|
|
8316
|
-
|
|
8609
|
+
if (!GUARD_EXEMPT_COMMANDS.has(command.name)) {
|
|
8610
|
+
ensureDirs();
|
|
8611
|
+
}
|
|
8612
|
+
if (command.group === "meta") {
|
|
8613
|
+
assertKnownFlags(args.slice(1), [], command.name);
|
|
8614
|
+
assertPositionalCount(args, 0, 1, `mihomo ${command.name}`);
|
|
8615
|
+
}
|
|
8317
8616
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8318
8617
|
}
|
|
8319
8618
|
main().catch((e) => {
|
|
8320
8619
|
if (e instanceof CliError) {
|
|
8321
|
-
console.error(`${
|
|
8620
|
+
console.error(`${stderrColors.red(`${e.label}:`)} ${e.message}`);
|
|
8322
8621
|
for (const line of e.hint) console.error(line);
|
|
8323
8622
|
process.exit(e.exitCode);
|
|
8324
8623
|
}
|
|
8325
|
-
|
|
8326
|
-
console.error(
|
|
8327
|
-
if (err.stack) console.error(err.stack.split("\n").slice(1).join("\n"));
|
|
8624
|
+
console.error(`${stderrColors.red("\u9519\u8BEF:")} ${errorMessage(e)}`);
|
|
8625
|
+
if (e instanceof Error && e.stack) console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8328
8626
|
process.exit(1);
|
|
8329
8627
|
});
|
|
8330
8628
|
/*! Bundled license information:
|