check.mjs 11 KB

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