mihomo-cli 26.10.111 → 26.10.112
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 +8 -0
- package/dist/index.js +1674 -1770
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1723,32 +1723,24 @@ function collectionTagName(state, event, defaultTagName) {
|
|
|
1723
1723
|
function isMappingTag(tag) {
|
|
1724
1724
|
return tag.nodeKind === "mapping";
|
|
1725
1725
|
}
|
|
1726
|
-
function chargeMergeWork(state) {
|
|
1727
|
-
state.totalMergeKeys++;
|
|
1728
|
-
if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
|
|
1729
|
-
}
|
|
1730
1726
|
function mergeKeys(state, frame, source, sourceTag) {
|
|
1731
|
-
chargeMergeWork(state);
|
|
1732
1727
|
for (const sourceKey of sourceTag.keys(source)) {
|
|
1733
|
-
|
|
1728
|
+
if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
|
|
1734
1729
|
if (frame.tag.has(frame.value, sourceKey)) continue;
|
|
1735
1730
|
const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
|
|
1736
1731
|
if (err) throwError$1(state, err);
|
|
1737
|
-
frame.overridable ??= /* @__PURE__ */ new Set();
|
|
1738
|
-
frame.overridable.add(sourceKey);
|
|
1732
|
+
(frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey);
|
|
1739
1733
|
}
|
|
1740
1734
|
}
|
|
1741
1735
|
function mergeSource(state, frame, source, sourceTag) {
|
|
1742
1736
|
state.position = frame.keyPosition;
|
|
1743
1737
|
if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
|
|
1744
|
-
else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
}
|
|
1751
|
-
} else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
|
|
1738
|
+
else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) {
|
|
1739
|
+
const elementTag = state.nodeTags.get(element);
|
|
1740
|
+
if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
|
|
1741
|
+
mergeKeys(state, frame, element, elementTag);
|
|
1742
|
+
}
|
|
1743
|
+
else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
|
|
1752
1744
|
}
|
|
1753
1745
|
function addMappingValue(state, frame, key, value, tag) {
|
|
1754
1746
|
state.position = frame.keyPosition;
|
|
@@ -2091,24 +2083,6 @@ function testDocumentSeparator(state, position = state.position) {
|
|
|
2091
2083
|
}
|
|
2092
2084
|
return false;
|
|
2093
2085
|
}
|
|
2094
|
-
function skipByteOrderMark(state) {
|
|
2095
|
-
if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
|
|
2096
|
-
state.position++;
|
|
2097
|
-
state.lineStart = state.position;
|
|
2098
|
-
}
|
|
2099
|
-
}
|
|
2100
|
-
function testDocumentBoundary(state) {
|
|
2101
|
-
if (state.position !== state.lineStart) return false;
|
|
2102
|
-
if (testDocumentSeparator(state)) return true;
|
|
2103
|
-
if (state.input.charCodeAt(state.position) !== 65279) return false;
|
|
2104
|
-
const snapshot = snapshotState(state);
|
|
2105
|
-
skipByteOrderMark(state);
|
|
2106
|
-
skipSeparationSpace(state, true);
|
|
2107
|
-
const ch = state.input.charCodeAt(state.position);
|
|
2108
|
-
const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
|
|
2109
|
-
restoreState(state, snapshot);
|
|
2110
|
-
return result;
|
|
2111
|
-
}
|
|
2112
2086
|
function skipUntilLineEnd(state) {
|
|
2113
2087
|
let ch = state.input.charCodeAt(state.position);
|
|
2114
2088
|
while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
|
|
@@ -2292,14 +2266,14 @@ function readBlockScalar(state, parentIndent, props) {
|
|
|
2292
2266
|
} else if (column > 0) valueEnd = linePosition + column;
|
|
2293
2267
|
break;
|
|
2294
2268
|
}
|
|
2295
|
-
if (
|
|
2269
|
+
if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break;
|
|
2296
2270
|
if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
|
|
2297
2271
|
if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
|
|
2298
2272
|
if (first === 9 && column < parentIndent) {
|
|
2299
2273
|
state.position = linePosition + column;
|
|
2300
2274
|
throwError(state, "tab characters must not be used in indentation");
|
|
2301
2275
|
}
|
|
2302
|
-
if (column
|
|
2276
|
+
if (column < maxLeadingIndent) {
|
|
2303
2277
|
state.position = linePosition + column;
|
|
2304
2278
|
throwError(state, "bad indentation of a mapping entry");
|
|
2305
2279
|
}
|
|
@@ -2345,7 +2319,7 @@ function readPlainScalar(state, nodeIndent, nodeContext, props) {
|
|
|
2345
2319
|
const inFlow = nodeContext === CONTEXT_FLOW_IN;
|
|
2346
2320
|
let multiline = false;
|
|
2347
2321
|
while (ch !== 0) {
|
|
2348
|
-
if (
|
|
2322
|
+
if (state.position === state.lineStart && testDocumentSeparator(state)) break;
|
|
2349
2323
|
if (ch === 58) {
|
|
2350
2324
|
const following = state.input.charCodeAt(state.position + 1);
|
|
2351
2325
|
if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
|
|
@@ -2509,16 +2483,13 @@ function readBlockMapping(state, nodeIndent, flowIndent, props) {
|
|
|
2509
2483
|
ch = state.input.charCodeAt(++state.position);
|
|
2510
2484
|
if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
|
|
2511
2485
|
if (!mappingOpened) {
|
|
2512
|
-
state
|
|
2513
|
-
|
|
2514
|
-
start: beforeKey.position,
|
|
2515
|
-
anchorStart: props.anchorStart,
|
|
2516
|
-
anchorEnd: props.anchorEnd,
|
|
2517
|
-
tagStart: props.tagStart,
|
|
2518
|
-
tagEnd: props.tagEnd,
|
|
2519
|
-
style: COLLECTION_STYLE.BLOCK
|
|
2520
|
-
});
|
|
2486
|
+
restoreState(state, beforeKey);
|
|
2487
|
+
addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
|
|
2521
2488
|
mappingOpened = true;
|
|
2489
|
+
parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
|
|
2490
|
+
ch = state.input.charCodeAt(state.position);
|
|
2491
|
+
while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
|
|
2492
|
+
state.position++;
|
|
2522
2493
|
}
|
|
2523
2494
|
detected = true;
|
|
2524
2495
|
atExplicitKey = false;
|
|
@@ -2705,7 +2676,7 @@ function readDocument(state) {
|
|
|
2705
2676
|
const documentEvent = state.events[documentEventIndex];
|
|
2706
2677
|
if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
|
|
2707
2678
|
addPopEvent(state);
|
|
2708
|
-
if (!explicitEnd && state.position < state.length && !
|
|
2679
|
+
if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected");
|
|
2709
2680
|
}
|
|
2710
2681
|
function parseEvents(input, options) {
|
|
2711
2682
|
const length = input.length;
|
|
@@ -2726,8 +2697,8 @@ function parseEvents(input, options) {
|
|
|
2726
2697
|
};
|
|
2727
2698
|
const nullpos = input.indexOf("\0");
|
|
2728
2699
|
if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
|
|
2700
|
+
if (state.input.charCodeAt(state.position) === 65279) state.position++;
|
|
2729
2701
|
while (state.position < state.length) {
|
|
2730
|
-
skipByteOrderMark(state);
|
|
2731
2702
|
skipSeparationSpace(state, true);
|
|
2732
2703
|
if (state.position >= state.length) break;
|
|
2733
2704
|
const documentStart = state.position;
|
|
@@ -2760,6 +2731,15 @@ function load(input, options) {
|
|
|
2760
2731
|
if (documents.length === 1) return documents[0];
|
|
2761
2732
|
throw new YAMLException("expected a single document in the stream, but found more");
|
|
2762
2733
|
}
|
|
2734
|
+
var Style = class {
|
|
2735
|
+
/** Whether to print the node's tag explicitly. */
|
|
2736
|
+
tagged = false;
|
|
2737
|
+
flow = false;
|
|
2738
|
+
singleQuoted = false;
|
|
2739
|
+
doubleQuoted = false;
|
|
2740
|
+
literal = false;
|
|
2741
|
+
folded = false;
|
|
2742
|
+
};
|
|
2763
2743
|
var INVALID = /* @__PURE__ */ Symbol("INVALID");
|
|
2764
2744
|
function buildRepresentTypes(schema) {
|
|
2765
2745
|
const defaultTags = new Set([
|
|
@@ -2808,6 +2788,8 @@ function build(state, object) {
|
|
|
2808
2788
|
if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
|
|
2809
2789
|
return {
|
|
2810
2790
|
kind: "alias",
|
|
2791
|
+
tag: "",
|
|
2792
|
+
style: new Style(),
|
|
2811
2793
|
anchor: existing.anchor
|
|
2812
2794
|
};
|
|
2813
2795
|
}
|
|
@@ -2820,20 +2802,24 @@ function build(state, object) {
|
|
|
2820
2802
|
}
|
|
2821
2803
|
const { tag, tagName, implicitTag } = matched;
|
|
2822
2804
|
const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
|
|
2823
|
-
if (tag.nodeKind === "scalar")
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2805
|
+
if (tag.nodeKind === "scalar") {
|
|
2806
|
+
const style2 = new Style();
|
|
2807
|
+
style2.tagged = !implicitTag;
|
|
2808
|
+
return {
|
|
2809
|
+
kind: "scalar",
|
|
2810
|
+
tag: nodeTagName,
|
|
2811
|
+
style: style2,
|
|
2812
|
+
value: tag.represent(object)
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2830
2815
|
if (tag.nodeKind === "sequence") {
|
|
2831
2816
|
const container = tag.represent(object);
|
|
2817
|
+
const style2 = new Style();
|
|
2818
|
+
style2.tagged = !implicitTag;
|
|
2832
2819
|
const node2 = {
|
|
2833
2820
|
kind: "sequence",
|
|
2834
2821
|
tag: nodeTagName,
|
|
2835
|
-
|
|
2836
|
-
style: COLLECTION_STYLE.BLOCK,
|
|
2822
|
+
style: style2,
|
|
2837
2823
|
items: []
|
|
2838
2824
|
};
|
|
2839
2825
|
if (!state.noRefs) state.refs.set(object, node2);
|
|
@@ -2846,11 +2832,12 @@ function build(state, object) {
|
|
|
2846
2832
|
return node2;
|
|
2847
2833
|
}
|
|
2848
2834
|
const map = tag.represent(object);
|
|
2835
|
+
const style = new Style();
|
|
2836
|
+
style.tagged = !implicitTag;
|
|
2849
2837
|
const node = {
|
|
2850
2838
|
kind: "mapping",
|
|
2851
2839
|
tag: nodeTagName,
|
|
2852
|
-
|
|
2853
|
-
style: COLLECTION_STYLE.BLOCK,
|
|
2840
|
+
style,
|
|
2854
2841
|
items: []
|
|
2855
2842
|
};
|
|
2856
2843
|
if (!state.noRefs) state.refs.set(object, node);
|
|
@@ -2918,204 +2905,82 @@ function visit(documents, visitor) {
|
|
|
2918
2905
|
isKey: false
|
|
2919
2906
|
})) return;
|
|
2920
2907
|
}
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
var
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2908
|
+
var CHAR_BOM = 65279;
|
|
2909
|
+
var CHAR_TAB = 9;
|
|
2910
|
+
var CHAR_LINE_FEED = 10;
|
|
2911
|
+
var CHAR_CARRIAGE_RETURN = 13;
|
|
2912
|
+
var CHAR_SPACE = 32;
|
|
2913
|
+
var CHAR_EXCLAMATION = 33;
|
|
2914
|
+
var CHAR_DOUBLE_QUOTE = 34;
|
|
2915
|
+
var CHAR_SHARP = 35;
|
|
2916
|
+
var CHAR_PERCENT = 37;
|
|
2917
|
+
var CHAR_AMPERSAND = 38;
|
|
2918
|
+
var CHAR_SINGLE_QUOTE = 39;
|
|
2919
|
+
var CHAR_ASTERISK = 42;
|
|
2920
|
+
var CHAR_COMMA = 44;
|
|
2921
|
+
var CHAR_MINUS = 45;
|
|
2922
|
+
var CHAR_COLON = 58;
|
|
2923
|
+
var CHAR_EQUALS = 61;
|
|
2924
|
+
var CHAR_GREATER_THAN = 62;
|
|
2925
|
+
var CHAR_QUESTION = 63;
|
|
2926
|
+
var CHAR_COMMERCIAL_AT = 64;
|
|
2927
|
+
var CHAR_LEFT_SQUARE_BRACKET = 91;
|
|
2928
|
+
var CHAR_RIGHT_SQUARE_BRACKET = 93;
|
|
2929
|
+
var CHAR_GRAVE_ACCENT = 96;
|
|
2930
|
+
var CHAR_LEFT_CURLY_BRACKET = 123;
|
|
2931
|
+
var CHAR_VERTICAL_LINE = 124;
|
|
2932
|
+
var CHAR_RIGHT_CURLY_BRACKET = 125;
|
|
2933
|
+
var ESCAPE_SEQUENCES = {};
|
|
2934
|
+
ESCAPE_SEQUENCES[0] = "\\0";
|
|
2935
|
+
ESCAPE_SEQUENCES[7] = "\\a";
|
|
2936
|
+
ESCAPE_SEQUENCES[8] = "\\b";
|
|
2937
|
+
ESCAPE_SEQUENCES[9] = "\\t";
|
|
2938
|
+
ESCAPE_SEQUENCES[10] = "\\n";
|
|
2939
|
+
ESCAPE_SEQUENCES[11] = "\\v";
|
|
2940
|
+
ESCAPE_SEQUENCES[12] = "\\f";
|
|
2941
|
+
ESCAPE_SEQUENCES[13] = "\\r";
|
|
2942
|
+
ESCAPE_SEQUENCES[27] = "\\e";
|
|
2943
|
+
ESCAPE_SEQUENCES[34] = '\\"';
|
|
2944
|
+
ESCAPE_SEQUENCES[92] = "\\\\";
|
|
2945
|
+
ESCAPE_SEQUENCES[133] = "\\N";
|
|
2946
|
+
ESCAPE_SEQUENCES[160] = "\\_";
|
|
2947
|
+
ESCAPE_SEQUENCES[8232] = "\\L";
|
|
2948
|
+
ESCAPE_SEQUENCES[8233] = "\\P";
|
|
2949
|
+
var DEFAULT_PRESENTER_OPTIONS = {
|
|
2950
|
+
indent: 2,
|
|
2951
|
+
seqNoIndent: false,
|
|
2952
|
+
seqInlineFirst: true,
|
|
2953
|
+
sortKeys: false,
|
|
2954
|
+
lineWidth: 80,
|
|
2955
|
+
flowBracketPadding: false,
|
|
2956
|
+
flowSkipCommaSpace: false,
|
|
2957
|
+
flowSkipColonSpace: false,
|
|
2958
|
+
quoteFlowKeys: false,
|
|
2959
|
+
quoteStyle: "single",
|
|
2960
|
+
forceQuotes: false,
|
|
2961
|
+
tagBeforeAnchor: false
|
|
2932
2962
|
};
|
|
2933
|
-
function
|
|
2934
|
-
|
|
2935
|
-
return SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2936
|
-
}
|
|
2937
|
-
function applyQuoteFlowKeysOption(layout) {
|
|
2938
|
-
if (!layout.presenterOptions.quoteFlowKeys) return;
|
|
2939
|
-
if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
|
|
2940
|
-
layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2941
|
-
}
|
|
2942
|
-
function doubleQuoteForInvisibles(layout) {
|
|
2943
|
-
if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2944
|
-
}
|
|
2945
|
-
function doubleQuoteWhitespaceOnly(layout) {
|
|
2946
|
-
if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2947
|
-
}
|
|
2948
|
-
function applyForceQuotesOption(layout) {
|
|
2949
|
-
if (!layout.presenterOptions.forceQuotes) return;
|
|
2950
|
-
if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
|
|
2951
|
-
if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
|
|
2952
|
-
layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
|
|
2953
|
-
}
|
|
2954
|
-
function tryLongOrMultilineAsBlock(layout) {
|
|
2955
|
-
if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
|
|
2956
|
-
const value = layout.node.value;
|
|
2957
|
-
const multiline = value.indexOf("\n") !== -1;
|
|
2958
|
-
if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
|
|
2959
|
-
if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2960
|
-
return;
|
|
2961
|
-
}
|
|
2962
|
-
const w = layout.presenterOptions.lineWidth;
|
|
2963
|
-
if (w === -1) {
|
|
2964
|
-
if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
|
|
2965
|
-
return;
|
|
2966
|
-
}
|
|
2967
|
-
const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
|
|
2968
|
-
let position = 0;
|
|
2969
|
-
let shouldFold = false;
|
|
2970
|
-
while (position <= value.length) {
|
|
2971
|
-
let lineEnd = value.length;
|
|
2972
|
-
const nextLineBreak = value.indexOf("\n", position);
|
|
2973
|
-
if (nextLineBreak !== -1) lineEnd = nextLineBreak;
|
|
2974
|
-
const line = value.slice(position, lineEnd);
|
|
2975
|
-
if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
|
|
2976
|
-
if (nextLineBreak === -1) break;
|
|
2977
|
-
position = nextLineBreak + 1;
|
|
2978
|
-
}
|
|
2979
|
-
if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
|
|
2980
|
-
else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
|
|
2981
|
-
}
|
|
2982
|
-
function quoteInvalidPlain(layout) {
|
|
2983
|
-
if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
|
|
2984
|
-
}
|
|
2985
|
-
function fallbackToDoubleQuoted(layout) {
|
|
2986
|
-
if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
|
|
2987
|
-
}
|
|
2988
|
-
function setBit(mask, bit) {
|
|
2989
|
-
return mask | 1 << bit;
|
|
2990
|
-
}
|
|
2991
|
-
var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
|
|
2992
|
-
var SRC_B_CHAR = "[\\n\\r]";
|
|
2993
|
-
var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
|
|
2994
|
-
var SRC_S_WHITE = "[ \\t]";
|
|
2995
|
-
var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
|
|
2996
|
-
var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
|
|
2997
|
-
var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
|
|
2998
|
-
var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
|
|
2999
|
-
var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
|
|
3000
|
-
var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
|
|
3001
|
-
var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
|
|
3002
|
-
var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
|
|
3003
|
-
var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
|
|
3004
|
-
var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
|
|
3005
|
-
var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
|
|
3006
|
-
var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
|
|
3007
|
-
var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
|
|
3008
|
-
var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
|
|
3009
|
-
var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
|
|
3010
|
-
var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
|
|
3011
|
-
var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
|
|
3012
|
-
var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
|
|
3013
|
-
var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
|
|
3014
|
-
var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
|
|
3015
|
-
var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
|
|
3016
|
-
var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
|
|
3017
|
-
var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
|
|
3018
|
-
var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
|
|
3019
|
-
var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
|
|
3020
|
-
var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
|
|
3021
|
-
var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
|
|
3022
|
-
var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
|
|
3023
|
-
var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
|
|
3024
|
-
var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
|
|
3025
|
-
function canUsePlain(layout) {
|
|
3026
|
-
const str = layout.node.value;
|
|
3027
|
-
if (str !== "") {
|
|
3028
|
-
if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false;
|
|
3029
|
-
if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
|
|
3030
|
-
if (layout.shiftOfContent === 0) {
|
|
3031
|
-
const firstLineBreak = str.indexOf("\n");
|
|
3032
|
-
if (firstLineBreak !== -1) {
|
|
3033
|
-
const content = str.slice(firstLineBreak + 1);
|
|
3034
|
-
if (C_FORBIDDEN_CONTENT.test(content)) return false;
|
|
3035
|
-
}
|
|
3036
|
-
}
|
|
3037
|
-
}
|
|
3038
|
-
const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
|
|
3039
|
-
if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
|
|
3040
|
-
if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
|
|
3041
|
-
return true;
|
|
3042
|
-
}
|
|
3043
|
-
function canUseSingleQuoted(layout) {
|
|
3044
|
-
const str = layout.node.value;
|
|
3045
|
-
if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
|
|
3046
|
-
if (/[ \t]\n|\n[ \t]/.test(str)) return false;
|
|
3047
|
-
if (!layout.isKey && layout.shiftOfContent === 0) {
|
|
3048
|
-
const firstLineBreak = str.indexOf("\n");
|
|
3049
|
-
if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
|
|
3050
|
-
}
|
|
3051
|
-
return true;
|
|
3052
|
-
}
|
|
3053
|
-
function canUseBlock(layout) {
|
|
3054
|
-
if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
|
|
3055
|
-
const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
|
|
3056
|
-
if (contentIndent < 1) return false;
|
|
3057
|
-
if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
|
|
3058
|
-
if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
|
|
3059
|
-
return true;
|
|
3060
|
-
}
|
|
3061
|
-
function detectAllowedStyles(layout) {
|
|
3062
|
-
let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
|
|
3063
|
-
if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
|
|
3064
|
-
if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
|
|
3065
|
-
if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
|
|
3066
|
-
layout.allowedStylesMask = mask;
|
|
3067
|
-
}
|
|
3068
|
-
function renderScalar(layout) {
|
|
3069
|
-
switch (layout.style) {
|
|
3070
|
-
case SCALAR_STYLE.PLAIN:
|
|
3071
|
-
return renderPlain(layout);
|
|
3072
|
-
case SCALAR_STYLE.SINGLE_QUOTED:
|
|
3073
|
-
return renderSingleQuoted(layout);
|
|
3074
|
-
case SCALAR_STYLE.LITERAL_BLOCK:
|
|
3075
|
-
return renderLiteralBlock(layout);
|
|
3076
|
-
case SCALAR_STYLE.FOLDED_BLOCK:
|
|
3077
|
-
return renderFoldedBlock(layout);
|
|
3078
|
-
case SCALAR_STYLE.DOUBLE_QUOTED:
|
|
3079
|
-
return renderDoubleQuoted(layout);
|
|
3080
|
-
}
|
|
3081
|
-
}
|
|
3082
|
-
function renderPlain(layout) {
|
|
3083
|
-
return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
|
|
3084
|
-
}
|
|
3085
|
-
function renderSingleQuoted(layout) {
|
|
3086
|
-
return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
|
|
3087
|
-
}
|
|
3088
|
-
function renderLiteralBlock(layout) {
|
|
3089
|
-
const value = layout.node.value;
|
|
3090
|
-
return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
|
|
3091
|
-
}
|
|
3092
|
-
function renderFoldedBlock(layout) {
|
|
3093
|
-
const value = layout.node.value;
|
|
3094
|
-
const w = layout.presenterOptions.lineWidth;
|
|
3095
|
-
let availableWidth = Infinity;
|
|
3096
|
-
if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
|
|
3097
|
-
return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
|
|
2963
|
+
function nodeTagShort(node) {
|
|
2964
|
+
return node.style.tagged ? node.tag : tagNameShort(node.tag);
|
|
3098
2965
|
}
|
|
3099
|
-
function
|
|
3100
|
-
|
|
2966
|
+
function createPresenterState(options) {
|
|
2967
|
+
const opts = {
|
|
2968
|
+
...DEFAULT_PRESENTER_OPTIONS,
|
|
2969
|
+
...options
|
|
2970
|
+
};
|
|
2971
|
+
return {
|
|
2972
|
+
...opts,
|
|
2973
|
+
defaultScalarTagName: opts.schema.defaultScalarTag.tagName
|
|
2974
|
+
};
|
|
3101
2975
|
}
|
|
3102
|
-
function
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
const
|
|
3106
|
-
|
|
3107
|
-
const lineRe = /(\n+)([^\n]*)/g;
|
|
3108
|
-
lineRe.lastIndex = nextLF;
|
|
3109
|
-
let match;
|
|
3110
|
-
while (match = lineRe.exec(string)) {
|
|
3111
|
-
const breaks = match[1].length;
|
|
3112
|
-
const line = match[2];
|
|
3113
|
-
result += "\n".repeat(breaks + 1) + pad + line;
|
|
3114
|
-
}
|
|
3115
|
-
return result;
|
|
2976
|
+
function encodeNonPrintable(character) {
|
|
2977
|
+
const string = character.toString(16).toUpperCase();
|
|
2978
|
+
const handle = character <= 255 ? "x" : "u";
|
|
2979
|
+
const length = character <= 255 ? 2 : 4;
|
|
2980
|
+
return `\\${handle}${"0".repeat(length - string.length)}${string}`;
|
|
3116
2981
|
}
|
|
3117
2982
|
function indentString(string, spaces) {
|
|
3118
|
-
const
|
|
2983
|
+
const ind = " ".repeat(spaces);
|
|
3119
2984
|
let position = 0;
|
|
3120
2985
|
let result = "";
|
|
3121
2986
|
const length = string.length;
|
|
@@ -3129,26 +2994,191 @@ function indentString(string, spaces) {
|
|
|
3129
2994
|
line = string.slice(position, next + 1);
|
|
3130
2995
|
position = next + 1;
|
|
3131
2996
|
}
|
|
3132
|
-
if (line.length && line !== "\n") result +=
|
|
2997
|
+
if (line.length && line !== "\n") result += ind;
|
|
3133
2998
|
result += line;
|
|
3134
2999
|
}
|
|
3135
3000
|
return result;
|
|
3136
3001
|
}
|
|
3002
|
+
function generateNextLine(state, level) {
|
|
3003
|
+
return `
|
|
3004
|
+
${" ".repeat(state.indent * level)}`;
|
|
3005
|
+
}
|
|
3006
|
+
function scalarLayout(state, level) {
|
|
3007
|
+
const indent = state.indent * Math.max(1, level);
|
|
3008
|
+
return {
|
|
3009
|
+
indent,
|
|
3010
|
+
blockIndent: level === 0 ? state.indent + 1 : state.indent,
|
|
3011
|
+
lineWidth: state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)
|
|
3012
|
+
};
|
|
3013
|
+
}
|
|
3014
|
+
function isWhitespace(c) {
|
|
3015
|
+
return c === CHAR_SPACE || c === CHAR_TAB;
|
|
3016
|
+
}
|
|
3017
|
+
function startsWithDocumentSeparator(string) {
|
|
3018
|
+
const marker = string.charCodeAt(0);
|
|
3019
|
+
if (marker !== CHAR_MINUS && marker !== 46 || string.charCodeAt(1) !== marker || string.charCodeAt(2) !== marker) return false;
|
|
3020
|
+
if (string.length === 3) return true;
|
|
3021
|
+
const following = string.charCodeAt(3);
|
|
3022
|
+
return isWhitespace(following) || following === CHAR_CARRIAGE_RETURN || following === CHAR_LINE_FEED;
|
|
3023
|
+
}
|
|
3024
|
+
function isPrintable(c) {
|
|
3025
|
+
return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
|
|
3026
|
+
}
|
|
3027
|
+
function isNsCharOrWhitespace(c) {
|
|
3028
|
+
return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
|
|
3029
|
+
}
|
|
3030
|
+
function isPlainSafe(c, prev, inblock) {
|
|
3031
|
+
const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
|
|
3032
|
+
const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
|
|
3033
|
+
return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar && (inblock || c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET);
|
|
3034
|
+
}
|
|
3035
|
+
function isPlainSafeFirst(c) {
|
|
3036
|
+
return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
|
|
3037
|
+
}
|
|
3038
|
+
function isPlainSafeAtStart(string, inblock) {
|
|
3039
|
+
const first = codePointAt(string, 0);
|
|
3040
|
+
if (isPlainSafeFirst(first)) return true;
|
|
3041
|
+
if (string.length > 1 && (first === CHAR_MINUS || first === CHAR_QUESTION || first === CHAR_COLON)) {
|
|
3042
|
+
const second = codePointAt(string, 1);
|
|
3043
|
+
return !isWhitespace(second) && isPlainSafe(second, first, inblock);
|
|
3044
|
+
}
|
|
3045
|
+
return false;
|
|
3046
|
+
}
|
|
3047
|
+
function isPlainSafeLast(c) {
|
|
3048
|
+
return !isWhitespace(c) && c !== CHAR_COLON;
|
|
3049
|
+
}
|
|
3050
|
+
function codePointAt(string, pos) {
|
|
3051
|
+
const first = string.charCodeAt(pos);
|
|
3052
|
+
let second;
|
|
3053
|
+
if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
|
|
3054
|
+
second = string.charCodeAt(pos + 1);
|
|
3055
|
+
if (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536;
|
|
3056
|
+
}
|
|
3057
|
+
return first;
|
|
3058
|
+
}
|
|
3137
3059
|
function needIndentIndicator(string) {
|
|
3138
3060
|
return /^\n* /.test(string);
|
|
3139
3061
|
}
|
|
3140
|
-
|
|
3141
|
-
|
|
3062
|
+
var STYLE_PLAIN = 1;
|
|
3063
|
+
var STYLE_SINGLE = 2;
|
|
3064
|
+
var STYLE_LITERAL = 3;
|
|
3065
|
+
var STYLE_FOLDED = 4;
|
|
3066
|
+
var STYLE_DOUBLE = 5;
|
|
3067
|
+
function chooseScalarStyle(state, string, layout, singleLineOnly, forceQuote, inblock) {
|
|
3068
|
+
const { blockIndent, lineWidth } = layout;
|
|
3069
|
+
let i;
|
|
3070
|
+
let char = 0;
|
|
3071
|
+
let prevChar = -1;
|
|
3072
|
+
let hasLineBreak = false;
|
|
3073
|
+
let hasFoldableLine = false;
|
|
3074
|
+
const shouldTrackWidth = lineWidth !== -1;
|
|
3075
|
+
let previousLineBreak = -1;
|
|
3076
|
+
let plain = !startsWithDocumentSeparator(string) && isPlainSafeAtStart(string, inblock) && isPlainSafeLast(codePointAt(string, string.length - 1));
|
|
3077
|
+
if (singleLineOnly || forceQuote) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
|
|
3078
|
+
char = codePointAt(string, i);
|
|
3079
|
+
if (!isPrintable(char)) return STYLE_DOUBLE;
|
|
3080
|
+
plain = plain && isPlainSafe(char, prevChar, inblock);
|
|
3081
|
+
prevChar = char;
|
|
3082
|
+
}
|
|
3083
|
+
else {
|
|
3084
|
+
for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
|
|
3085
|
+
char = codePointAt(string, i);
|
|
3086
|
+
if (char === CHAR_LINE_FEED) {
|
|
3087
|
+
hasLineBreak = true;
|
|
3088
|
+
if (shouldTrackWidth) {
|
|
3089
|
+
hasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
|
|
3090
|
+
previousLineBreak = i;
|
|
3091
|
+
}
|
|
3092
|
+
} else if (!isPrintable(char)) return STYLE_DOUBLE;
|
|
3093
|
+
plain = plain && isPlainSafe(char, prevChar, inblock);
|
|
3094
|
+
prevChar = char;
|
|
3095
|
+
}
|
|
3096
|
+
hasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && !isMoreIndented(string[previousLineBreak + 1]);
|
|
3097
|
+
}
|
|
3098
|
+
if (!hasLineBreak && !hasFoldableLine) {
|
|
3099
|
+
if (plain && !forceQuote) return STYLE_PLAIN;
|
|
3100
|
+
return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
|
|
3101
|
+
}
|
|
3102
|
+
if (blockIndent > 9 && needIndentIndicator(string)) return STYLE_DOUBLE;
|
|
3103
|
+
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
|
|
3104
|
+
}
|
|
3105
|
+
function renderScalarStyle(string, style, layout) {
|
|
3106
|
+
const { indent, blockIndent, lineWidth } = layout;
|
|
3107
|
+
switch (style) {
|
|
3108
|
+
case STYLE_PLAIN:
|
|
3109
|
+
return encodeFlowBreaks(string, indent);
|
|
3110
|
+
case STYLE_SINGLE:
|
|
3111
|
+
return `'${encodeFlowBreaks(string, indent).replace(/'/g, "''")}'`;
|
|
3112
|
+
case STYLE_LITERAL:
|
|
3113
|
+
return "|" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(string, indent));
|
|
3114
|
+
case STYLE_FOLDED:
|
|
3115
|
+
return ">" + blockHeader(string, blockIndent) + dropEndingNewline(indentString(foldBlockScalar(string, lineWidth), indent));
|
|
3116
|
+
case STYLE_DOUBLE:
|
|
3117
|
+
return `"${escapeString(string)}"`;
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
function resolveScalarStyle(state, node, layout, iskey, inblock) {
|
|
3121
|
+
const singleLineOnly = iskey || !inblock;
|
|
3122
|
+
if (node.style.singleQuoted) return STYLE_SINGLE;
|
|
3123
|
+
if (node.style.doubleQuoted) return STYLE_DOUBLE;
|
|
3124
|
+
if (!singleLineOnly) {
|
|
3125
|
+
if (node.style.literal) return STYLE_LITERAL;
|
|
3126
|
+
if (node.style.folded) return STYLE_FOLDED;
|
|
3127
|
+
}
|
|
3128
|
+
const string = node.value;
|
|
3129
|
+
if (string.length === 0) {
|
|
3130
|
+
if (node.style.tagged || state.schema.resolveImplicitScalarTag(string).tag.tagName === node.tag) return STYLE_PLAIN;
|
|
3131
|
+
return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
|
|
3132
|
+
}
|
|
3133
|
+
const style = chooseScalarStyle(state, string, layout, singleLineOnly, state.forceQuotes && !iskey, inblock);
|
|
3134
|
+
if (style === STYLE_PLAIN && !node.style.tagged && state.schema.resolveImplicitScalarTag(string).tag.tagName !== node.tag) return state.quoteStyle === "double" ? STYLE_DOUBLE : STYLE_SINGLE;
|
|
3135
|
+
return style;
|
|
3136
|
+
}
|
|
3137
|
+
function blockHeader(string, indentPerLevel) {
|
|
3138
|
+
const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
|
|
3142
3139
|
const clip = string[string.length - 1] === "\n";
|
|
3143
3140
|
return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
|
|
3144
3141
|
`;
|
|
3145
3142
|
}
|
|
3143
|
+
function encodeFlowBreaks(string, indent) {
|
|
3144
|
+
let nextLF = string.indexOf("\n");
|
|
3145
|
+
if (nextLF === -1) return string;
|
|
3146
|
+
const pad = " ".repeat(indent);
|
|
3147
|
+
let result = string.slice(0, nextLF);
|
|
3148
|
+
const lineRe = /(\n+)([^\n]*)/g;
|
|
3149
|
+
lineRe.lastIndex = nextLF;
|
|
3150
|
+
let match;
|
|
3151
|
+
while (match = lineRe.exec(string)) {
|
|
3152
|
+
const breaks = match[1].length;
|
|
3153
|
+
const line = match[2];
|
|
3154
|
+
result += "\n".repeat(breaks + 1) + pad + line;
|
|
3155
|
+
}
|
|
3156
|
+
return result;
|
|
3157
|
+
}
|
|
3146
3158
|
function dropEndingNewline(string) {
|
|
3147
3159
|
return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
|
|
3148
3160
|
}
|
|
3149
3161
|
function isMoreIndented(char) {
|
|
3150
3162
|
return char === " " || char === " ";
|
|
3151
3163
|
}
|
|
3164
|
+
function foldBlockScalar(string, width) {
|
|
3165
|
+
const lineRe = /(\n+)([^\n]*)/g;
|
|
3166
|
+
let nextLF = string.indexOf("\n");
|
|
3167
|
+
if (nextLF === -1) nextLF = string.length;
|
|
3168
|
+
lineRe.lastIndex = nextLF;
|
|
3169
|
+
let result = foldLine(string.slice(0, nextLF), width);
|
|
3170
|
+
let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
|
|
3171
|
+
let moreIndented;
|
|
3172
|
+
let match;
|
|
3173
|
+
while (match = lineRe.exec(string)) {
|
|
3174
|
+
const prefix = match[1];
|
|
3175
|
+
const line = match[2];
|
|
3176
|
+
moreIndented = line !== "" && isMoreIndented(line[0]);
|
|
3177
|
+
result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
|
|
3178
|
+
prevMoreIndented = moreIndented;
|
|
3179
|
+
}
|
|
3180
|
+
return result;
|
|
3181
|
+
}
|
|
3152
3182
|
function foldLine(line, width) {
|
|
3153
3183
|
if (line === "" || isMoreIndented(line[0])) return line;
|
|
3154
3184
|
const breakRe = / [^ \t]/g;
|
|
@@ -3174,133 +3204,43 @@ ${line.slice(curr + 1)}`;
|
|
|
3174
3204
|
else result += line.slice(start);
|
|
3175
3205
|
return result.slice(1);
|
|
3176
3206
|
}
|
|
3177
|
-
function
|
|
3178
|
-
|
|
3179
|
-
let
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3207
|
+
function escapeString(string) {
|
|
3208
|
+
let result = "";
|
|
3209
|
+
let char = 0;
|
|
3210
|
+
for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
|
|
3211
|
+
char = codePointAt(string, i);
|
|
3212
|
+
const escapeSeq = ESCAPE_SEQUENCES[char];
|
|
3213
|
+
if (escapeSeq) {
|
|
3214
|
+
result += escapeSeq;
|
|
3215
|
+
continue;
|
|
3216
|
+
}
|
|
3217
|
+
if (isPrintable(char)) {
|
|
3218
|
+
result += string[i];
|
|
3219
|
+
if (char >= 65536) result += string[i + 1];
|
|
3220
|
+
continue;
|
|
3221
|
+
}
|
|
3222
|
+
result += encodeNonPrintable(char);
|
|
3192
3223
|
}
|
|
3193
3224
|
return result;
|
|
3194
3225
|
}
|
|
3195
|
-
var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
|
|
3196
|
-
function escapeCharacter(character) {
|
|
3197
|
-
switch (character) {
|
|
3198
|
-
case "\0":
|
|
3199
|
-
return "\\0";
|
|
3200
|
-
case "\x07":
|
|
3201
|
-
return "\\a";
|
|
3202
|
-
case "\b":
|
|
3203
|
-
return "\\b";
|
|
3204
|
-
case " ":
|
|
3205
|
-
return "\\t";
|
|
3206
|
-
case "\n":
|
|
3207
|
-
return "\\n";
|
|
3208
|
-
case "\v":
|
|
3209
|
-
return "\\v";
|
|
3210
|
-
case "\f":
|
|
3211
|
-
return "\\f";
|
|
3212
|
-
case "\r":
|
|
3213
|
-
return "\\r";
|
|
3214
|
-
case "\x1B":
|
|
3215
|
-
return "\\e";
|
|
3216
|
-
case '"':
|
|
3217
|
-
return '\\"';
|
|
3218
|
-
case "\\":
|
|
3219
|
-
return "\\\\";
|
|
3220
|
-
case "\x85":
|
|
3221
|
-
return "\\N";
|
|
3222
|
-
case "\xA0":
|
|
3223
|
-
return "\\_";
|
|
3224
|
-
case "\u2028":
|
|
3225
|
-
return "\\L";
|
|
3226
|
-
case "\u2029":
|
|
3227
|
-
return "\\P";
|
|
3228
|
-
}
|
|
3229
|
-
const code = character.charCodeAt(0);
|
|
3230
|
-
const hex = code.toString(16).toUpperCase();
|
|
3231
|
-
if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
|
|
3232
|
-
return `\\u${"0".repeat(4 - hex.length)}${hex}`;
|
|
3233
|
-
}
|
|
3234
|
-
function escapeString(string) {
|
|
3235
|
-
return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
|
|
3236
|
-
}
|
|
3237
|
-
var CHAR_LINE_FEED = 10;
|
|
3238
|
-
var DEFAULT_PRESENTER_OPTIONS = {
|
|
3239
|
-
indent: 2,
|
|
3240
|
-
seqNoIndent: false,
|
|
3241
|
-
seqInlineFirst: true,
|
|
3242
|
-
lineWidth: 80,
|
|
3243
|
-
flowBracketPadding: false,
|
|
3244
|
-
flowSkipCommaSpace: false,
|
|
3245
|
-
flowSkipColonSpace: false,
|
|
3246
|
-
quoteFlowKeys: false,
|
|
3247
|
-
quoteStyle: "single",
|
|
3248
|
-
forceQuotes: false,
|
|
3249
|
-
scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
|
|
3250
|
-
tagBeforeAnchor: false
|
|
3251
|
-
};
|
|
3252
|
-
function nodeTagShort(node) {
|
|
3253
|
-
return node.tagged ? node.tag : tagNameShort(node.tag);
|
|
3254
|
-
}
|
|
3255
|
-
function createPresenterState(options) {
|
|
3256
|
-
const opts = {
|
|
3257
|
-
...DEFAULT_PRESENTER_OPTIONS,
|
|
3258
|
-
...options
|
|
3259
|
-
};
|
|
3260
|
-
if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
|
|
3261
|
-
return {
|
|
3262
|
-
...opts,
|
|
3263
|
-
defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
|
|
3264
|
-
openEnded: false
|
|
3265
|
-
};
|
|
3266
|
-
}
|
|
3267
|
-
function generateNextLine(state, level) {
|
|
3268
|
-
return `
|
|
3269
|
-
${" ".repeat(state.indent * level)}`;
|
|
3270
|
-
}
|
|
3271
|
-
function scalarLayout(state, node, parent, level, isKey, flowOnly) {
|
|
3272
|
-
return {
|
|
3273
|
-
node,
|
|
3274
|
-
parent,
|
|
3275
|
-
level,
|
|
3276
|
-
isKey,
|
|
3277
|
-
flowOnly,
|
|
3278
|
-
shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
|
|
3279
|
-
shiftOfContent: state.indent * Math.max(1, level),
|
|
3280
|
-
shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
|
|
3281
|
-
presenterOptions: state,
|
|
3282
|
-
allowedStylesMask: 0,
|
|
3283
|
-
style: node.style
|
|
3284
|
-
};
|
|
3285
|
-
}
|
|
3286
3226
|
function writeFlowSequence(state, level, node) {
|
|
3287
3227
|
let result = "";
|
|
3288
3228
|
for (let index = 0, length = node.items.length; index < length; index += 1) {
|
|
3289
|
-
const item = writeNode(state, level, node.items[index],
|
|
3290
|
-
if (
|
|
3229
|
+
const item = writeNode(state, level, node.items[index], {});
|
|
3230
|
+
if (result !== "") result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
|
|
3291
3231
|
result += item;
|
|
3292
3232
|
}
|
|
3293
|
-
const pad = state.flowBracketPadding &&
|
|
3233
|
+
const pad = state.flowBracketPadding && result !== "" ? " " : "";
|
|
3294
3234
|
return `[${pad}${result}${pad}]`;
|
|
3295
3235
|
}
|
|
3296
3236
|
function writeBlockSequence(state, level, node, compact) {
|
|
3297
3237
|
let result = "";
|
|
3298
3238
|
for (let index = 0, length = node.items.length; index < length; index += 1) {
|
|
3299
|
-
const item = writeNode(state, level + 1, node.items[index],
|
|
3239
|
+
const item = writeNode(state, level + 1, node.items[index], {
|
|
3300
3240
|
block: true,
|
|
3301
3241
|
compact: state.seqInlineFirst,
|
|
3302
3242
|
isblockseq: true
|
|
3303
|
-
})
|
|
3243
|
+
});
|
|
3304
3244
|
if (!compact || result !== "") result += generateNextLine(state, level);
|
|
3305
3245
|
if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
|
|
3306
3246
|
else result += "- ";
|
|
@@ -3310,51 +3250,70 @@ function writeBlockSequence(state, level, node, compact) {
|
|
|
3310
3250
|
}
|
|
3311
3251
|
function writeFlowMapping(state, level, node) {
|
|
3312
3252
|
let result = "";
|
|
3313
|
-
|
|
3253
|
+
const items = sortMappingItems(state, node.items);
|
|
3254
|
+
for (const { key, value } of items) {
|
|
3314
3255
|
let pairBuffer = "";
|
|
3315
3256
|
if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
|
|
3316
|
-
const
|
|
3317
|
-
const
|
|
3318
|
-
|
|
3257
|
+
const keyText = writeNode(state, level, key, { iskey: true });
|
|
3258
|
+
const explicitPair = keyText.length > 1024;
|
|
3259
|
+
if (explicitPair) pairBuffer += "? ";
|
|
3260
|
+
else if (state.quoteFlowKeys) pairBuffer += '"';
|
|
3261
|
+
const valueText = writeNode(state, level, value, {});
|
|
3319
3262
|
const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
|
|
3320
|
-
|
|
3321
|
-
const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
|
|
3322
|
-
pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
|
|
3263
|
+
pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '"' : ""}:${sep}${valueText}`;
|
|
3323
3264
|
result += pairBuffer;
|
|
3324
3265
|
}
|
|
3325
3266
|
const pad = state.flowBracketPadding && result !== "" ? " " : "";
|
|
3326
3267
|
return `{${pad}${result}${pad}}`;
|
|
3327
3268
|
}
|
|
3269
|
+
function sortKeyValue(key) {
|
|
3270
|
+
return key.kind === "scalar" ? key.value : key;
|
|
3271
|
+
}
|
|
3272
|
+
function sortMappingItems(state, items) {
|
|
3273
|
+
if (!state.sortKeys) return items;
|
|
3274
|
+
const copy = items.slice();
|
|
3275
|
+
if (state.sortKeys === true) copy.sort((a, b) => {
|
|
3276
|
+
const x = sortKeyValue(a.key);
|
|
3277
|
+
const y = sortKeyValue(b.key);
|
|
3278
|
+
if (x < y) return -1;
|
|
3279
|
+
if (x > y) return 1;
|
|
3280
|
+
return 0;
|
|
3281
|
+
});
|
|
3282
|
+
else {
|
|
3283
|
+
const fn = state.sortKeys;
|
|
3284
|
+
copy.sort((a, b) => fn(sortKeyValue(a.key), sortKeyValue(b.key)));
|
|
3285
|
+
}
|
|
3286
|
+
return copy;
|
|
3287
|
+
}
|
|
3328
3288
|
function writeBlockMapping(state, level, node, compact) {
|
|
3329
3289
|
let result = "";
|
|
3330
|
-
|
|
3290
|
+
const items = sortMappingItems(state, node.items);
|
|
3291
|
+
for (let index = 0, length = items.length; index < length; index += 1) {
|
|
3331
3292
|
let pairBuffer = "";
|
|
3332
3293
|
if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
|
|
3333
|
-
const { key, value } =
|
|
3334
|
-
const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style
|
|
3335
|
-
const
|
|
3294
|
+
const { key, value } = items[index];
|
|
3295
|
+
const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && !key.style.flow && key.items.length !== 0 || key.kind === "scalar" && (key.style.literal || key.style.folded);
|
|
3296
|
+
const keyText = keyIsBlock ? writeNode(state, level + 1, key, {
|
|
3336
3297
|
block: true,
|
|
3337
3298
|
compact: true,
|
|
3338
3299
|
isblockseq: !cannotBeCompact(state, key, level + 1)
|
|
3339
|
-
}) : writeNode(state, level + 1, key,
|
|
3300
|
+
}) : writeNode(state, level + 1, key, {
|
|
3340
3301
|
block: true,
|
|
3341
3302
|
compact: true,
|
|
3342
3303
|
iskey: true
|
|
3343
3304
|
});
|
|
3344
|
-
const keyText = keyRender.text;
|
|
3345
3305
|
const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
|
|
3346
|
-
const
|
|
3347
|
-
const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
|
|
3306
|
+
const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024;
|
|
3348
3307
|
if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
|
|
3349
3308
|
else pairBuffer += "? ";
|
|
3350
3309
|
pairBuffer += keyText;
|
|
3351
3310
|
if (explicitPair) pairBuffer += generateNextLine(state, level);
|
|
3352
|
-
const valueText = writeNode(state, level + 1, value,
|
|
3311
|
+
const valueText = writeNode(state, level + 1, value, {
|
|
3353
3312
|
block: true,
|
|
3354
3313
|
compact: explicitPair,
|
|
3355
3314
|
isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
|
|
3356
|
-
})
|
|
3357
|
-
const keyIsBareProps = key.kind === "scalar" &&
|
|
3315
|
+
});
|
|
3316
|
+
const keyIsBareProps = key.kind === "scalar" && key.value === "" && keyText !== "" && keyText.charCodeAt(keyText.length - 1) !== CHAR_SINGLE_QUOTE && keyText.charCodeAt(keyText.length - 1) !== CHAR_DOUBLE_QUOTE;
|
|
3358
3317
|
const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
|
|
3359
3318
|
if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
|
|
3360
3319
|
else pairBuffer += `${keyColonSep}: `;
|
|
@@ -3364,41 +3323,29 @@ function writeBlockMapping(state, level, node, compact) {
|
|
|
3364
3323
|
return result;
|
|
3365
3324
|
}
|
|
3366
3325
|
function cannotBeCompact(state, node, level) {
|
|
3367
|
-
|
|
3368
|
-
return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
|
|
3326
|
+
return node.style.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
|
|
3369
3327
|
}
|
|
3370
|
-
function writeNode(state, level, node,
|
|
3371
|
-
if (node.kind === "alias") {
|
|
3372
|
-
state.openEnded = false;
|
|
3373
|
-
return {
|
|
3374
|
-
text: `*${node.anchor}`,
|
|
3375
|
-
noBody: false
|
|
3376
|
-
};
|
|
3377
|
-
}
|
|
3328
|
+
function writeNode(state, level, node, ctx) {
|
|
3329
|
+
if (node.kind === "alias") return `*${node.anchor}`;
|
|
3378
3330
|
const { block = false, iskey = false, isblockseq = false } = ctx;
|
|
3379
3331
|
let compact = ctx.compact ?? false;
|
|
3380
3332
|
const hasAnchor = node.anchor !== void 0;
|
|
3381
3333
|
if (cannotBeCompact(state, node, level)) compact = false;
|
|
3382
3334
|
let body;
|
|
3383
|
-
let shouldPrintTag = node.tagged;
|
|
3384
|
-
const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style
|
|
3335
|
+
let shouldPrintTag = node.style.tagged;
|
|
3336
|
+
const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && !node.style.flow && node.items.length !== 0;
|
|
3385
3337
|
if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
|
|
3386
3338
|
else body = writeFlowMapping(state, level, node);
|
|
3387
3339
|
else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
|
|
3388
3340
|
else body = writeBlockSequence(state, level, node, compact);
|
|
3389
3341
|
else body = writeFlowSequence(state, level, node);
|
|
3390
3342
|
else {
|
|
3391
|
-
const layout = scalarLayout(state,
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
|
|
3397
|
-
}
|
|
3398
|
-
if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
|
|
3343
|
+
const layout = scalarLayout(state, level);
|
|
3344
|
+
const style = resolveScalarStyle(state, node, layout, iskey, block);
|
|
3345
|
+
body = renderScalarStyle(node.value, style, layout);
|
|
3346
|
+
shouldPrintTag = node.style.tagged || style !== STYLE_PLAIN && node.tag !== state.defaultScalarTagName;
|
|
3347
|
+
}
|
|
3399
3348
|
if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
|
|
3400
|
-
const noBody = body === "";
|
|
3401
|
-
let text = body;
|
|
3402
3349
|
if (shouldPrintTag || hasAnchor) {
|
|
3403
3350
|
const props = [];
|
|
3404
3351
|
const tag = shouldPrintTag ? nodeTagShort(node) : null;
|
|
@@ -3411,15 +3358,19 @@ function writeNode(state, level, node, parent, ctx) {
|
|
|
3411
3358
|
if (tag !== null) props.push(tag);
|
|
3412
3359
|
}
|
|
3413
3360
|
const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
|
|
3414
|
-
|
|
3361
|
+
body = `${props.join(" ")}${sep}${body}`;
|
|
3415
3362
|
}
|
|
3416
|
-
return
|
|
3417
|
-
text,
|
|
3418
|
-
noBody
|
|
3419
|
-
};
|
|
3363
|
+
return body;
|
|
3420
3364
|
}
|
|
3421
3365
|
function rootStartsOwnLine(node) {
|
|
3422
|
-
return (node.kind === "sequence" || node.kind === "mapping") && node.style
|
|
3366
|
+
return (node.kind === "sequence" || node.kind === "mapping") && !node.style.flow && node.items.length !== 0 && !node.style.tagged && node.anchor === void 0;
|
|
3367
|
+
}
|
|
3368
|
+
function isOpenEnded(node) {
|
|
3369
|
+
let leaf = node;
|
|
3370
|
+
while ((leaf.kind === "sequence" || leaf.kind === "mapping") && !leaf.style.flow && leaf.items.length !== 0) leaf = leaf.kind === "sequence" ? leaf.items[leaf.items.length - 1] : leaf.items[leaf.items.length - 1].value;
|
|
3371
|
+
if (leaf.kind !== "scalar" || !(leaf.style.literal || leaf.style.folded)) return false;
|
|
3372
|
+
const { value } = leaf;
|
|
3373
|
+
return value.endsWith("\n\n") || value === "\n";
|
|
3423
3374
|
}
|
|
3424
3375
|
function writeDocumentDirectives(doc) {
|
|
3425
3376
|
let result = "";
|
|
@@ -3441,7 +3392,6 @@ function present(documents, options) {
|
|
|
3441
3392
|
let previousEnded = false;
|
|
3442
3393
|
for (let index = 0; index < documents.length; index += 1) {
|
|
3443
3394
|
const doc = documents[index];
|
|
3444
|
-
state.openEnded = false;
|
|
3445
3395
|
const directives = writeDocumentDirectives(doc);
|
|
3446
3396
|
const hasDirectives = directives !== "";
|
|
3447
3397
|
const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
|
|
@@ -3449,18 +3399,18 @@ function present(documents, options) {
|
|
|
3449
3399
|
if (doc.contents === null) {
|
|
3450
3400
|
if (marker) result += "---\n";
|
|
3451
3401
|
} else if (marker) {
|
|
3452
|
-
const body = writeNode(state, 0, doc.contents,
|
|
3402
|
+
const body = writeNode(state, 0, doc.contents, {
|
|
3453
3403
|
block: true,
|
|
3454
3404
|
compact: true
|
|
3455
|
-
})
|
|
3405
|
+
});
|
|
3456
3406
|
const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
|
|
3457
3407
|
result += `---${sep}${body}
|
|
3458
3408
|
`;
|
|
3459
|
-
} else result += writeNode(state, 0, doc.contents,
|
|
3409
|
+
} else result += writeNode(state, 0, doc.contents, {
|
|
3460
3410
|
block: true,
|
|
3461
3411
|
compact: true
|
|
3462
|
-
})
|
|
3463
|
-
previousEnded = doc.explicitEnd ||
|
|
3412
|
+
}) + "\n";
|
|
3413
|
+
previousEnded = doc.explicitEnd || doc.contents !== null && isOpenEnded(doc.contents);
|
|
3464
3414
|
if (previousEnded) result += "...\n";
|
|
3465
3415
|
}
|
|
3466
3416
|
return result;
|
|
@@ -3471,17 +3421,9 @@ var DEFAULT_DUMP_OPTIONS = {
|
|
|
3471
3421
|
skipInvalid: false,
|
|
3472
3422
|
noRefs: false,
|
|
3473
3423
|
flowLevel: -1,
|
|
3474
|
-
sortKeys: false,
|
|
3475
3424
|
transform: () => {
|
|
3476
3425
|
}
|
|
3477
3426
|
};
|
|
3478
|
-
function defaultCompareFn(a, b) {
|
|
3479
|
-
const x = String(a);
|
|
3480
|
-
const y = String(b);
|
|
3481
|
-
if (x < y) return -1;
|
|
3482
|
-
if (x > y) return 1;
|
|
3483
|
-
return 0;
|
|
3484
|
-
}
|
|
3485
3427
|
function dump(input, options = {}) {
|
|
3486
3428
|
const opts = {
|
|
3487
3429
|
...DEFAULT_DUMP_OPTIONS,
|
|
@@ -3493,16 +3435,9 @@ function dump(input, options = {}) {
|
|
|
3493
3435
|
});
|
|
3494
3436
|
if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
|
|
3495
3437
|
if (ctx.depth < opts.flowLevel) return;
|
|
3496
|
-
|
|
3438
|
+
node.style.flow = true;
|
|
3497
3439
|
return VISIT_SKIP;
|
|
3498
3440
|
});
|
|
3499
|
-
if (opts.sortKeys) {
|
|
3500
|
-
const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
|
|
3501
|
-
visit(documents, (node) => {
|
|
3502
|
-
if (node.kind !== "mapping") return;
|
|
3503
|
-
node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
|
|
3504
|
-
});
|
|
3505
|
-
}
|
|
3506
3441
|
opts.transform(documents);
|
|
3507
3442
|
return present(documents, {
|
|
3508
3443
|
...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
|
|
@@ -4999,14 +4934,6 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
|
4999
4934
|
return `${Math.floor(month / 12)} \u5E74\u524D`;
|
|
5000
4935
|
}
|
|
5001
4936
|
|
|
5002
|
-
// src/service.ts
|
|
5003
|
-
import { spawnSync as spawnSync7 } from "child_process";
|
|
5004
|
-
import fs12 from "fs";
|
|
5005
|
-
import path7 from "path";
|
|
5006
|
-
|
|
5007
|
-
// src/hot-reload.ts
|
|
5008
|
-
import fs8 from "fs";
|
|
5009
|
-
|
|
5010
4937
|
// src/launchctl.ts
|
|
5011
4938
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
5012
4939
|
import fs5 from "fs";
|
|
@@ -5144,1529 +5071,1516 @@ async function waitUntilUnloaded(target = serviceTarget()) {
|
|
|
5144
5071
|
});
|
|
5145
5072
|
}
|
|
5146
5073
|
|
|
5147
|
-
// src/
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
|
|
5074
|
+
// src/suggest.ts
|
|
5075
|
+
function levenshtein(a, b) {
|
|
5076
|
+
if (a === b) return 0;
|
|
5077
|
+
if (a.length === 0) return b.length;
|
|
5078
|
+
if (b.length === 0) return a.length;
|
|
5079
|
+
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
5080
|
+
for (let i = 1; i <= a.length; i++) {
|
|
5081
|
+
const curr = [i];
|
|
5082
|
+
for (let j = 1; j <= b.length; j++) {
|
|
5083
|
+
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
5084
|
+
}
|
|
5085
|
+
prev = curr;
|
|
5086
|
+
}
|
|
5087
|
+
return prev[b.length];
|
|
5157
5088
|
}
|
|
5158
|
-
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
|
|
5167
|
-
|
|
5168
|
-
|
|
5169
|
-
|
|
5170
|
-
}
|
|
5171
|
-
const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|
|
5172
|
-
if (!match) return NOT_RUNNING;
|
|
5173
|
-
return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
|
|
5174
|
-
} catch {
|
|
5175
|
-
return NOT_RUNNING;
|
|
5089
|
+
function suggestSimilar(input, candidates) {
|
|
5090
|
+
const lower = input.toLowerCase();
|
|
5091
|
+
if (lower === "") return [];
|
|
5092
|
+
const scored = [];
|
|
5093
|
+
for (const cand of candidates) {
|
|
5094
|
+
const c = cand.toLowerCase();
|
|
5095
|
+
if (cand === input) continue;
|
|
5096
|
+
if (c.startsWith(lower)) {
|
|
5097
|
+
scored.push({ name: cand, score: 0, lenDiff: Math.abs(cand.length - input.length) });
|
|
5098
|
+
} else if (lower.length >= 3) {
|
|
5099
|
+
const d = levenshtein(lower, c);
|
|
5100
|
+
if (d <= 2) scored.push({ name: cand, score: d, lenDiff: Math.abs(cand.length - input.length) });
|
|
5101
|
+
}
|
|
5176
5102
|
}
|
|
5103
|
+
scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
|
|
5104
|
+
return scored.slice(0, 3).map((s) => s.name);
|
|
5177
5105
|
}
|
|
5178
|
-
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5186
|
-
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5106
|
+
|
|
5107
|
+
// src/commands/help.ts
|
|
5108
|
+
function printShortHelp() {
|
|
5109
|
+
console.log(`
|
|
5110
|
+
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u770B\u5B8C\u6574\u5E2E\u52A9)
|
|
5111
|
+
`);
|
|
5112
|
+
const steps = [];
|
|
5113
|
+
if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
|
|
5114
|
+
if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
|
|
5115
|
+
if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
|
|
5116
|
+
if (steps.length > 0) {
|
|
5117
|
+
steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
|
|
5118
|
+
const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
|
|
5119
|
+
console.log("\u5F00\u59CB\u4F7F\u7528:");
|
|
5120
|
+
steps.forEach(([cmd, desc], i) => {
|
|
5121
|
+
console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
|
|
5122
|
+
});
|
|
5123
|
+
console.log("");
|
|
5124
|
+
return;
|
|
5190
5125
|
}
|
|
5126
|
+
console.log(
|
|
5127
|
+
`\u5E38\u7528\u547D\u4EE4:
|
|
5128
|
+
${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
|
|
5129
|
+
${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
|
|
5130
|
+
${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
|
|
5131
|
+
${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
|
|
5132
|
+
`
|
|
5133
|
+
);
|
|
5191
5134
|
}
|
|
5192
|
-
|
|
5193
|
-
|
|
5194
|
-
|
|
5195
|
-
|
|
5135
|
+
var GROUP_TITLES = [
|
|
5136
|
+
["control", "\u63A7\u5236:"],
|
|
5137
|
+
["interface", "\u754C\u9762:"],
|
|
5138
|
+
["subscription", "\u8BA2\u9605:"],
|
|
5139
|
+
["config", "\u914D\u7F6E:"],
|
|
5140
|
+
["system", "\u7CFB\u7EDF:"]
|
|
5141
|
+
];
|
|
5142
|
+
function printHelp(commands) {
|
|
5143
|
+
const lines = [`
|
|
5144
|
+
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
|
|
5145
|
+
const allUsage = commands.flatMap((c) => c.usage);
|
|
5146
|
+
const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
|
|
5147
|
+
const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
|
|
5148
|
+
for (const [group, title] of GROUP_TITLES) {
|
|
5149
|
+
const usageLines = commands.filter((c) => c.group === group).flatMap((c) => c.usage);
|
|
5150
|
+
if (usageLines.length === 0) continue;
|
|
5151
|
+
lines.push("", colors.cyan(title));
|
|
5152
|
+
for (const u of usageLines) lines.push(formatUsage(u));
|
|
5153
|
+
}
|
|
5154
|
+
const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
|
|
5155
|
+
if (meta.length > 0) {
|
|
5156
|
+
lines.push("", colors.cyan("\u5143:"));
|
|
5157
|
+
for (const u of meta) lines.push(formatUsage(u));
|
|
5158
|
+
}
|
|
5159
|
+
lines.push(
|
|
5160
|
+
"",
|
|
5161
|
+
`${colors.cyan("\u793A\u4F8B:")}`,
|
|
5162
|
+
// 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
|
|
5163
|
+
// 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
|
|
5164
|
+
" mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
|
|
5165
|
+
" mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
5166
|
+
" mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
|
|
5167
|
+
" mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
|
|
5168
|
+
" mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
|
|
5169
|
+
" mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
|
|
5170
|
+
" mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
5171
|
+
" mihomo-cli ui # \u6253\u5F00 Web UI",
|
|
5172
|
+
"",
|
|
5173
|
+
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
5174
|
+
" tun = start tun",
|
|
5175
|
+
" use <name> = subscription use <name>",
|
|
5176
|
+
" restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
|
|
5177
|
+
"",
|
|
5178
|
+
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
5179
|
+
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
|
|
5180
|
+
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
|
|
5181
|
+
"",
|
|
5182
|
+
`${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
|
|
5183
|
+
" \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
|
|
5184
|
+
` \u9ED8\u8BA4: ${USER_DATA_DIR}`
|
|
5185
|
+
);
|
|
5186
|
+
console.log(lines.join("\n"));
|
|
5196
5187
|
}
|
|
5197
|
-
function
|
|
5198
|
-
|
|
5188
|
+
function printCommandHelp(command) {
|
|
5189
|
+
const aliasText = command.aliases.length > 0 ? colors.gray(`\uFF08\u522B\u540D: ${command.aliases.join(", ")}\uFF09`) : "";
|
|
5190
|
+
const lines = ["", `${colors.cyan(colors.bold(`mihomo-cli ${command.name}`))}${aliasText}`];
|
|
5191
|
+
if (command.usage.length > 0) {
|
|
5192
|
+
lines.push("", "\u7528\u6CD5:");
|
|
5193
|
+
const width = Math.max(...command.usage.map((u) => displayWidth(u.signature)));
|
|
5194
|
+
for (const u of command.usage) {
|
|
5195
|
+
lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
|
|
5196
|
+
}
|
|
5197
|
+
} else {
|
|
5198
|
+
lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
|
|
5199
|
+
}
|
|
5200
|
+
console.log(lines.join("\n"));
|
|
5199
5201
|
}
|
|
5200
|
-
function
|
|
5201
|
-
const
|
|
5202
|
-
if (
|
|
5203
|
-
|
|
5204
|
-
|
|
5205
|
-
});
|
|
5202
|
+
function printHelpEntry(args, commands, finder) {
|
|
5203
|
+
const token = args[1];
|
|
5204
|
+
if (!token) {
|
|
5205
|
+
printHelp(commands);
|
|
5206
|
+
return;
|
|
5206
5207
|
}
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
|
|
5208
|
+
const command = finder(token.toLowerCase());
|
|
5209
|
+
if (!command) {
|
|
5210
|
+
const suggestion = suggestSimilar(
|
|
5211
|
+
token,
|
|
5212
|
+
commands.flatMap((c) => [c.name, ...c.aliases])
|
|
5213
|
+
);
|
|
5214
|
+
throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
|
|
5215
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
|
|
5210
5216
|
});
|
|
5211
5217
|
}
|
|
5212
|
-
|
|
5218
|
+
printCommandHelp(command);
|
|
5213
5219
|
}
|
|
5214
|
-
function
|
|
5215
|
-
const
|
|
5216
|
-
|
|
5217
|
-
|
|
5220
|
+
function printVersion() {
|
|
5221
|
+
const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
|
|
5222
|
+
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
5223
|
+
console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
|
|
5224
|
+
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
5218
5225
|
}
|
|
5219
|
-
|
|
5220
|
-
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
5224
|
-
|
|
5225
|
-
return
|
|
5226
|
+
|
|
5227
|
+
// src/redact.ts
|
|
5228
|
+
var SECRET_KEYS = /* @__PURE__ */ new Set(["password", "uuid", "private-key", "pre-shared-key", "auth-str", "auth", "obfs-password", "token", "secret"]);
|
|
5229
|
+
var URL_PROVIDER_KEYS = /* @__PURE__ */ new Set(["proxy-providers", "rule-providers"]);
|
|
5230
|
+
function walk(node, withinProvider, state) {
|
|
5231
|
+
if (Array.isArray(node)) {
|
|
5232
|
+
return node.map((item) => walk(item, withinProvider, state));
|
|
5233
|
+
}
|
|
5234
|
+
if (node !== null && typeof node === "object") {
|
|
5235
|
+
const out = {};
|
|
5236
|
+
for (const [key, value] of Object.entries(node)) {
|
|
5237
|
+
const assign = (v) => {
|
|
5238
|
+
if (key === "__proto__") {
|
|
5239
|
+
Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
|
|
5240
|
+
} else {
|
|
5241
|
+
out[key] = v;
|
|
5242
|
+
}
|
|
5243
|
+
};
|
|
5244
|
+
if (typeof value === "string" && SECRET_KEYS.has(key.toLowerCase())) {
|
|
5245
|
+
assign("***");
|
|
5246
|
+
state.changed = true;
|
|
5247
|
+
} else if (typeof value === "string" && withinProvider && key === "url") {
|
|
5248
|
+
const masked = maskUrl(value);
|
|
5249
|
+
assign(masked);
|
|
5250
|
+
if (masked !== value) state.changed = true;
|
|
5251
|
+
} else {
|
|
5252
|
+
assign(walk(value, withinProvider || URL_PROVIDER_KEYS.has(key), state));
|
|
5253
|
+
}
|
|
5254
|
+
}
|
|
5255
|
+
return out;
|
|
5226
5256
|
}
|
|
5257
|
+
return node;
|
|
5227
5258
|
}
|
|
5228
|
-
function
|
|
5229
|
-
const
|
|
5230
|
-
|
|
5231
|
-
const p = probeProcess(pid);
|
|
5232
|
-
if (!isProbedMihomo(p)) return { running: false, pid: null, memory: null };
|
|
5233
|
-
return {
|
|
5234
|
-
running: true,
|
|
5235
|
-
pid,
|
|
5236
|
-
memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5"
|
|
5237
|
-
};
|
|
5259
|
+
function redactConfigSecrets(config) {
|
|
5260
|
+
const state = { changed: false };
|
|
5261
|
+
return { config: walk(config, false, state), changed: state.changed };
|
|
5238
5262
|
}
|
|
5239
5263
|
|
|
5240
|
-
// src/
|
|
5241
|
-
var
|
|
5242
|
-
|
|
5264
|
+
// src/http.ts
|
|
5265
|
+
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5266
|
+
var MAX_REDIRECTS = 20;
|
|
5267
|
+
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
5268
|
+
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5269
|
+
function isHttpsUrl(url) {
|
|
5243
5270
|
try {
|
|
5244
|
-
|
|
5245
|
-
if (r.status !== 0) return null;
|
|
5246
|
-
return parsePidList(r.stdout);
|
|
5271
|
+
return new URL(url).protocol === "https:";
|
|
5247
5272
|
} catch {
|
|
5248
|
-
return
|
|
5273
|
+
return false;
|
|
5249
5274
|
}
|
|
5250
5275
|
}
|
|
5251
|
-
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
}
|
|
5255
|
-
var PROBE_TIMEOUT_MS = 2e3;
|
|
5256
|
-
async function probeProxyConnectivity(port) {
|
|
5257
|
-
const start = Date.now();
|
|
5276
|
+
function createHttpError(status, bodyText) {
|
|
5277
|
+
const error = new Error(`HTTP ${status}`);
|
|
5278
|
+
error.response = { status };
|
|
5258
5279
|
try {
|
|
5259
|
-
|
|
5260
|
-
"curl",
|
|
5261
|
-
["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
5262
|
-
{
|
|
5263
|
-
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
5264
|
-
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
5265
|
-
env: buildCurlSpawnEnv()
|
|
5266
|
-
}
|
|
5267
|
-
);
|
|
5268
|
-
const code = Number.parseInt(stdout.trim(), 10);
|
|
5269
|
-
const statusCode = Number.isFinite(code) ? code : null;
|
|
5270
|
-
const ok = isProbeSuccessStatus(statusCode);
|
|
5271
|
-
return {
|
|
5272
|
-
ok,
|
|
5273
|
-
statusCode,
|
|
5274
|
-
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
5275
|
-
durationMs: Date.now() - start
|
|
5276
|
-
};
|
|
5277
|
-
} catch (e) {
|
|
5278
|
-
const err = e;
|
|
5279
|
-
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
5280
|
-
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
5281
|
-
}
|
|
5282
|
-
}
|
|
5283
|
-
|
|
5284
|
-
// src/stop-epoch.ts
|
|
5285
|
-
import fs7 from "fs";
|
|
5286
|
-
function readStopEpoch() {
|
|
5287
|
-
try {
|
|
5288
|
-
const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
5289
|
-
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
5280
|
+
error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
|
|
5290
5281
|
} catch {
|
|
5291
|
-
return 0;
|
|
5292
5282
|
}
|
|
5283
|
+
return error;
|
|
5293
5284
|
}
|
|
5294
|
-
|
|
5295
|
-
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
|
|
5299
|
-
|
|
5300
|
-
|
|
5285
|
+
function createHttpClient(options = {}) {
|
|
5286
|
+
const { timeout = 6e4 } = options;
|
|
5287
|
+
return {
|
|
5288
|
+
async get(url, config) {
|
|
5289
|
+
const controller = new AbortController();
|
|
5290
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
5291
|
+
const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
|
|
5292
|
+
try {
|
|
5293
|
+
let currentUrl = url;
|
|
5294
|
+
let response;
|
|
5295
|
+
for (let hop = 0; ; hop++) {
|
|
5296
|
+
response = await fetch(currentUrl, {
|
|
5297
|
+
signal,
|
|
5298
|
+
redirect: "manual",
|
|
5299
|
+
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5300
|
+
});
|
|
5301
|
+
if (!REDIRECT_STATUSES.has(response.status)) break;
|
|
5302
|
+
if (hop >= MAX_REDIRECTS) {
|
|
5303
|
+
throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
|
|
5304
|
+
}
|
|
5305
|
+
const location = response.headers.get("location");
|
|
5306
|
+
if (!location) break;
|
|
5307
|
+
const nextUrl = new URL(location, currentUrl).toString();
|
|
5308
|
+
if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
|
|
5309
|
+
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5310
|
+
}
|
|
5311
|
+
await response.body?.cancel().catch(() => void 0);
|
|
5312
|
+
currentUrl = nextUrl;
|
|
5313
|
+
}
|
|
5314
|
+
if (!response.ok) {
|
|
5315
|
+
let text2 = "";
|
|
5316
|
+
try {
|
|
5317
|
+
text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
|
|
5318
|
+
} catch {
|
|
5319
|
+
}
|
|
5320
|
+
throw createHttpError(response.status, text2);
|
|
5321
|
+
}
|
|
5322
|
+
const declaredLen = Number(response.headers.get("content-length"));
|
|
5323
|
+
if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
|
|
5324
|
+
throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
|
|
5325
|
+
}
|
|
5326
|
+
const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
|
|
5327
|
+
const data = config?.responseType === "json" ? JSON.parse(text) : text;
|
|
5328
|
+
return { data, headers: response.headers };
|
|
5329
|
+
} catch (e) {
|
|
5330
|
+
if (controller.signal.aborted && e.name === "AbortError") {
|
|
5331
|
+
throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
|
|
5332
|
+
}
|
|
5333
|
+
throw e;
|
|
5334
|
+
} finally {
|
|
5335
|
+
clearTimeout(timer);
|
|
5336
|
+
}
|
|
5337
|
+
}
|
|
5338
|
+
};
|
|
5301
5339
|
}
|
|
5302
|
-
function
|
|
5340
|
+
async function readBodyWithLimit(response, controller, limit) {
|
|
5341
|
+
if (!response.body) return response.text();
|
|
5342
|
+
const reader = response.body.getReader();
|
|
5343
|
+
const chunks = [];
|
|
5344
|
+
let total = 0;
|
|
5303
5345
|
try {
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5346
|
+
while (true) {
|
|
5347
|
+
const { done, value } = await reader.read();
|
|
5348
|
+
if (done) break;
|
|
5349
|
+
if (value) {
|
|
5350
|
+
total += value.byteLength;
|
|
5351
|
+
if (total > limit) {
|
|
5352
|
+
controller.abort();
|
|
5353
|
+
throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
|
|
5354
|
+
}
|
|
5355
|
+
chunks.push(value);
|
|
5356
|
+
}
|
|
5357
|
+
}
|
|
5358
|
+
} finally {
|
|
5359
|
+
reader.releaseLock();
|
|
5307
5360
|
}
|
|
5361
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
5308
5362
|
}
|
|
5309
|
-
|
|
5310
|
-
|
|
5363
|
+
|
|
5364
|
+
// src/spinner.ts
|
|
5365
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
5366
|
+
var INTERVAL_MS = 80;
|
|
5367
|
+
async function withSpinner(label, fn) {
|
|
5368
|
+
if (!process.stdout.isTTY) {
|
|
5369
|
+
console.log(label);
|
|
5370
|
+
return fn();
|
|
5371
|
+
}
|
|
5372
|
+
const start = Date.now();
|
|
5373
|
+
let frame = 0;
|
|
5374
|
+
const render = () => {
|
|
5375
|
+
const secs = ((Date.now() - start) / 1e3).toFixed(0);
|
|
5376
|
+
process.stdout.write(`\r${colors.cyan(FRAMES[frame])} ${label} ${colors.gray(`${secs}s`)}\x1B[K`);
|
|
5377
|
+
frame = (frame + 1) % FRAMES.length;
|
|
5378
|
+
};
|
|
5379
|
+
render();
|
|
5380
|
+
const timer = setInterval(render, INTERVAL_MS);
|
|
5381
|
+
try {
|
|
5382
|
+
return await fn();
|
|
5383
|
+
} finally {
|
|
5384
|
+
clearInterval(timer);
|
|
5385
|
+
process.stdout.write("\r\x1B[K");
|
|
5386
|
+
}
|
|
5311
5387
|
}
|
|
5312
|
-
|
|
5313
|
-
|
|
5388
|
+
|
|
5389
|
+
// src/subscription.ts
|
|
5390
|
+
function resolveUpdateInterval(cachedInterval) {
|
|
5391
|
+
return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
|
|
5314
5392
|
}
|
|
5315
|
-
function
|
|
5316
|
-
|
|
5393
|
+
function isSubscriptionStale(cached, nowMs = Date.now()) {
|
|
5394
|
+
if (!cached.updated_at) return false;
|
|
5395
|
+
const t = new Date(cached.updated_at).getTime();
|
|
5396
|
+
if (Number.isNaN(t) || t > nowMs) return false;
|
|
5397
|
+
const ageHours = (nowMs - t) / 36e5;
|
|
5398
|
+
return ageHours > resolveUpdateInterval(cached.update_interval);
|
|
5317
5399
|
}
|
|
5318
|
-
|
|
5319
|
-
|
|
5320
|
-
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
5321
|
-
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5322
|
-
function logOversized() {
|
|
5400
|
+
var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
|
|
5401
|
+
function isValidHttpUrl(url) {
|
|
5323
5402
|
try {
|
|
5324
|
-
|
|
5403
|
+
const u = new URL(url.trim());
|
|
5404
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
5325
5405
|
} catch {
|
|
5326
5406
|
return false;
|
|
5327
5407
|
}
|
|
5328
5408
|
}
|
|
5329
|
-
|
|
5330
|
-
|
|
5331
|
-
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
const
|
|
5335
|
-
|
|
5336
|
-
const
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
if (!probe.ok) return false;
|
|
5343
|
-
const info = await probe.json();
|
|
5344
|
-
if (typeof info?.version !== "string") return false;
|
|
5345
|
-
const listenerPids = lsofListenPids(endpoint.port);
|
|
5346
|
-
if (listenerPids === null || listenerPids[0] !== status.pid) return false;
|
|
5347
|
-
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
5348
|
-
method: "PUT",
|
|
5349
|
-
headers,
|
|
5350
|
-
body: "{}",
|
|
5351
|
-
signal: controller.signal
|
|
5352
|
-
});
|
|
5353
|
-
return res.ok;
|
|
5354
|
-
} finally {
|
|
5355
|
-
clearTimeout(timer);
|
|
5356
|
-
}
|
|
5357
|
-
} catch {
|
|
5358
|
-
return false;
|
|
5409
|
+
function parseUserInfo(header) {
|
|
5410
|
+
if (!header) return null;
|
|
5411
|
+
const info = {};
|
|
5412
|
+
let hasAny = false;
|
|
5413
|
+
for (const part of header.split(";")) {
|
|
5414
|
+
const [rawKey, rawVal] = part.split("=");
|
|
5415
|
+
const key = rawKey?.trim();
|
|
5416
|
+
const val = rawVal?.trim();
|
|
5417
|
+
if (!key || val === void 0 || val === "") continue;
|
|
5418
|
+
const numVal = Number(val);
|
|
5419
|
+
if (!Number.isFinite(numVal) || numVal < 0) continue;
|
|
5420
|
+
info[key] = numVal;
|
|
5421
|
+
hasAny = true;
|
|
5359
5422
|
}
|
|
5423
|
+
return hasAny ? info : null;
|
|
5360
5424
|
}
|
|
5361
|
-
function
|
|
5362
|
-
|
|
5425
|
+
function parsePositiveInterval(header) {
|
|
5426
|
+
if (!header) return null;
|
|
5427
|
+
const n = parseInt(header, 10);
|
|
5428
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
5363
5429
|
}
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
function isArchiveLogFilename(filename) {
|
|
5372
|
-
return ARCHIVE_LOG_RE.test(filename);
|
|
5430
|
+
function parseUsernameFromContentDisposition(header) {
|
|
5431
|
+
if (!header) return null;
|
|
5432
|
+
const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
|
|
5433
|
+
if (!match) return null;
|
|
5434
|
+
const filename = match[1];
|
|
5435
|
+
const parts = filename.split("/");
|
|
5436
|
+
return parts[parts.length - 1] || null;
|
|
5373
5437
|
}
|
|
5374
|
-
function
|
|
5375
|
-
|
|
5376
|
-
|
|
5438
|
+
function extractSubscriptionMeta(headers) {
|
|
5439
|
+
return {
|
|
5440
|
+
userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
|
|
5441
|
+
updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
|
|
5442
|
+
// 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
|
|
5443
|
+
webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
|
|
5444
|
+
username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
|
|
5445
|
+
};
|
|
5377
5446
|
}
|
|
5378
|
-
function
|
|
5379
|
-
const
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
if (
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
const buf = Buffer.alloc(length);
|
|
5387
|
-
fd = fs9.openSync(PATHS.logFile, "r");
|
|
5388
|
-
const bytesRead = fs9.readSync(fd, buf, 0, length, start);
|
|
5389
|
-
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5390
|
-
} catch {
|
|
5391
|
-
return [];
|
|
5392
|
-
} finally {
|
|
5393
|
-
if (fd !== null) {
|
|
5394
|
-
try {
|
|
5395
|
-
fs9.closeSync(fd);
|
|
5396
|
-
} catch {
|
|
5397
|
-
}
|
|
5398
|
-
}
|
|
5447
|
+
function saveSubscriptionMeta(subName, meta) {
|
|
5448
|
+
const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
5449
|
+
if (meta.userInfo) {
|
|
5450
|
+
const { upload, download, total, expire } = meta.userInfo;
|
|
5451
|
+
if (upload !== void 0) cacheData.upload = upload;
|
|
5452
|
+
if (download !== void 0) cacheData.download = download;
|
|
5453
|
+
if (total !== void 0) cacheData.total = total;
|
|
5454
|
+
if (expire !== void 0) cacheData.expire = expire;
|
|
5399
5455
|
}
|
|
5456
|
+
if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
|
|
5457
|
+
if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
|
|
5458
|
+
if (meta.username) cacheData.username = meta.username;
|
|
5459
|
+
saveSubscriptionCache(subName, cacheData);
|
|
5400
5460
|
}
|
|
5401
|
-
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5409
|
-
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
5461
|
+
function formatProxySummary(info) {
|
|
5462
|
+
const parts = [];
|
|
5463
|
+
if (info.proxyGroups && info.proxyGroups > 0) parts.push(`${info.proxyGroups} \u7EC4`);
|
|
5464
|
+
parts.push(`${info.proxies || 0} \u8282\u70B9`);
|
|
5465
|
+
return parts.join(", ");
|
|
5466
|
+
}
|
|
5467
|
+
function getActiveSubscription() {
|
|
5468
|
+
const settings = readSettings();
|
|
5469
|
+
const subs = getSubscriptions(settings);
|
|
5470
|
+
if (subs.length === 0) return null;
|
|
5471
|
+
const activeName = settings.active_subscription;
|
|
5472
|
+
if (activeName) {
|
|
5473
|
+
const found = subs.find((s) => s.name === activeName);
|
|
5474
|
+
if (found) return found;
|
|
5475
|
+
}
|
|
5476
|
+
return subs[0];
|
|
5477
|
+
}
|
|
5478
|
+
function noSubscriptionsError() {
|
|
5479
|
+
return new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
|
|
5480
|
+
}
|
|
5481
|
+
function requireActiveSubscription() {
|
|
5482
|
+
const sub = getActiveSubscription();
|
|
5483
|
+
if (!sub) {
|
|
5484
|
+
throw noSubscriptionsError();
|
|
5485
|
+
}
|
|
5486
|
+
return sub;
|
|
5487
|
+
}
|
|
5488
|
+
function resolveSubscription(subs, pattern) {
|
|
5489
|
+
const lowerPattern = pattern.toLowerCase();
|
|
5490
|
+
const exact = [];
|
|
5491
|
+
const prefix = [];
|
|
5492
|
+
const includes = [];
|
|
5493
|
+
for (const s of subs) {
|
|
5494
|
+
const name = s.name.toLowerCase();
|
|
5495
|
+
if (name === lowerPattern) {
|
|
5496
|
+
exact.push(s);
|
|
5497
|
+
} else if (name.startsWith(lowerPattern)) {
|
|
5498
|
+
prefix.push(s);
|
|
5499
|
+
} else if (name.includes(lowerPattern)) {
|
|
5500
|
+
includes.push(s);
|
|
5417
5501
|
}
|
|
5418
|
-
return archivePath;
|
|
5419
5502
|
}
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5503
|
+
const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
|
|
5504
|
+
if (matched.length === 0) {
|
|
5505
|
+
throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
|
|
5506
|
+
}
|
|
5507
|
+
if (matched.length === 1) return matched[0];
|
|
5508
|
+
throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
|
|
5509
|
+
hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...matched.map((s) => ` ${s.name}`)]
|
|
5423
5510
|
});
|
|
5424
5511
|
}
|
|
5425
|
-
function
|
|
5426
|
-
const
|
|
5427
|
-
|
|
5512
|
+
function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
5513
|
+
const hasProxies = Array.isArray(parsed.proxies) && parsed.proxies.length > 0;
|
|
5514
|
+
const hasGroups = Array.isArray(parsed["proxy-groups"]) && parsed["proxy-groups"].length > 0;
|
|
5515
|
+
const providers = parsed["proxy-providers"];
|
|
5516
|
+
const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
|
|
5517
|
+
if (hasProxies || hasGroups || hasProviders) return;
|
|
5518
|
+
const serverMsg = sanitizeTerminal(
|
|
5519
|
+
["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
|
|
5520
|
+
);
|
|
5521
|
+
throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
|
|
5522
|
+
label: "\u8BA2\u9605\u65E0\u6548",
|
|
5523
|
+
hint: [
|
|
5524
|
+
...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
|
|
5525
|
+
`URL: ${maskedUrl}`,
|
|
5526
|
+
"\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
|
|
5527
|
+
"\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
|
|
5528
|
+
]
|
|
5529
|
+
});
|
|
5530
|
+
}
|
|
5531
|
+
async function downloadSubscription(url, subName, signal) {
|
|
5532
|
+
let response;
|
|
5428
5533
|
try {
|
|
5429
|
-
|
|
5534
|
+
response = await HTTP_CLIENT.get(url, { responseType: "text", signal });
|
|
5430
5535
|
} catch (e) {
|
|
5431
|
-
|
|
5432
|
-
|
|
5536
|
+
const maskedUrl = maskUrl(url);
|
|
5537
|
+
let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
|
|
5538
|
+
const err = e;
|
|
5539
|
+
if (err.response) {
|
|
5540
|
+
errorMsg += ` (HTTP ${err.response.status})`;
|
|
5541
|
+
}
|
|
5542
|
+
errorMsg += `
|
|
5543
|
+
URL: ${maskedUrl}`;
|
|
5544
|
+
throw new Error(errorMsg);
|
|
5433
5545
|
}
|
|
5434
|
-
|
|
5435
|
-
|
|
5546
|
+
const content = response.data;
|
|
5547
|
+
if (!content?.trim()) {
|
|
5548
|
+
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5549
|
+
}
|
|
5550
|
+
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5551
|
+
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5552
|
+
saveSubscriptionRawConfig(subName, content);
|
|
5553
|
+
const meta = extractSubscriptionMeta(response.headers);
|
|
5436
5554
|
try {
|
|
5437
|
-
|
|
5555
|
+
saveSubscriptionMeta(subName, meta);
|
|
5438
5556
|
} catch (e) {
|
|
5439
5557
|
try {
|
|
5440
|
-
|
|
5441
|
-
} catch {
|
|
5442
|
-
}
|
|
5443
|
-
if (e.code === "ENOENT") return;
|
|
5444
|
-
throw e;
|
|
5445
|
-
}
|
|
5446
|
-
}
|
|
5447
|
-
function cleanupOldLogs() {
|
|
5448
|
-
const logsDir = DIRS.logs;
|
|
5449
|
-
if (!fs9.existsSync(logsDir)) return;
|
|
5450
|
-
const files = fs9.readdirSync(logsDir);
|
|
5451
|
-
const now = Date.now();
|
|
5452
|
-
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5453
|
-
for (const file of files) {
|
|
5454
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
5455
|
-
try {
|
|
5456
|
-
const filePath = path5.join(logsDir, file);
|
|
5457
|
-
const stat = fs9.statSync(filePath);
|
|
5458
|
-
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5459
|
-
fs9.unlinkSync(filePath);
|
|
5460
|
-
}
|
|
5558
|
+
removeSubscriptionRawConfig(subName);
|
|
5461
5559
|
} catch {
|
|
5462
5560
|
}
|
|
5561
|
+
throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
|
|
5562
|
+
label: "\u66F4\u65B0\u5931\u8D25",
|
|
5563
|
+
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5564
|
+
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5565
|
+
hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
5566
|
+
});
|
|
5463
5567
|
}
|
|
5568
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5569
|
+
return { proxies, proxyGroups };
|
|
5464
5570
|
}
|
|
5465
|
-
function
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
size: stat.size,
|
|
5474
|
-
mtime: stat.mtime,
|
|
5475
|
-
isCurrent: true
|
|
5476
|
-
};
|
|
5477
|
-
}
|
|
5478
|
-
if (!fs9.existsSync(logsDir)) return result;
|
|
5479
|
-
const files = fs9.readdirSync(logsDir);
|
|
5480
|
-
for (const file of files) {
|
|
5481
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
5482
|
-
try {
|
|
5483
|
-
const filePath = path5.join(logsDir, file);
|
|
5484
|
-
const stat = fs9.statSync(filePath);
|
|
5485
|
-
result.archives.push({
|
|
5486
|
-
name: file,
|
|
5487
|
-
path: filePath,
|
|
5488
|
-
size: stat.size,
|
|
5489
|
-
mtime: stat.mtime,
|
|
5490
|
-
isCurrent: false
|
|
5571
|
+
async function prepareConfigForStart(mode, subName) {
|
|
5572
|
+
let rawContent;
|
|
5573
|
+
try {
|
|
5574
|
+
rawContent = requireSubscriptionRawConfig(subName);
|
|
5575
|
+
} catch (e) {
|
|
5576
|
+
if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
|
|
5577
|
+
throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
|
|
5578
|
+
hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
|
|
5491
5579
|
});
|
|
5492
|
-
} catch {
|
|
5493
5580
|
}
|
|
5581
|
+
throw e;
|
|
5494
5582
|
}
|
|
5495
|
-
|
|
5496
|
-
|
|
5583
|
+
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5584
|
+
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5585
|
+
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
5586
|
+
return {
|
|
5587
|
+
buildResult,
|
|
5588
|
+
info: countConfigNodes(buildResult.config)
|
|
5589
|
+
};
|
|
5497
5590
|
}
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
import fs10 from "fs";
|
|
5506
|
-
import path6 from "path";
|
|
5507
|
-
var SUDO_TIMEOUT_MS = 6e4;
|
|
5508
|
-
var SudoAuthError = class extends Error {
|
|
5509
|
-
constructor() {
|
|
5510
|
-
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
5511
|
-
this.name = "SudoAuthError";
|
|
5591
|
+
function commitPreparedConfig(prepared) {
|
|
5592
|
+
const { buildResult } = prepared;
|
|
5593
|
+
if (buildResult.warnings.length > 0) {
|
|
5594
|
+
for (const warning of buildResult.warnings) {
|
|
5595
|
+
console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
|
|
5596
|
+
}
|
|
5597
|
+
console.log("");
|
|
5512
5598
|
}
|
|
5513
|
-
|
|
5514
|
-
|
|
5515
|
-
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
5516
|
-
}
|
|
5517
|
-
function sudoExitToError(action, status, codeMessages) {
|
|
5518
|
-
if (status === 1) return new SudoAuthError();
|
|
5519
|
-
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
5520
|
-
const custom = codeMessages?.[status];
|
|
5521
|
-
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
5599
|
+
writeMihomoConfig(buildResult.config);
|
|
5600
|
+
return prepared.info;
|
|
5522
5601
|
}
|
|
5523
|
-
function
|
|
5524
|
-
|
|
5602
|
+
function needsAutoUpdate(sub) {
|
|
5603
|
+
if (!sub.updated_at) return true;
|
|
5604
|
+
const lastUpdate = new Date(sub.updated_at).getTime();
|
|
5605
|
+
if (Number.isNaN(lastUpdate)) return true;
|
|
5606
|
+
if (lastUpdate > Date.now()) return true;
|
|
5607
|
+
const intervalHours = resolveUpdateInterval(sub.update_interval);
|
|
5608
|
+
const intervalMs = intervalHours * 60 * 60 * 1e3;
|
|
5609
|
+
return Date.now() - lastUpdate > intervalMs;
|
|
5525
5610
|
}
|
|
5526
|
-
function
|
|
5527
|
-
if (!process.stdin.isTTY) {
|
|
5528
|
-
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");
|
|
5529
|
-
}
|
|
5530
|
-
ensureDirs();
|
|
5531
|
-
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
5532
|
-
fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
5533
|
-
fs10.chmodSync(scriptPath, 448);
|
|
5611
|
+
async function tryUpdateOne(sub, signal) {
|
|
5534
5612
|
try {
|
|
5535
|
-
const
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5539
|
-
}
|
|
5540
|
-
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
5541
|
-
} finally {
|
|
5542
|
-
try {
|
|
5543
|
-
fs10.unlinkSync(scriptPath);
|
|
5544
|
-
} catch {
|
|
5545
|
-
}
|
|
5613
|
+
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
5614
|
+
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
5615
|
+
} catch (e) {
|
|
5616
|
+
return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
|
|
5546
5617
|
}
|
|
5547
5618
|
}
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
|
|
5555
|
-
rmrf(DIRS.runtime);
|
|
5619
|
+
function printUpdateResult(r) {
|
|
5620
|
+
if (r.success) {
|
|
5621
|
+
console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
|
|
5622
|
+
} else if (r.aborted) {
|
|
5623
|
+
console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
|
|
5624
|
+
} else {
|
|
5625
|
+
console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
|
|
5556
5626
|
}
|
|
5557
|
-
ensureDirs();
|
|
5558
5627
|
}
|
|
5559
|
-
function
|
|
5560
|
-
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
|
|
5565
|
-
console.log(MANUAL_PKILL_HINT);
|
|
5566
|
-
}
|
|
5567
|
-
function warnPidCleanupFailed(err) {
|
|
5568
|
-
if (!err) return;
|
|
5569
|
-
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
5570
|
-
}
|
|
5571
|
-
function clearPid() {
|
|
5572
|
-
try {
|
|
5573
|
-
fs11.unlinkSync(PATHS.pidFile);
|
|
5574
|
-
return null;
|
|
5575
|
-
} catch (e) {
|
|
5576
|
-
if (e.code === "ENOENT") return null;
|
|
5577
|
-
return e;
|
|
5628
|
+
async function autoUpdateStaleSubscription(options = {}) {
|
|
5629
|
+
const allSubs = getSubscriptionsWithCache();
|
|
5630
|
+
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
5631
|
+
if (staleSubs.length === 0) {
|
|
5632
|
+
return;
|
|
5578
5633
|
}
|
|
5579
|
-
|
|
5580
|
-
|
|
5634
|
+
if (staleSubs.length === 1) {
|
|
5635
|
+
const sub = staleSubs[0];
|
|
5636
|
+
const interval = resolveUpdateInterval(sub.update_interval);
|
|
5637
|
+
console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
|
|
5638
|
+
} else {
|
|
5639
|
+
console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
|
|
5640
|
+
}
|
|
5641
|
+
const timeoutMs = options.timeout ?? DEFAULT_AUTO_UPDATE_TIMEOUT;
|
|
5642
|
+
const controller = new AbortController();
|
|
5643
|
+
const results = [];
|
|
5644
|
+
const updatePromise = Promise.all(
|
|
5645
|
+
staleSubs.map(
|
|
5646
|
+
(sub) => tryUpdateOne(sub, controller.signal).then((r) => {
|
|
5647
|
+
results.push(r);
|
|
5648
|
+
return r;
|
|
5649
|
+
})
|
|
5650
|
+
)
|
|
5651
|
+
);
|
|
5581
5652
|
try {
|
|
5582
|
-
|
|
5583
|
-
return true;
|
|
5653
|
+
await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
|
|
5584
5654
|
} catch (e) {
|
|
5585
|
-
|
|
5655
|
+
if (!(e instanceof TimeoutError)) throw e;
|
|
5656
|
+
controller.abort();
|
|
5657
|
+
await updatePromise.catch(() => {
|
|
5658
|
+
});
|
|
5659
|
+
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
5660
|
+
}
|
|
5661
|
+
for (const r of results) {
|
|
5662
|
+
printUpdateResult(r);
|
|
5586
5663
|
}
|
|
5587
5664
|
}
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
|
|
5591
|
-
|
|
5665
|
+
|
|
5666
|
+
// src/commands/config.ts
|
|
5667
|
+
function cmdConfig(args = []) {
|
|
5668
|
+
assertKnownFlags(args.slice(1), ["-j", "--json", "--reveal"], "config [--json] [--reveal]");
|
|
5669
|
+
assertPositionalCount(args, 0, 1, "mihomo-cli config [--json] [--reveal]");
|
|
5670
|
+
const asJson = hasFlag(args, "-j", "--json");
|
|
5671
|
+
const reveal = hasFlag(args, "--reveal");
|
|
5672
|
+
const active = getActiveSubscription();
|
|
5673
|
+
if (!active) {
|
|
5674
|
+
throw noSubscriptionsError();
|
|
5675
|
+
}
|
|
5676
|
+
const rawContent = requireSubscriptionRawConfig(active.name);
|
|
5677
|
+
const mode = deriveRuntimeMode(getConfigInfo());
|
|
5678
|
+
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
5679
|
+
const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
|
|
5680
|
+
const shown = redacted.config;
|
|
5681
|
+
if (asJson) {
|
|
5682
|
+
console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
|
|
5683
|
+
return;
|
|
5684
|
+
}
|
|
5685
|
+
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
5686
|
+
console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
|
|
5687
|
+
if (!reveal && redacted.changed) {
|
|
5688
|
+
console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
|
|
5689
|
+
}
|
|
5690
|
+
console.log("");
|
|
5691
|
+
console.log(dumpYaml(shown).trimEnd());
|
|
5692
|
+
if (warnings.length > 0) {
|
|
5693
|
+
console.log("");
|
|
5694
|
+
for (const w of warnings) console.log(colors.yellow(`# ${w}`));
|
|
5592
5695
|
}
|
|
5593
5696
|
}
|
|
5594
|
-
|
|
5697
|
+
|
|
5698
|
+
// src/open.ts
|
|
5699
|
+
import { spawn } from "child_process";
|
|
5700
|
+
|
|
5701
|
+
// src/lifecycle.ts
|
|
5702
|
+
var silentSigint = false;
|
|
5703
|
+
function setSilentSigint(value) {
|
|
5704
|
+
silentSigint = value;
|
|
5705
|
+
}
|
|
5706
|
+
function isSilentSigint() {
|
|
5707
|
+
return silentSigint;
|
|
5708
|
+
}
|
|
5709
|
+
|
|
5710
|
+
// src/open.ts
|
|
5711
|
+
function openUrl(url) {
|
|
5595
5712
|
try {
|
|
5596
|
-
|
|
5597
|
-
|
|
5713
|
+
const child = spawn("open", ["--", url], { stdio: "ignore", detached: true });
|
|
5714
|
+
child.unref();
|
|
5715
|
+
child.on("error", () => {
|
|
5716
|
+
});
|
|
5598
5717
|
} catch {
|
|
5599
|
-
return false;
|
|
5600
5718
|
}
|
|
5601
5719
|
}
|
|
5602
|
-
function
|
|
5603
|
-
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
|
|
5720
|
+
function viewLogWithTail(logPath, options) {
|
|
5721
|
+
const follow = options?.follow;
|
|
5722
|
+
const lines = options?.lines || 100;
|
|
5723
|
+
console.log(`\u65E5\u5FD7: ${logPath}`);
|
|
5724
|
+
if (follow) {
|
|
5725
|
+
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
5726
|
+
} else {
|
|
5727
|
+
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
5728
|
+
`);
|
|
5609
5729
|
}
|
|
5730
|
+
const tailArgs = [];
|
|
5731
|
+
if (follow) tailArgs.push("-f");
|
|
5732
|
+
tailArgs.push("-n", lines.toString());
|
|
5733
|
+
tailArgs.push(logPath);
|
|
5734
|
+
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5735
|
+
if (follow) setSilentSigint(true);
|
|
5736
|
+
tail.on("close", (code) => process.exit(code ?? 0));
|
|
5737
|
+
tail.on("error", (e) => {
|
|
5738
|
+
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5739
|
+
process.exit(1);
|
|
5740
|
+
});
|
|
5610
5741
|
}
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5742
|
+
|
|
5743
|
+
// src/commands/shared.ts
|
|
5744
|
+
import readline from "readline";
|
|
5745
|
+
|
|
5746
|
+
// src/log-files.ts
|
|
5747
|
+
import fs6 from "fs";
|
|
5748
|
+
import path5 from "path";
|
|
5749
|
+
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5750
|
+
var LOG_TAIL_LINES = 15;
|
|
5751
|
+
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5752
|
+
function isArchiveLogFilename(filename) {
|
|
5753
|
+
return ARCHIVE_LOG_RE.test(filename);
|
|
5621
5754
|
}
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5755
|
+
function rotateAndCleanupLogs() {
|
|
5756
|
+
rotateLog();
|
|
5757
|
+
cleanupOldLogs();
|
|
5758
|
+
}
|
|
5759
|
+
function readLogTail() {
|
|
5760
|
+
const TAIL_BYTES = 64 * 1024;
|
|
5761
|
+
let fd = null;
|
|
5762
|
+
try {
|
|
5763
|
+
const size = fs6.statSync(PATHS.logFile).size;
|
|
5764
|
+
if (size === 0) return [];
|
|
5765
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
5766
|
+
const length = size - start;
|
|
5767
|
+
const buf = Buffer.alloc(length);
|
|
5768
|
+
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5769
|
+
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5770
|
+
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5771
|
+
} catch {
|
|
5772
|
+
return [];
|
|
5773
|
+
} finally {
|
|
5774
|
+
if (fd !== null) {
|
|
5775
|
+
try {
|
|
5776
|
+
fs6.closeSync(fd);
|
|
5777
|
+
} catch {
|
|
5778
|
+
}
|
|
5779
|
+
}
|
|
5626
5780
|
}
|
|
5627
|
-
|
|
5628
|
-
|
|
5629
|
-
|
|
5630
|
-
const
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5781
|
+
}
|
|
5782
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5783
|
+
function allocateArchivePath() {
|
|
5784
|
+
const timestamp = formatLocalTimestamp();
|
|
5785
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5786
|
+
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
5787
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
5788
|
+
let fd = null;
|
|
5634
5789
|
try {
|
|
5635
|
-
|
|
5636
|
-
action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
|
|
5637
|
-
file: "cleanup-residue.sh",
|
|
5638
|
-
codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
|
|
5639
|
-
});
|
|
5640
|
-
killedCount = pids.length;
|
|
5790
|
+
fd = fs6.openSync(archivePath, "wx");
|
|
5641
5791
|
} catch (e) {
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
} else if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
5645
|
-
if (killAllMihomo()) {
|
|
5646
|
-
killedCount = pids.length;
|
|
5647
|
-
} else {
|
|
5648
|
-
failedPids.push(...pids);
|
|
5792
|
+
if (e.code === "EEXIST") continue;
|
|
5793
|
+
throw e;
|
|
5649
5794
|
}
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
if (!probed || !isProbedMihomo(probed)) {
|
|
5654
|
-
killedCount++;
|
|
5655
|
-
continue;
|
|
5656
|
-
}
|
|
5657
|
-
if (killProcess(pid)) {
|
|
5658
|
-
killedCount++;
|
|
5659
|
-
} else {
|
|
5660
|
-
failedPids.push(pid);
|
|
5661
|
-
}
|
|
5795
|
+
try {
|
|
5796
|
+
fs6.closeSync(fd);
|
|
5797
|
+
} catch {
|
|
5662
5798
|
}
|
|
5799
|
+
return archivePath;
|
|
5663
5800
|
}
|
|
5664
|
-
|
|
5665
|
-
|
|
5666
|
-
|
|
5667
|
-
|
|
5801
|
+
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`, {
|
|
5802
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
5803
|
+
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`]
|
|
5804
|
+
});
|
|
5668
5805
|
}
|
|
5669
|
-
function
|
|
5670
|
-
const
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
5675
|
-
|
|
5676
|
-
|
|
5677
|
-
|
|
5806
|
+
function rotateLog() {
|
|
5807
|
+
const logFile = PATHS.logFile;
|
|
5808
|
+
let stat;
|
|
5809
|
+
try {
|
|
5810
|
+
stat = fs6.statSync(logFile);
|
|
5811
|
+
} catch (e) {
|
|
5812
|
+
if (e.code === "ENOENT") return;
|
|
5813
|
+
throw e;
|
|
5814
|
+
}
|
|
5815
|
+
if (stat.size === 0) return;
|
|
5816
|
+
const rotatedPath = allocateArchivePath();
|
|
5817
|
+
try {
|
|
5818
|
+
fs6.renameSync(logFile, rotatedPath);
|
|
5819
|
+
} catch (e) {
|
|
5820
|
+
try {
|
|
5821
|
+
fs6.unlinkSync(rotatedPath);
|
|
5822
|
+
} catch {
|
|
5823
|
+
}
|
|
5824
|
+
if (e.code === "ENOENT") return;
|
|
5825
|
+
throw e;
|
|
5678
5826
|
}
|
|
5679
|
-
return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5680
|
-
}
|
|
5681
|
-
function classifyResidueCleanup(result) {
|
|
5682
|
-
if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
|
|
5683
|
-
return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
|
|
5684
5827
|
}
|
|
5685
|
-
function
|
|
5686
|
-
const
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
const
|
|
5692
|
-
|
|
5693
|
-
if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
|
|
5694
|
-
if (verdict === "warn") warnResidueCleanup(result, ctx);
|
|
5695
|
-
return result;
|
|
5696
|
-
}
|
|
5697
|
-
async function stop() {
|
|
5698
|
-
const allPids = getMihomoPids();
|
|
5699
|
-
if (allPids.length === 0) {
|
|
5700
|
-
warnPidCleanupFailed(clearPid());
|
|
5701
|
-
clearRuntime();
|
|
5702
|
-
return {};
|
|
5703
|
-
}
|
|
5704
|
-
const result = await cleanupAll();
|
|
5705
|
-
if (result.remaining.length === 0) {
|
|
5706
|
-
warnPidCleanupFailed(result.pidError);
|
|
5707
|
-
if (result.scriptError) {
|
|
5708
|
-
console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
|
|
5709
|
-
}
|
|
5710
|
-
}
|
|
5711
|
-
const remaining = result.remaining;
|
|
5712
|
-
if (remaining.length > 0) {
|
|
5713
|
-
console.log("");
|
|
5714
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5715
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5716
|
-
console.log(MANUAL_PKILL_HINT);
|
|
5717
|
-
console.log("");
|
|
5718
|
-
return { remaining };
|
|
5719
|
-
}
|
|
5720
|
-
clearRuntime();
|
|
5721
|
-
return {};
|
|
5722
|
-
}
|
|
5723
|
-
|
|
5724
|
-
// src/service.ts
|
|
5725
|
-
var SERVICE_HEALTH_INTERVAL_MS = 100;
|
|
5726
|
-
var SERVICE_OBSERVE_MS = 1200;
|
|
5727
|
-
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
5728
|
-
async function waitServiceHealthy() {
|
|
5729
|
-
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
5730
|
-
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
5731
|
-
let last = null;
|
|
5732
|
-
const unhealthy = (state, crashed, pid = null) => ({
|
|
5733
|
-
healthy: false,
|
|
5734
|
-
crashed,
|
|
5735
|
-
pid,
|
|
5736
|
-
exitCode: state.lastExitCode,
|
|
5737
|
-
terminatingSignal: state.lastTerminatingSignal
|
|
5738
|
-
});
|
|
5739
|
-
do {
|
|
5740
|
-
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5828
|
+
function cleanupOldLogs() {
|
|
5829
|
+
const logsDir = DIRS.logs;
|
|
5830
|
+
if (!fs6.existsSync(logsDir)) return;
|
|
5831
|
+
const files = fs6.readdirSync(logsDir);
|
|
5832
|
+
const now = Date.now();
|
|
5833
|
+
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5834
|
+
for (const file of files) {
|
|
5835
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
5741
5836
|
try {
|
|
5742
|
-
|
|
5837
|
+
const filePath = path5.join(logsDir, file);
|
|
5838
|
+
const stat = fs6.statSync(filePath);
|
|
5839
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5840
|
+
fs6.unlinkSync(filePath);
|
|
5841
|
+
}
|
|
5743
5842
|
} catch {
|
|
5744
|
-
continue;
|
|
5745
5843
|
}
|
|
5746
|
-
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5844
|
+
}
|
|
5845
|
+
}
|
|
5846
|
+
function listLogs() {
|
|
5847
|
+
const logsDir = DIRS.logs;
|
|
5848
|
+
const result = { current: null, archives: [] };
|
|
5849
|
+
if (fs6.existsSync(PATHS.logFile)) {
|
|
5850
|
+
const stat = fs6.statSync(PATHS.logFile);
|
|
5851
|
+
result.current = {
|
|
5852
|
+
name: "mihomo.log (\u5F53\u524D)",
|
|
5853
|
+
path: PATHS.logFile,
|
|
5854
|
+
size: stat.size,
|
|
5855
|
+
mtime: stat.mtime,
|
|
5856
|
+
isCurrent: true
|
|
5857
|
+
};
|
|
5858
|
+
}
|
|
5859
|
+
if (!fs6.existsSync(logsDir)) return result;
|
|
5860
|
+
const files = fs6.readdirSync(logsDir);
|
|
5861
|
+
for (const file of files) {
|
|
5862
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
5758
5863
|
try {
|
|
5759
|
-
|
|
5864
|
+
const filePath = path5.join(logsDir, file);
|
|
5865
|
+
const stat = fs6.statSync(filePath);
|
|
5866
|
+
result.archives.push({
|
|
5867
|
+
name: file,
|
|
5868
|
+
path: filePath,
|
|
5869
|
+
size: stat.size,
|
|
5870
|
+
mtime: stat.mtime,
|
|
5871
|
+
isCurrent: false
|
|
5872
|
+
});
|
|
5760
5873
|
} catch {
|
|
5761
|
-
continue;
|
|
5762
|
-
}
|
|
5763
|
-
graceQueried = true;
|
|
5764
|
-
if (isCrashed(last)) {
|
|
5765
|
-
return unhealthy(last, true);
|
|
5766
5874
|
}
|
|
5767
|
-
if (!last.loaded) break;
|
|
5768
|
-
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
5769
5875
|
}
|
|
5770
|
-
|
|
5771
|
-
return
|
|
5876
|
+
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
5877
|
+
return result;
|
|
5772
5878
|
}
|
|
5773
|
-
|
|
5879
|
+
|
|
5880
|
+
// src/process-probe.ts
|
|
5881
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
5882
|
+
import fs7 from "fs";
|
|
5883
|
+
var PS_TIMEOUT_MS = 5e3;
|
|
5884
|
+
var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
|
|
5885
|
+
function probeProcess(pid) {
|
|
5886
|
+
if (!pid) return NOT_RUNNING;
|
|
5774
5887
|
try {
|
|
5775
|
-
const
|
|
5776
|
-
|
|
5888
|
+
const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
|
|
5889
|
+
encoding: "utf8",
|
|
5890
|
+
timeout: PS_TIMEOUT_MS
|
|
5891
|
+
});
|
|
5892
|
+
const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|
|
5893
|
+
if (!match) return NOT_RUNNING;
|
|
5894
|
+
return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
|
|
5777
5895
|
} catch {
|
|
5896
|
+
return NOT_RUNNING;
|
|
5778
5897
|
}
|
|
5779
|
-
return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
|
|
5780
5898
|
}
|
|
5781
|
-
function
|
|
5782
|
-
|
|
5783
|
-
if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
|
|
5784
|
-
return null;
|
|
5899
|
+
function isProbedMihomo(p) {
|
|
5900
|
+
return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
|
|
5785
5901
|
}
|
|
5786
|
-
|
|
5787
|
-
|
|
5788
|
-
|
|
5902
|
+
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
5903
|
+
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
5904
|
+
function getPid() {
|
|
5905
|
+
if (!fs7.existsSync(PATHS.pidFile)) return null;
|
|
5906
|
+
try {
|
|
5907
|
+
const pid = parseInt(fs7.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
5908
|
+
return pid > 0 ? pid : null;
|
|
5909
|
+
} catch {
|
|
5910
|
+
return null;
|
|
5911
|
+
}
|
|
5789
5912
|
}
|
|
5790
|
-
function
|
|
5791
|
-
|
|
5913
|
+
function isRunning() {
|
|
5914
|
+
const pid = getPid();
|
|
5915
|
+
if (!pid) return false;
|
|
5916
|
+
return isMihomoProcess(pid);
|
|
5792
5917
|
}
|
|
5793
|
-
function
|
|
5794
|
-
return
|
|
5918
|
+
function isMihomoProcess(pid) {
|
|
5919
|
+
return isProbedMihomo(probeProcess(pid));
|
|
5795
5920
|
}
|
|
5796
|
-
function
|
|
5797
|
-
|
|
5798
|
-
|
|
5799
|
-
|
|
5921
|
+
function getMihomoPids() {
|
|
5922
|
+
const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
|
|
5923
|
+
if (result.error || result.status === null) {
|
|
5924
|
+
throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
|
|
5925
|
+
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
|
|
5926
|
+
});
|
|
5927
|
+
}
|
|
5928
|
+
if (result.status !== 0 && result.status !== 1) {
|
|
5929
|
+
throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
|
|
5930
|
+
hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
|
|
5931
|
+
});
|
|
5932
|
+
}
|
|
5933
|
+
return parsePidList(result.stdout);
|
|
5800
5934
|
}
|
|
5801
|
-
function
|
|
5802
|
-
|
|
5803
|
-
|
|
5804
|
-
|
|
5935
|
+
function parsePidList(stdout) {
|
|
5936
|
+
const output = stdout.trim();
|
|
5937
|
+
if (!output) return [];
|
|
5938
|
+
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
5805
5939
|
}
|
|
5806
|
-
function
|
|
5807
|
-
|
|
5940
|
+
function isPidFileOwnedByRoot() {
|
|
5941
|
+
if (!fs7.existsSync(PATHS.pidFile)) return false;
|
|
5808
5942
|
try {
|
|
5809
|
-
const
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
const code = e.code;
|
|
5814
|
-
if (code === "EINVAL") {
|
|
5815
|
-
try {
|
|
5816
|
-
fs12.unlinkSync(PATHS.serviceBinary);
|
|
5817
|
-
} catch {
|
|
5818
|
-
}
|
|
5819
|
-
} else if (code !== "ENOENT") {
|
|
5820
|
-
throw e;
|
|
5821
|
-
}
|
|
5943
|
+
const stat = fs7.statSync(PATHS.pidFile);
|
|
5944
|
+
return stat.uid === 0;
|
|
5945
|
+
} catch {
|
|
5946
|
+
return false;
|
|
5822
5947
|
}
|
|
5948
|
+
}
|
|
5949
|
+
function getStatus() {
|
|
5950
|
+
const pid = getPid();
|
|
5951
|
+
if (!pid) return { running: false, pid: null, memory: null };
|
|
5952
|
+
const p = probeProcess(pid);
|
|
5953
|
+
if (!isProbedMihomo(p)) return { running: false, pid: null, memory: null };
|
|
5954
|
+
return {
|
|
5955
|
+
running: true,
|
|
5956
|
+
pid,
|
|
5957
|
+
memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5"
|
|
5958
|
+
};
|
|
5959
|
+
}
|
|
5960
|
+
|
|
5961
|
+
// src/process-start.ts
|
|
5962
|
+
import fs13 from "fs";
|
|
5963
|
+
|
|
5964
|
+
// src/service.ts
|
|
5965
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
5966
|
+
import fs12 from "fs";
|
|
5967
|
+
import path7 from "path";
|
|
5968
|
+
|
|
5969
|
+
// src/hot-reload.ts
|
|
5970
|
+
import fs9 from "fs";
|
|
5971
|
+
|
|
5972
|
+
// src/proxy-probe.ts
|
|
5973
|
+
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
5974
|
+
import { promisify as promisify2 } from "util";
|
|
5975
|
+
|
|
5976
|
+
// src/curl-spawn.ts
|
|
5977
|
+
function buildCurlSpawnEnv() {
|
|
5978
|
+
const env = { ...process.env };
|
|
5979
|
+
env.no_proxy = "";
|
|
5980
|
+
env.NO_PROXY = "";
|
|
5981
|
+
return env;
|
|
5982
|
+
}
|
|
5983
|
+
|
|
5984
|
+
// src/proxy-probe.ts
|
|
5985
|
+
var execFileAsync = promisify2(execFile2);
|
|
5986
|
+
function lsofListenPids(port) {
|
|
5823
5987
|
try {
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
|
|
5828
|
-
|
|
5829
|
-
existing = fs12.readlinkSync(PATHS.serviceBinary);
|
|
5830
|
-
} catch {
|
|
5831
|
-
throw e;
|
|
5832
|
-
}
|
|
5833
|
-
if (existing !== "mihomo") throw e;
|
|
5988
|
+
const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5989
|
+
if (r.status !== 0) return null;
|
|
5990
|
+
return parsePidList(r.stdout);
|
|
5991
|
+
} catch {
|
|
5992
|
+
return null;
|
|
5834
5993
|
}
|
|
5835
5994
|
}
|
|
5836
|
-
|
|
5837
|
-
|
|
5838
|
-
|
|
5839
|
-
if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
|
|
5840
|
-
const detail = result.stderr.trim();
|
|
5841
|
-
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
5842
|
-
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
5843
|
-
});
|
|
5844
|
-
}
|
|
5845
|
-
function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5846
|
-
const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
|
|
5847
|
-
if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
|
|
5848
|
-
const detail = result.stderr.trim();
|
|
5849
|
-
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
5850
|
-
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
5851
|
-
});
|
|
5995
|
+
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
5996
|
+
function isProbeSuccessStatus(code) {
|
|
5997
|
+
return code !== null && code >= 200 && code < 300;
|
|
5852
5998
|
}
|
|
5853
|
-
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
ensureServiceSymlink();
|
|
5857
|
-
let restoreSkipped = false;
|
|
5858
|
-
const stagePath = PATHS.servicePlistStage;
|
|
5859
|
-
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5999
|
+
var PROBE_TIMEOUT_MS = 2e3;
|
|
6000
|
+
async function probeProxyConnectivity(port) {
|
|
6001
|
+
const start = Date.now();
|
|
5860
6002
|
try {
|
|
5861
|
-
const
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
fs12.unlinkSync(stagePath);
|
|
5884
|
-
} catch {
|
|
5885
|
-
}
|
|
5886
|
-
}
|
|
5887
|
-
if (!wasRunning) {
|
|
5888
|
-
disableServiceAutoStart();
|
|
6003
|
+
const { stdout } = await execFileAsync(
|
|
6004
|
+
"curl",
|
|
6005
|
+
["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6006
|
+
{
|
|
6007
|
+
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6008
|
+
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
6009
|
+
env: buildCurlSpawnEnv()
|
|
6010
|
+
}
|
|
6011
|
+
);
|
|
6012
|
+
const code = Number.parseInt(stdout.trim(), 10);
|
|
6013
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
6014
|
+
const ok = isProbeSuccessStatus(statusCode);
|
|
6015
|
+
return {
|
|
6016
|
+
ok,
|
|
6017
|
+
statusCode,
|
|
6018
|
+
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6019
|
+
durationMs: Date.now() - start
|
|
6020
|
+
};
|
|
6021
|
+
} catch (e) {
|
|
6022
|
+
const err = e;
|
|
6023
|
+
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6024
|
+
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
5889
6025
|
}
|
|
5890
|
-
return { restoreSkipped };
|
|
5891
6026
|
}
|
|
5892
|
-
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
hint: [
|
|
5902
|
-
"\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
|
|
5903
|
-
"\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
|
|
5904
|
-
"",
|
|
5905
|
-
"\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
|
|
5906
|
-
"\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
|
|
5907
|
-
]
|
|
5908
|
-
});
|
|
6027
|
+
|
|
6028
|
+
// src/stop-epoch.ts
|
|
6029
|
+
import fs8 from "fs";
|
|
6030
|
+
function readStopEpoch() {
|
|
6031
|
+
try {
|
|
6032
|
+
const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
6033
|
+
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
6034
|
+
} catch {
|
|
6035
|
+
return 0;
|
|
5909
6036
|
}
|
|
5910
|
-
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
|
|
5911
|
-
bootoutService();
|
|
5912
|
-
await waitUntilUnloaded();
|
|
5913
|
-
rotateAndCleanupLogs();
|
|
5914
|
-
let started = true;
|
|
5915
|
-
withFileLock(PATHS.serviceLock, () => {
|
|
5916
|
-
if (startAbortedByConcurrentStop()) {
|
|
5917
|
-
started = false;
|
|
5918
|
-
return;
|
|
5919
|
-
}
|
|
5920
|
-
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5921
|
-
bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
|
|
5922
|
-
});
|
|
5923
|
-
return { started };
|
|
5924
6037
|
}
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
6038
|
+
var stopEpochBaselineCaptured = null;
|
|
6039
|
+
function captureStopEpochBaseline() {
|
|
6040
|
+
stopEpochBaselineCaptured = readStopEpoch();
|
|
6041
|
+
return stopEpochBaselineCaptured;
|
|
6042
|
+
}
|
|
6043
|
+
function stopEpochBaseline() {
|
|
6044
|
+
return stopEpochBaselineCaptured ?? readStopEpoch();
|
|
6045
|
+
}
|
|
6046
|
+
function bumpStopEpoch() {
|
|
6047
|
+
try {
|
|
6048
|
+
ensureDirs();
|
|
6049
|
+
atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
|
|
6050
|
+
} catch {
|
|
5932
6051
|
}
|
|
6052
|
+
}
|
|
6053
|
+
function recordServiceStopped() {
|
|
5933
6054
|
bumpStopEpoch();
|
|
5934
6055
|
}
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5938
|
-
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5939
|
-
});
|
|
5940
|
-
await waitUntilUnloaded();
|
|
6056
|
+
function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
|
|
6057
|
+
return stopEpochNow !== stopEpochBefore;
|
|
5941
6058
|
}
|
|
5942
|
-
|
|
5943
|
-
|
|
5944
|
-
await bootoutAndDisableInLock();
|
|
5945
|
-
return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
|
|
6059
|
+
function startAbortedByConcurrentStop() {
|
|
6060
|
+
return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
|
|
5946
6061
|
}
|
|
5947
|
-
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
} catch (e) {
|
|
5953
|
-
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5954
|
-
}
|
|
5955
|
-
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6062
|
+
|
|
6063
|
+
// src/hot-reload.ts
|
|
6064
|
+
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
6065
|
+
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6066
|
+
function logOversized() {
|
|
5956
6067
|
try {
|
|
5957
|
-
|
|
6068
|
+
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5958
6069
|
} catch {
|
|
6070
|
+
return false;
|
|
5959
6071
|
}
|
|
5960
|
-
return cleanup;
|
|
5961
6072
|
}
|
|
5962
|
-
async function
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
const
|
|
6073
|
+
async function tryHotReload(prefetched) {
|
|
6074
|
+
const controller = new AbortController();
|
|
6075
|
+
try {
|
|
6076
|
+
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6077
|
+
if (!status.running || status.pid === null) return false;
|
|
6078
|
+
const endpoint = getControllerEndpoint();
|
|
6079
|
+
if (endpoint.port === null) return false;
|
|
6080
|
+
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6081
|
+
const headers = { "Content-Type": "application/json" };
|
|
6082
|
+
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6083
|
+
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
5973
6084
|
try {
|
|
5974
|
-
|
|
5975
|
-
|
|
5976
|
-
|
|
6085
|
+
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6086
|
+
if (!probe.ok) return false;
|
|
6087
|
+
const info = await probe.json();
|
|
6088
|
+
if (typeof info?.version !== "string") return false;
|
|
6089
|
+
const listenerPids = lsofListenPids(endpoint.port);
|
|
6090
|
+
if (listenerPids === null || listenerPids[0] !== status.pid) return false;
|
|
6091
|
+
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6092
|
+
method: "PUT",
|
|
6093
|
+
headers,
|
|
6094
|
+
body: "{}",
|
|
6095
|
+
signal: controller.signal
|
|
6096
|
+
});
|
|
6097
|
+
return res.ok;
|
|
6098
|
+
} finally {
|
|
6099
|
+
clearTimeout(timer);
|
|
5977
6100
|
}
|
|
6101
|
+
} catch {
|
|
6102
|
+
return false;
|
|
5978
6103
|
}
|
|
5979
|
-
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
5980
|
-
let started = true;
|
|
5981
|
-
if (kick.status !== 0) {
|
|
5982
|
-
withFileLock(PATHS.serviceLock, () => {
|
|
5983
|
-
if (startAbortedByConcurrentStop()) {
|
|
5984
|
-
started = false;
|
|
5985
|
-
return;
|
|
5986
|
-
}
|
|
5987
|
-
runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5988
|
-
bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
|
|
5989
|
-
});
|
|
5990
|
-
if (!started) return { hotReloaded: false, started: false };
|
|
5991
|
-
}
|
|
5992
|
-
cleanupOldLogs();
|
|
5993
|
-
return { hotReloaded: false, started: true };
|
|
5994
6104
|
}
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
function levenshtein(a, b) {
|
|
5998
|
-
if (a === b) return 0;
|
|
5999
|
-
if (a.length === 0) return b.length;
|
|
6000
|
-
if (b.length === 0) return a.length;
|
|
6001
|
-
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
6002
|
-
for (let i = 1; i <= a.length; i++) {
|
|
6003
|
-
const curr = [i];
|
|
6004
|
-
for (let j = 1; j <= b.length; j++) {
|
|
6005
|
-
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
6006
|
-
}
|
|
6007
|
-
prev = curr;
|
|
6008
|
-
}
|
|
6009
|
-
return prev[b.length];
|
|
6105
|
+
function concludeHotReload(stopEpochBefore, stopEpochNow) {
|
|
6106
|
+
return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
|
|
6010
6107
|
}
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6108
|
+
|
|
6109
|
+
// src/process-stop.ts
|
|
6110
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6111
|
+
import fs11 from "fs";
|
|
6112
|
+
|
|
6113
|
+
// src/sudo.ts
|
|
6114
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
6115
|
+
import fs10 from "fs";
|
|
6116
|
+
import path6 from "path";
|
|
6117
|
+
var SUDO_TIMEOUT_MS = 6e4;
|
|
6118
|
+
var SudoAuthError = class extends Error {
|
|
6119
|
+
constructor() {
|
|
6120
|
+
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
6121
|
+
this.name = "SudoAuthError";
|
|
6122
|
+
}
|
|
6123
|
+
};
|
|
6124
|
+
function describeSudoFailure(e) {
|
|
6125
|
+
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
6126
|
+
}
|
|
6127
|
+
function sudoExitToError(action, status, codeMessages) {
|
|
6128
|
+
if (status === 1) return new SudoAuthError();
|
|
6129
|
+
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
6130
|
+
const custom = codeMessages?.[status];
|
|
6131
|
+
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
6132
|
+
}
|
|
6133
|
+
function sudoTimeoutError(action) {
|
|
6134
|
+
return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
|
|
6135
|
+
}
|
|
6136
|
+
function runSudoScript(scriptBody, opts) {
|
|
6137
|
+
if (!process.stdin.isTTY) {
|
|
6138
|
+
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");
|
|
6139
|
+
}
|
|
6140
|
+
ensureDirs();
|
|
6141
|
+
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
6142
|
+
fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
6143
|
+
fs10.chmodSync(scriptPath, 448);
|
|
6144
|
+
try {
|
|
6145
|
+
const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
6146
|
+
if (result.error) {
|
|
6147
|
+
if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
|
|
6148
|
+
throw result.error;
|
|
6149
|
+
}
|
|
6150
|
+
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
6151
|
+
} finally {
|
|
6152
|
+
try {
|
|
6153
|
+
fs10.unlinkSync(scriptPath);
|
|
6154
|
+
} catch {
|
|
6023
6155
|
}
|
|
6024
6156
|
}
|
|
6025
|
-
scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
|
|
6026
|
-
return scored.slice(0, 3).map((s) => s.name);
|
|
6027
6157
|
}
|
|
6028
6158
|
|
|
6029
|
-
// src/
|
|
6030
|
-
|
|
6031
|
-
|
|
6032
|
-
|
|
6033
|
-
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
|
|
6037
|
-
if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
|
|
6038
|
-
if (steps.length > 0) {
|
|
6039
|
-
steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
|
|
6040
|
-
const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
|
|
6041
|
-
console.log("\u5F00\u59CB\u4F7F\u7528:");
|
|
6042
|
-
steps.forEach(([cmd, desc], i) => {
|
|
6043
|
-
console.log(` ${i + 1}. ${colors.bold(padEndDisplay(cmd, width))} ${colors.gray(`# ${desc}`)}`);
|
|
6044
|
-
});
|
|
6045
|
-
console.log("");
|
|
6046
|
-
return;
|
|
6159
|
+
// src/process-stop.ts
|
|
6160
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6161
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
6162
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
6163
|
+
function clearRuntime() {
|
|
6164
|
+
if (fs11.existsSync(DIRS.runtime)) {
|
|
6165
|
+
rmrf(DIRS.runtime);
|
|
6047
6166
|
}
|
|
6048
|
-
|
|
6049
|
-
`\u5E38\u7528\u547D\u4EE4:
|
|
6050
|
-
${colors.bold("start")} / ${colors.bold("stop")} \u542F\u52A8/\u505C\u6B62\u4EE3\u7406
|
|
6051
|
-
${colors.bold("sub")} [use|update] \u8BA2\u9605\u7BA1\u7406
|
|
6052
|
-
${colors.bold("ow")} [on|off] \u8986\u5199\u914D\u7F6E
|
|
6053
|
-
${colors.bold("ui")} [zash|dash|yacd] \u6253\u5F00 Web UI
|
|
6054
|
-
`
|
|
6055
|
-
);
|
|
6167
|
+
ensureDirs();
|
|
6056
6168
|
}
|
|
6057
|
-
|
|
6058
|
-
|
|
6059
|
-
|
|
6060
|
-
|
|
6061
|
-
|
|
6062
|
-
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
const meta = commands.filter((c) => c.group === "meta").flatMap((c) => c.usage);
|
|
6077
|
-
if (meta.length > 0) {
|
|
6078
|
-
lines.push("", colors.cyan("\u5143:"));
|
|
6079
|
-
for (const u of meta) lines.push(formatUsage(u));
|
|
6169
|
+
function describePidCleanupFailure(err) {
|
|
6170
|
+
return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
|
|
6171
|
+
}
|
|
6172
|
+
var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
|
|
6173
|
+
function printResidueWarning(remaining) {
|
|
6174
|
+
console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
|
|
6175
|
+
console.log(MANUAL_PKILL_HINT);
|
|
6176
|
+
}
|
|
6177
|
+
function warnPidCleanupFailed(err) {
|
|
6178
|
+
if (!err) return;
|
|
6179
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
6180
|
+
}
|
|
6181
|
+
function clearPid() {
|
|
6182
|
+
try {
|
|
6183
|
+
fs11.unlinkSync(PATHS.pidFile);
|
|
6184
|
+
return null;
|
|
6185
|
+
} catch (e) {
|
|
6186
|
+
if (e.code === "ENOENT") return null;
|
|
6187
|
+
return e;
|
|
6080
6188
|
}
|
|
6081
|
-
lines.push(
|
|
6082
|
-
"",
|
|
6083
|
-
`${colors.cyan("\u793A\u4F8B:")}`,
|
|
6084
|
-
// 顺序即首次使用的依赖顺序(kernel → 订阅 → 服务 → 启动):install 在无内核时会被
|
|
6085
|
-
// 拦下提示先跑 kernel,示例若把 install 放第一条,照着敲的新用户第一步就撞墙
|
|
6086
|
-
" mihomo-cli kernel # \u4E0B\u8F7D\u5185\u6838\uFF08\u9996\u6B21\u4F7F\u7528\u7684\u7B2C\u4E00\u6B65\uFF09",
|
|
6087
|
-
" mihomo-cli sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
6088
|
-
" mihomo-cli install # \u5B89\u88C5\u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u7684\u524D\u7F6E\uFF0C\u53EA\u9700\u4E00\u6B21\uFF09",
|
|
6089
|
-
" mihomo-cli start # \u542F\u52A8\u4EE3\u7406\u5E76\u5F00\u542F\u767B\u5F55\u81EA\u542F",
|
|
6090
|
-
" mihomo-cli stop # \u505C\u6B62\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F",
|
|
6091
|
-
" mihomo-cli start tun # \u4E34\u65F6 TUN \u900F\u660E\u4EE3\u7406\uFF08\u4E0D\u8D70\u670D\u52A1\uFF0C\u9700 sudo\uFF09",
|
|
6092
|
-
" mihomo-cli start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
6093
|
-
" mihomo-cli ui # \u6253\u5F00 Web UI",
|
|
6094
|
-
"",
|
|
6095
|
-
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
6096
|
-
" tun = start tun",
|
|
6097
|
-
" use <name> = subscription use <name>",
|
|
6098
|
-
" restart = start\uFF08start \u672C\u8EAB\u5373\u91CD\u542F\uFF09",
|
|
6099
|
-
"",
|
|
6100
|
-
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
6101
|
-
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)\uFF0C\u7531 launchd \u670D\u52A1\u6258\u7BA1\uFF0C\u5D29\u6E83/\u767B\u5F55\u81EA\u52A8\u62C9\u8D77",
|
|
6102
|
-
" tun \u900F\u660E\u4EE3\u7406\uFF0C\u5168\u5C40\u81EA\u52A8\u8DEF\u7531\uFF0C\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u9700\u8981 sudo",
|
|
6103
|
-
"",
|
|
6104
|
-
`${colors.cyan("\u6570\u636E\u76EE\u5F55:")}`,
|
|
6105
|
-
" \u73AF\u5883\u53D8\u91CF MIHOMO_CLI_DIR \u53EF\u81EA\u5B9A\u4E49\u4F4D\u7F6E",
|
|
6106
|
-
` \u9ED8\u8BA4: ${USER_DATA_DIR}`
|
|
6107
|
-
);
|
|
6108
|
-
console.log(lines.join("\n"));
|
|
6109
6189
|
}
|
|
6110
|
-
function
|
|
6111
|
-
|
|
6112
|
-
|
|
6113
|
-
|
|
6114
|
-
|
|
6115
|
-
|
|
6116
|
-
for (const u of command.usage) {
|
|
6117
|
-
lines.push(` ${colors.bold(padEndDisplay(u.signature, width))} ${u.description}`);
|
|
6118
|
-
}
|
|
6119
|
-
} else {
|
|
6120
|
-
lines.push("", colors.gray("\u5FEB\u6377\u547D\u4EE4\uFF0C\u5B8C\u6574\u7528\u6CD5\u89C1 mihomo-cli help"));
|
|
6190
|
+
function pidAlive(pid) {
|
|
6191
|
+
try {
|
|
6192
|
+
process.kill(pid, 0);
|
|
6193
|
+
return true;
|
|
6194
|
+
} catch (e) {
|
|
6195
|
+
return e.code !== "ESRCH";
|
|
6121
6196
|
}
|
|
6122
|
-
console.log(lines.join("\n"));
|
|
6123
6197
|
}
|
|
6124
|
-
function
|
|
6125
|
-
|
|
6126
|
-
|
|
6127
|
-
|
|
6128
|
-
return;
|
|
6198
|
+
async function waitUntilNoMihomo(pids) {
|
|
6199
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6200
|
+
if (!pids.some(pidAlive)) return;
|
|
6201
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
6129
6202
|
}
|
|
6130
|
-
|
|
6131
|
-
|
|
6132
|
-
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
);
|
|
6136
|
-
throw new CliError(`\u672A\u77E5\u547D\u4EE4: ${token}`, {
|
|
6137
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5168\u90E8\u547D\u4EE4']
|
|
6138
|
-
});
|
|
6203
|
+
}
|
|
6204
|
+
function killProcess(pid) {
|
|
6205
|
+
try {
|
|
6206
|
+
process.kill(pid, "SIGKILL");
|
|
6207
|
+
} catch {
|
|
6139
6208
|
}
|
|
6140
|
-
printCommandHelp(command);
|
|
6141
6209
|
}
|
|
6142
|
-
function
|
|
6143
|
-
|
|
6144
|
-
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
6145
|
-
console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
|
|
6146
|
-
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
6210
|
+
function killAllMihomo() {
|
|
6211
|
+
spawnSync6("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
|
|
6147
6212
|
}
|
|
6148
|
-
|
|
6149
|
-
|
|
6150
|
-
|
|
6151
|
-
|
|
6152
|
-
|
|
6153
|
-
|
|
6154
|
-
|
|
6213
|
+
function buildKernelCleanupScript() {
|
|
6214
|
+
return [
|
|
6215
|
+
"#!/bin/bash",
|
|
6216
|
+
// pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
|
|
6217
|
+
`pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
|
|
6218
|
+
"rc=$?",
|
|
6219
|
+
"[ $rc -le 1 ] || exit 2",
|
|
6220
|
+
"exit 0",
|
|
6221
|
+
""
|
|
6222
|
+
].join("\n");
|
|
6223
|
+
}
|
|
6224
|
+
async function cleanupAll() {
|
|
6225
|
+
const pids = getMihomoPids();
|
|
6226
|
+
if (pids.length === 0) {
|
|
6227
|
+
return { remaining: [], scriptError: null, pidError: clearPid() };
|
|
6155
6228
|
}
|
|
6156
|
-
|
|
6157
|
-
|
|
6158
|
-
|
|
6159
|
-
|
|
6160
|
-
|
|
6161
|
-
|
|
6162
|
-
|
|
6163
|
-
|
|
6164
|
-
|
|
6165
|
-
|
|
6166
|
-
|
|
6167
|
-
|
|
6168
|
-
|
|
6169
|
-
|
|
6170
|
-
|
|
6171
|
-
|
|
6172
|
-
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6229
|
+
let scriptError = null;
|
|
6230
|
+
const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
|
|
6231
|
+
const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
|
|
6232
|
+
if (rootPids.length > 0) {
|
|
6233
|
+
console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
|
|
6234
|
+
try {
|
|
6235
|
+
runSudoScript(buildKernelCleanupScript(), {
|
|
6236
|
+
action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B",
|
|
6237
|
+
file: "cleanup-residue.sh",
|
|
6238
|
+
codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" }
|
|
6239
|
+
});
|
|
6240
|
+
} catch (e) {
|
|
6241
|
+
scriptError = e;
|
|
6242
|
+
}
|
|
6243
|
+
} else if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
6244
|
+
killAllMihomo();
|
|
6245
|
+
} else {
|
|
6246
|
+
for (const pid of pids) {
|
|
6247
|
+
const probed = probes.get(pid);
|
|
6248
|
+
if (probed && isProbedMihomo(probed)) killProcess(pid);
|
|
6176
6249
|
}
|
|
6177
|
-
return out;
|
|
6178
6250
|
}
|
|
6179
|
-
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
return { config: walk(config, false, state), changed: state.changed };
|
|
6251
|
+
await waitUntilNoMihomo(pids);
|
|
6252
|
+
const remaining = getMihomoPids();
|
|
6253
|
+
const pidError = remaining.length === 0 ? clearPid() : null;
|
|
6254
|
+
return { remaining, scriptError, pidError };
|
|
6184
6255
|
}
|
|
6185
|
-
|
|
6186
|
-
|
|
6187
|
-
|
|
6188
|
-
|
|
6189
|
-
|
|
6190
|
-
|
|
6191
|
-
|
|
6192
|
-
|
|
6193
|
-
return new
|
|
6194
|
-
} catch {
|
|
6195
|
-
return false;
|
|
6256
|
+
function buildRootResidueCleanupError(result, ctx) {
|
|
6257
|
+
const { scriptError, pidError } = result;
|
|
6258
|
+
const hasKernelResidue = result.remaining.length > 0;
|
|
6259
|
+
const pidList = `PID ${result.remaining.join(", ")}`;
|
|
6260
|
+
const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
|
|
6261
|
+
const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
|
|
6262
|
+
hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
6263
|
+
if (scriptError instanceof SudoAuthError) {
|
|
6264
|
+
return new CliError(`${describeSudoFailure(scriptError)}\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406`, { label: "\u5DF2\u53D6\u6D88", hint });
|
|
6196
6265
|
}
|
|
6266
|
+
return new CliError(scriptError?.message ?? pidError?.message ?? "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0", { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
6197
6267
|
}
|
|
6198
|
-
function
|
|
6199
|
-
|
|
6200
|
-
|
|
6201
|
-
try {
|
|
6202
|
-
error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
|
|
6203
|
-
} catch {
|
|
6204
|
-
}
|
|
6205
|
-
return error;
|
|
6268
|
+
function classifyResidueCleanup(result) {
|
|
6269
|
+
if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
|
|
6270
|
+
return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
|
|
6206
6271
|
}
|
|
6207
|
-
function
|
|
6208
|
-
const
|
|
6209
|
-
|
|
6210
|
-
|
|
6211
|
-
const controller = new AbortController();
|
|
6212
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
6213
|
-
const signal = config?.signal ? AbortSignal.any([controller.signal, config.signal]) : controller.signal;
|
|
6214
|
-
try {
|
|
6215
|
-
let currentUrl = url;
|
|
6216
|
-
let response;
|
|
6217
|
-
for (let hop = 0; ; hop++) {
|
|
6218
|
-
response = await fetch(currentUrl, {
|
|
6219
|
-
signal,
|
|
6220
|
-
redirect: "manual",
|
|
6221
|
-
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
6222
|
-
});
|
|
6223
|
-
if (!REDIRECT_STATUSES.has(response.status)) break;
|
|
6224
|
-
if (hop >= MAX_REDIRECTS) {
|
|
6225
|
-
throw new Error(`\u91CD\u5B9A\u5411\u6B21\u6570\u8D85\u8FC7 ${MAX_REDIRECTS}\uFF0C\u5DF2\u4E2D\u6B62: ${maskUrl(url)}`);
|
|
6226
|
-
}
|
|
6227
|
-
const location = response.headers.get("location");
|
|
6228
|
-
if (!location) break;
|
|
6229
|
-
const nextUrl = new URL(location, currentUrl).toString();
|
|
6230
|
-
if (isHttpsUrl(url) && !isHttpsUrl(nextUrl)) {
|
|
6231
|
-
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${maskUrl(nextUrl)}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
6232
|
-
}
|
|
6233
|
-
await response.body?.cancel().catch(() => void 0);
|
|
6234
|
-
currentUrl = nextUrl;
|
|
6235
|
-
}
|
|
6236
|
-
if (!response.ok) {
|
|
6237
|
-
let text2 = "";
|
|
6238
|
-
try {
|
|
6239
|
-
text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
|
|
6240
|
-
} catch {
|
|
6241
|
-
}
|
|
6242
|
-
throw createHttpError(response.status, text2);
|
|
6243
|
-
}
|
|
6244
|
-
const declaredLen = Number(response.headers.get("content-length"));
|
|
6245
|
-
if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
|
|
6246
|
-
throw new Error(`\u54CD\u5E94\u4F53\u8FC7\u5927\uFF08${formatBytes(declaredLen)}\uFF0C\u4E0A\u9650 ${formatBytes(MAX_RESPONSE_BYTES)}\uFF09`);
|
|
6247
|
-
}
|
|
6248
|
-
const text = await readBodyWithLimit(response, controller, MAX_RESPONSE_BYTES);
|
|
6249
|
-
const data = config?.responseType === "json" ? JSON.parse(text) : text;
|
|
6250
|
-
return { data, headers: response.headers };
|
|
6251
|
-
} catch (e) {
|
|
6252
|
-
if (controller.signal.aborted && e.name === "AbortError") {
|
|
6253
|
-
throw new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${Math.round(timeout / 1e3)}s\uFF09: ${maskUrl(url)}`);
|
|
6254
|
-
}
|
|
6255
|
-
throw e;
|
|
6256
|
-
} finally {
|
|
6257
|
-
clearTimeout(timer);
|
|
6258
|
-
}
|
|
6259
|
-
}
|
|
6260
|
-
};
|
|
6272
|
+
function warnResidueCleanup(result, ctx) {
|
|
6273
|
+
const err = buildRootResidueCleanupError(result, ctx);
|
|
6274
|
+
console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
|
|
6275
|
+
for (const line of err.hint) console.warn(colors.gray(line));
|
|
6261
6276
|
}
|
|
6262
|
-
async function
|
|
6263
|
-
|
|
6264
|
-
const
|
|
6265
|
-
|
|
6266
|
-
|
|
6267
|
-
|
|
6268
|
-
|
|
6269
|
-
|
|
6270
|
-
|
|
6271
|
-
|
|
6272
|
-
|
|
6273
|
-
|
|
6274
|
-
|
|
6275
|
-
|
|
6276
|
-
|
|
6277
|
-
|
|
6278
|
-
|
|
6277
|
+
async function cleanupKernelsOrThrow(ctx) {
|
|
6278
|
+
const result = await cleanupAll();
|
|
6279
|
+
const verdict = classifyResidueCleanup(result);
|
|
6280
|
+
if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
|
|
6281
|
+
if (verdict === "warn") warnResidueCleanup(result, ctx);
|
|
6282
|
+
return result;
|
|
6283
|
+
}
|
|
6284
|
+
async function stop() {
|
|
6285
|
+
const allPids = getMihomoPids();
|
|
6286
|
+
if (allPids.length === 0) {
|
|
6287
|
+
warnPidCleanupFailed(clearPid());
|
|
6288
|
+
clearRuntime();
|
|
6289
|
+
return {};
|
|
6290
|
+
}
|
|
6291
|
+
const result = await cleanupAll();
|
|
6292
|
+
if (result.remaining.length === 0) {
|
|
6293
|
+
warnPidCleanupFailed(result.pidError);
|
|
6294
|
+
if (result.scriptError) {
|
|
6295
|
+
console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
|
|
6279
6296
|
}
|
|
6280
|
-
} finally {
|
|
6281
|
-
reader.releaseLock();
|
|
6282
6297
|
}
|
|
6283
|
-
|
|
6298
|
+
const remaining = result.remaining;
|
|
6299
|
+
if (remaining.length > 0) {
|
|
6300
|
+
console.log("");
|
|
6301
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
6302
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
6303
|
+
console.log(MANUAL_PKILL_HINT);
|
|
6304
|
+
console.log("");
|
|
6305
|
+
return { remaining };
|
|
6306
|
+
}
|
|
6307
|
+
clearRuntime();
|
|
6308
|
+
return {};
|
|
6284
6309
|
}
|
|
6285
6310
|
|
|
6286
|
-
// src/
|
|
6287
|
-
var
|
|
6288
|
-
var
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
const
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
};
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6311
|
+
// src/service.ts
|
|
6312
|
+
var SERVICE_HEALTH_INTERVAL_MS = 100;
|
|
6313
|
+
var SERVICE_OBSERVE_MS = 1200;
|
|
6314
|
+
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
6315
|
+
async function waitServiceHealthy() {
|
|
6316
|
+
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
6317
|
+
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
6318
|
+
let last = null;
|
|
6319
|
+
const unhealthy = (state, crashed, pid = null) => ({
|
|
6320
|
+
healthy: false,
|
|
6321
|
+
crashed,
|
|
6322
|
+
pid,
|
|
6323
|
+
exitCode: state.lastExitCode,
|
|
6324
|
+
terminatingSignal: state.lastTerminatingSignal
|
|
6325
|
+
});
|
|
6326
|
+
do {
|
|
6327
|
+
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
6328
|
+
try {
|
|
6329
|
+
last = getServiceStatus({ withDisabled: false });
|
|
6330
|
+
} catch {
|
|
6331
|
+
continue;
|
|
6332
|
+
}
|
|
6333
|
+
if (isCrashed(last)) {
|
|
6334
|
+
return unhealthy(last, true);
|
|
6335
|
+
}
|
|
6336
|
+
if (!last.loaded) {
|
|
6337
|
+
return unhealthy(last, false);
|
|
6338
|
+
}
|
|
6339
|
+
} while (Date.now() < deadline);
|
|
6340
|
+
if (last === null) return healthViaProcessProbe();
|
|
6341
|
+
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
6342
|
+
let graceQueried = false;
|
|
6343
|
+
while (Date.now() < graceDeadline) {
|
|
6344
|
+
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
6345
|
+
try {
|
|
6346
|
+
last = getServiceStatus({ withDisabled: false });
|
|
6347
|
+
} catch {
|
|
6348
|
+
continue;
|
|
6349
|
+
}
|
|
6350
|
+
graceQueried = true;
|
|
6351
|
+
if (isCrashed(last)) {
|
|
6352
|
+
return unhealthy(last, true);
|
|
6353
|
+
}
|
|
6354
|
+
if (!last.loaded) break;
|
|
6355
|
+
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
6308
6356
|
}
|
|
6357
|
+
if (!graceQueried) return healthViaProcessProbe();
|
|
6358
|
+
return unhealthy(last, false, last.pid);
|
|
6309
6359
|
}
|
|
6310
|
-
|
|
6311
|
-
// src/subscription.ts
|
|
6312
|
-
function resolveUpdateInterval(cachedInterval) {
|
|
6313
|
-
return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
|
|
6314
|
-
}
|
|
6315
|
-
function isSubscriptionStale(cached, nowMs = Date.now()) {
|
|
6316
|
-
if (!cached.updated_at) return false;
|
|
6317
|
-
const t = new Date(cached.updated_at).getTime();
|
|
6318
|
-
if (Number.isNaN(t) || t > nowMs) return false;
|
|
6319
|
-
const ageHours = (nowMs - t) / 36e5;
|
|
6320
|
-
return ageHours > resolveUpdateInterval(cached.update_interval);
|
|
6321
|
-
}
|
|
6322
|
-
var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
|
|
6323
|
-
function isValidHttpUrl(url) {
|
|
6360
|
+
function healthViaProcessProbe() {
|
|
6324
6361
|
try {
|
|
6325
|
-
const
|
|
6326
|
-
|
|
6362
|
+
const pids = getMihomoPids();
|
|
6363
|
+
if (pids.length > 0) return { healthy: true, crashed: false, pid: pids[0], exitCode: null, terminatingSignal: null };
|
|
6327
6364
|
} catch {
|
|
6328
|
-
return false;
|
|
6329
|
-
}
|
|
6330
|
-
}
|
|
6331
|
-
function parseUserInfo(header) {
|
|
6332
|
-
if (!header) return null;
|
|
6333
|
-
const info = {};
|
|
6334
|
-
let hasAny = false;
|
|
6335
|
-
for (const part of header.split(";")) {
|
|
6336
|
-
const [rawKey, rawVal] = part.split("=");
|
|
6337
|
-
const key = rawKey?.trim();
|
|
6338
|
-
const val = rawVal?.trim();
|
|
6339
|
-
if (!key || val === void 0 || val === "") continue;
|
|
6340
|
-
const numVal = Number(val);
|
|
6341
|
-
if (!Number.isFinite(numVal) || numVal < 0) continue;
|
|
6342
|
-
info[key] = numVal;
|
|
6343
|
-
hasAny = true;
|
|
6344
|
-
}
|
|
6345
|
-
return hasAny ? info : null;
|
|
6346
|
-
}
|
|
6347
|
-
function parsePositiveInterval(header) {
|
|
6348
|
-
if (!header) return null;
|
|
6349
|
-
const n = parseInt(header, 10);
|
|
6350
|
-
return Number.isFinite(n) && n > 0 ? n : null;
|
|
6351
|
-
}
|
|
6352
|
-
function parseUsernameFromContentDisposition(header) {
|
|
6353
|
-
if (!header) return null;
|
|
6354
|
-
const match = header.match(/filename\s*=\s*["']?([^"';\s]+)["']?/i);
|
|
6355
|
-
if (!match) return null;
|
|
6356
|
-
const filename = match[1];
|
|
6357
|
-
const parts = filename.split("/");
|
|
6358
|
-
return parts[parts.length - 1] || null;
|
|
6359
|
-
}
|
|
6360
|
-
function extractSubscriptionMeta(headers) {
|
|
6361
|
-
return {
|
|
6362
|
-
userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
|
|
6363
|
-
updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
|
|
6364
|
-
// 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
|
|
6365
|
-
webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
|
|
6366
|
-
username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
|
|
6367
|
-
};
|
|
6368
|
-
}
|
|
6369
|
-
function saveSubscriptionMeta(subName, meta) {
|
|
6370
|
-
const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
6371
|
-
if (meta.userInfo) {
|
|
6372
|
-
const { upload, download, total, expire } = meta.userInfo;
|
|
6373
|
-
if (upload !== void 0) cacheData.upload = upload;
|
|
6374
|
-
if (download !== void 0) cacheData.download = download;
|
|
6375
|
-
if (total !== void 0) cacheData.total = total;
|
|
6376
|
-
if (expire !== void 0) cacheData.expire = expire;
|
|
6377
6365
|
}
|
|
6378
|
-
|
|
6379
|
-
if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
|
|
6380
|
-
if (meta.username) cacheData.username = meta.username;
|
|
6381
|
-
saveSubscriptionCache(subName, cacheData);
|
|
6366
|
+
return { healthy: false, crashed: false, pid: null, exitCode: null, terminatingSignal: null };
|
|
6382
6367
|
}
|
|
6383
|
-
function
|
|
6384
|
-
|
|
6385
|
-
if (
|
|
6386
|
-
|
|
6387
|
-
return parts.join(", ");
|
|
6368
|
+
function describeExitCause(exitCode, terminatingSignal) {
|
|
6369
|
+
if (terminatingSignal !== null) return `\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF08${terminatingSignal}\uFF09`;
|
|
6370
|
+
if (exitCode !== null && exitCode !== 0) return `\u9000\u51FA\u7801 ${exitCode}`;
|
|
6371
|
+
return null;
|
|
6388
6372
|
}
|
|
6389
|
-
function
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
if (subs.length === 0) return null;
|
|
6393
|
-
const activeName = settings.active_subscription;
|
|
6394
|
-
if (activeName) {
|
|
6395
|
-
const found = subs.find((s) => s.name === activeName);
|
|
6396
|
-
if (found) return found;
|
|
6397
|
-
}
|
|
6398
|
-
return subs[0];
|
|
6373
|
+
function isCrashed(status) {
|
|
6374
|
+
if (status.running) return false;
|
|
6375
|
+
return describeExitCause(status.lastExitCode, status.lastTerminatingSignal) !== null;
|
|
6399
6376
|
}
|
|
6400
|
-
function
|
|
6401
|
-
return
|
|
6377
|
+
function describeAbnormalExit(status) {
|
|
6378
|
+
return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
|
|
6402
6379
|
}
|
|
6403
|
-
function
|
|
6404
|
-
|
|
6405
|
-
if (!sub) {
|
|
6406
|
-
throw noSubscriptionsError();
|
|
6407
|
-
}
|
|
6408
|
-
return sub;
|
|
6380
|
+
function tunBlockedHint(lastLine) {
|
|
6381
|
+
return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
|
|
6409
6382
|
}
|
|
6410
|
-
function
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
const prefix = [];
|
|
6414
|
-
const includes = [];
|
|
6415
|
-
for (const s of subs) {
|
|
6416
|
-
const name = s.name.toLowerCase();
|
|
6417
|
-
if (name === lowerPattern) {
|
|
6418
|
-
exact.push(s);
|
|
6419
|
-
} else if (name.startsWith(lowerPattern)) {
|
|
6420
|
-
prefix.push(s);
|
|
6421
|
-
} else if (name.includes(lowerPattern)) {
|
|
6422
|
-
includes.push(s);
|
|
6423
|
-
}
|
|
6424
|
-
}
|
|
6425
|
-
const matched = exact.length > 0 ? exact : prefix.length > 0 ? prefix : includes;
|
|
6426
|
-
if (matched.length === 0) {
|
|
6427
|
-
throw new CliError(`\u672A\u627E\u5230\u5339\u914D "${pattern}" \u7684\u8BA2\u9605`);
|
|
6428
|
-
}
|
|
6429
|
-
if (matched.length === 1) return matched[0];
|
|
6430
|
-
throw new CliError("\u5339\u914D\u5230\u591A\u4E2A\u8BA2\u9605\uFF0C\u8BF7\u66F4\u7CBE\u786E\u6307\u5B9A", {
|
|
6431
|
-
hint: ["", "\u5339\u914D\u7684\u8BA2\u9605:", ...matched.map((s) => ` ${s.name}`)]
|
|
6383
|
+
function tunBlockedByRunningService() {
|
|
6384
|
+
return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
|
|
6385
|
+
hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
|
|
6432
6386
|
});
|
|
6433
6387
|
}
|
|
6434
|
-
function
|
|
6435
|
-
|
|
6436
|
-
|
|
6437
|
-
const providers = parsed["proxy-providers"];
|
|
6438
|
-
const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
|
|
6439
|
-
if (hasProxies || hasGroups || hasProviders) return;
|
|
6440
|
-
const serverMsg = sanitizeTerminal(
|
|
6441
|
-
["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
|
|
6442
|
-
);
|
|
6443
|
-
throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
|
|
6444
|
-
label: "\u8BA2\u9605\u65E0\u6548",
|
|
6445
|
-
hint: [
|
|
6446
|
-
...serverMsg ? [`\u670D\u52A1\u7AEF\u8FD4\u56DE: ${serverMsg}`] : [],
|
|
6447
|
-
`URL: ${maskedUrl}`,
|
|
6448
|
-
"\u5E38\u89C1\u539F\u56E0\uFF1A\u8BA2\u9605\u94FE\u63A5\u8FC7\u671F\u3001\u6D41\u91CF\u8017\u5C3D\u3001\u9700\u8981\u91CD\u65B0\u83B7\u53D6\u8BA2\u9605\u5730\u5740\u3002",
|
|
6449
|
-
"\u78C1\u76D8\u4E0A\u539F\u6709\u7684\u8BA2\u9605\u914D\u7F6E\u672A\u88AB\u8986\u76D6\u3002"
|
|
6450
|
-
]
|
|
6388
|
+
function tunBlockedByConcurrentStart() {
|
|
6389
|
+
return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
|
|
6390
|
+
hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
|
|
6451
6391
|
});
|
|
6452
6392
|
}
|
|
6453
|
-
|
|
6454
|
-
|
|
6393
|
+
function ensureServiceSymlink() {
|
|
6394
|
+
assertKernelInstalled();
|
|
6455
6395
|
try {
|
|
6456
|
-
|
|
6396
|
+
const current = fs12.readlinkSync(PATHS.serviceBinary);
|
|
6397
|
+
if (current === "mihomo") return;
|
|
6398
|
+
fs12.unlinkSync(PATHS.serviceBinary);
|
|
6457
6399
|
} catch (e) {
|
|
6458
|
-
const
|
|
6459
|
-
|
|
6460
|
-
|
|
6461
|
-
|
|
6462
|
-
|
|
6400
|
+
const code = e.code;
|
|
6401
|
+
if (code === "EINVAL") {
|
|
6402
|
+
try {
|
|
6403
|
+
fs12.unlinkSync(PATHS.serviceBinary);
|
|
6404
|
+
} catch {
|
|
6405
|
+
}
|
|
6406
|
+
} else if (code !== "ENOENT") {
|
|
6407
|
+
throw e;
|
|
6463
6408
|
}
|
|
6464
|
-
errorMsg += `
|
|
6465
|
-
URL: ${maskedUrl}`;
|
|
6466
|
-
throw new Error(errorMsg);
|
|
6467
|
-
}
|
|
6468
|
-
const content = response.data;
|
|
6469
|
-
if (!content?.trim()) {
|
|
6470
|
-
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
6471
6409
|
}
|
|
6472
|
-
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
6473
|
-
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
6474
|
-
saveSubscriptionRawConfig(subName, content);
|
|
6475
|
-
const meta = extractSubscriptionMeta(response.headers);
|
|
6476
6410
|
try {
|
|
6477
|
-
|
|
6411
|
+
fs12.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
6478
6412
|
} catch (e) {
|
|
6413
|
+
if (e.code !== "EEXIST") throw e;
|
|
6414
|
+
let existing;
|
|
6479
6415
|
try {
|
|
6480
|
-
|
|
6416
|
+
existing = fs12.readlinkSync(PATHS.serviceBinary);
|
|
6481
6417
|
} catch {
|
|
6418
|
+
throw e;
|
|
6482
6419
|
}
|
|
6483
|
-
|
|
6484
|
-
label: "\u66F4\u65B0\u5931\u8D25",
|
|
6485
|
-
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
6486
|
-
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
6487
|
-
hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
6488
|
-
});
|
|
6420
|
+
if (existing !== "mihomo") throw e;
|
|
6489
6421
|
}
|
|
6490
|
-
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
6491
|
-
return { proxies, proxyGroups };
|
|
6492
6422
|
}
|
|
6493
|
-
|
|
6494
|
-
|
|
6423
|
+
function bootstrapServiceIdempotentOrThrow(what) {
|
|
6424
|
+
const result = runLaunchctl(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6425
|
+
if (result.status === 0) return;
|
|
6426
|
+
if (result.status === 5 && runLaunchctl(["print", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS).status === 0) return;
|
|
6427
|
+
const detail = result.stderr.trim();
|
|
6428
|
+
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
6429
|
+
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
6430
|
+
});
|
|
6431
|
+
}
|
|
6432
|
+
function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
6433
|
+
const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
|
|
6434
|
+
if (result.status === 0 || isBootoutNotLoaded(result.status)) return;
|
|
6435
|
+
const detail = result.stderr.trim();
|
|
6436
|
+
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
6437
|
+
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
6438
|
+
});
|
|
6439
|
+
}
|
|
6440
|
+
async function installService(wasRunning) {
|
|
6441
|
+
assertServiceLabelSafe();
|
|
6442
|
+
ensureDirs();
|
|
6443
|
+
ensureServiceSymlink();
|
|
6444
|
+
let restoreSkipped = false;
|
|
6445
|
+
const stagePath = PATHS.servicePlistStage;
|
|
6446
|
+
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
6495
6447
|
try {
|
|
6496
|
-
|
|
6497
|
-
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6448
|
+
const lint = spawnSync7("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
|
|
6449
|
+
if (lint.status !== 0) {
|
|
6450
|
+
throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
|
|
6451
|
+
hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
|
|
6452
|
+
});
|
|
6453
|
+
}
|
|
6454
|
+
bootoutService();
|
|
6455
|
+
await waitUntilUnloaded();
|
|
6456
|
+
fs12.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
6457
|
+
atomicWriteFileSync(PATHS.userAgentPlist, fs12.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
6458
|
+
if (wasRunning) {
|
|
6459
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
6460
|
+
if (startAbortedByConcurrentStop()) {
|
|
6461
|
+
restoreSkipped = true;
|
|
6462
|
+
return;
|
|
6463
|
+
}
|
|
6464
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6465
|
+
bootstrapServiceIdempotentOrThrow("\u88C5\u8F7D\u670D\u52A1");
|
|
6501
6466
|
});
|
|
6502
6467
|
}
|
|
6503
|
-
|
|
6504
|
-
|
|
6505
|
-
|
|
6506
|
-
|
|
6507
|
-
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
6508
|
-
return {
|
|
6509
|
-
buildResult,
|
|
6510
|
-
info: countConfigNodes(buildResult.config)
|
|
6511
|
-
};
|
|
6512
|
-
}
|
|
6513
|
-
function commitPreparedConfig(prepared) {
|
|
6514
|
-
const { buildResult } = prepared;
|
|
6515
|
-
if (buildResult.warnings.length > 0) {
|
|
6516
|
-
for (const warning of buildResult.warnings) {
|
|
6517
|
-
console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
|
|
6468
|
+
} finally {
|
|
6469
|
+
try {
|
|
6470
|
+
fs12.unlinkSync(stagePath);
|
|
6471
|
+
} catch {
|
|
6518
6472
|
}
|
|
6519
|
-
console.log("");
|
|
6520
|
-
}
|
|
6521
|
-
writeMihomoConfig(buildResult.config);
|
|
6522
|
-
return prepared.info;
|
|
6523
|
-
}
|
|
6524
|
-
function needsAutoUpdate(sub) {
|
|
6525
|
-
if (!sub.updated_at) return true;
|
|
6526
|
-
const lastUpdate = new Date(sub.updated_at).getTime();
|
|
6527
|
-
if (Number.isNaN(lastUpdate)) return true;
|
|
6528
|
-
if (lastUpdate > Date.now()) return true;
|
|
6529
|
-
const intervalHours = resolveUpdateInterval(sub.update_interval);
|
|
6530
|
-
const intervalMs = intervalHours * 60 * 60 * 1e3;
|
|
6531
|
-
return Date.now() - lastUpdate > intervalMs;
|
|
6532
|
-
}
|
|
6533
|
-
async function tryUpdateOne(sub, signal) {
|
|
6534
|
-
try {
|
|
6535
|
-
const info = await downloadSubscription(sub.url, sub.name, signal);
|
|
6536
|
-
return { name: sub.name, success: true, proxies: info.proxies, proxyGroups: info.proxyGroups };
|
|
6537
|
-
} catch (e) {
|
|
6538
|
-
return { name: sub.name, success: false, aborted: signal?.aborted === true, error: e.message };
|
|
6539
6473
|
}
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
if (r.success) {
|
|
6543
|
-
console.log(`${colors.green("\u2713")} ${r.name}: ${colors.green("\u5DF2\u66F4\u65B0")} (${formatProxySummary(r)})`);
|
|
6544
|
-
} else if (r.aborted) {
|
|
6545
|
-
console.log(`${colors.gray("\xB7")} ${r.name}: ${colors.gray("\u8DF3\u8FC7\uFF08\u66F4\u65B0\u8D85\u65F6\uFF0C\u4F7F\u7528\u672C\u5730\u7F13\u5B58\uFF09")}`);
|
|
6546
|
-
} else {
|
|
6547
|
-
console.log(`${colors.red("\u2717")} ${r.name}: ${colors.red("\u5931\u8D25")} (${firstLine(r.error || "")})`);
|
|
6474
|
+
if (!wasRunning) {
|
|
6475
|
+
disableServiceAutoStart();
|
|
6548
6476
|
}
|
|
6477
|
+
return { restoreSkipped };
|
|
6549
6478
|
}
|
|
6550
|
-
async function
|
|
6551
|
-
|
|
6552
|
-
|
|
6553
|
-
if (
|
|
6554
|
-
|
|
6555
|
-
}
|
|
6556
|
-
if (staleSubs.length === 1) {
|
|
6557
|
-
const sub = staleSubs[0];
|
|
6558
|
-
const interval = resolveUpdateInterval(sub.update_interval);
|
|
6559
|
-
console.log(`\u8BA2\u9605 "${sub.name}" \u8D85\u8FC7 ${interval} \u5C0F\u65F6\u672A\u66F4\u65B0\uFF0C\u6B63\u5728\u66F4\u65B0...`);
|
|
6560
|
-
} else {
|
|
6561
|
-
console.log(`\u68C0\u6D4B\u5230 ${staleSubs.length} \u4E2A\u8BA2\u9605\u9700\u8981\u66F4\u65B0\uFF0C\u6B63\u5728\u5E76\u884C\u66F4\u65B0...`);
|
|
6479
|
+
async function startService() {
|
|
6480
|
+
assertServiceLabelSafe();
|
|
6481
|
+
ensureServiceSymlink();
|
|
6482
|
+
if (!isServiceInstalled()) {
|
|
6483
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
6562
6484
|
}
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
|
|
6566
|
-
|
|
6567
|
-
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
|
|
6573
|
-
);
|
|
6574
|
-
try {
|
|
6575
|
-
await withSpinner("\u66F4\u65B0\u8BA2\u9605\u4E2D", () => withTimeout(updatePromise, timeoutMs));
|
|
6576
|
-
} catch (e) {
|
|
6577
|
-
if (!(e instanceof TimeoutError)) throw e;
|
|
6578
|
-
controller.abort();
|
|
6579
|
-
await updatePromise.catch(() => {
|
|
6485
|
+
assertRuntimeConfigPresent();
|
|
6486
|
+
if (getConfigInfo()?.tun) {
|
|
6487
|
+
throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
|
|
6488
|
+
hint: [
|
|
6489
|
+
"\u670D\u52A1\u4EE5\u666E\u901A\u7528\u6237\u8EAB\u4EFD\u8FD0\u884C\uFF08\u7528\u6237\u7EA7 LaunchAgent\uFF09\uFF0C\u65E0\u6743\u521B\u5EFA TUN \u8BBE\u5907\uFF0C",
|
|
6490
|
+
"\u5F3A\u884C\u542F\u52A8\u53EA\u4F1A\u8BA9\u5185\u6838\u53CD\u590D\u5D29\u6E83\u91CD\u542F\u3002",
|
|
6491
|
+
"",
|
|
6492
|
+
"\u6309 Mixed \u91CD\u5EFA\u914D\u7F6E\u5E76\u542F\u52A8: mihomo-cli start mixed",
|
|
6493
|
+
"\u786E\u5B9E\u8981\u7528 TUN: mihomo-cli tun"
|
|
6494
|
+
]
|
|
6580
6495
|
});
|
|
6581
|
-
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
6582
|
-
}
|
|
6583
|
-
for (const r of results) {
|
|
6584
|
-
printUpdateResult(r);
|
|
6585
6496
|
}
|
|
6497
|
+
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo-cli start" });
|
|
6498
|
+
bootoutService();
|
|
6499
|
+
await waitUntilUnloaded();
|
|
6500
|
+
rotateAndCleanupLogs();
|
|
6501
|
+
let started = true;
|
|
6502
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
6503
|
+
if (startAbortedByConcurrentStop()) {
|
|
6504
|
+
started = false;
|
|
6505
|
+
return;
|
|
6506
|
+
}
|
|
6507
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1", SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6508
|
+
bootstrapServiceIdempotentOrThrow("\u542F\u52A8\u670D\u52A1");
|
|
6509
|
+
});
|
|
6510
|
+
return { started };
|
|
6586
6511
|
}
|
|
6587
|
-
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
6591
|
-
|
|
6592
|
-
|
|
6593
|
-
|
|
6594
|
-
const active = getActiveSubscription();
|
|
6595
|
-
if (!active) {
|
|
6596
|
-
throw noSubscriptionsError();
|
|
6597
|
-
}
|
|
6598
|
-
const rawContent = requireSubscriptionRawConfig(active.name);
|
|
6599
|
-
const mode = deriveRuntimeMode(getConfigInfo());
|
|
6600
|
-
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
6601
|
-
const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
|
|
6602
|
-
const shown = redacted.config;
|
|
6603
|
-
if (asJson) {
|
|
6604
|
-
console.log(JSON.stringify({ config: shown, warnings, redacted: !reveal && redacted.changed }, null, 2));
|
|
6605
|
-
return;
|
|
6606
|
-
}
|
|
6607
|
-
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
6608
|
-
console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
|
|
6609
|
-
if (!reveal && redacted.changed) {
|
|
6610
|
-
console.log(colors.gray("# \u51ED\u636E\u5DF2\u8131\u654F\u663E\u793A\uFF0C--reveal \u53EF\u67E5\u770B\u539F\u6587"));
|
|
6611
|
-
}
|
|
6612
|
-
console.log("");
|
|
6613
|
-
console.log(dumpYaml(shown).trimEnd());
|
|
6614
|
-
if (warnings.length > 0) {
|
|
6615
|
-
console.log("");
|
|
6616
|
-
for (const w of warnings) console.log(colors.yellow(`# ${w}`));
|
|
6512
|
+
function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
6513
|
+
assertServiceLabelSafe();
|
|
6514
|
+
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
|
|
6515
|
+
if (!isServiceDisabledInLaunchd(timeoutMs)) {
|
|
6516
|
+
throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
|
|
6517
|
+
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"]
|
|
6518
|
+
});
|
|
6617
6519
|
}
|
|
6520
|
+
bumpStopEpoch();
|
|
6618
6521
|
}
|
|
6619
|
-
|
|
6620
|
-
|
|
6621
|
-
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
function setSilentSigint(value) {
|
|
6626
|
-
silentSigint = value;
|
|
6522
|
+
async function bootoutAndDisableInLock() {
|
|
6523
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
6524
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6525
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6526
|
+
});
|
|
6527
|
+
await waitUntilUnloaded();
|
|
6627
6528
|
}
|
|
6628
|
-
function
|
|
6629
|
-
|
|
6529
|
+
async function stopService() {
|
|
6530
|
+
assertServiceLabelSafe();
|
|
6531
|
+
await bootoutAndDisableInLock();
|
|
6532
|
+
return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
|
|
6630
6533
|
}
|
|
6631
|
-
|
|
6632
|
-
|
|
6633
|
-
|
|
6534
|
+
async function uninstallService() {
|
|
6535
|
+
assertServiceLabelSafe();
|
|
6536
|
+
await bootoutAndDisableInLock();
|
|
6634
6537
|
try {
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
|
|
6638
|
-
|
|
6538
|
+
fs12.rmSync(PATHS.userAgentPlist, { force: true });
|
|
6539
|
+
} catch (e) {
|
|
6540
|
+
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
6541
|
+
}
|
|
6542
|
+
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6543
|
+
try {
|
|
6544
|
+
fs12.rmSync(PATHS.serviceBinary, { force: true });
|
|
6639
6545
|
} catch {
|
|
6640
6546
|
}
|
|
6547
|
+
return cleanup;
|
|
6641
6548
|
}
|
|
6642
|
-
function
|
|
6643
|
-
|
|
6644
|
-
|
|
6645
|
-
|
|
6646
|
-
if (follow) {
|
|
6647
|
-
console.log("\u6309 Ctrl+C \u9000\u51FA\n");
|
|
6648
|
-
} else {
|
|
6649
|
-
console.log(`\u663E\u793A\u6700\u540E ${lines} \u884C
|
|
6650
|
-
`);
|
|
6549
|
+
async function restartService(prefetched) {
|
|
6550
|
+
assertServiceLabelSafe();
|
|
6551
|
+
if (!isServiceInstalled()) {
|
|
6552
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
6651
6553
|
}
|
|
6652
|
-
const
|
|
6653
|
-
if (
|
|
6654
|
-
|
|
6655
|
-
|
|
6656
|
-
|
|
6657
|
-
|
|
6658
|
-
|
|
6659
|
-
|
|
6660
|
-
|
|
6661
|
-
|
|
6662
|
-
|
|
6554
|
+
const oversized = logOversized();
|
|
6555
|
+
if (!oversized && await tryHotReload(prefetched)) {
|
|
6556
|
+
return concludeHotReload(stopEpochBaseline(), readStopEpoch());
|
|
6557
|
+
}
|
|
6558
|
+
if (oversized) {
|
|
6559
|
+
const archiveFile = allocateArchivePath();
|
|
6560
|
+
try {
|
|
6561
|
+
fs12.copyFileSync(PATHS.logFile, archiveFile);
|
|
6562
|
+
fs12.writeFileSync(PATHS.logFile, "");
|
|
6563
|
+
} catch {
|
|
6564
|
+
}
|
|
6565
|
+
}
|
|
6566
|
+
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
6567
|
+
let started = true;
|
|
6568
|
+
if (kick.status !== 0) {
|
|
6569
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
6570
|
+
if (startAbortedByConcurrentStop()) {
|
|
6571
|
+
started = false;
|
|
6572
|
+
return;
|
|
6573
|
+
}
|
|
6574
|
+
runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6575
|
+
bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
|
|
6576
|
+
});
|
|
6577
|
+
if (!started) return { hotReloaded: false, started: false };
|
|
6578
|
+
}
|
|
6579
|
+
cleanupOldLogs();
|
|
6580
|
+
return { hotReloaded: false, started: true };
|
|
6663
6581
|
}
|
|
6664
6582
|
|
|
6665
|
-
// src/commands/shared.ts
|
|
6666
|
-
import readline from "readline";
|
|
6667
|
-
|
|
6668
6583
|
// src/process-start.ts
|
|
6669
|
-
import fs13 from "fs";
|
|
6670
6584
|
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6671
6585
|
function buildTunLaunchScript() {
|
|
6672
6586
|
const binary = shellQuote(PATHS.mihomoBinary);
|
|
@@ -7624,7 +7538,6 @@ async function checkUpdate(opts) {
|
|
|
7624
7538
|
current: currentDisplay,
|
|
7625
7539
|
latest: latestVersion,
|
|
7626
7540
|
needsUpdate,
|
|
7627
|
-
assets: latest.assets,
|
|
7628
7541
|
release: latest,
|
|
7629
7542
|
ghFallbackToDirect
|
|
7630
7543
|
};
|
|
@@ -7683,18 +7596,9 @@ function buildGhDownloadEnv(proxy) {
|
|
|
7683
7596
|
}
|
|
7684
7597
|
return env;
|
|
7685
7598
|
}
|
|
7686
|
-
function
|
|
7687
|
-
if (channel.kind === "gh") {
|
|
7688
|
-
return channel.proxy ? { proxy: channel.proxy, useGh: false } : { proxy: null, useGh: true };
|
|
7689
|
-
}
|
|
7690
|
-
if (channel.kind === "proxy") return { proxy: channel.proxy, useGh: false };
|
|
7691
|
-
if (channel.kind === "mirror") return { proxy: channel.proxy ?? null, useGh: false };
|
|
7692
|
-
return { proxy: null, useGh: false };
|
|
7693
|
-
}
|
|
7694
|
-
async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
7599
|
+
async function downloadKernel(progressCallback, channel, latest) {
|
|
7695
7600
|
ensureDirs();
|
|
7696
|
-
const
|
|
7697
|
-
const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
|
|
7601
|
+
const downloadProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
|
|
7698
7602
|
const arch = getArch();
|
|
7699
7603
|
const platform = process.platform;
|
|
7700
7604
|
const asset = findMatchingAsset(latest.assets, platform, arch);
|
|
@@ -7750,7 +7654,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7750
7654
|
"curl",
|
|
7751
7655
|
buildKernelCurlArgs({
|
|
7752
7656
|
url: downloadUrl,
|
|
7753
|
-
proxy:
|
|
7657
|
+
proxy: downloadProxy,
|
|
7754
7658
|
maxBytes,
|
|
7755
7659
|
outputPath: tempPath
|
|
7756
7660
|
}),
|
|
@@ -9474,5 +9378,5 @@ main().catch((e) => {
|
|
|
9474
9378
|
/*! Bundled license information:
|
|
9475
9379
|
|
|
9476
9380
|
js-yaml/dist/js-yaml.mjs:
|
|
9477
|
-
(*! js-yaml 5.
|
|
9381
|
+
(*! js-yaml 5.3.0 https://github.com/nodeca/js-yaml @license MIT *)
|
|
9478
9382
|
*/
|