reconcile.mjs 5.17 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,纯读磁盘把「配置漂移」翻出来。
 *
 * 检查四类最容易静默出错的事:
 *  1. workspace:* 指向的包是否真的在 workspace 里
 *  2. catalog: 引用的依赖是否在 pnpm-workspace.yaml 的 default catalog 里
 *  3. Vite alias / tsconfig paths 的目标文件是否真实存在(否则 dev 报「无法解析」且看不出是路径算错)
 *  4. 每个子应用的必需文件与端口是否齐备、有没有撞端口
 */
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:alias 目标 ----
const APPS = [
  { dir: 'apps/web/shell', kind: 'shell' },
  { dir: 'apps/web/micro-apps/system', kind: 'subapp' },
  { dir: 'apps/web/micro-apps/store', kind: 'subapp' },
];
for (const { dir, kind } of APPS) {
  const appDir = path.join(ROOT, dir);
  if (!fs.existsSync(appDir)) {
    problems.push(`缺应用目录 ${dir}`);
    continue;
  }
  for (const alias of createAliases({ appDir, kind })) {
    const target = alias.replacement.replace(/\$1$/, '').replace(/[\\/]$/, '');
    if (!fs.existsSync(target)) {
      problems.push(`${dir}: alias ${alias.find} -> ${alias.replacement} 目标不存在`);
    }
  }
}

// ---- 4:子应用必需文件与端口 ----
// shell 与子应用的必需文件不同:主壳没有 App.tsx/wujie.d.ts,子应用没有 router/MicroApp。
const COMMON = [
  'index.html',
  'vite.config.ts',
  'tsconfig.json',
  'src/main.tsx',
  'src/api/index.ts',
];
const SHELL_ONLY = [
  'src/router.tsx',
  'src/MicroApp.tsx',
  'src/subapps.ts',
  'src/subapp-props.ts',
  'src/subapp-handshake.ts',
  'src/layouts/BasicLayout.tsx',
  'src/theme/design.css',
];
const SUBAPP_ONLY = ['src/App.tsx', 'src/wujie.d.ts', 'src/index.css', 'src/api/core/client.ts'];
const ports = new Map();
for (const { dir, kind } of APPS) {
  const appDir = path.join(ROOT, dir);
  const REQUIRED = [...COMMON, ...(kind === 'shell' ? SHELL_ONLY : SUBAPP_ONLY)];
  for (const f of REQUIRED) {
    if (!fs.existsSync(path.join(appDir, f))) problems.push(`${dir}: 缺 ${f}`);
  }
  const pkg = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'));
  const vite = fs.readFileSync(path.join(appDir, 'vite.config.ts'), 'utf8');
  const portMatch = /port:\s*(\d+)/.exec(vite);
  const declared = pkg.uj?.entry;
  if (portMatch) {
    const port = portMatch[1];
    if (ports.has(port)) problems.push(`${dir} 与 ${ports.get(port)} 撞端口 ${port}`);
    ports.set(port, dir);
    if (declared && !declared.includes(`:${port}`)) {
      problems.push(`${dir}: uj.entry=${declared} 与 vite.config.ts 的 port=${port} 不一致`);
    }
  }
  if (pkg.uj?.route && !/^[\w-]+$/.test(pkg.uj.route)) {
    problems.push(`${dir}: uj.route=${pkg.uj.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] 通过');