dev.mjs 14.4 KB
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * 一条命令起全站,开发者只访问 http://localhost:5173。
 *
 * wujie 的子应用必须有自己的 dev server 才有 HMR,进程数确实变多;
 * 但入口仍是一个命令、一个浏览器地址 —— 符合「一个前端」的既有要求。
 * 服务启停由人控制:本脚本不常驻、不自动拉起,Ctrl+C 会把所有子进程一起收掉。
 *
 * 用法:
 *   pnpm dev                        # shell + system + store
 *   pnpm dev --scope=shell          # 只起主壳
 *   pnpm dev --scope=store          # 只起门店域
 *
 * ── 输出约定 ─────────────────────────────────────────────────────────
 * 1. 端口只从各 app 的 vite.config.ts 读(正则同 scripts/reconcile.mjs),
 *    不在此处再维护一份真源;工厂已开 strictPort,端口不会被 vite 私自 +1,
 *    所以面板上写出的地址就是真实地址。
 * 2. 面板是「就绪报告」而不是「启动预告」:全部 dev server 拿到 ready 才打印,
 *    每个应用后面直接带真实启动耗时。启动期间只有一行进度提示,别的不刷。
 *    这样一屏就是结论,不需要再逐条打就绪行。
 * 3. 噪音收编:pnpm 的 lifecycle banner(`> @uj/xxx@0.0.0 dev <dir>` + `> vite`)
 *    用 --reporter=silent 关掉(实测只抑制 pnpm 自己的报告,vite 的报错照常到
 *    stderr);vite 的三行 banner(版本 / Local / Network)在输出层吞掉并转成
 *    ready 信号。其余输出(重优化、报错、HMR)原样转发。
 * 4. 非 TTY(重定向到文件 / CI)自动关闭颜色,避免日志里留 ANSI 转义。
 */

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const argv = process.argv.slice(2);
const scopeArg = argv.find((a) => a.startsWith('--scope='));
const scope = scopeArg ? scopeArg.slice('--scope='.length).split(',') : null;

// ─── 终端样式 ────────────────────────────────────────────────────────
// 只用标准 16 色 + bold/faint:256 色的浅色号在浅色终端里会看不见。
const COLOR =
  Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && !process.env.TERM?.includes('dumb');
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const bold = paint('1');
const dim = paint('2');
const cyan = paint('36');
const green = paint('32');
const red = paint('31');

// 匹配 ANSI 转义序列。ESC 控制字符是必需成分:这里只用于把子进程输出 strip 成纯文本
// 再做等宽测量与 banner 识别,不参与任何输出,因此关掉 no-control-regex。
// eslint-disable-next-line no-control-regex
const ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/g;
const strip = (s) => s.replace(ANSI_RE, '');
/** 显示宽度:CJK / 全角记 2 列,否则面板右边框会参差。 */
function width(s) {
  let w = 0;
  for (const ch of strip(s)) {
    const cp = ch.codePointAt(0);
    w +=
      (cp >= 0x1100 && cp <= 0x115f) ||
      cp === 0x2329 ||
      cp === 0x232a ||
      (cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
      (cp >= 0xac00 && cp <= 0xd7a3) ||
      (cp >= 0xf900 && cp <= 0xfaff) ||
      (cp >= 0xfe30 && cp <= 0xfe6f) ||
      (cp >= 0xff00 && cp <= 0xff60) ||
      (cp >= 0xffe0 && cp <= 0xffe6)
        ? 2
        : 1;
  }
  return w;
}
const padEnd = (s, n) => s + ' '.repeat(Math.max(0, n - width(s)));
const padStart = (s, n) => ' '.repeat(Math.max(0, n - width(s))) + s;

// ─── 应用发现 ────────────────────────────────────────────────────────
/** 从 vite.config.ts 读端口,与 scripts/reconcile.mjs 的正则保持一致。 */
function readPort(appDir) {
  const viteFile = path.join(appDir, 'vite.config.ts');
  if (!fs.existsSync(viteFile)) return null;
  const m = /port:\s*(\d+)/.exec(fs.readFileSync(viteFile, 'utf8'));
  return m ? m[1] : null;
}

function collectApps(dir) {
  const out = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (!entry.isDirectory() || entry.name === 'node_modules' || entry.name === 'dist') continue;
    const appDir = path.join(dir, entry.name);
    const pkgPath = path.join(appDir, 'package.json');
    if (fs.existsSync(pkgPath)) {
      const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
      if (pkg.scripts?.dev) {
        const port = readPort(appDir);
        out.push({
          name: pkg.name,
          short: pkg.name.replace('@uj/web-', ''),
          dir: path.relative(ROOT, appDir).split(path.sep).join('/'),
          port,
          url: pkg.uj?.entry ?? (port ? `http://localhost:${port}/` : null),
          // 运行期状态,面板据此着色
          ms: null,
          failed: null,
        });
      }
    } else {
      out.push(...collectApps(appDir));
    }
  }
  return out;
}

// shell 恒排第一(它是唯一入口),其余按名字排 —— 不依赖 readdir 的返回顺序。
const apps = collectApps(path.join(ROOT, 'apps', 'web'))
  .filter((a) => !scope || scope.includes(a.short))
  .sort((a, b) =>
    a.short === 'shell' ? -1 : b.short === 'shell' ? 1 : a.short.localeCompare(b.short),
  );

if (apps.length === 0) {
  console.error(
    `${dim('▎')} ${bold('UJ Admin')} 没有找到可启动的应用,检查 apps/web 下的 package.json。`,
  );
  process.exit(1);
}

const GUTTER = '  ';
const entry = apps.find((a) => a.short === 'shell') ?? null;
const entryUrl = entry?.url ?? (entry?.port ? `http://localhost:${entry.port}/` : null);

// ─── 局域网共享模式 ─────────────────────────────────────────────────
// 默认自动探测本机物理网卡 IPv4,把子应用入口通过 VITE_<SHORT>_SUBAPP_URL 注入主壳,
// 覆盖 package.json 里写死的 http://localhost:<port>/(开发默认)。这样同事用
// http://<IP>:5173/ 开主壳时,wujie 会按同一 IP 去拉子应用,而不是连他自己机器。
//   · 关闭(纯本地):UJ_DEV_LAN=0
//   · 手动指定 IP:UJ_DEV_HOST=192.168.1.50   (跳过自动探测,适合多网卡/ VPN 环境)
const lanRaw = (process.env.UJ_DEV_LAN ?? '1').toLowerCase();
const lanEnabled = lanRaw !== '0' && lanRaw !== 'false' && lanRaw !== 'no';

function getLanIp() {
  if (process.env.UJ_DEV_HOST) return process.env.UJ_DEV_HOST;
  // 跳过虚拟网卡(WSL / Docker / VMware / VPN / 隧道等),避免选到同事访问不了的地址。
  const skipNic =
    /wsl|docker|vmnet|virtualbox|vethernet|hyper-?v|tap|tun|wireguard|tailscale|openvpn|zero?tier|utun|ppp|loopback|isatap|teredo|6to4/i;
  const cands = [];
  for (const [name, list] of Object.entries(os.networkInterfaces())) {
    if (!list || skipNic.test(name)) continue;
    for (const ni of list) {
      if (ni.family !== 'IPv4' || ni.internal) continue;
      if (ni.address.startsWith('169.254.')) continue; // link-local,不是真实 LAN
      let rank = 3;
      if (ni.address.startsWith('192.168.')) rank = 0;
      else if (ni.address.startsWith('10.')) rank = 1;
      else if (/^172\.(1[6-9]|2\d|3[01])\./.test(ni.address)) rank = 2;
      cands.push({ ip: ni.address, rank });
    }
  }
  cands.sort((a, b) => a.rank - b.rank);
  return cands[0]?.ip ?? null;
}

const lanHost = lanEnabled ? getLanIp() : null;
const lanEntryUrl = lanHost ? `http://${lanHost}:${entry?.port ?? 5173}/` : null;
// 只给主壳进程注入:subapps.ts 在主壳里读这些 env 推导子应用入口(package.json 优先级低于 env)。
const lanEnv = lanHost
  ? Object.fromEntries(
      apps
        .filter((a) => a.short !== 'shell' && a.port)
        .map((a) => [`VITE_${a.short.toUpperCase()}_SUBAPP_URL`, `http://${lanHost}:${a.port}/`]),
    )
  : {};

// ─── 就绪报告面板 ────────────────────────────────────────────────────
/** 一个应用一种颜色,让日志前缀与面板里的名字对得上。 */
const APP_COLORS = ['36', '35', '32', '34', '33'];
const colorOf = new Map(apps.map((a, i) => [a.short, paint(APP_COLORS[i % APP_COLORS.length])]));
const nameW = Math.max(...apps.map((a) => width(a.short)));
const dirW = Math.max(...apps.map((a) => width(a.dir)));

/** 耗时列:就绪给真实 ms,失败给退出码,未就绪给占位符。列宽 7 = 「9999ms」。 */
function statCell(a) {
  if (a.failed) return red(padStart(`exit ${a.failed}`, 7));
  if (a.ms != null) return `${dim(String(a.ms).padStart(4))}${dim('ms')}`;
  return dim(padStart('—', 7));
}
function markCell(a) {
  if (a.failed) return red('✗');
  if (a.ms != null) return green('✓');
  return dim('·');
}

function buildRows(withDir) {
  const msW = 7;
  const rows = [''];
  rows.push(
    `▎ ${bold('UJ ADMIN')}   ${dim('dev')}${scope ? dim(`  only: ${scope.join(',')}`) : ''}`,
  );
  rows.push('');
  for (const a of apps) {
    const tint = colorOf.get(a.short);
    rows.push(
      ` ${markCell(a)}  ${tint(padEnd(a.short, nameW))}` +
        (withDir ? `   ${dim(padEnd(a.dir, dirW))}` : '') +
        `   ${bold(padStart(a.port ? `:${a.port}` : ':?', 5))}` +
        `   ${padEnd(statCell(a), msW)}`,
    );
  }
  rows.push('');
  rows.push(`${cyan('▸')}  ${bold(entryUrl ?? '(本次未启动 shell,直接访问各应用端口)')}`);
  if (lanEntryUrl) rows.push(`${cyan(lanEntryUrl)}`);
  rows.push(dim('   Ctrl+C 停止全部进程'));
  rows.push('');
  return rows;
}

let panelShown = false;
function renderPanel() {
  if (panelShown) return;
  panelShown = true;

  // 渲染总宽 = GUTTER 2 + 边框 2 + 内边距 2 + 内容最宽,超了就丢掉目录列重排。
  const cols = process.stdout.columns || 80;
  let rows = buildRows(true);
  if (Math.max(...rows.map(width)) + 6 > cols) rows = buildRows(false);

  const inner = Math.max(...rows.map(width));
  const rule = (l, r) => dim(l + '─'.repeat(inner + 2) + r);
  const body = (s) => dim('│') + ' ' + s + ' '.repeat(inner - width(s)) + ' ' + dim('│');

  console.log('');
  console.log(GUTTER + rule('╭', '╮'));
  for (const line of rows) console.log(GUTTER + body(line));
  console.log(GUTTER + rule('╰', '╯'));
  console.log('');
}

/**
 * 等所有进程都到达终态(就绪或失败)再出面板。
 * 不因为有人失败就整场不出 —— 那样已经起来的应用也看不到端口,
 * 反而把最需要的信息(哪些还活着)藏掉了。
 */
function maybeRender() {
  if (panelShown) return;
  if (apps.some((a) => a.ms == null && !a.failed)) return;
  renderPanel();
}

// 兜底:ready 信号靠匹配 vite banner 文本,万一版本换了格式就永远等不到。
// 超时后按当前状态出一次面板(未就绪的显示 —),不至于整场没有端口清单。
const PANEL_TIMEOUT = Number(process.env.UJ_DEV_PANEL_TIMEOUT ?? 20000);
setTimeout(renderPanel, PANEL_TIMEOUT).unref();

// ─── 子进程 ──────────────────────────────────────────────────────────
console.log('');
console.log(
  `${GUTTER}${dim('▎')} ${dim(`正在启动 ${apps.length} 个 dev server…`)}` +
    (entryUrl ? `   ${dim('→')} ${cyan(entryUrl)}` : '') +
    (lanEntryUrl ? `   ${dim('· 局域网')} ${cyan(lanEntryUrl)}` : ''),
);

const children = [];

for (const a of apps) {
  // --reporter=silent 关掉 pnpm 自己的 lifecycle banner,见文件头「输出约定」第 3 条。
  const child = spawn('pnpm', ['--filter', a.name, '--reporter=silent', 'dev'], {
    cwd: ROOT,
    shell: true,
    stdio: ['ignore', 'pipe', 'pipe'],
    env: { ...process.env, FORCE_COLOR: COLOR ? '1' : '0', ...(a.short === 'shell' ? lanEnv : {}) },
  });
  const tint = colorOf.get(a.short);
  const rail = `${GUTTER}${tint(padEnd(a.short, nameW))} ${dim('│')} `;
  const emit = (line, toErr = false) => (toErr ? console.error : console.log)(rail + line);

  // 按行缓冲:一行的字节可能跨 chunk 到达,直接 split 会把半行拆成两条日志。
  let tail = '';
  const pump = (buf, toErr) => {
    tail += String(buf);
    const lines = tail.split(/\r?\n/);
    tail = lines.pop() ?? '';
    if (tail.length > 8192) {
      lines.push(tail);
      tail = '';
    }
    for (const raw of lines) {
      if (!raw) continue;
      const text = strip(raw);
      // vite banner 三行收编成 ready 信号(地址已在面板里,这里不再重复输出)。
      const ready = /VITE v[\d.]+\s+ready in (\d+)\s*ms/.exec(text);
      if (ready) {
        a.ms = Number(ready[1]);
        maybeRender();
        continue;
      }
      if (/➜\s+Local:/.test(text) || /➜\s+Network:/.test(text)) continue;
      emit(raw, toErr);
    }
  };

  child.stdout.on('data', (buf) => pump(buf, false));
  child.stderr.on('data', (buf) => pump(buf, true));
  child.on('exit', (code) => {
    if (code && code !== 0) {
      a.failed = code;
      console.error(`${rail}${red('✗')} ${dim(`退出 code=${code}`)}`);
      maybeRender();
    }
  });
  children.push(child);
}

/**
 * 收掉一条 dev server 进程树。
 *
 * shell: true 时 child 是 cmd.exe 一层壳,child.kill() 只杀壳、vite 变孤儿继续占端口
 * (已实测:SIGTERM 后子进程仍在跑;配合 strictPort 表现为「Ctrl+C 之后下次 pnpm dev 直接失败」)。
 * 所以 Windows 走 taskkill /T 树杀,且必须用 spawnSync —— shutdown 末尾立刻 exit,
 * 异步 spawn 的杀进程来不及执行。非 Windows 上 shell 只是个 sh,SIGTERM 语义本来就对。
 */
function killTree(child) {
  if (child.exitCode !== null || child.signalCode !== null) return;
  try {
    if (process.platform === 'win32') {
      spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
    } else {
      child.kill('SIGTERM');
    }
  } catch {
    /* 进程已退出或 pid 已复用,忽略 */
  }
}

function shutdown() {
  console.log('');
  console.log(`  ${dim('⏻')}  正在停止 ${children.length} 个 dev server…`);
  for (const child of children) killTree(child);
  process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);