reconcile.mjs 5.53 KB
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createAliases } from '../packages/vite-config/src/aliases.mjs';

/**
 * 工程对账:不依赖 pnpm install,纯读磁盘把「配置漂移」翻出来。
 * 内核(.kernel/)与业务(apps/*)物理分离后,本脚本校验:
 *  1. workspace:* 指向的包是否真的在 workspace 里
 *  2. catalog: 引用的依赖是否在 pnpm-workspace.yaml 的 default catalog 里
 *  3. Vite alias / tsconfig paths 的目标文件是否真实存在
 *  4. 内核 shell 与业务子应用的必需文件与端口是否齐备、有没有撞端口
 *
 * ROOT 从 .kernel/scripts 上溯两级。
 */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const problems = [];
const notes = [];

function collect(dir, filename) {
  const out = [];
  if (!fs.existsSync(dir)) return out;
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (['node_modules', '.git', 'dist', '.turbo', '.tmp'].includes(entry.name)) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) out.push(...collect(full, filename));
    else if (entry.name === filename) out.push(full);
  }
  return out;
}

const pkgFiles = collect(ROOT, 'package.json');
const byName = new Map();
for (const file of pkgFiles) {
  try {
    const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
    if (pkg.name) byName.set(pkg.name, { file, pkg });
  } catch (err) {
    problems.push(`package.json 解析失败 ${path.relative(ROOT, file)}: ${err.message}`);
  }
}

// ---- 1 / 2:依赖声明 ----
const workspaceYaml = fs.readFileSync(path.join(ROOT, 'pnpm-workspace.yaml'), 'utf8');
const catalogKeys = new Set();
const catalogBlock = workspaceYaml.split('catalogs:')[1] ?? '';
for (const line of catalogBlock.split(/\r?\n/)) {
  const m = /^\s{4}'?([^:\s']+)'?:\s*\S/.exec(line);
  if (m) catalogKeys.add(m[1]);
}

for (const { file, pkg } of byName.values()) {
  const rel = path.relative(ROOT, file).split(path.sep).join('/');
  for (const section of ['dependencies', 'devDependencies', 'peerDependencies']) {
    for (const [dep, version] of Object.entries(pkg[section] ?? {})) {
      if (typeof version !== 'string') continue;
      if (version.startsWith('workspace:') && !byName.has(dep)) {
        problems.push(`${rel}: ${dep} 声明为 ${version},但 workspace 里没有这个包`);
      }
      if (version === 'catalog:' && !catalogKeys.has(dep)) {
        problems.push(`${rel}: ${dep} 写了 catalog:,但 pnpm-workspace.yaml 的 default catalog 没有它`);
      }
    }
  }
}
notes.push(`workspace 包 ${byName.size} 个 / catalog 条目 ${catalogKeys.size} 个`);

// ---- 3 / 4:alias 目标 + 必需文件 + 端口 ----
// 内核 shell + 动态扫描的业务子应用(apps/*)。新增子应用零登记。
const SHELL_DIR = path.join(ROOT, '.kernel', 'apps', 'shell');
const APPS = [{ dir: SHELL_DIR, kind: 'shell', rel: '.kernel/apps/shell' }];
const APPS_ROOT = path.join(ROOT, 'apps');
if (fs.existsSync(APPS_ROOT)) {
  for (const e of fs.readdirSync(APPS_ROOT, { withFileTypes: true })) {
    if (e.isDirectory() && fs.existsSync(path.join(APPS_ROOT, e.name, 'package.json'))) {
      APPS.push({
        dir: path.join(APPS_ROOT, e.name),
        kind: 'subapp',
        rel: `apps/${e.name}`,
      });
    }
  }
}

const COMMON = ['index.html', 'vite.config.ts', 'tsconfig.json', 'src/main.tsx'];
const SHELL_ONLY = [
  'src/router.tsx', 'src/MicroApp.tsx', 'src/subapps.ts',
  'src/subapp-props.ts', 'src/layouts/BasicLayout.tsx', 'src/theme/design.css',
];
const SUBAPP_ONLY = ['src/App.tsx', 'src/wujie.d.ts', 'src/index.css', 'src/api/index.ts'];
const ports = new Map();

for (const { dir, kind, rel } of APPS) {
  if (!fs.existsSync(dir)) {
    problems.push(`缺应用目录 ${rel}`);
    continue;
  }
  for (const alias of createAliases({ appDir: dir, kind })) {
    // 通配符 alias(如 @app/$1 -> packages/$1/src)的替换串含 $n 捕获组,
    // 目标路径随具体业务包而变,静态无法判定存在性——跳过,交给运行时解析。
    if (/\$\d/.test(alias.replacement)) continue;
    const target = alias.replacement.replace(/[\\/]$/, '');
    if (!fs.existsSync(target)) {
      problems.push(`${rel}: alias ${alias.find} -> ${alias.replacement} 目标不存在`);
    }
  }
  const REQUIRED = [...COMMON, ...(kind === 'shell' ? SHELL_ONLY : SUBAPP_ONLY)];
  for (const f of REQUIRED) {
    if (!fs.existsSync(path.join(dir, f))) problems.push(`${rel}: 缺 ${f}`);
  }
  const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
  const vite = fs.readFileSync(path.join(dir, 'vite.config.ts'), 'utf8');
  const portMatch = /port:\s*(\d+)/.exec(vite);
  const declared = pkg.venus?.entry;
  if (portMatch) {
    const port = portMatch[1];
    if (ports.has(port)) problems.push(`${rel} 与 ${ports.get(port)} 撞端口 ${port}`);
    ports.set(port, rel);
    if (declared && !declared.includes(`:${port}`)) {
      problems.push(`${rel}: venus.entry=${declared} 与 vite.config.ts 的 port=${port} 不一致`);
    }
  }
  if (pkg.venus?.route && !/^[\w-]+$/.test(pkg.venus.route)) {
    problems.push(`${rel}: venus.route=${pkg.venus.route} 不是合法路由前缀`);
  }
}
notes.push(`端口:${[...ports.entries()].map(([p, d]) => `${d}=${p}`).join(' / ')}`);

for (const n of notes) console.log(`[reconcile] ${n}`);
for (const p of problems) console.error(`  ✗ ${p}`);
console.log(`[reconcile] 问题 ${problems.length}`);
if (problems.length) process.exit(1);
console.log('[reconcile] 通过');