ai-direct-preview-project.mjs 7.54 KB
#!/usr/bin/env node

import child_process from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		bundleFile: "",
		name: "",
		dir: "apps/web/ai-previews",
		existingProjectRoot: "",
		force: false,
		install: false,
	};

	for (let index = 0; index < args.length; index++) {
		const arg = args[index];
		const next = args[index + 1];

		if (arg === "--bundle-file" && next) {
			parsed.bundleFile = next;
			index++;
		} else if (arg === "--name" && next) {
			parsed.name = next;
			index++;
		} else if (arg === "--dir" && next) {
			parsed.dir = next;
			index++;
		} else if (arg === "--existing-project-root" && next) {
			parsed.existingProjectRoot = next;
			index++;
		} else if (arg === "--force") {
			parsed.force = true;
		} else if (arg === "--install") {
			parsed.install = true;
		}
	}

	return parsed;
}

function readJson(filePath) {
	return JSON.parse(fs.readFileSync(filePath, "utf8"));
}

function slugify(value) {
	const normalized = String(value || "")
		.trim()
		.toLowerCase()
		.replaceAll(/[^a-z0-9]+/g, "-")
		.replaceAll(/^-+|-+$/g, "");

	return normalized || "figma-page";
}

function toAbsolutePath(targetPath) {
	return path.isAbsolute(targetPath) ? targetPath : path.resolve(targetPath);
}

function quote(value) {
	return `"${String(value).replaceAll('"', String.raw`\"`)}"`;
}

function ensureCliBuilt() {
	const cliEntry = path.join(repoRoot, "packages", "cli", "dist", "index.cjs.js");
	if (fs.existsSync(cliEntry)) {
		return;
	}

	throw new Error("Venus CLI 未构建,请先执行 pnpm run venus:build");
}

function normalizePath(targetPath) {
	return targetPath.replaceAll("\\", "/");
}

function buildPreviewArgs({ previewName, bundle, targetDir, install, force }) {
	const policy = bundle.rules.previewProjectPolicy || {};
	if (!policy.mustUseVenusCli) {
		throw new Error("当前 bundle 未声明 mustUseVenusCli,拒绝创建预览项目");
	}
	if (!policy.cliTemplate) {
		throw new Error("当前框架没有可用的 Venus CLI 模板,无法创建预览项目");
	}

	ensureCliBuilt();
	const args = [
		"venus",
		"create",
		previewName,
		"--template",
		policy.cliTemplate,
		"--dir",
		targetDir,
		"--root",
		repoRoot,
		"--router",
		"--store",
		"--eslint",
	];

	if (policy.cliUiOption) {
		args.push("--ui", policy.cliUiOption);
	}
	if (!install) {
		args.push("--no-install");
	}
	if (force) {
		args.push("--force");
	}

	return args;
}

function run() {
	const args = parseCliArgs();
	if (!args.bundleFile) {
		throw new Error(
			"用法: node scripts/ai-direct-preview-project.mjs --bundle-file <bundle.json> [--name preview-name]",
		);
	}

	const bundlePath = toAbsolutePath(args.bundleFile);
	const bundle = readJson(bundlePath);
	const summaryPath = path.join(
		path.dirname(bundlePath),
		`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.preview-project.json`,
	);
	const previewName = args.name || `${slugify(bundle.figma.pageSlug || bundle.figma.pageName)}-preview`;

	let projectPath = "";
	let command = "";
	let mode = "create";

	if (args.existingProjectRoot) {
		projectPath = toAbsolutePath(args.existingProjectRoot);
		command = "[reuse existing preview project]";
		mode = "reuse-existing";

		if (!fs.existsSync(projectPath)) {
			throw new Error(`指定的现有预览项目不存在: ${projectPath}`);
		}
	} else {
		const createArgs = buildPreviewArgs({
			previewName,
			bundle,
			targetDir: args.dir,
			install: args.install,
			force: args.force,
		});
		command = `pnpm ${createArgs.join(" ")}`;
		projectPath = path.join(repoRoot, args.dir, previewName);
	}

	console.log("[ai-direct-preview-project] 准备预览项目...");
	console.log(`  → bundle: ${bundlePath}`);
	console.log(`  → mode: ${mode}`);

	if (mode === "create") {
		console.log(`  → name: ${previewName}`);
		console.log(`  → dir: ${args.dir}`);
		console.log(`  → force: ${args.force}`);
		console.log(`  → command: ${command}`);

		// 如果目标目录已存在,清理除 .ai-direct 外的内容
		let aiDirectBackup = null;
		if (fs.existsSync(projectPath)) {
			console.log(`  → 目标目录已存在,正在清理: ${projectPath}`);
			const entries = fs.readdirSync(projectPath, { withFileTypes: true });
			for (const entry of entries) {
				if (entry.name === ".ai-direct") {
					// 备份 .ai-direct 到临时位置,创建完再移回
					aiDirectBackup = path.join(projectPath, "..", `.${previewName}-ai-direct-tmp`);
					const srcPath = path.join(projectPath, entry.name);
					
					// Windows 文件锁问题:重试 rename,失败则降级为 cpSync+rmSync
					let backedUp = false;
					for (let attempt = 0; attempt < 3; attempt++) {
						try {
							fs.renameSync(srcPath, aiDirectBackup);
							backedUp = true;
							break;
						} catch (err) {
							if (err.code === "EPERM" && attempt < 2) {
								console.warn(`  ⚠ .ai-direct 目录被占用,等待重试 (${attempt + 1}/3)...`);
								child_process.execSync("ping -n 2 127.0.0.1 > nul", { stdio: "ignore" });
							} else {
								break;
							}
						}
					}
					
					// 降级:cpSync + rmSync
					if (!backedUp) {
						try {
							console.warn(`  ⚠ 无法重命名 .ai-direct,尝试复制备份...`);
							fs.cpSync(srcPath, aiDirectBackup, { recursive: true, force: true });
							fs.rmSync(srcPath, { recursive: true, force: true });
							backedUp = true;
							console.log(`  → 备份完成(复制模式)`);
						} catch (copyErr) {
							console.warn(`  ⚠ 备份失败,删除旧 .ai-direct 继续: ${copyErr.message}`);
							fs.rmSync(srcPath, { recursive: true, force: true });
							aiDirectBackup = null;
						}
					}
					continue;
				}
				const fullPath = path.join(projectPath, entry.name);
				fs.rmSync(fullPath, { recursive: true, force: true });
			}
			// 如果目录空了则删除,让 venus create 重新创建
			const remaining = fs.readdirSync(projectPath);
			if (remaining.length === 0) {
				fs.rmSync(projectPath, { recursive: true, force: true });
			}
			console.log(`  → 清理完成`);
		}

		const createArgs = buildPreviewArgs({
			previewName,
			bundle,
			targetDir: args.dir,
			install: args.install,
			force: args.force,
		});
		child_process.execFileSync("pnpm", createArgs, {
			cwd: repoRoot,
			stdio: "inherit",
			shell: process.platform === "win32",
		});

		// 恢复 .ai-direct 备份
		if (aiDirectBackup && fs.existsSync(aiDirectBackup)) {
			const target = path.join(projectPath, ".ai-direct");
			if (fs.existsSync(target)) {
				fs.rmSync(target, { recursive: true, force: true });
			}
			fs.renameSync(aiDirectBackup, target);
			console.log(`  → 已恢复 .ai-direct 目录`);
		}
	} else {
		console.log(`  → project: ${projectPath}`);
	}

	const summary = {
		meta: {
			generator: "scripts/ai-direct-preview-project.mjs",
			generatedAt: new Date().toISOString(),
			mode,
			bundleFile: normalizePath(bundlePath),
		},
		previewProject: {
			name: path.basename(projectPath),
			projectRoot: normalizePath(projectPath),
			template: bundle.rules.previewProjectPolicy.cliTemplate,
			ui: bundle.rules.previewProjectPolicy.cliUiOption,
			install: mode === "create" ? args.install : false,
			command,
		},
	};

	fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");

	console.log("[ai-direct-preview-project] ✓ 完成");
	console.log(`  → project: ${projectPath}`);
	console.log(`  → summary: ${summaryPath}`);
}

run();
process.exit(0);