check.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import fs from "fs-extra";
  2. import zlib from "zlib";
  3. import tar from "tar";
  4. import path from "path";
  5. import AdmZip from "adm-zip";
  6. import fetch from "node-fetch";
  7. import proxyAgent from "https-proxy-agent";
  8. import { execSync } from "child_process";
  9. const cwd = process.cwd();
  10. const TEMP_DIR = path.join(cwd, "node_modules/.verge");
  11. const FORCE = process.argv.includes("--force");
  12. const PLATFORM_MAP = {
  13. "x86_64-pc-windows-msvc": "win32",
  14. "i686-pc-windows-msvc": "win32",
  15. "aarch64-pc-windows-msvc": "win32",
  16. "x86_64-apple-darwin": "darwin",
  17. "aarch64-apple-darwin": "darwin",
  18. "x86_64-unknown-linux-gnu": "linux",
  19. "aarch64-unknown-linux-gnu": "linux",
  20. "armv7-unknown-linux-gnueabihf": "linux",
  21. };
  22. const ARCH_MAP = {
  23. "x86_64-pc-windows-msvc": "x64",
  24. "i686-pc-windows-msvc": "ia32",
  25. "aarch64-pc-windows-msvc": "arm64",
  26. "x86_64-apple-darwin": "x64",
  27. "aarch64-apple-darwin": "arm64",
  28. "x86_64-unknown-linux-gnu": "x64",
  29. "aarch64-unknown-linux-gnu": "arm64",
  30. "armv7-unknown-linux-gnueabihf": "arm",
  31. };
  32. const arg1 = process.argv.slice(2)[0];
  33. const arg2 = process.argv.slice(2)[1];
  34. const target = arg1 === "--force" ? arg2 : arg1;
  35. const { platform, arch } = target
  36. ? { platform: PLATFORM_MAP[target], arch: ARCH_MAP[target] }
  37. : process;
  38. const SIDECAR_HOST = target
  39. ? target
  40. : execSync("rustc -vV")
  41. .toString()
  42. .match(/(?<=host: ).+(?=\s*)/g)[0];
  43. /* ======= clash meta alpha======= */
  44. const VERSION_URL =
  45. "https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha/version.txt";
  46. const META_ALPHA_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha`;
  47. let META_ALPHA_VERSION;
  48. const META_ALPHA_MAP = {
  49. "win32-x64": "mihomo-windows-amd64-compatible",
  50. "win32-ia32": "mihomo-windows-386",
  51. "win32-arm64": "mihomo-windows-arm64",
  52. "darwin-x64": "mihomo-darwin-amd64",
  53. "darwin-arm64": "mihomo-darwin-arm64",
  54. "linux-x64": "mihomo-linux-amd64-compatible",
  55. "linux-ia32": "mihomo-linux-386",
  56. "linux-arm64": "mihomo-linux-arm64",
  57. "linux-arm": "mihomo-linux-armv7",
  58. };
  59. // Fetch the latest release version from the version.txt file
  60. async function getLatestVersion() {
  61. try {
  62. const response = await fetch(VERSION_URL, { method: "GET" });
  63. let v = await response.text();
  64. META_ALPHA_VERSION = v.trim(); // Trim to remove extra whitespaces
  65. console.log(`Latest release version: ${META_ALPHA_VERSION}`);
  66. } catch (error) {
  67. console.error("Error fetching latest release version:", error.message);
  68. process.exit(1);
  69. }
  70. }
  71. /* ======= clash meta stable ======= */
  72. const META_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download`;
  73. let META_VERSION = "v1.17.0";
  74. const META_MAP = {
  75. "win32-x64": "mihomo-windows-amd64-compatible",
  76. "win32-ia32": "mihomo-windows-386",
  77. "win32-arm64": "mihomo-windows-arm64",
  78. "darwin-x64": "mihomo-darwin-amd64",
  79. "darwin-arm64": "mihomo-darwin-arm64",
  80. "linux-x64": "mihomo-linux-amd64-compatible",
  81. "linux-ia32": "mihomo-linux-386",
  82. "linux-arm64": "mihomo-linux-arm64",
  83. "linux-arm": "mihomo-linux-armv7",
  84. };
  85. /*
  86. * check available
  87. */
  88. if (!META_MAP[`${platform}-${arch}`]) {
  89. throw new Error(
  90. `clash meta alpha unsupported platform "${platform}-${arch}"`
  91. );
  92. }
  93. if (!META_ALPHA_MAP[`${platform}-${arch}`]) {
  94. throw new Error(
  95. `clash meta alpha unsupported platform "${platform}-${arch}"`
  96. );
  97. }
  98. /**
  99. * core info
  100. */
  101. function clashMetaAlpha() {
  102. const name = META_ALPHA_MAP[`${platform}-${arch}`];
  103. const isWin = platform === "win32";
  104. const urlExt = isWin ? "zip" : "gz";
  105. const downloadURL = `${META_ALPHA_URL_PREFIX}/${name}-${META_ALPHA_VERSION}.${urlExt}`;
  106. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  107. const zipFile = `${name}-${META_ALPHA_VERSION}.${urlExt}`;
  108. return {
  109. name: "clash-meta-alpha",
  110. targetFile: `clash-meta-alpha-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  111. exeFile,
  112. zipFile,
  113. downloadURL,
  114. };
  115. }
  116. function clashMeta() {
  117. const name = META_MAP[`${platform}-${arch}`];
  118. const isWin = platform === "win32";
  119. const urlExt = isWin ? "zip" : "gz";
  120. const downloadURL = `${META_URL_PREFIX}/${META_VERSION}/${name}-${META_VERSION}.${urlExt}`;
  121. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  122. const zipFile = `${name}-${META_VERSION}.${urlExt}`;
  123. return {
  124. name: "clash-meta",
  125. targetFile: `clash-meta-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  126. exeFile,
  127. zipFile,
  128. downloadURL,
  129. };
  130. }
  131. /**
  132. * download sidecar and rename
  133. */
  134. async function resolveSidecar(binInfo) {
  135. const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo;
  136. const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
  137. const sidecarPath = path.join(sidecarDir, targetFile);
  138. await fs.mkdirp(sidecarDir);
  139. if (!FORCE && (await fs.pathExists(sidecarPath))) return;
  140. const tempDir = path.join(TEMP_DIR, name);
  141. const tempZip = path.join(tempDir, zipFile);
  142. const tempExe = path.join(tempDir, exeFile);
  143. await fs.mkdirp(tempDir);
  144. try {
  145. if (!(await fs.pathExists(tempZip))) {
  146. await downloadFile(downloadURL, tempZip);
  147. }
  148. if (zipFile.endsWith(".zip")) {
  149. const zip = new AdmZip(tempZip);
  150. zip.getEntries().forEach((entry) => {
  151. console.log(`[DEBUG]: "${name}" entry name`, entry.entryName);
  152. });
  153. zip.extractAllTo(tempDir, true);
  154. await fs.rename(tempExe, sidecarPath);
  155. console.log(`[INFO]: "${name}" unzip finished`);
  156. } else if (zipFile.endsWith(".tgz")) {
  157. // tgz
  158. await fs.mkdirp(tempDir);
  159. await tar.extract({
  160. cwd: tempDir,
  161. file: tempZip,
  162. //strip: 1, // 可能需要根据实际的 .tgz 文件结构调整
  163. });
  164. const files = await fs.readdir(tempDir);
  165. console.log(`[DEBUG]: "${name}" files in tempDir:`, files);
  166. const extractedFile = files.find((file) => file.startsWith("虚空终端-"));
  167. if (extractedFile) {
  168. const extractedFilePath = path.join(tempDir, extractedFile);
  169. await fs.rename(extractedFilePath, sidecarPath);
  170. console.log(`[INFO]: "${name}" file renamed to "${sidecarPath}"`);
  171. execSync(`chmod 755 ${sidecarPath}`);
  172. console.log(`[INFO]: "${name}" chmod binary finished`);
  173. } else {
  174. throw new Error(`Expected file not found in ${tempDir}`);
  175. }
  176. } else {
  177. // gz
  178. const readStream = fs.createReadStream(tempZip);
  179. const writeStream = fs.createWriteStream(sidecarPath);
  180. await new Promise((resolve, reject) => {
  181. const onError = (error) => {
  182. console.error(`[ERROR]: "${name}" gz failed:`, error.message);
  183. reject(error);
  184. };
  185. readStream
  186. .pipe(zlib.createGunzip().on("error", onError))
  187. .pipe(writeStream)
  188. .on("finish", () => {
  189. console.log(`[INFO]: "${name}" gunzip finished`);
  190. execSync(`chmod 755 ${sidecarPath}`);
  191. console.log(`[INFO]: "${name}" chmod binary finished`);
  192. resolve();
  193. })
  194. .on("error", onError);
  195. });
  196. }
  197. } catch (err) {
  198. // 需要删除文件
  199. await fs.remove(sidecarPath);
  200. throw err;
  201. } finally {
  202. // delete temp dir
  203. await fs.remove(tempDir);
  204. }
  205. }
  206. /**
  207. * download the file to the resources dir
  208. */
  209. async function resolveResource(binInfo) {
  210. const { file, downloadURL } = binInfo;
  211. const resDir = path.join(cwd, "src-tauri/resources");
  212. const targetPath = path.join(resDir, file);
  213. if (!FORCE && (await fs.pathExists(targetPath))) return;
  214. await fs.mkdirp(resDir);
  215. await downloadFile(downloadURL, targetPath);
  216. console.log(`[INFO]: ${file} finished`);
  217. }
  218. /**
  219. * download file and save to `path`
  220. */
  221. async function downloadFile(url, path) {
  222. const options = {};
  223. const httpProxy =
  224. process.env.HTTP_PROXY ||
  225. process.env.http_proxy ||
  226. process.env.HTTPS_PROXY ||
  227. process.env.https_proxy;
  228. if (httpProxy) {
  229. options.agent = proxyAgent(httpProxy);
  230. }
  231. const response = await fetch(url, {
  232. ...options,
  233. method: "GET",
  234. headers: { "Content-Type": "application/octet-stream" },
  235. });
  236. const buffer = await response.arrayBuffer();
  237. await fs.writeFile(path, new Uint8Array(buffer));
  238. console.log(`[INFO]: download finished "${url}"`);
  239. }
  240. /**
  241. * main
  242. */
  243. const SERVICE_URL =
  244. "https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
  245. const resolveService = () =>
  246. resolveResource({
  247. file: "clash-verge-service.exe",
  248. downloadURL: `${SERVICE_URL}/clash-verge-service.exe`,
  249. });
  250. const resolveInstall = () =>
  251. resolveResource({
  252. file: "install-service.exe",
  253. downloadURL: `${SERVICE_URL}/install-service.exe`,
  254. });
  255. const resolveUninstall = () =>
  256. resolveResource({
  257. file: "uninstall-service.exe",
  258. downloadURL: `${SERVICE_URL}/uninstall-service.exe`,
  259. });
  260. const resolveMmdb = () =>
  261. resolveResource({
  262. file: "Country.mmdb",
  263. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
  264. });
  265. const resolveGeosite = () =>
  266. resolveResource({
  267. file: "geosite.dat",
  268. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat`,
  269. });
  270. const resolveGeoIP = () =>
  271. resolveResource({
  272. file: "geoip.dat",
  273. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat`,
  274. });
  275. const resolveEnableLoopback = () =>
  276. resolveResource({
  277. file: "enableLoopback.exe",
  278. downloadURL: `https://github.com/Kuingsmile/uwp-tool/releases/download/latest/enableLoopback.exe`,
  279. });
  280. const tasks = [
  281. // { name: "clash", func: resolveClash, retry: 5 },
  282. {
  283. name: "clash-meta-alpha",
  284. func: () => getLatestVersion().then(() => resolveSidecar(clashMetaAlpha())),
  285. retry: 5,
  286. },
  287. {
  288. name: "clash-meta",
  289. func: () => resolveSidecar(clashMeta()),
  290. retry: 5,
  291. },
  292. // { name: "wintun", func: resolveWintun, retry: 5, winOnly: true },
  293. { name: "service", func: resolveService, retry: 5, winOnly: true },
  294. { name: "install", func: resolveInstall, retry: 5, winOnly: true },
  295. { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
  296. { name: "mmdb", func: resolveMmdb, retry: 5 },
  297. { name: "geosite", func: resolveGeosite, retry: 5 },
  298. { name: "geoip", func: resolveGeoIP, retry: 5 },
  299. {
  300. name: "enableLoopback",
  301. func: resolveEnableLoopback,
  302. retry: 5,
  303. winOnly: true,
  304. },
  305. ];
  306. async function runTask() {
  307. const task = tasks.shift();
  308. if (!task) return;
  309. if (task.winOnly && process.platform !== "win32") return runTask();
  310. for (let i = 0; i < task.retry; i++) {
  311. try {
  312. await task.func();
  313. break;
  314. } catch (err) {
  315. console.error(`[ERROR]: task::${task.name} try ${i} ==`, err.message);
  316. if (i === task.retry - 1) throw err;
  317. }
  318. }
  319. return runTask();
  320. }
  321. runTask();
  322. runTask();