unis_crm/scripts/verify-frontend-merge.mjs

1162 lines
53 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env node
/**
* 双前端整合回归校验:frontend1(系统管理前端)整体并入 frontend 的 /admin/*。
*
* 零依赖 Node ESM,逐条断言并打印 PASS / WARN / FAIL。
*
* node scripts/verify-frontend-merge.mjs # 全量(含构建产物体检)
* node scripts/verify-frontend-merge.mjs --skip-build # 只跑静态断言,跳过构建
* node scripts/verify-frontend-merge.mjs --keep-dist # 构建后保留 frontend/dist-verify
*
* 退出码:0 = 没有 FAIL(WARN 不影响退出码);1 = 至少一条 FAIL。
*
* WARN 的语义:断言字面上不成立,但命中只出现在注释里(不改变构建/部署行为)。
* 降级成 WARN 并把行号打出来,由人决定是否连字样一起清掉。
*/
import { spawnSync } from "node:child_process";
import zlib from "node:zlib";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const argv = process.argv.slice(2);
const SKIP_BUILD = argv.includes("--skip-build");
const KEEP_DIST = argv.includes("--keep-dist");
const VERIFY_OUT_DIR = "dist-verify";
const ADMIN_DIR = "frontend/src/admin";
const ADMIN_CSS = ADMIN_DIR + "/styles/admin.css";
const APP_TSX = "frontend/src/App.tsx";
const VITE_CONFIG = "frontend/vite.config.ts";
const CHUNKING = "frontend/build-chunking.ts";
const NGINX_TEMPLATE = "frontend/nginx/default.conf.template";
const AIO_DOCKERFILE = "deploy/all-in-one/Dockerfile";
const AIO_NGINX = "deploy/all-in-one/nginx/unis-scc.conf";
const COMPOSE = "docker-compose.yml";
const PUSH_SCRIPT = "deploy/build-and-push.sh";
const K3S = "deploy/k3s-unis-scc.yaml";
const PERM_SQL = "sql/20261119_admin_portal_perm.sql";
const CRM_ROOT = "frontend/src";
const CRM_HTML_ROOT = "/usr/share/nginx/html/crm";
/** item 8 的体检范围:构建与部署链路(不含 docs/、*.md、sql/ 里的叙述) */
const CHAIN_FILES = [
COMPOSE,
"package.json",
"frontend/package.json",
"frontend/Dockerfile",
VITE_CONFIG,
"frontend/index.html",
NGINX_TEMPLATE,
"frontend/nginx/start.sh",
"backend/Dockerfile",
AIO_DOCKERFILE,
AIO_NGINX,
"deploy/all-in-one/nginx/proxy-backend.conf",
"deploy/all-in-one/start.sh",
"deploy/all-in-one/healthcheck.sh",
PUSH_SCRIPT,
"deploy/check-manifests.py",
K3S,
"deploy/k3s-unis-scc-allinone.yaml",
"deploy/k3s-unis-scc-allinone.min.yaml",
];
/** 只是 ignore 规则,不影响构建行为;frontend1/ 目录还在,这些行是良性的 */
const HYGIENE_FILES = [".dockerignore", ".gitignore"];
const results = [];
let currentGroup = "(未分组)";
function group(title) {
currentGroup = title;
}
function record(status, name, details) {
results.push({
group: currentGroup,
name,
status,
details: (details || []).filter((d) => d !== undefined && d !== null && d !== ""),
});
}
/** check 回调返回 true / false / {ok, details} / {status, details};抛错记 FAIL */
function check(name, fn) {
let outcome;
try {
outcome = fn();
} catch (error) {
record("FAIL", name, ["校验脚本抛错:" + (error && error.message ? error.message : String(error))]);
return;
}
if (outcome === true) record("PASS", name);
else if (outcome === false) record("FAIL", name);
else if (outcome && outcome.status) record(outcome.status, name, outcome.details);
else if (outcome && typeof outcome.ok === "boolean") record(outcome.ok ? "PASS" : "FAIL", name, outcome.details);
else record("FAIL", name, ["断言回调没有返回有效结果"]);
}
const abs = (rel) => path.join(ROOT, rel);
const exists = (rel) => fs.existsSync(abs(rel));
const read = (rel) => fs.readFileSync(abs(rel), "utf8").replace(/^\uFEFF/, "");
const readSafe = (rel) => (exists(rel) ? read(rel) : null);
const rowsOf = (rel) => (readSafe(rel) === null ? null : read(rel).split(/\r?\n/));
function walk(absDir) {
const out = [];
for (const entry of fs.readdirSync(absDir, { withFileTypes: true })) {
const p = path.join(absDir, entry.name);
if (entry.isDirectory()) out.push(...walk(p));
else out.push(p);
}
return out;
}
function relPath(p) {
return path.relative(ROOT, p).split(path.sep).join("/");
}
function adminFiles() {
return exists(ADMIN_DIR) ? walk(abs(ADMIN_DIR)).map(relPath) : [];
}
/** 只有代码文件参与 URL 前缀对账;AGENTS.md 这类文档里会正当地叙述 /api/sys/**。 */
function adminCodeFiles() {
return adminFiles().filter((rel) => /[.](ts|tsx|js|jsx|mjs|less|css)$/i.test(rel));
}
function crmFiles() {
return walk(abs(CRM_ROOT)).map(relPath).filter((rel) => !rel.startsWith(ADMIN_DIR + "/"));
}
const COMMENT_MARKERS = {
".ts": "//", ".tsx": "//", ".js": "//", ".mjs": "//", ".jsx": "//",
".yml": "#", ".yaml": "#", ".sh": "#", ".py": "#", ".sql": "--",
};
function isCommentLine(line, rel) {
const text = line.trim();
if (!text) return true;
const ext = path.extname(rel);
if (ext === "" || ext === ".conf" || ext === ".template" || ext === ".html") return text.startsWith("#");
const marker = COMMENT_MARKERS[ext];
if (marker === "#") return text.startsWith("#");
if (marker === "--") return text.startsWith("--");
if (marker === "//") return text.startsWith("//") || text.startsWith("/*") || text.startsWith("*");
return false;
}
/** 在文件里找关键字,按“代码行 / 注释行”分类返回命中 */
function findToken(rel, token) {
const content = readSafe(rel);
if (content === null) return null;
const all = [];
content.split(/\r?\n/).forEach((line, index) => {
if (line.includes(token)) all.push({ no: index + 1, line: line.trim(), comment: isCommentLine(line, rel) });
});
return { all, code: all.filter((h) => !h.comment), comment: all.filter((h) => h.comment) };
}
function formatHits(hits, limit) {
const cap = limit || 5;
const shown = hits.slice(0, cap).map((h) => "L" + h.no + ": " + h.line);
if (hits.length > cap) shown.push("… 另有 " + (hits.length - cap) + " 处同类命中");
return shown;
}
function firstLineMatching(rel, re) {
const rows = rowsOf(rel);
if (rows === null) return -1;
for (let i = 0; i < rows.length; i += 1) if (re.test(rows[i])) return i + 1;
return -1;
}
const EXT_HINTS = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".json", "/index.ts", "/index.tsx", "/index.js", "/index.jsx"];
function resolvesFrom(baseDir, spec) {
return EXT_HINTS.some((ext) => fs.existsSync(path.join(baseDir, spec + ext)));
}
/** 从 fromIndex 起取第一个花括号配对的块(含大括号) */
function braceBlock(text, fromIndex) {
const start = text.indexOf("{", fromIndex);
if (start < 0) return null;
let depth = 0;
for (let i = start; i < text.length; i += 1) {
if (text[i] === "{") depth += 1;
else if (text[i] === "}") {
depth -= 1;
if (depth === 0) return text.slice(start, i + 1);
}
}
return null;
}
/** 粗略拆出 CSS 的 “选择器 / 声明块” 对(嵌套 @media 取最内层选择器) */
function cssRules(rel) {
const content = readSafe(rel);
if (content === null) return null;
const cleaned = content.replace(/\/\*[\s\S]*?\*\//g, "");
const rules = [];
const re = /([^{}]+)\{([^{}]*)\}/g;
let match;
while ((match = re.exec(cleaned))) {
rules.push({ selector: match[1].trim().replace(/\s+/g, " "), body: match[2] });
}
return rules;
}
function matchesOf(text, re) {
const out = [];
let match;
re.lastIndex = 0;
while ((match = re.exec(text))) out.push(match);
return out;
}
function kb(bytes) {
return (bytes / 1024).toFixed(1) + " KB";
}
function lineNo(text, index) {
return text.slice(0, index).split("\n").length;
}
// ------------------------------------------------------------------ 1. 路由与门禁
group("1. 路由挂载与管理端门禁");
check("1.1 App.tsx 声明 /admin/* 路由", () => {
const text = readSafe(APP_TSX);
if (text === null) return { ok: false, details: ["缺文件 " + APP_TSX] };
const no = firstLineMatching(APP_TSX, /path\s*=\s*["']\/admin\/\*["']/);
return {
ok: no > 0,
details: no > 0 ? [APP_TSX + ":" + no + " " + rowsOf(APP_TSX)[no - 1].trim()] : ["未找到 /admin/* 路由声明"],
};
});
check("1.2 /admin/* 的 element 由 RequireAdminPortal 包住 AdminApp", () => {
const text = readSafe(APP_TSX);
if (text === null) return { ok: false, details: ["缺文件 " + APP_TSX] };
const at = text.search(/path\s*=\s*["']\/admin\/\*["']/);
if (at < 0) return { ok: false, details: ["没有 /admin/* 路由,无法核对门禁包裹"] };
const slice = text.slice(at, at + 600);
const hasGate = /RequireAdminPortal/.test(slice);
const hasApp = /<AdminApp\s*\/>/.test(slice);
return {
ok: hasGate && hasApp,
details: [
hasGate ? "✓ 包了 RequireAdminPortal" : "✗ 缺 RequireAdminPortal",
hasApp ? "✓ 渲染 AdminApp" : "✗ 缺 <AdminApp />",
"element 片段:" + slice.replace(/\s+/g, " ").slice(0, 140),
],
};
});
check("1.3 RequireAdminPortal 门禁逻辑完整(未登录→/login,无权→/?adminDenied=1)", () => {
const text = readSafe(APP_TSX);
if (text === null) return { ok: false, details: ["缺文件 " + APP_TSX] };
const start = text.indexOf("function RequireAdminPortal");
if (start < 0) return { ok: false, details: ["未定义 RequireAdminPortal"] };
const body = text.slice(start, start + 900);
const missing = [];
if (!/useAdminPortalStatus\(\)/.test(body)) missing.push("未读 useAdminPortalStatus()");
if (!/isAuthed\(\)/.test(body)) missing.push("未做登录判定");
if (!/to=["']\/login["']/.test(body)) missing.push("未登录未跳 /login");
if (!/loading/.test(body)) missing.push("loading 态未处理");
if (!/denied[\s\S]*adminDenied=1/.test(body)) missing.push("denied 未跳 /?adminDenied=1");
return { ok: missing.length === 0, details: missing.length ? missing : ["定义于 " + APP_TSX + ":" + lineNo(text, start)] };
});
check("1.4 存在 * 兜底路由", () => {
const no = firstLineMatching(APP_TSX, /<Route\s+path=["']\*["']/);
return {
ok: no > 0,
details: no > 0 ? [APP_TSX + ":" + no + " " + rowsOf(APP_TSX)[no - 1].trim()] : ["未找到兜底的 * 路由声明"],
};
});
check("1.5 兜底路由把老管理端路径补 /admin 前缀,且不抢 CRM 的 profile", () => {
const text = readSafe(APP_TSX);
if (text === null) return { ok: false, details: ["缺文件 " + APP_TSX] };
const prefixes = /LegacyAdminRedirect/.test(text) && /["']\/admin["']\s*\+\s*location\.pathname/.test(text);
const table = (text.match(/legacyAdminPaths[\s\S]*?\]/) || [""])[0];
const steals = /["']profile["']/.test(table);
return {
ok: prefixes && !steals,
details: [
prefixes ? "✓ 老路径重定向到 /admin + 原路径(含 search)" : "✗ 未把老路径补 /admin 前缀",
steals ? "✗ legacyAdminPaths 含 profile,会抢 CRM 个人中心" : "✓ legacyAdminPaths 未包含 profile",
"legacyAdminPaths 条目数:" + matchesOf(table, /["'][a-z-]+["']/g).length,
],
};
});
check("1.6 AdminApp 走 lazy 动态 import(antd 不进首屏)", () => {
const no = firstLineMatching(APP_TSX, /lazy\(\s*\(\)\s*=>\s*import\(["']\.\/admin\/AdminApp["']\)\)/);
return { ok: no > 0, details: no > 0 ? [APP_TSX + ":" + no] : ["未找到 lazy(() => import(\"./admin/AdminApp\"))"] };
});
// --------------------------------------------------------- 2. 管理端源码规模与登录页
check("1.7 管理端门禁并发取画像与权限码(不许多花一个往返)", () => {
const rel = "frontend/src/lib/adminAccess.ts";
const text = readSafe(rel);
if (text === null) return { ok: false, details: ["缺文件 " + rel] };
const at = text.indexOf("async function resolveAdminPortalStatus");
if (at < 0) return { ok: false, details: ["找不到 resolveAdminPortalStatus,判据要跟着改"] };
const body = braceBlock(text, at) || "";
const kicked = /const\s+\w+\s*=\s*getCurrentUser\(\s*\)/.test(body) && /const\s+\w+\s*=\s*listMyPermissions\(\s*\)/.test(body);
const serialized = /await\s+getCurrentUser\(\s*\)/.test(body);
return {
ok: kicked && !serialized,
details: [
kicked ? "✓ 两个请求都先发出、再分别 await" : "✗ 有一个仍在 await 之后才发起",
serialized ? "✗ 又写回 await getCurrentUser() 了:非超管账号进 /admin 会白等一个 RTT(120ms 桩实测 123ms)" : "✓ 没有「先取画像、再决定要不要取权限码」的串行写法",
"超管多取的那次不浪费:AppLayout 算侧边栏菜单要用同一份权限码,@/lib/auth 里有会话缓存 + 并发去重",
],
};
});
group("2. 管理端源码规模与自带登录页");
check("2.1 frontend/src/admin 文件数 > 60", () => {
const files = adminFiles();
const byExt = {};
for (const rel of files) {
const ext = path.extname(rel) || "(none)";
byExt[ext] = (byExt[ext] || 0) + 1;
}
const summary = Object.keys(byExt).sort().map((ext) => ext + "=" + byExt[ext]).join(" ");
return { ok: files.length > 60, details: ["共 " + files.length + " 个文件;" + summary] };
});
check("2.2 admin/pages/auth 已删除(管理端不再自带登录页)", () => {
const leftovers = adminFiles().filter((rel) => /\/pages\/(auth|login)(\/|$)/i.test(rel));
const routesText = readSafe(ADMIN_DIR + "/routes.tsx") || "";
const importsLogin = /import[^\n]*Login/i.test(routesText);
return {
ok: leftovers.length === 0 && !importsLogin,
details: [
leftovers.length ? "✗ 残留文件:" + leftovers.join(", ") : "✓ 无 admin/pages/auth|login",
importsLogin ? "✗ routes.tsx 仍 import 登录页组件" : "✓ routes.tsx 无登录页路由",
],
};
});
// ---------------------------------------------------- 3. admin 子树路径别名与接口前缀
group("3. admin 子树路径别名与接口前缀");
check("3.1 admin 子树没有裸 @/xxx 老路径(应为 @/admin/xxx)", () => {
const files = adminFiles();
if (!files.length) return { ok: false, details: ["缺目录 " + ADMIN_DIR] };
const stale = [];
const broken = [];
const toCrm = [];
for (const rel of files) {
const text = read(rel);
for (const m of matchesOf(text, /["']@\/([^"']+)["']/g)) {
const target = m[1];
if (target.startsWith("admin/")) continue;
const label = rel + ":" + lineNo(text, m.index) + " @/" + target;
if (resolvesFrom(abs(ADMIN_DIR), target)) stale.push(label + " ← admin 子树里有同名文件,应写 @/admin/" + target);
else if (!resolvesFrom(abs(CRM_ROOT), target)) broken.push(label + " ← frontend/src 下解析不到");
else toCrm.push(label);
}
}
const details = [];
if (broken.length) details.push("解析失败(" + broken.length + "):").push(...broken);
if (stale.length) details.push("老路径未改写(" + stale.length + "):").push(...stale);
details.push("跨引 CRM 共享模块(允许," + toCrm.length + " 处)");
for (const label of toCrm) details.push(" · " + label);
return { ok: !broken.length && !stale.length, details };
});
check("3.2 admin 子树没有 /api/sys/ 误写(管理端只走 /sys/**)", () => {
const hits = [];
for (const rel of adminCodeFiles()) {
const rows = rowsOf(rel);
rows.forEach((line, index) => {
if (line.includes("/api/sys/")) hits.push(rel + ":" + (index + 1) + " " + line.trim());
});
}
return { ok: hits.length === 0, details: hits.length ? ["命中 " + hits.length + " 处:"].concat(hits.slice(0, 8)) : ["admin 子树 0 命中"] };
});
check("3.3 admin 子树的 /api/** 字面量只有 /api/idp/**", () => {
const offenders = new Map();
let idp = 0;
for (const rel of adminCodeFiles()) {
const text = read(rel);
for (const m of matchesOf(text, /["'\u0060](\/api\/[^"'\u0060\s]*)["'\u0060]/g)) {
if (m[1].startsWith("/api/idp/")) idp += 1;
else offenders.set(m[1], rel + ":" + lineNo(text, m.index));
}
}
const details = ["/api/idp/** 命中 " + idp + " 处"];
if (offenders.size) {
details.push("非 /api/idp 的 /api/** 字面量:");
for (const [p, where] of offenders) details.push(" · " + p + " (" + where + ")");
}
return { ok: offenders.size === 0, details };
});
check("3.4 admin 子树确实在调 /sys/** 系统接口", () => {
const paths = new Set();
for (const rel of adminFiles()) {
for (const m of matchesOf(read(rel), /["'\u0060](\/sys\/[a-zA-Z0-9_/.:-]*)["'\u0060]/g)) paths.add(m[1]);
}
return { ok: paths.size >= 10, details: ["去重后 " + paths.size + " 条 /sys/** 路径", [...paths].sort().slice(0, 8).join(", ")] };
});
// ------------------------------------------------------------- 4. antd 静态用法
group("4. antd 按需接入(禁静态方法)");
function antdNamedBindings(text) {
const names = [];
for (const m of matchesOf(text, /(?:import|export)\s*(?:type\s*)?\{([^{}]*)\}\s*from\s*(?:type\s*)?["']antd["']/g)) {
for (const part of m[1].split(",")) {
const name = part.trim().split(/\s+as\s+/)[0].trim();
if (name) names.push(name);
}
}
return names;
}
check("4.1 admin 子树不从 antd 直接 import message / notification", () => {
const hits = [];
for (const rel of adminFiles()) {
const text = read(rel);
for (const name of antdNamedBindings(text)) {
if (name === "message" || name === "notification") hits.push(rel + " import { " + name + " } from antd");
}
for (const m of matchesOf(text, /^(?:import|export)[^;\n]*from\s*["']antd\/(?:es|lib)\/(?:message|notification)[^"']*["']/gm)) {
if (/^\s*import\s+type\b/.test(m[0])) continue;
hits.push(rel + ":" + lineNo(text, m.index) + " " + m[0].trim());
}
}
return {
ok: hits.length === 0,
details: hits.length ? hits.slice(0, 10) : ["admin 子树 " + adminFiles().length + " 个文件 0 命中(提示统一走 App.useApp / utils/antdApp)"],
};
});
check("4.2 admin 子树没有 Modal.confirm 等静态方法", () => {
const hits = [];
for (const rel of adminFiles()) {
const text = read(rel);
for (const m of matchesOf(text, /\bModal\s*\.\s*(confirm|info|success|error|warning)\s*\(/g)) {
hits.push(rel + ":" + lineNo(text, m.index) + " " + m[0].trim());
}
}
return { ok: hits.length === 0, details: hits.length ? hits.slice(0, 10) : ["App.useApp 提供的小写 modal.confirm 不计入"] };
});
check("4.3 antd / @ant-design / dayjs 只被 admin 子树引用", () => {
const hits = [];
for (const rel of crmFiles()) {
if (!/\.(ts|tsx|js|jsx|css)$/.test(rel)) continue;
const text = readSafe(rel);
if (text === null) continue;
for (const m of matchesOf(text, /from\s*["'](antd|antd\/[^"']+|@ant-design\/[^"']+|dayjs[^"']*)["']/g)) {
hits.push(rel + ":" + lineNo(text, m.index) + " " + m[0]);
}
}
return {
ok: hits.length === 0,
details: hits.length ? hits.slice(0, 10) : ["CRM 侧 " + crmFiles().length + " 个文件 0 引用 antd 生态,vendor-antd 只挂在 /admin 分支"],
};
});
// ----------------------------------------------------------------- 5. 样式隔离
group("5. 样式隔离");
check("5.1 frontend 未引入 antd/dist/reset.css", () => {
const hits = [];
for (const rel of adminFiles().concat(crmFiles())) {
if (!/\.(ts|tsx|js|jsx|css|html)$/.test(rel)) continue;
const rows = rowsOf(rel);
if (rows === null) continue;
rows.forEach((line, index) => {
if (!line.includes("reset.css") || isCommentLine(line, rel)) return;
if (!/(import|require|@import)/.test(line)) return;
hits.push(rel + ":" + (index + 1) + " " + line.trim());
});
}
return { ok: hits.length === 0, details: hits.length ? hits : ["admin.css 头部注释里提到 reset.css,但没有实际 import/@import"] };
});
check("5.2 admin.css 没有会外溢的全局选择器", () => {
const rules = cssRules(ADMIN_CSS);
if (rules === null) return { ok: false, details: ["缺文件 " + ADMIN_CSS] };
const banned = [];
for (const rule of rules) {
for (const selRaw of rule.selector.split(",")) {
const sel = selRaw.trim();
if (!sel) continue;
if (/(^|[\s,>+~])(body|html)(?![\w-])/.test(sel)) banned.push(rule.selector + " ← 裸 body/html");
else if (/#root\b/.test(sel)) banned.push(rule.selector + " ← #root");
else if (/:root\[["']?data-theme\b/.test(sel)) banned.push(rule.selector + " ← 老的 :root[data-theme]");
else if (/^:root(?![\w[])/.test(sel)) {
const decls = rule.body.split(";").map((d) => d.trim()).filter(Boolean);
if (!decls.every((d) => /^--[\w-]+\s*:/.test(d))) banned.push(rule.selector + " ← 裸 :root 内含非自定义属性声明");
}
}
}
const details = ["扫描 " + rules.length + " 条规则"];
if (banned.length) {
details.push("外溢选择器:");
details.push(...Array.from(new Set(banned)).slice(0, 10));
} else {
details.push("裸 :root 只声明 --app-* 变量(antd 的 Modal/Drawer/message 挂在 body 上需要读得到),不会外溢样式");
}
return { ok: banned.length === 0, details };
});
check("5.3 主题作用域已改成 :root[data-admin-theme] 且由 themeStore 写入", () => {
const css = readSafe(ADMIN_CSS) || "";
const store = readSafe(ADMIN_DIR + "/store/themeStore.ts") || "";
const scoped = matchesOf(css, /:root\[data-admin-theme=["'][^"']+["']\]/g).length;
const writes = matchesOf(store, /setAttribute\(\s*["']data-admin-theme["']/g).length;
const oldStyle = /:root\[data-theme=["']/.test(css);
const hasRootClass = /.admin-root\s*\{/.test(css);
return {
ok: scoped > 0 && writes > 0 && !oldStyle && hasRootClass,
details: [
scoped ? "✓ admin.css 内 " + scoped + " 个 :root[data-admin-theme=…] 作用域块" : "✗ admin.css 无 :root[data-admin-theme] 作用域块",
writes ? "✓ themeStore 写入 data-admin-theme " + writes + " 处" : "✗ themeStore 未写入 data-admin-theme",
oldStyle ? "✗ admin.css 仍有老的 :root[data-theme=…]" : "✓ admin.css 无老的 :root[data-theme=…]",
hasRootClass ? "✓ 存在 .admin-root 作用域根" : "✗ 缺 .admin-root 作用域根",
],
};
});
// ------------------------------------------------------------ 6. dev 代理与分包
group("6. dev 代理与构建分包");
function proxyBlock() {
const text = readSafe(VITE_CONFIG);
if (text === null) return null;
// 不能只认第一个 "proxy:":配置里 `function watchBackend(proxy: unknown, ...)` 这类
// 形参标注会抢先命中,拿到的是函数体而不是 server.proxy。挑真正带 target 的那一段。
for (const m of matchesOf(text, /\bproxy:\s*\{/g)) {
const block = braceBlock(text, m.index);
if (block && /target\s*:/.test(block)) return block;
}
const at = text.indexOf("proxy:");
return at < 0 ? "" : braceBlock(text, at);
}
check("6.1 vite server.proxy 同时代理 /api 与 /sys", () => {
const proxy = proxyBlock();
if (proxy === null) return { ok: false, details: ["缺文件 " + VITE_CONFIG] };
if (proxy === "") return { ok: false, details: ["vite.config.ts 里没有 server.proxy"] };
const api = /["']\/api["']\s*:/.test(proxy);
const sys = /["']\/sys["']\s*:/.test(proxy);
const targets = Array.from(new Set(matchesOf(proxy, /target:\s*["']([^"']+)["']/g).map((m) => m[1])));
return {
ok: api && sys,
details: [
api ? "✓ /api 已代理" : "✗ /api 未代理",
sys ? "✓ /sys 已代理" : "✗ /sys 未代理——dev 下管理端接口会掉回 SPA 外壳拿到 index.html",
"proxy target:" + targets.join(", "),
],
};
});
check("6.2 dev 代理保留 /api/sys → /sys 重写(与生产 nginx 口径一致)", () => {
const proxy = proxyBlock();
if (!proxy) return { ok: false, details: ["拿不到 server.proxy"] };
const flat = proxy.replace(/\\/g, "");
const ok = /rewrite:/.test(proxy) && flat.includes("/^/api/sys/") && flat.includes("'/sys'");
return { ok, details: [ok ? "✓ rewrite 把 /api/sys/* 打回后端真实 /sys/*" : "✗ 缺 /api/sys → /sys 的 rewrite"] };
});
check("6.3 分包按管理端外壳闭包切,vendor-antd 独立成包", () => {
const vite = readSafe(VITE_CONFIG);
const chunking = readSafe(CHUNKING);
if (vite === null) return { ok: false, details: ["缺文件 " + VITE_CONFIG] };
if (chunking === null) return { ok: false, details: ["缺文件 " + CHUNKING] };
const wired = /manualChunks:\s*createManualChunks\(__dirname\)/.test(vite);
const core = /export const ANTD_CORE\s*=\s*["']vendor-antd["']/.test(chunking);
const shellSeeds = /ADMIN_SHELL_ENTRIES\s*=\s*\[[^\]]*AdminApp[^\]]*routes/.test(chunking);
// 图标一旦被分桶收进 core,1697 个图标组件会整体挂上管理端首屏(实测 core 130KB → 342KB)
const iconsFree = /pkg === ["']@ant-design\/icons["']\s*\|\|\s*pkg === ["']@ant-design\/icons-svg["']\)\s*return undefined/.test(chunking);
const buckets = [...new Set(matchesOf(chunking, /["'](vendor-antd[a-z-]*)["']/g).map((m) => m[1]))];
return {
ok: wired && core && shellSeeds && iconsFree,
details: [
wired ? "✓ vite.config.ts 挂的是 createManualChunks(__dirname)" : "✗ vite.config.ts 没接上 createManualChunks",
core ? "✓ 外壳桶名字仍是 vendor-antd(10.2 / 10.3 靠它判首屏泄漏)" : "✗ 没导出 ANTD_CORE = vendor-antd",
shellSeeds ? "✓ 外壳口径 = AdminApp.tsx + routes.tsx 的静态 import 闭包" : "✗ ADMIN_SHELL_ENTRIES 口径被改,首屏预算要重测",
iconsFree ? "✓ @ant-design/icons 不参与分桶(按消费者切,图标不会钉在首屏)" : "✗ 图标被分桶收编,管理端首屏会多约 200 KB gzip",
"分桶:" + buckets.join(", "),
],
};
});
check("6.4 antd 深路径改写的等价性前提仍然成立", () => {
const chunking = readSafe(CHUNKING);
if (chunking === null) return { ok: false, details: ["缺文件 " + CHUNKING] };
const barrelPath = path.join(ROOT, "frontend", "node_modules", "antd", "es", "index.js");
if (!fs.existsSync(barrelPath)) return { ok: true, details: ["node_modules 里没装 antd,跳过(CI 装完依赖后再跑)"] };
const barrel = fs.readFileSync(barrelPath, "utf8");
const aliases = matchesOf(barrel, /export\s*\{\s*default as\s+([A-Za-z_$][\w$]*)\s*\}\s*from\s*['"]\.\/([\w-]+)['"]/g);
const notAlias = matchesOf(barrel, /^export\s+(?!\{\s*default as)[^;]+from\s*['"][^"']+['"]/gm).filter((m) => !/export\s*\{\s*default as/.test(m[0]));
const missing = aliases.filter((m) => !fs.existsSync(path.join(path.dirname(barrelPath), m[2]))).map((m) => m[1]);
return {
ok: aliases.length > 50 && missing.length === 0,
details: [
"改写前提:barrel 里每个组件都必须是 export { default as X } from './x',实测 " + aliases.length + " 个",
missing.length ? "✗ 这些名字找不到对应目录:" + missing.join(", ") : "✓ 全部能落到 antd/es/<目录>",
notAlias.length
? "注意:barrel 里还有 " + notAlias.length + " 条非 default-as 再导出(如 unstableSetRender),插件会原样保留 from \"antd\""
: "✓ barrel 里没有其它形式的再导出",
],
};
});
// ------------------------------------------------------------------- 7. 部署收敛
group("7. 部署清单收敛");
function tokenAbsent(rel, token, options) {
const found = findToken(rel, token);
if (found === null) return { ok: false, details: ["缺文件 " + rel] };
if (found.all.length === 0) return { ok: true, details: [rel + " 未出现 " + token] };
if (options && options.allowComment && found.code.length === 0) {
return {
status: "WARN",
details: [rel + " 的注释里仍写着 " + token + "(" + found.comment.length + " 处,不影响构建):"].concat(formatHits(found.comment)),
};
}
return { ok: false, details: [rel + " 仍引用 " + token + "(" + found.all.length + " 处):"].concat(formatHits(found.all)) };
}
check("7.1 docker-compose.yml 不再出现 frontend1", () => tokenAbsent(COMPOSE, "frontend1", { allowComment: true }));
check("7.2 docker-compose.yml 里没有独立的管理前端服务", () => {
const text = readSafe(COMPOSE);
if (text === null) return { ok: false, details: ["缺文件 " + COMPOSE] };
const services = matchesOf(text, /^ ([A-Za-z0-9_-]+):\s*$/gm).map((m) => m[1]);
const bad = services.filter((s) => /sys|admin|system/i.test(s));
return {
ok: services.length > 0 && bad.length === 0,
details: ["服务列表:" + services.join(", "), bad.length ? "✗ 多余服务:" + bad.join(", ") : "✓ 只剩后端 + 单一前端"],
};
});
check("7.3 all-in-one Dockerfile 不再构建 sys-web 阶段", () => {
const text = readSafe(AIO_DOCKERFILE);
if (text === null) return { ok: false, details: ["缺文件 " + AIO_DOCKERFILE] };
const stages = matchesOf(text, /^FROM\s+\S+(?:\s+AS\s+(\S+))?/gim).map((m) => m[1]).filter(Boolean);
const copies = Array.from(new Set(matchesOf(text, /COPY\s+--from=(\S+)/g).map((m) => m[1])));
const badStage = stages.filter((s) => /sys/i.test(s));
const badCopy = copies.filter((s) => /sys/i.test(s));
return {
ok: stages.length > 0 && badStage.length === 0 && badCopy.length === 0,
details: [
"构建阶段:" + stages.join(", "),
"COPY --from:" + copies.join(", "),
badStage.length || badCopy.length ? "✗ 仍有管理端专属阶段/拷贝" : "✓ 只构建一份前端产物",
],
};
});
check("7.4 all-in-one Dockerfile 连注释都不再出现 sys-web 字样", () => tokenAbsent(AIO_DOCKERFILE, "sys-web", { allowComment: true }));
check("7.5 build-and-push.sh 组件表只剩 app/backend/frontend", () => {
const text = readSafe(PUSH_SCRIPT);
if (text === null) return { ok: false, details: ["缺文件 " + PUSH_SCRIPT] };
const comps = matchesOf(text, /^\s*([a-z][a-z0-9-]*)\)\s+echo/gm).map((m) => m[1]);
const bad = comps.filter((c) => /sys|system|admin/i.test(c));
const token = findToken(PUSH_SCRIPT, "frontend1");
const details = ["spec() 组件:" + comps.join(" / "), "未知组件兜底:" + (/\*\)\s*return 1/.test(text) ? "有" : "无")];
if (bad.length) details.push("✗ 残留管理端组件:" + bad.join(", "));
if (token.all.length) details.push("✗ 仍引用 frontend1:", ...formatHits(token.all));
return { ok: comps.includes("app") && comps.includes("frontend") && !bad.length && token.code.length === 0, details };
});
check("7.6 k3s-unis-scc.yaml 不再有 unis-scc-system 的 kind 段", () => {
const text = readSafe(K3S);
if (text === null) return { ok: false, details: ["缺文件 " + K3S] };
const docs = text.split(/^---\s*$/m);
const offenders = [];
const kinds = [];
docs.forEach((doc, index) => {
const kind = (doc.match(/^kind:\s*(\S+)/m) || [])[1];
if (!kind) return;
const name = (doc.match(/^\s*name:\s*["']?([^"'\s]+)["']?/m) || [])[1];
kinds.push(kind + "/" + name);
if (name === "unis-scc-system") offenders.push("doc#" + index + " 仍声明 unis-scc-system 资源");
if (/image:.*(?:sys-web|frontend1)/.test(doc)) offenders.push("doc#" + index + " 仍拉旧管理端镜像");
});
const nodePort = matchesOf(text, /nodePort:\s*(\d+)/g).map((m) => m[1]);
const details = ["现存资源:" + kinds.join(", "), "NodePort:" + nodePort.join(", ")];
if (nodePort.includes("30083")) offenders.push("仍占用 NodePort 30083");
const comment = findToken(K3S, "unis-scc-system").comment;
if (comment.length) details.push("(" + comment.map((h) => "L" + h.no).join(", ") + " 是历史说明注释,不算 kind 段)");
return { ok: offenders.length === 0, details: details.concat(offenders) };
});
function nginxLocations(rel) {
const text = readSafe(rel);
if (text === null) return null;
const out = [];
const re = /location\s+(?:=\s|\^~\s|~\*?\s)?([^\s{]+)\s*\{/g;
for (const m of matchesOf(text, re)) {
out.push({ path: m[1], body: braceBlock(text, m.index + m[0].length - 1) || "" });
}
return out;
}
check("7.7 all-in-one :8090 改为托管同一份前端产物", () => {
const text = readSafe(AIO_NGINX);
if (text === null) return { ok: false, details: ["缺文件 " + AIO_NGINX] };
const roots = matchesOf(text, /\broot\s+([^;]+);/g).map((m) => m[1].trim());
const offRoots = Array.from(new Set(roots.filter((r) => r !== CRM_HTML_ROOT)));
const has8090 = /listen\s+8090/.test(text);
const servers = matchesOf(text, /listen\s+(\d+)/g).map((m) => m[1]);
return {
ok: has8090 && roots.length >= 2 && offRoots.length === 0,
details: [
"listen 端口:" + servers.join(", "),
"root 列表:" + Array.from(new Set(roots)).join(", "),
has8090 ? "✓ 8090 仍在听(老地址兼容)" : "✗ 8090 监听已丢失",
offRoots.length ? "✗ 8090 指向了另一套产物:" + offRoots.join(", ") : "✓ 80/8090 共用 " + CRM_HTML_ROOT,
],
};
});
check("7.8 all-in-one nginx 配置文件完好(无游离引号行)", () => {
const rows = rowsOf(AIO_NGINX);
if (rows === null) return { ok: false, details: ["缺文件 " + AIO_NGINX] };
const stray = [];
rows.forEach((line, index) => {
if (/^\s*'/.test(line)) stray.push("L" + (index + 1) + ": " + line.trim());
});
const bracesOpen = rows.join("\n").split("{").length - 1;
const bracesClose = rows.join("\n").split("}").length - 1;
const details = ["共 " + rows.length + " 行,{ " + bracesOpen + " 个 / } " + bracesClose + " 个"];
if (stray.length) details.push("游离单引号行 " + stray.length + " 处(nginx -t 会 unknown directive 炸):", ...stray.slice(0, 6));
if (bracesOpen !== bracesClose) details.push("✗ 花括号不配对,server/location 块已损坏");
return { ok: stray.length === 0 && bracesOpen === bracesClose, details };
});
// ------------------------------------------------------- 8. frontend1 引用体检
group("8. frontend1 引用体检(构建 / 部署链路)");
check("8.1 构建与部署链路文件齐全", () => {
const missing = CHAIN_FILES.filter((rel) => !exists(rel));
return {
ok: missing.length === 0,
details: ["体检范围 " + CHAIN_FILES.length + " 个文件", missing.length ? "缺失:" + missing.join(", ") : "全部存在"],
};
});
check("8.2 链路文件不再引用 frontend1(注释命中降级 WARN)", () => {
const code = [];
const comment = [];
for (const rel of CHAIN_FILES) {
const found = findToken(rel, "frontend1");
if (found === null) continue;
for (const hit of found.all) (hit.comment ? comment : code).push(rel + ":L" + hit.no + " " + hit.line);
}
const details = ["扫描 " + CHAIN_FILES.length + " 个构建/部署文件;代码命中 " + code.length + " 处,注释命中 " + comment.length + " 处"];
if (code.length) return { ok: false, details: details.concat(["代码级引用:"].concat(code.slice(0, 8))) };
if (comment.length) return { status: "WARN", details: details.concat(["注释里仍在叙述 frontend1:"].concat(comment.slice(0, 8))) };
return { ok: true, details };
});
check("8.3 frontend1 只残留在 ignore 规则里(.dockerignore / .gitignore)", () => {
const hits = [];
for (const rel of HYGIENE_FILES) {
const found = findToken(rel, "frontend1");
if (found === null) continue;
for (const hit of found.all) hits.push(rel + ":L" + hit.no + " " + hit.line);
}
if (!hits.length) return { ok: true, details: [".dockerignore / .gitignore 已无 frontend1 条目"] };
return { status: "WARN", details: ["frontend1/ 目录仍在仓库里(下个周期删),ignore 规则先留着无害;删除目录时一并清理:"].concat(hits) };
});
// ------------------------------------------------------------------------ 9. SQL
group("9. 门禁权限码 SQL");
check("9.1 " + PERM_SQL + " 存在", () => {
if (!exists(PERM_SQL)) return { ok: false, details: ["缺文件 " + PERM_SQL] };
const rows = rowsOf(PERM_SQL);
return { ok: true, details: [PERM_SQL + " 共 " + rows.length + " 行 / " + fs.statSync(abs(PERM_SQL)).size + " 字节"] };
});
check("9.2 定义了权限码 menu:admin-portal", () => {
const found = findToken(PERM_SQL, "menu:admin-portal");
if (found === null) return { ok: false, details: ["缺文件 " + PERM_SQL] };
const insert = matchesOf(readSafe(PERM_SQL) || "", /insert into sys_permission[\s\S]{0,400}?menu:admin-portal/gi).length;
return {
ok: found.code.length > 0 && insert > 0,
details: ["命中 " + found.all.length + " 行(代码行 " + found.code.length + ")", "sys_permission 插入语句 " + insert + " 条"],
};
});
check("9.3 含 sys_role_permission 授权写入", () => {
const text = readSafe(PERM_SQL);
if (text === null) return { ok: false, details: ["缺文件 " + PERM_SQL] };
const inserts = matchesOf(text, /insert into sys_role_permission/gi).length;
const bindsPerm = matchesOf(text, /insert into sys_role_permission[\s\S]{0,300}?v_menu_perm_id/gi).length;
return {
ok: inserts > 0 && bindsPerm > 0,
details: ["insert into sys_role_permission:" + inserts + " 条", "其中绑定 menu:admin-portal 权限 id:" + bindsPerm + " 条"],
};
});
check("9.4 权限码 is_visible = 1(否则门禁码下发不到前端)", () => {
const rows = rowsOf(PERM_SQL);
if (rows === null) return { ok: false, details: ["缺文件 " + PERM_SQL] };
const code = [];
const zero = [];
rows.forEach((line, index) => {
if (!/is_visible/i.test(line) || isCommentLine(line, PERM_SQL)) return;
code.push("L" + (index + 1) + ": " + line.trim());
if (/is_visible\s*=\s*0/.test(line)) zero.push("L" + (index + 1) + ": " + line.trim());
});
const hasOne = code.some((l) => /is_visible\s*=\s*1/i.test(l));
const insertVisible = /sort_order,\s*is_visible,\s*status[\s\S]{0,200}?'SettingOutlined',\s*\d+,\s*1,\s*1/.test(readSafe(PERM_SQL) || "");
return {
ok: hasOne && insertVisible && !zero.length,
details: ["is_visible 相关代码行 " + code.length + " 处", "UPDATE 置 1:" + (hasOne ? "✓" : "✗"), "INSERT 落库值 is_visible=1:" + (insertVisible ? "✓" : "✗"), zero.length ? "✗ 存在置 0:" + zero.join(" ; ") : "✓ 无置 0 分支"],
};
});
// ------------------------------------------------------------- 10. 构建产物体检
group("10. 构建产物体检(antd 是否真的按需加载)");
// chunk 之间的静态 import 一旦成环,浏览器按 import 顺序求值时,后求值的 chunk 会去读
// 先求值 chunk 里还没初始化完的 const —— ReferenceError: Cannot access 'x' before
// initialization,整页空白。dev 不打包、vite build 也照样绿,只有跑真实产物才炸;
// 2026-11-23 的 vendor-antd 分桶就是把 /admin/roles、/admin/users 这么打空的。
// 判据用 Kahn:把入度为 0 的点逐个摘掉,摘完还剩下的点就一定落在环里(或被环拖着)。
function findChunkCycleMembers(graph) {
const indegree = new Map();
for (const [name, deps] of graph) {
if (!indegree.has(name)) indegree.set(name, 0);
for (const dep of deps) indegree.set(dep, (indegree.get(dep) || 0) + 1);
}
const queue = [...graph.keys()].filter((name) => !indegree.get(name));
const removed = new Set();
while (queue.length) {
const name = queue.pop();
if (removed.has(name)) continue;
removed.add(name);
for (const dep of graph.get(name) || []) {
if (!graph.has(dep) || removed.has(dep)) continue;
const next = (indegree.get(dep) || 0) - 1;
indegree.set(dep, next);
if (next === 0) queue.push(dep);
}
}
return [...graph.keys()].filter((name) => !removed.has(name));
}
function collectBuildInfo(outDir) {
const htmlPath = path.join(outDir, "index.html");
if (!fs.existsSync(htmlPath)) return null;
const html = fs.readFileSync(htmlPath, "utf8").replace(/^\uFEFF/, "");
const preloads = matchesOf(html, /<link\b[^>]*>/g)
.map((m) => m[0])
.filter((tag) => /rel=["']modulepreload["']/.test(tag))
.map((tag) => (tag.match(/href=["']([^"']+)["']/) || [])[1])
.filter(Boolean);
const scripts = matchesOf(html, /<script\b[^>]*>/g)
.map((m) => m[0])
.filter((tag) => /type=["']module["']/.test(tag))
.map((tag) => (tag.match(/src=["']([^"']+)["']/) || [])[1])
.filter(Boolean);
const assetsDir = path.join(outDir, "assets");
const assets = fs.existsSync(assetsDir)
? fs
.readdirSync(assetsDir)
.filter((name) => fs.statSync(path.join(assetsDir, name)).isFile())
.map((name) => ({ name, bytes: fs.statSync(path.join(assetsDir, name)).size }))
.sort((a, b) => b.bytes - a.bytes)
: [];
const entrySources = scripts
.map((ref) => path.join(outDir, ref.replace(/^\//, "")))
.filter((f) => fs.existsSync(f))
.map((f) => ({ file: f, text: fs.readFileSync(f, "utf8") }));
// 管理端首屏:index.html 直接引的 + AdminApp chunk 的静态 import 闭包(懒加载页面不算)。
// outDir 随后就会被删掉,所以趁文件还在磁盘上把字节量算出来。
const assetsDir2 = path.join(outDir, "assets");
const byName = new Map(assets.map((a) => [a.name, a]));
const staticDepsOf = (name) => {
const file = path.join(assetsDir2, name);
if (!fs.existsSync(file)) return [];
const text = fs.readFileSync(file, "utf8");
const out = [];
for (const m of matchesOf(text, /(?:from|import)\s*"\.\/([^"]+\.js)"/g)) out.push(m[1]);
return out;
};
const adminShell = assets.map((a) => a.name).filter((n) => /^AdminApp[-.]/.test(n));
const seen = new Set();
const stack = scripts
.concat(preloads)
.map((ref) => path.basename(ref))
.filter((n) => byName.has(n))
.concat(adminShell);
while (stack.length) {
const cur = stack.pop();
if (seen.has(cur)) continue;
seen.add(cur);
for (const d of staticDepsOf(cur)) if (byName.has(d)) stack.push(d);
}
let eagerBytes = 0;
let eagerGzip = 0;
for (const name of seen) {
const buf = fs.readFileSync(path.join(assetsDir2, name));
eagerBytes += buf.length;
eagerGzip += zlib.gzipSync(buf, { level: 9 }).length;
}
const crmBase = scripts
.concat(preloads)
.map((ref) => path.basename(ref))
.filter((n) => byName.has(n));
let baseGzip = 0;
for (const name of new Set(crmBase)) baseGzip += zlib.gzipSync(fs.readFileSync(path.join(assetsDir2, name)), { level: 9 }).length;
const chunkGraph = new Map();
for (const asset of assets) {
if (!asset.name.endsWith('.js')) continue;
chunkGraph.set(asset.name, staticDepsOf(asset.name).filter((dep) => byName.has(dep) && dep !== asset.name));
}
return { html, preloads, scripts, assets, entrySources, adminEager: [...seen], eagerBytes, eagerGzip, baseGzip, chunkGraph, chunkCycles: findChunkCycleMembers(chunkGraph) };
}
const outDir = path.join(ROOT, "frontend", VERIFY_OUT_DIR);
let build = null;
if (SKIP_BUILD) {
record("WARN", "10.0 已跳过构建(--skip-build)", ["index.html / vendor-antd chunk 未验证,交付前请完整跑一次不带 --skip-build"]);
} else {
fs.rmSync(outDir, { recursive: true, force: true });
const startedAt = Date.now();
let buildResult;
try {
buildResult = spawnSync("npm", ["run", "build", "--", "--outDir", VERIFY_OUT_DIR, "--emptyOutDir"], {
cwd: path.join(ROOT, "frontend"),
encoding: "utf8",
});
build = collectBuildInfo(outDir);
} finally {
if (!KEEP_DIST) fs.rmSync(outDir, { recursive: true, force: true });
}
const seconds = ((Date.now() - startedAt) / 1000).toFixed(1);
const log = String((buildResult.stdout || "") + "\n" + (buildResult.stderr || "")).trim().split("\n");
const tail = log.filter((l) => l.trim()).slice(-10);
check("10.1 npm run build --outDir " + VERIFY_OUT_DIR + " 成功", () => ({
ok: buildResult.status === 0 && build !== null,
details: ["耗时 " + seconds + "s,exit=" + buildResult.status, "输出末尾:"].concat(tail),
}));
check("10.2 入口 / modulepreload 不含 vendor-antd", () => {
if (build === null) return { ok: false, details: ["没有构建产物可解析"] };
const entry = build.preloads.concat(build.scripts);
const leaked = entry.filter((ref) => /vendor-antd|vendor-admin|vendor-i18n/.test(ref));
const staticRefs = [];
for (const src of build.entrySources) {
for (const m of matchesOf(src.text, /\bfrom\s*["']\.?\/(?:assets\/)?(vendor-antd-[A-Za-z0-9_.-]+\.js)["']/g)) {
staticRefs.push(path.basename(src.file) + " static-import " + m[1]);
}
}
return {
ok: leaked.length === 0 && staticRefs.length === 0,
details: [
"index.html 里的 module 入口:" + (build.scripts.join(", ") || "(无)"),
"index.html 里的 modulepreload:" + (build.preloads.join(", ") || "(无)"),
leaked.length ? "✗ 管理端专属分包进了首屏:" + leaked.join(", ") : "✓ vendor-antd / vendor-admin / vendor-i18n 都不在首屏",
staticRefs.length ? "✗ 入口 chunk 静态 import 了 antd:" + staticRefs.join(" ; ") : "✓ 入口 chunk 没有静态 import vendor-antd",
],
};
});
check("10.3 vendor-antd chunk 真实存在", () => {
if (build === null) return { ok: false, details: ["没有构建产物可解析"] };
const antdChunks = build.assets.filter((a) => /^vendor-antd[-.][A-Za-z0-9_.-]+\.js$/.test(a.name));
const adminChunks = build.assets
.filter((a) => /^(vendor-admin|vendor-i18n|AdminApp)[-.-]/.test(a.name))
.map((a) => a.name + " " + kb(a.bytes));
return {
ok: antdChunks.length > 0,
details: [
antdChunks.length ? "✓ " + antdChunks.map((a) => a.name + " (" + kb(a.bytes) + ")").join(", ") : "✗ assets 下找不到 vendor-antd*.js",
"其它管理端 chunk:" + (adminChunks.join(" ; ") || "(无)"),
],
};
});
check("10.4 关键 chunk 体积", () => {
if (build === null) return { ok: false, details: ["没有构建产物可解析"] };
const top = build.assets.slice(0, 14).map((a) => " " + a.name.padEnd(46) + kb(a.bytes));
const jsBytes = build.assets.filter((a) => a.name.endsWith(".js")).reduce((sum, a) => sum + a.bytes, 0);
const cssBytes = build.assets.filter((a) => a.name.endsWith(".css")).reduce((sum, a) => sum + a.bytes, 0);
const firstPaint = build.scripts
.concat(build.preloads)
.map((ref) => build.assets.find((a) => a.name === path.basename(ref)))
.filter(Boolean)
.reduce((sum, a) => sum + a.bytes, 0);
return {
ok: true,
details: [
"产物合计:js " + kb(jsBytes) + " / css " + kb(cssBytes) + " / 文件 " + build.assets.length + " 个",
"首屏(index.html 直接引用的 js):" + kb(firstPaint),
"体积 Top" + Math.min(14, build.assets.length) + ":",
].concat(top),
};
});
// 2026-11-23 实测:改分包之前 /admin 首屏 824 KB gzip(antd 一整桶 572 KB + 1697 个图标全量),
// 改完 598 KB。留 100 KB 余量当闸门,谁再把重组件挂回外壳就会在这里红。
const ADMIN_EAGER_BUDGET_KB = 700;
check("10.5 管理端首屏传输预算 ≤ " + ADMIN_EAGER_BUDGET_KB + " KB gzip", () => {
if (build === null) return { ok: false, details: ["没有构建产物可解析"] };
const kb = (n) => (n / 1024).toFixed(1) + " KB";
const big = build.adminEager
.map((n) => ({ n, bytes: (build.assets.find((a) => a.name === n) || { bytes: 0 }).bytes }))
.sort((a, b) => b.bytes - a.bytes)
.slice(0, 8)
.map((x) => " " + x.n.padEnd(44) + kb(x.bytes));
const over = build.eagerGzip > ADMIN_EAGER_BUDGET_KB * 1024;
return {
ok: !over,
details: [
"进 /admin 必下(index.html + AdminApp 静态闭包,含 css):" + kb(build.eagerGzip) + " gzip / " + kb(build.eagerBytes) + " 原文件",
"CRM 首屏(同一口径,不含管理端):" + kb(build.baseGzip) + " gzip",
over ? "✗ 超预算 " + kb(build.eagerGzip - ADMIN_EAGER_BUDGET_KB * 1024) + ":检查是不是把重组件(Table/Form/DatePicker/图标全量)挂回外壳了" : "✓ 在预算内",
"其中最大的几个:",
].concat(big),
};
});
check('10.6 产物 chunk 之间不成环(成环会在真实浏览器里 TDZ 白屏)', () => {
if (build === null) return { ok: false, details: ['没有构建产物可解析'] };
const cycles = build.chunkCycles || [];
const nameOf = (n) => n.replace(/-[A-Za-z0-9_-]{8}\.js$/, '');
return {
ok: cycles.length === 0,
details: cycles.length
? [
'✗ 有 ' + cycles.length + ' 个 chunk 落在循环依赖里:' + cycles.map(nameOf).join(', '),
' 环上的 chunk 会互相读对方还没初始化的 const,真实浏览器直接白屏;dev 模式看不出来。',
' 修法:在 frontend/build-chunking.ts 里让被指向的桶更「共享」,或把成环的桶合并(planCycleFixups 会自动并环)。',
]
: ['✓ chunk 依赖图无环(' + (build.chunkGraph ? build.chunkGraph.size : 0) + ' 个 js chunk)'],
};
});
}
// ----------------------------------------------------------- 11. 生产 nginx 前缀
group("11. 生产 nginx 接口前缀(frontend/nginx/default.conf.template)");
check("11.1 location /api/sys/ 仍在,并把 /api 前缀 rewrite 掉", () => {
const locs = nginxLocations(NGINX_TEMPLATE);
if (locs === null) return { ok: false, details: ["缺文件 " + NGINX_TEMPLATE] };
const target = locs.find((l) => l.path === "/api/sys/");
if (!target) return { ok: false, details: ["没有 location /api/sys/"] };
const flat = target.body.replace(/\\/g, "");
const hasRewrite = flat.includes("rewrite ^/api/(.*)$ /$1 break;");
return {
ok: hasRewrite && /proxy_pass/.test(target.body),
details: [
"location /api/sys/ 命中",
hasRewrite ? "✓ rewrite ^/api/(.*)$ /$1 break;" : "✗ 缺 rewrite,/api/sys/* 会原样打到后端 404",
/proxy_pass/.test(target.body) ? "✓ proxy_pass 指向后端" : "✗ 缺 proxy_pass",
],
};
});
check("11.2 location /sys/ 直传后端(合并后管理端依赖它)", () => {
const locs = nginxLocations(NGINX_TEMPLATE);
if (locs === null) return { ok: false, details: ["缺文件 " + NGINX_TEMPLATE] };
const target = locs.find((l) => l.path === "/sys/");
if (!target) return { ok: false, details: ["没有 location /sys/,管理端接口会掉回 SPA 外壳"] };
return {
ok: /proxy_pass/.test(target.body) && !/rewrite /.test(target.body),
details: [
"location /sys/ 命中",
/proxy_pass/.test(target.body) ? "✓ proxy_pass 指向后端" : "✗ 缺 proxy_pass",
/rewrite /.test(target.body) ? "✗ 直传不该有 rewrite" : "✓ 无 rewrite,路径原样透传",
],
};
});
check("11.3 SPA 兜底 location / 仍 try_files 到 index.html(/admin/* 深链接可用)", () => {
const locs = nginxLocations(NGINX_TEMPLATE);
if (locs === null) return { ok: false, details: ["缺文件 " + NGINX_TEMPLATE] };
const root = locs.find((l) => l.path === "/");
const ok = !!root && /try_files[^;]*\/index\.html;/.test(root.body);
return { ok, details: [ok ? "✓ " + (root.body.match(/try_files[^;]*;/) || [""])[0].trim() : "✗ 缺 SPA 兜底"] };
});
check("11.4 前端 nginx 开了 JS/CSS 压缩与 hash 资源长缓存", () => {
const files = [NGINX_TEMPLATE, "deploy/all-in-one/nginx/unis-scc.conf"];
const rows = [];
let ok = true;
for (const rel of files) {
const text = readSafe(rel);
if (text === null) {
ok = false;
rows.push(rel + " 缺文件");
continue;
}
const hasGzip = /(^|\n)\s*gzip\s+on\s*;/.test(text);
// 只认行首的指令:注释里也写了 "gzip_types 默认只有 text/html",不锚定就会抓到注释
const types = (text.match(/(^|\n)\s*gzip_types[\s\S]*?;/) || [""])[0];
const js = /javascript/.test(types);
const css = /text\/css/.test(types);
const assets = /location\s+\/assets\/\s*\{[\s\S]*?immutable/.test(text);
if (!hasGzip || !js || !css || !assets) ok = false;
rows.push(
rel +
":" +
(hasGzip ? "✓ gzip on" : "✗ 没开 gzip(官方镜像默认只压 text/html,2 MB 的 JS 会裸传)") +
" / " + (js && css ? "✓ 压 js+css" : "✗ gzip_types 缺 js 或 css") +
" / " + (assets ? "✓ /assets/ immutable" : "✗ 缺 /assets/ 长缓存"),
);
}
return { ok, details: rows };
});
// ----------------------------------------------------------------------- 输出
const counts = { PASS: 0, WARN: 0, FAIL: 0 };
for (const item of results) counts[item.status] = (counts[item.status] || 0) + 1;
console.log("");
console.log("=".repeat(78));
console.log(" 双前端整合回归校验 " + new Date().toLocaleString("zh-CN", { hour12: false }));
console.log(" 仓库:" + ROOT);
console.log("=".repeat(78));
let lastGroup = null;
for (const item of results) {
if (item.group !== lastGroup) {
lastGroup = item.group;
console.log("");
console.log("【" + item.group + "】");
}
console.log(" [" + item.status + "] " + item.name);
for (const detail of item.details) {
console.log(" " + String(detail).split("\n").join("\n "));
}
}
console.log("");
console.log("-".repeat(78));
console.log(" 合计:" + counts.PASS + " PASS / " + counts.WARN + " WARN / " + counts.FAIL + " FAIL(共 " + results.length + " 项)");
if (counts.FAIL) console.log(" FAIL 明细:");
for (const item of results) if (item.status === "FAIL") console.log(" - " + item.name);
if (counts.WARN) console.log(" WARN 明细:");
for (const item of results) if (item.status === "WARN") console.log(" - " + item.name);
console.log("-".repeat(78));
process.exit(counts.FAIL > 0 ? 1 : 0);