refactor(use-clash): centralize patch typing and port validation logic

This commit is contained in:
Slinetrac
2025-12-03 13:43:13 +08:00
parent 135d14b170
commit 4f8ed63cf0

View File

@@ -8,6 +8,49 @@ import {
getRuntimeConfig,
} from "@/services/cmds";
const PORT_KEYS = [
"port",
"socks-port",
"mixed-port",
"redir-port",
"tproxy-port",
] as const;
type ClashInfoPatch = Partial<
Pick<
IConfigData,
| "port"
| "socks-port"
| "mixed-port"
| "redir-port"
| "tproxy-port"
| "external-controller"
| "secret"
>
>;
const hasClashInfoPayload = (patch: ClashInfoPatch) =>
PORT_KEYS.some((key) => patch[key] != null) ||
patch["external-controller"] != null ||
patch.secret != null;
const validatePortRange = (port: number) => {
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
};
const validatePorts = (patch: ClashInfoPatch) => {
PORT_KEYS.forEach((key) => {
const port = patch[key];
if (!port) return;
validatePortRange(port);
});
};
export const useClash = () => {
const { data: clash, mutate: mutateClash } = useSWR(
"getRuntimeConfig",
@@ -43,80 +86,10 @@ export const useClashInfo = () => {
getClashInfo,
);
const patchInfo = async (
patch: Partial<
Pick<
IConfigData,
| "port"
| "socks-port"
| "mixed-port"
| "redir-port"
| "tproxy-port"
| "external-controller"
| "secret"
>
>,
) => {
const hasInfo =
patch["redir-port"] != null ||
patch["tproxy-port"] != null ||
patch["mixed-port"] != null ||
patch["socks-port"] != null ||
patch["port"] != null ||
patch["external-controller"] != null ||
patch.secret != null;
const patchInfo = async (patch: ClashInfoPatch) => {
if (!hasClashInfoPayload(patch)) return;
if (!hasInfo) return;
if (patch["redir-port"]) {
const port = patch["redir-port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
if (patch["tproxy-port"]) {
const port = patch["tproxy-port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
if (patch["mixed-port"]) {
const port = patch["mixed-port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
if (patch["socks-port"]) {
const port = patch["socks-port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
if (patch["port"]) {
const port = patch["port"];
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
}
validatePorts(patch);
await patchClashConfig(patch);
mutateInfo();