Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: make CN mirrors explicit opt-in
Tw93e30f3250816e
diff --git a/bin/builders/BaseBuilder.ts b/bin/builders/BaseBuilder.tsindex 1a48ce22..d416557c 100644--- a/bin/builders/BaseBuilder.ts+++ b/bin/builders/BaseBuilder.ts@@ -14,7 +14,7 @@ import {import { npmDirectory } from '@/utils/dir';import { getSpinner } from '@/utils/info';import { shellExec } from '@/utils/shell';-import { isChinaDomain } from '@/utils/ip';+import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';import { IS_MAC } from '@/utils/platform';import logger from '@/options/logger';@@ -102,6 +102,61 @@ export default abstract class BaseBuilder {}}+ private getInstallCommand(+ packageManager: string,+ useCnMirror: boolean,+ ): string {+ const registryOption = useCnMirror+ ? ' --registry=https://registry.npmmirror.com'+ : '';+ const peerDepsOption =+ packageManager === 'npm' ? ' --legacy-peer-deps' : '';++ return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;+ }++ private isGeneratedCnMirrorConfig(+ projectConfig: string,+ cnMirrorConfig: string,+ ): boolean {+ return projectConfig.trim() === cnMirrorConfig.trim();+ }++ private async configureCargoRegistry(+ tauriSrcPath: string,+ useCnMirror: boolean,+ ): Promise<void> {+ const rustProjectDir = path.join(tauriSrcPath, '.cargo');+ const projectConf = path.join(rustProjectDir, 'config.toml');+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');++ if (useCnMirror) {+ await fsExtra.ensureDir(rustProjectDir);+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);+ return;+ }++ if (!(await fsExtra.pathExists(projectConf))) {+ return;+ }++ const [projectConfig, cnMirrorConfig] = await Promise.all([+ fsExtra.readFile(projectConf, 'utf8'),+ fsExtra.readFile(projectCnConf, 'utf8'),+ ]);++ if (this.isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {+ await fsExtra.remove(projectConf);+ return;+ }++ if (projectConfig.includes('rsproxy.cn')) {+ logger.warn(+ `✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`,+ );+ }+ }+async prepare() {const tauriSrcPath = path.join(npmDirectory, 'src-tauri');const tauriTargetPath = path.join(tauriSrcPath, 'target');@@ -129,17 +184,12 @@ export default abstract class BaseBuilder {}}- const isChina = await isChinaDomain('www.npmjs.com');const spinner = getSpinner('Installing package...');- const rustProjectDir = path.join(tauriSrcPath, '.cargo');- const projectConf = path.join(rustProjectDir, 'config.toml');- await fsExtra.ensureDir(rustProjectDir);+ const useCnMirror = isCnMirrorEnabled();+ await this.configureCargoRegistry(tauriSrcPath, useCnMirror);// Detect available package managerconst packageManager = await this.detectPackageManager();- const registryOption = ' --registry=https://registry.npmmirror.com';- const peerDepsOption =- packageManager === 'npm' ? ' --legacy-peer-deps' : '';const timeout = this.getInstallTimeout();const buildEnv = this.getBuildEnvironment();@@ -153,64 +203,30 @@ export default abstract class BaseBuilder {);}- let usedMirror = isChina;+ if (useCnMirror) {+ logger.info(+ `✺ ${CN_MIRROR_ENV}=1 detected, using ${packageManager}/rsProxy CN mirror.`,+ );+ }try {- if (isChina) {- logger.info(- `✺ Located in China, using ${packageManager}/rsProxy CN mirror.`,- );- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);- await shellExec(- `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`,- timeout,- { ...buildEnv, CI: 'true' },- );- } else {- await shellExec(- `cd "${npmDirectory}" && ${packageManager} install${peerDepsOption}`,- timeout,- { ...buildEnv, CI: 'true' },- );- }+ await shellExec(+ this.getInstallCommand(packageManager, useCnMirror),+ timeout,+ {+ ...buildEnv,+ CI: 'true',+ },+ );spinner.succeed(chalk.green('Package installed!'));- } catch (error: unknown) {- // If installation times out and we haven't tried the mirror yet, retry with mirror- if (- error instanceof Error &&- error.message.includes('timed out') &&- !usedMirror- ) {- spinner.fail(- chalk.yellow('Installation timed out, retrying with CN mirror...'),- );+ } catch (error) {+ spinner.fail(chalk.red('Installation failed'));+ if (!useCnMirror) {logger.info(- '✺ Retrying installation with CN mirror for better speed...',+ `✺ If downloads are slow in China, retry with ${CN_MIRROR_ENV}=1 to use CN mirrors.`,);-- const retrySpinner = getSpinner('Retrying installation...');- usedMirror = true;-- try {- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);- await shellExec(- `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`,- timeout,- { ...buildEnv, CI: 'true' },- );- retrySpinner.succeed(- chalk.green('Package installed with CN mirror!'),- );- } catch (retryError) {- retrySpinner.fail(chalk.red('Installation failed'));- throw retryError;- }- } else {- spinner.fail(chalk.red('Installation failed'));- throw error;}+ throw error;}if (!tauriTargetPathExists) {diff --git a/bin/helpers/rust.ts b/bin/helpers/rust.tsindex 946408c8..4a61f76a 100644--- a/bin/helpers/rust.ts+++ b/bin/helpers/rust.ts@@ -5,9 +5,9 @@ import chalk from 'chalk';import { execaSync } from 'execa';import { getSpinner } from '@/utils/info';+import { isCnMirrorEnabled } from '@/utils/mirror';import { IS_WIN } from '@/utils/platform';import { shellExec } from '@/utils/shell';-import { isChinaDomain } from '@/utils/ip';function normalizePathForComparison(targetPath: string) {const normalized = path.normalize(targetPath);@@ -68,19 +68,16 @@ export function ensureRustEnv() {}export async function installRust() {- const isActions = process.env.GITHUB_ACTIONS;- const isInChina = await isChinaDomain('sh.rustup.rs');- const rustInstallScriptForMac =- isInChina && !isActions- ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'- : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";+ const rustInstallScriptForUnix = isCnMirrorEnabled()+ ? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh'+ : "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';const spinner = getSpinner('Downloading Rust...');try {await shellExec(- IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac,+ IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForUnix,300000,undefined,);diff --git a/bin/utils/ip.ts b/bin/utils/ip.tsdeleted file mode 100644index daf29999..00000000--- a/bin/utils/ip.ts+++ /dev/null@@ -1,57 +0,0 @@-import dns from 'dns';-import http from 'http';-import { promisify } from 'util';--import logger from '@/options/logger';--const resolve = promisify(dns.resolve);--const ping = async (host: string) => {- const lookup = promisify(dns.lookup);- const ip = await lookup(host);- const start = new Date();-- // Prevent timeouts from affecting user experience.- const requestPromise = new Promise<number>((resolve, reject) => {- const req = http.get(`http://${ip.address}`, (res) => {- const delay = new Date().getTime() - start.getTime();- res.resume();- resolve(delay);- });-- req.on('error', (err) => {- reject(err);- });- });-- const timeoutPromise = new Promise<number>((_, reject) => {- setTimeout(() => {- reject(new Error('Request timed out after 3 seconds'));- }, 1000);- });-- return Promise.race([requestPromise, timeoutPromise]);-};--async function isChinaDomain(domain: string): Promise<boolean> {- try {- const [ip] = await resolve(domain);- return await isChinaIP(ip, domain);- } catch (error) {- logger.debug(`${domain} can't be parse!`);- return true;- }-}--async function isChinaIP(ip: string, domain: string): Promise<boolean> {- try {- const delay = await ping(ip);- logger.debug(`${domain} latency is ${delay} ms`);- return delay > 1000;- } catch (error) {- logger.debug(`ping ${domain} failed!`);- return true;- }-}--export { isChinaDomain, isChinaIP };diff --git a/bin/utils/mirror.ts b/bin/utils/mirror.tsnew file mode 100644index 00000000..aa4d589c--- /dev/null+++ b/bin/utils/mirror.ts@@ -0,0 +1,7 @@+const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);++export const CN_MIRROR_ENV = 'PAKE_USE_CN_MIRROR';++export function isCnMirrorEnabled(value = process.env[CN_MIRROR_ENV]): boolean {+ return TRUE_VALUES.has((value ?? '').trim().toLowerCase());+}diff --git a/dist/cli.js b/dist/cli.jsindex 9f4ddb8b..076d2e4a 100644--- a/dist/cli.js+++ b/dist/cli.js@@ -10,9 +10,6 @@ import os from 'os';import { execa, execaSync } from 'execa';import crypto from 'crypto';import ora from 'ora';-import dns from 'dns';-import http from 'http';-import { promisify } from 'util';import fs from 'fs/promises';import { dir } from 'tmp-promise';import { fileTypeFromBuffer } from 'file-type';@@ -23,18 +20,18 @@ import { InvalidArgumentError, program as program$1, Option } from 'commander';import fs$1 from 'fs';var name = "pake-cli";-var version = "3.11.3";+var version = "3.11.4";var description = "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。";var engines = {node: ">=18.0.0"};var packageManager = "[email protected]";var bin = {- pake: "./dist/cli.js"+ pake: "dist/cli.js"};var repository = {type: "git",- url: "https://github.com/tw93/pake.git"+ url: "git+https://github.com/tw93/pake.git"};var author = {name: "Tw93",@@ -220,6 +217,12 @@ function getSpinner(text) {}).start();}+const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);+const CN_MIRROR_ENV = 'PAKE_USE_CN_MIRROR';+function isCnMirrorEnabled(value = process.env[CN_MIRROR_ENV]) {+ return TRUE_VALUES.has((value ?? '').trim().toLowerCase());+}+const { platform: platform$1 } = process;const IS_MAC = platform$1 === 'darwin';const IS_WIN = platform$1 === 'win32';@@ -279,69 +282,6 @@ async function shellExec(command, timeout = 300000, env) {}}-const logger = {- info(...msg) {- log.info(...msg.map((m) => chalk.white(m)));- },- debug(...msg) {- log.debug(...msg);- },- error(...msg) {- log.error(...msg.map((m) => chalk.red(m)));- },- warn(...msg) {- log.warn(...msg.map((m) => chalk.yellow(m)));- },- success(...msg) {- log.info(...msg.map((m) => chalk.green(m)));- },-};--const resolve = promisify(dns.resolve);-const ping = async (host) => {- const lookup = promisify(dns.lookup);- const ip = await lookup(host);- const start = new Date();- // Prevent timeouts from affecting user experience.- const requestPromise = new Promise((resolve, reject) => {- const req = http.get(`http://${ip.address}`, (res) => {- const delay = new Date().getTime() - start.getTime();- res.resume();- resolve(delay);- });- req.on('error', (err) => {- reject(err);- });- });- const timeoutPromise = new Promise((_, reject) => {- setTimeout(() => {- reject(new Error('Request timed out after 3 seconds'));- }, 1000);- });- return Promise.race([requestPromise, timeoutPromise]);-};-async function isChinaDomain(domain) {- try {- const [ip] = await resolve(domain);- return await isChinaIP(ip, domain);- }- catch (error) {- logger.debug(`${domain} can't be parse!`);- return true;- }-}-async function isChinaIP(ip, domain) {- try {- const delay = await ping(ip);- logger.debug(`${domain} latency is ${delay} ms`);- return delay > 1000;- }- catch (error) {- logger.debug(`ping ${domain} failed!`);- return true;- }-}-function normalizePathForComparison(targetPath) {const normalized = path.normalize(targetPath);return IS_WIN ? normalized.toLowerCase() : normalized;@@ -389,15 +329,13 @@ function ensureRustEnv() {ensureCargoBinOnPath();}async function installRust() {- const isActions = process.env.GITHUB_ACTIONS;- const isInChina = await isChinaDomain('sh.rustup.rs');- const rustInstallScriptForMac = isInChina && !isActions+ const rustInstallScriptForUnix = isCnMirrorEnabled()? 'export RUSTUP_DIST_SERVER="https://rsproxy.cn" && export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup" && curl --proto "=https" --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh': "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y";const rustInstallScriptForWindows = 'winget install --id Rustlang.Rustup';const spinner = getSpinner('Downloading Rust...');try {- await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForMac, 300000, undefined);+ await shellExec(IS_WIN ? rustInstallScriptForWindows : rustInstallScriptForUnix, 300000, undefined);spinner.succeed(chalk.green('✔ Rust installed successfully!'));ensureRustEnv();}@@ -443,6 +381,24 @@ async function combineFiles(files, output) {return files;}+const logger = {+ info(...msg) {+ log.info(...msg.map((m) => chalk.white(m)));+ },+ debug(...msg) {+ log.debug(...msg);+ },+ error(...msg) {+ log.error(...msg.map((m) => chalk.red(m)));+ },+ warn(...msg) {+ log.warn(...msg.map((m) => chalk.yellow(m)));+ },+ success(...msg) {+ log.info(...msg.map((m) => chalk.green(m)));+ },+};+function generateSafeFilename(name) {return name.replace(/[<>:"/\\|?*]/g, '_')@@ -873,6 +829,40 @@ class BaseBuilder {throw error;}}+ getInstallCommand(packageManager, useCnMirror) {+ const registryOption = useCnMirror+ ? ' --registry=https://registry.npmmirror.com'+ : '';+ const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';+ return `cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`;+ }+ isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig) {+ return projectConfig.trim() === cnMirrorConfig.trim();+ }+ async configureCargoRegistry(tauriSrcPath, useCnMirror) {+ const rustProjectDir = path.join(tauriSrcPath, '.cargo');+ const projectConf = path.join(rustProjectDir, 'config.toml');+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');+ if (useCnMirror) {+ await fsExtra.ensureDir(rustProjectDir);+ await this.copyFileWithSamePathGuard(projectCnConf, projectConf);+ return;+ }+ if (!(await fsExtra.pathExists(projectConf))) {+ return;+ }+ const [projectConfig, cnMirrorConfig] = await Promise.all([+ fsExtra.readFile(projectConf, 'utf8'),+ fsExtra.readFile(projectCnConf, 'utf8'),+ ]);+ if (this.isGeneratedCnMirrorConfig(projectConfig, cnMirrorConfig)) {+ await fsExtra.remove(projectConf);+ return;+ }+ if (projectConfig.includes('rsproxy.cn')) {+ logger.warn(`✼ ${projectConf} still references rsproxy.cn. Remove it or set ${CN_MIRROR_ENV}=1 if you want to use the CN mirror.`);+ }+ }async prepare() {const tauriSrcPath = path.join(npmDirectory, 'src-tauri');const tauriTargetPath = path.join(tauriSrcPath, 'target');@@ -896,15 +886,11 @@ class BaseBuilder {process.exit(1);}}- const isChina = await isChinaDomain('www.npmjs.com');const spinner = getSpinner('Installing package...');- const rustProjectDir = path.join(tauriSrcPath, '.cargo');- const projectConf = path.join(rustProjectDir, 'config.toml');- await fsExtra.ensureDir(rustProjectDir);+ const useCnMirror = isCnMirrorEnabled();+ await this.configureCargoRegistry(tauriSrcPath, useCnMirror);// Detect available package managerconst packageManager = await this.detectPackageManager();- const registryOption = ' --registry=https://registry.npmmirror.com';- const peerDepsOption = packageManager === 'npm' ? ' --legacy-peer-deps' : '';const timeout = this.getInstallTimeout();const buildEnv = this.getBuildEnvironment();// Show helpful message for first-time users@@ -913,43 +899,22 @@ class BaseBuilder {? '✺ First-time setup may take 10-15 minutes on Windows (compiling dependencies)...': '✺ First-time setup may take 5-10 minutes (installing dependencies)...');}- let usedMirror = isChina;+ if (useCnMirror) {+ logger.info(`✺ ${CN_MIRROR_ENV}=1 detected, using ${packageManager}/rsProxy CN mirror.`);+ }try {- if (isChina) {- logger.info(`✺ Located in China, using ${packageManager}/rsProxy CN mirror.`);- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);- await shellExec(`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`, timeout, { ...buildEnv, CI: 'true' });- }- else {- await shellExec(`cd "${npmDirectory}" && ${packageManager} install${peerDepsOption}`, timeout, { ...buildEnv, CI: 'true' });- }+ await shellExec(this.getInstallCommand(packageManager, useCnMirror), timeout, {+ ...buildEnv,+ CI: 'true',+ });spinner.succeed(chalk.green('Package installed!'));}catch (error) {- // If installation times out and we haven't tried the mirror yet, retry with mirror- if (error instanceof Error &&- error.message.includes('timed out') &&- !usedMirror) {- spinner.fail(chalk.yellow('Installation timed out, retrying with CN mirror...'));- logger.info('✺ Retrying installation with CN mirror for better speed...');- const retrySpinner = getSpinner('Retrying installation...');- usedMirror = true;- try {- const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');- await this.copyFileWithSamePathGuard(projectCnConf, projectConf);- await shellExec(`cd "${npmDirectory}" && ${packageManager} install${registryOption}${peerDepsOption}`, timeout, { ...buildEnv, CI: 'true' });- retrySpinner.succeed(chalk.green('Package installed with CN mirror!'));- }- catch (retryError) {- retrySpinner.fail(chalk.red('Installation failed'));- throw retryError;- }- }- else {- spinner.fail(chalk.red('Installation failed'));- throw error;+ spinner.fail(chalk.red('Installation failed'));+ if (!useCnMirror) {+ logger.info(`✺ If downloads are slow in China, retry with ${CN_MIRROR_ENV}=1 to use CN mirrors.`);}+ throw error;}if (!tauriTargetPathExists) {logger.warn('✼ The first packaging may be slow, please be patient and wait, it will be faster afterwards.');diff --git a/docs/faq.md b/docs/faq.mdindex edbeda1b..4c81dedf 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -219,13 +219,23 @@ First-time installation on Windows can be slow due to:- Windows Defender real-time scanning- Network connectivity issues-**Solution 1: Automatic Retry (Built-in)**+**Solution 1: Enable CN Mirror Explicitly**-Pake CLI now automatically retries with CN mirror if the initial installation times out. Simply wait for the retry to complete.+Pake CLI uses the official npm and Rust sources by default. If downloads are slow in China, opt in to CN mirrors:++```bash+# macOS/Linux+PAKE_USE_CN_MIRROR=1 pake https://github.com --name GitHub+```++```powershell+# Windows PowerShell+$env:PAKE_USE_CN_MIRROR="1"; pake https://github.com --name GitHub+```**Solution 2: Manual Installation**-If automatic retry fails, manually install dependencies:+If dependency installation still fails, manually install dependencies:```bash# Navigate to pake-cli installation directorydiff --git a/docs/faq_CN.md b/docs/faq_CN.mdindex 87085ec7..d1c56c6d 100644--- a/docs/faq_CN.md+++ b/docs/faq_CN.md@@ -219,13 +219,23 @@ Windows 首次安装可能较慢,原因包括:- Windows Defender 实时扫描- 网络连接问题-**解决方案 1:自动重试(内置)**+**解决方案 1:显式启用国内镜像**-Pake CLI 现在会在初次安装超时后自动使用国内镜像重试。只需等待重试完成即可。+Pake CLI 默认使用官方 npm 和 Rust 源。如果在国内下载较慢,可以显式启用国内镜像:++```bash+# macOS/Linux+PAKE_USE_CN_MIRROR=1 pake https://github.com --name GitHub+```++```powershell+# Windows PowerShell+$env:PAKE_USE_CN_MIRROR="1"; pake https://github.com --name GitHub+```**解决方案 2:手动安装依赖**-如果自动重试失败,可手动安装依赖:+如果依赖安装仍然失败,可手动安装依赖:```bash# 进入 pake-cli 安装目录diff --git a/package.json b/package.jsonindex b9c66e6e..9e601609 100644--- a/package.json+++ b/package.json@@ -1,17 +1,17 @@{"name": "pake-cli",- "version": "3.11.3",+ "version": "3.11.4","description": "🤱🏻 Turn any webpage into a desktop app with one command. 🤱🏻 一键打包网页生成轻量桌面应用。","engines": {"node": ">=18.0.0"},"packageManager": "[email protected]","bin": {- "pake": "./dist/cli.js"+ "pake": "dist/cli.js"},"repository": {"type": "git",- "url": "https://github.com/tw93/pake.git"+ "url": "git+https://github.com/tw93/pake.git"},"author": {"name": "Tw93",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0c0d29bf..9ebec02d 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "pake"-version = "3.11.3"+version = "3.11.4"description = "🤱🏻 Turn any webpage into a desktop app with Rust."authors = ["Tw93"]license = "MIT"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex f41d38a2..65c4b6b0 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"productName": "Weekly","identifier": "com.pake.weekly",- "version": "3.11.3",+ "version": "3.11.4","app": {"withGlobalTauri": true,"trayIcon": {diff --git a/tests/unit/base-builder.test.ts b/tests/unit/base-builder.test.tsindex 61d50293..6f70a26b 100644--- a/tests/unit/base-builder.test.ts+++ b/tests/unit/base-builder.test.ts@@ -1,3 +1,4 @@+import os from 'os';import path from 'path';import fsExtra from 'fs-extra';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -8,6 +9,8 @@ vi.mock('@/utils/dir', () => ({}));import BaseBuilder from '@/builders/BaseBuilder';+import logger from '@/options/logger';+import { CN_MIRROR_ENV, isCnMirrorEnabled } from '@/utils/mirror';class TestBuilder extends BaseBuilder {getFileName(): string {@@ -15,9 +18,50 @@ class TestBuilder extends BaseBuilder {}}+const originalCnMirrorEnv = process.env[CN_MIRROR_ENV];+const tempDirs: string[] = [];++const GENERATED_MIRROR_CONFIG = `[source.crates-io]+replace-with = 'rsproxy-sparse'+[source.rsproxy]+registry = "https://rsproxy.cn/crates.io-index"+[source.rsproxy-sparse]+registry = "sparse+https://rsproxy.cn/index/"+[registries.rsproxy]+index = "https://rsproxy.cn/crates.io-index"+[net]+git-fetch-with-cli = true+`;++async function createCargoFixture(projectConfig?: string) {+ const tempDir = await fsExtra.mkdtemp(+ path.join(os.tmpdir(), 'pake-base-builder-'),+ );+ tempDirs.push(tempDir);++ const tauriSrcPath = path.join(tempDir, 'src-tauri');+ const projectConf = path.join(tauriSrcPath, '.cargo', 'config.toml');+ const projectCnConf = path.join(tauriSrcPath, 'rust_proxy.toml');++ await fsExtra.outputFile(projectCnConf, GENERATED_MIRROR_CONFIG);+ if (projectConfig !== undefined) {+ await fsExtra.outputFile(projectConf, projectConfig);+ }++ return { tauriSrcPath, projectConf, projectCnConf };+}+describe('BaseBuilder guards', () => {- afterEach(() => {+ afterEach(async () => {vi.restoreAllMocks();++ if (originalCnMirrorEnv === undefined) {+ delete process.env[CN_MIRROR_ENV];+ } else {+ process.env[CN_MIRROR_ENV] = originalCnMirrorEnv;+ }++ await Promise.all(tempDirs.splice(0).map((dir) => fsExtra.remove(dir)));});it('prepends /usr/bin to PATH for macOS build environment', () => {@@ -70,4 +114,78 @@ describe('BaseBuilder guards', () => {(builder as any).copyFileWithSamePathGuard('/tmp/a', '/tmp/b'),).rejects.toThrow('permission denied');});++ it('does not enable CN mirror by default', () => {+ delete process.env[CN_MIRROR_ENV];++ expect(isCnMirrorEnabled()).toBe(false);+ expect(isCnMirrorEnabled('false')).toBe(false);+ expect(isCnMirrorEnabled('0')).toBe(false);+ });++ it.each(['1', 'true', 'yes', 'on', ' TRUE '])(+ 'enables CN mirror for %s',+ (value) => {+ process.env[CN_MIRROR_ENV] = value;++ expect(isCnMirrorEnabled()).toBe(true);+ },+ );++ it('uses official npm registry by default', () => {+ const builder = new TestBuilder({} as any);+ const command = (builder as any).getInstallCommand('pnpm', false);++ expect(command).toContain('pnpm install');+ expect(command).not.toContain('registry.npmmirror.com');+ });++ it('uses npmmirror only when CN mirror is enabled', () => {+ const builder = new TestBuilder({} as any);+ const command = (builder as any).getInstallCommand('npm', true);++ expect(command).toContain(+ 'npm install --registry=https://registry.npmmirror.com --legacy-peer-deps',+ );+ });++ it('copies Cargo mirror config only when CN mirror is enabled', async () => {+ const builder = new TestBuilder({} as any);+ const { tauriSrcPath, projectConf, projectCnConf } =+ await createCargoFixture();++ await (builder as any).configureCargoRegistry(tauriSrcPath, true);++ expect(await fsExtra.readFile(projectConf, 'utf8')).toBe(+ await fsExtra.readFile(projectCnConf, 'utf8'),+ );+ });++ it('removes generated Cargo mirror config when CN mirror is disabled', async () => {+ const builder = new TestBuilder({} as any);+ const { tauriSrcPath, projectConf } = await createCargoFixture(+ GENERATED_MIRROR_CONFIG,+ );++ await (builder as any).configureCargoRegistry(tauriSrcPath, false);++ expect(await fsExtra.pathExists(projectConf)).toBe(false);+ });++ it('keeps custom Cargo config when CN mirror is disabled', async () => {+ const builder = new TestBuilder({} as any);+ const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});+ const customConfig = `${GENERATED_MIRROR_CONFIG}+# custom user setting+`;+ const { tauriSrcPath, projectConf } =+ await createCargoFixture(customConfig);++ await (builder as any).configureCargoRegistry(tauriSrcPath, false);++ expect(await fsExtra.readFile(projectConf, 'utf8')).toBe(customConfig);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('still references rsproxy.cn'),+ );+ });});