buildToRoot.mjs 6.53 KB
/**
 * 自定义构建脚本
 * 功能:
 * 1. 清理根目录的 dist 文件夹
 * 2. 安装指定项目的依赖(智能检测)
 * 3. 构建指定的项目
 * 4. 将构建产物复制到根目录的 dist 文件夹
 */

import { execSync } from "node:child_process";
import { existsSync, mkdirSync, rmSync, statSync } from "node:fs";
import { copyFile, readdir, readFile } from "node:fs/promises";
import { join } from "node:path";

// 常量定义
const rootDir = process.cwd();
const rootDistDir = join(rootDir, "dist");
const PACKAGE_SEARCH_PATHS = [
	[ "apps", "web", "venus-agentic" ],
	[ "apps", "web" ],
	[ "apps", "frontend-micro" ],
	[ "apps", "frontend", "vue" ],
	[ "apps" ],
	[ "packages" ],
	[ "docs" ],
];

// ==================== 构建配置开关 ====================
/**
 * 是否在构建前安装依赖
 * - true:  启用依赖安装(默认,智能检测)
 * - false: 跳过依赖安装步骤
 */
const ENABLE_INSTALL_DEPS = true;

/**
 * 是否强制安装依赖(仅在 ENABLE_INSTALL_DEPS 为 true 时生效)
 * - true:  强制重新安装依赖,跳过智能检测
 * - false: 智能检测依赖是否需要安装(默认)
 */
const FORCE_INSTALL_DEPS = false;
// ====================================================

// 公共执行配置
const execConfig = {
	stdio: "inherit",
	cwd: rootDir,
	shell: true,
	env: {
		...process.env,
		NODE_OPTIONS: "--max-old-space-size=8192",
	},
};

/**
 * 执行命令的统一封装
 */
function execCommand(command, errorMsg) {
	try {
		execSync(command, execConfig);
	} catch (error) {
		console.error(errorMsg);
		console.error(`错误详情: ${error?.message || String(error)}`);
		process.exit(1);
	}
}

/**
 * 清理根目录的 dist 文件夹
 */
function cleanRootDist() {
	console.log("清理根目录的 dist 文件夹...");
	if (existsSync(rootDistDir)) {
		rmSync(rootDistDir, { recursive: true, force: true });
		console.log("根目录 dist 文件夹已清理");
	} else {
		console.log("根目录 dist 文件夹不存在,跳过清理");
	}
}

/**
 * 查找包的路径
 */
async function findPackagePath(packageName) {
	const cleanName = packageName.replace("@venus/", "");
	const nameVariants = new Set([ `@venus/${cleanName}`, cleanName, packageName ]);

	for (const pathSegments of PACKAGE_SEARCH_PATHS) {
		const packagePath = join(rootDir, ...pathSegments, cleanName);
		if (!existsSync(packagePath)) continue;

		const packageJsonPath = join(packagePath, "package.json");
		if (!existsSync(packageJsonPath)) continue;

		try {
			const content = await readFile(packageJsonPath, "utf8");
			const packageJson = JSON.parse(content);
			if (nameVariants.has(packageJson.name)) {
				return packagePath;
			}
		} catch {
			// 忽略解析错误,继续查找
		}
	}

	return null;
}

/**
 * 检查是否需要安装依赖
 */
async function shouldInstallDeps(packageName) {
	const packagePath = await findPackagePath(packageName);
	if (!packagePath) return true;

	const nodeModulesPath = join(packagePath, "node_modules");
	if (!existsSync(nodeModulesPath)) return true;

	const packageJsonPath = join(packagePath, "package.json");
	const pnpmLockPath = join(rootDir, "pnpm-lock.yaml");
	if (!existsSync(packageJsonPath) || !existsSync(pnpmLockPath)) return true;

	try {
		const [ packageJsonTime, lockTime, nodeModulesTime ] = [
			statSync(packageJsonPath).mtime,
			statSync(pnpmLockPath).mtime,
			statSync(nodeModulesPath).mtime,
		];
		return packageJsonTime > nodeModulesTime || lockTime > nodeModulesTime;
	} catch {
		return true;
	}
}

/**
 * 安装指定项目的依赖
 */
async function installDeps(packageName, force = false) {
	if (!force) {
		console.log(`\n📥 检查依赖状态: ${packageName}`);
		if (!(await shouldInstallDeps(packageName))) {
			console.log("✅ 依赖已是最新,跳过安装");
			return;
		}
	}

	console.log(`\n📦 开始安装依赖: ${packageName}`);
	execCommand(`pnpm install --filter="${packageName}" --prefer-offline`, `❌ 依赖安装失败: ${packageName}`);
	console.log(`✅ 依赖安装完成: ${packageName}`);
}

/**
 * 构建指定的项目
 */
function buildPackage(packageName) {
	console.log(`\n📦 开始构建项目: ${packageName}`);
	execCommand(`pnpm --filter="${packageName}" run build`, `❌ 项目构建失败: ${packageName}`);
	console.log(`✅ 项目构建完成: ${packageName}`);
}

/**
 * 递归复制目录
 */
async function copyDirectory(src, dest) {
	if (!existsSync(dest)) {
		mkdirSync(dest, { recursive: true });
	}

	for (const entry of await readdir(src, { withFileTypes: true })) {
		const srcPath = join(src, entry.name);
		const destPath = join(dest, entry.name);
		await (entry.isDirectory() ? copyDirectory(srcPath, destPath) : copyFile(srcPath, destPath));
	}
}

/**
 * 复制构建产物到根目录
 */
async function copyBuildToRoot(packageName) {
	const packagePath = await findPackagePath(packageName);
	if (!packagePath) {
		console.error(`❌ 无法找到包: ${packageName}`);
		process.exit(1);
	}

	const sourceDistDir = join(packagePath, "dist");
	if (!existsSync(sourceDistDir)) {
		console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
		process.exit(1);
	}

	console.log(`\n复制构建产物到根目录...`);
	console.log(`   源目录: ${sourceDistDir}`);
	console.log(`   目标目录: ${rootDistDir}`);

	try {
		await copyDirectory(sourceDistDir, rootDistDir);
		console.log("✅ 构建产物已复制到根目录的 dist 文件夹");
	} catch (error) {
		console.error(`❌ 复制构建产物失败: ${error?.message || String(error)}`);
		process.exit(1);
	}
}

/**
 * 验证根目录
 */
function validateRootDir() {
	const workspaceFile = join(rootDir, "pnpm-workspace.yaml");
	const rootPackageJson = join(rootDir, "package.json");
	if (!existsSync(workspaceFile) && !existsSync(rootPackageJson)) {
		console.error("❌ 错误:请在项目根目录执行此命令");
		console.error(`当前目录: ${rootDir}`);
		process.exit(1);
	}
}

/**
 * 主函数
 */
async function main() {
	const packageName = process.argv[2];
	if (!packageName) {
		console.error("❌ 请指定要构建的项目名");
		process.exit(1);
	}

	validateRootDir();

	console.log("开始自定义构建流程");

	cleanRootDist();

	if (ENABLE_INSTALL_DEPS) {
		await installDeps(packageName, FORCE_INSTALL_DEPS);
	} else {
		console.log("跳过依赖安装步骤\n");
	}

	buildPackage(packageName);
	await copyBuildToRoot(packageName);

	console.log("\n✅ 构建流程完成!");
	console.log(`📁 构建产物位置: ${rootDistDir}`);
}

// 执行主函数
main().catch((error) => {
	console.error(`构建过程中出现错误: ${error.message}`);
	process.exit(1);
});