Files
novalon-website/scripts/utils/check-heading-hierarchy.ts
zhangxiang 7d1a22a596 feat(ia): 一级导航改对标双轴(行业 × 能力 + 洞察),并把导航真源从 DB 行反转为代码
依据实测:Bain 一级导航 = Industries · Consulting Services · Digital · Insights · About · Careers,
Porsche = 行业 · 实践 · 洞察 · 职业 · 关于我们 —— **两家的导航里都没有「产品」**。
咨询业按「客户的问题空间 × 本所的能力」组织,不按产品 SKU 组织。本仓此前 7 项里
产品居首,且 案例(case-study 0 行)、新闻动态(2 行) 是挂在骨架上的空渠道。

落地策略是**换标签、不换路由**:行业→既有 /solutions(solution 模型本就是行业),
能力→既有 /services(service 模型的 4 行本就是能力组)。
理由不是省事,而是避免制造重复内容:若新增 /capabilities 与 /services 并行,
同一个 ContentItem 会同时挂在两个 URL 下 —— 那是 canonical 冲突,比不改更糟。
URL 改名 + 308 留给第二批一次性处理。唯一真正新增的面是 /insights:
它聚合 news + methodology + case-study,今天没有任何单一页面做过这件事,故不构成重复。

「轴 = 视图,模型 = 真源」:本轮零新 ContentModel、零 schema、零 seed 权限测试改动。
沿用 solution/service/product 三个 code ⇒ src/lib/seed-permissions.test.ts:50 的
SUPER_ADMIN_ONLY_MODELS 断言保持绿。**这是设计选择的回报,不是没做事。**

最关键的一处:反转导航优先级
  layout.tsx 原为 `(navData?.mainNav) || NAVIGATION_V2` —— **DB 行胜出、代码只兜底**。
  `navigation` 的字段是泛型 json,改导航不需动 schema,听起来省事,实际是:
  只改 navigation.ts 会上线一个**生产静默忽略它**的新导航。
  而 footer 按 megaDropdown 的 key 取栏目 —— 新代码 key 对旧 DB key ⇒ 页脚三栏静默变空。
  我在工作树里真的复现了这个状态:本地 navigation/default 行仍是旧 7 项,
  它**内部完全自洽**(每个 dropdownKey 都找得到面板),所以「自洽即放行」会继续覆盖代码。
  ⇒ 新校验器的标准是「它是不是这套 IA」(必须覆盖 industries/capabilities/insights 三轴),
    而不是「它是不是合法 JSON」。不合格则 fail-closed 到代码 + 把原因 console.warn 出来
    (渲染期不写库:Notification 是后台数据,在 RSC 里写它等于给每次首页渲染挂写副作用)。
  这条有专门用例:「旧 IA 的自洽配置必须被拒」。

顺带修掉两处同族缺陷
- injectStandaloneProducts 原按 `key === 'products'` 匹配;双轴改名后该 key 不存在 ⇒
  独立产品会**静默不再注入**。改为按组 id(STANDALONE_GROUP_ID)找,组 id 比 key 稳定。
- 激活判定原来有**三套**:header 的 8 分支 per-id 阶梯(末尾落回 pathname===`/${item.id}`,
  新 id industries 会拼出一个不存在的路由 ⇒ 行业永不高亮)、mobile-tab-bar 的 per-id
  if 阶梯(改名后每项静默返回 false ⇒ tab bar 照渲染、永不高亮 = 绿但空洞)、footer 自一套。
  现统一为 lib/nav-active.ts,按 segment 切(不被 /solutionship 这类同前缀误点亮)。

撤下两个空渠道入口(含一处我自己计划里的回退,已当场纠正)
- /cases 从一级导航与移动端 tab bar 撤下:case-study 0 行,点进去是空列表。
  路由与模型**保留休眠**,真实授权案例到位当天即可渲染,不必二次迁移。
- 补 { id: 'all-products', href: '/products' } 进能力轴第二层:
  撤「产品」时若不补这一条,/products(sitemap priority 0.9、6 个详情页的上游 hub)
  就变成**没有导航入口的孤儿页** —— 那是回退不是重构。「降级」不等于「消失」,
  已加守卫用例「被退出一级导航的 hub 必须在第二层仍可达」。

/insights 的三处登记(少一处就是「新页面没人扫、门禁仍然绿」的静默覆盖收缩)
- sitemap.ts:新增,priority 0.8;/news 暂留(已索引),第二批 301 归并
- check:headings 的 PAGES 列表:新增(该列表是硬编码路由清单)
- revalidate:新增 INSIGHTS_AFFECTED_MODELS(news/case-study/methodology)
  —— /insights 不在 CONTENT_TYPE_CONFIGS 的任何 listPage 里,通用推导只刷 /news、
  /methodology;少登记这条的后果不是报错,而是后台发了新内容、洞察页仍端出旧 ISR
  快照最长 1 小时,且没有任何门禁会红。已钉 3 正向 + 1 负向(product 变更不得刷
  /insights,否则该断言恒真、失去约束力)+ 1 去重。

删除 NAVIGATION(V1):7 个 href 全是 '/'、全站零生产引用,只被 constants.test.ts 供着 ——
那 4 条用例的作用是让死码看起来「有人在用」。已改写成断言活的 NAVIGATION_V2,
并保留其原有意图(每个目的地互不相同,正是 V1 缺的那条)。

KNOWN-RED: test:visual —— 一级导航 7→4、页脚三栏改标题改取数、移动端 tab bar 换轴,
header/footer 相关基线预期 churn。按计划 #10 在所有代码落地后一次性重捕(需 AUTH-VISUAL)。

待授权(本笔**未**执行,且必须执行才能对用户生效):
  CMS 的 navigation/default 行仍是旧 7 项。本笔的反转校验会让它 fail-closed 到代码,
  所以**新导航会立即在页面上生效**(不再被旧行遮蔽),但后台那一行要改需
  `npm run db:seed`(生产为独立授权动作)。seed.ts:945 直接引用 NAVIGATION_V2,
  重跑即得新行 —— 本地已复跑验证过(库内 mainNav 已是 industries/capabilities/insights)。

门禁实测:type-check EXIT=0 · 全量 jest 146 套件 / 1807 例通过 ·
eslint --quiet 改动文件 0 error · check:grammar 9/9 及其 selftest 9/9 ·
check:token-twins 44/44 · check:contrast 44/44 · check:brand-token 0 违规 ·
e2e nav-keyboard@chromium 6 passed(含 /insights 实测 HTTP 200)
2026-10-16 20:34:34 +08:00

292 lines
9.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env tsx
/**
* 标题层级检查脚本
*
* 对关键页面进行标题(h1-h6)层级扫描,确保:
* 1. 每个页面有且仅有一个 h1
* 2. 标题层级不跳跃(例如 h1 后直接出现 h3)
* 3. 标题不为空
*/
import { chromium } from "playwright";
import { spawn } from "child_process";
import path from "path";
const BASE_URL = process.env.E2E_BASE_URL || "http://localhost:3000";
const PAGES = [
{ path: "/", name: "首页" },
{ path: "/about", name: "关于我们" },
{ path: "/products", name: "产品中心" },
{ path: "/products/erp", name: "产品详情-ERP" },
{ path: "/solutions", name: "解决方案" },
{ path: "/solutions/manufacturing", name: "解决方案详情-制造" },
{ path: "/services", name: "服务列表" },
{ path: "/services/software", name: "服务详情-软件开发" },
{ path: "/news", name: "新闻列表" },
// 双轴新增的洞察枢纽 —— 不登记就会出现「新页面没人扫,门禁仍然绿」的静默覆盖收缩
{ path: "/insights", name: "洞察枢纽" },
{ path: "/contact", name: "联系我们" },
];
interface HeadingIssue {
type:
| "missing_h1"
| "multiple_h1"
| "empty_heading"
| "skipped_level"
| "http_error";
message: string;
detail?: string;
}
interface PageResult {
name: string;
url: string;
passed: boolean;
headings: Array<{ level: number; text: string }>;
issues: HeadingIssue[];
}
function startServer(): Promise<ReturnType<typeof spawn>> {
return new Promise((resolve, reject) => {
// N-24:`npm run preview` = `next start -p 3000`,而本项目是 output:'standalone',
// Next 16 明确告警 `"next start" does not work with "output: standalone"` ⇒ 此前该门禁跑在不受支持的降级路径上。
// 有产物就直起 standalone server(与 check:axe / Jenkinsfile / lighthouserc 同法),否则回退并大声告警。
const standalone = path.resolve(
__dirname,
"../../dist/standalone/server.js",
);
const useStandalone = require("fs").existsSync(standalone);
if (!useStandalone) {
console.warn(
"⚠ 未找到 dist/standalone/server.js,回退到 `npm run preview`(该路径在 standalone 下不受支持,结论仅参考)",
);
}
const server = spawn(
useStandalone ? "node" : "npm",
useStandalone ? [standalone] : ["run", "preview"],
{
env: useStandalone
? {
...process.env,
HOSTNAME: "localhost",
PORT: "3000",
NODE_ENV: "production",
}
: process.env,
cwd: path.resolve(__dirname, "../.."),
stdio: "pipe",
shell: true,
detached: true,
},
);
server.stdout?.on("data", (data: Buffer) => {
const output = data.toString();
if (output.includes("Ready") || output.includes("3000")) {
resolve(server);
}
});
server.stderr?.on("data", (data: Buffer) => {
const output = data.toString();
if (output.includes("EADDRINUSE") || output.includes("Failed")) {
reject(new Error(output));
}
});
setTimeout(() => resolve(server), 5000);
});
}
// 负 PID = 杀整个进程组。spawn 的 `npm run preview` 只是包装进程,真正 LISTEN :3000 的是它的
// next-server 孙进程;只 kill 包装进程会让孙进程被 init 收养继续占端口(验收报告 §9 实测残留 39 分钟),
// 叠加 Playwright 的 reuseExistingServer: true 后,下一轮 E2E / Lighthouse 会静默复用它。
let serverStopped = false;
function stopServer(server: ReturnType<typeof spawn> | null | undefined): void {
if (!server?.pid || serverStopped) return;
serverStopped = true;
try {
process.kill(-server.pid, "SIGTERM");
} catch {
/* 进程组已自行退出 */
}
}
async function waitForServer(url: string, retries = 30): Promise<void> {
for (let i = 0; i < retries; i++) {
try {
const res = await fetch(url, { method: "HEAD" });
// N-24:原本 `|| res.status === 404` 把「已响应但站点是错的」当成就绪;
// 而 :3000 上任何别的服务都会立刻满足它,于是整轮量的是错对象。
if (res.ok) return;
} catch {
// 服务未起:连接被拒
}
// 就绪等待必须每轮都退避:启动期返回 503/500 等非 ok 状态时,
// 若只在 catch 里 sleep,30 次重试会在毫秒内跑完并误报「服务未就绪」。
await new Promise((r) => setTimeout(r, 1000));
}
throw new Error(`Server at ${url} did not become ready in time`);
}
function checkHeadings(
headings: Array<{ level: number; text: string }>,
): HeadingIssue[] {
const issues: HeadingIssue[] = [];
const h1Headings = headings.filter((h) => h.level === 1);
if (h1Headings.length === 0) {
issues.push({ type: "missing_h1", message: "页面缺少 h1 标题" });
} else if (h1Headings.length > 1) {
issues.push({
type: "multiple_h1",
message: `页面存在 ${h1Headings.length} 个 h1 标题`,
detail: h1Headings.map((h) => h.text).join(" | "),
});
}
for (let i = 0; i < headings.length; i++) {
const current = headings[i]!;
if (!current.text.trim()) {
issues.push({
type: "empty_heading",
message: `h${current.level} 标题内容为空`,
});
continue;
}
if (i === 0) continue;
const previous = headings[i - 1]!;
if (current.level > previous.level + 1) {
issues.push({
type: "skipped_level",
message: `标题层级跳跃: h${previous.level} → h${current.level}`,
detail: `"${previous.text}" → "${current.text}"`,
});
}
}
return issues;
}
async function runCheck() {
let server;
try {
console.log("🚀 启动预览服务...");
server = await startServer();
await waitForServer(BASE_URL);
console.log("🔍 检查页面标题层级...\n");
const browser = await chromium.launch();
const context = await browser.newContext({
viewport: { width: 1280, height: 800 },
});
const page = await context.newPage();
const results: PageResult[] = [];
let totalIssues = 0;
for (const { path: pagePath, name } of PAGES) {
const url = `${BASE_URL}${pagePath}`;
try {
const response = await page.goto(url, {
waitUntil: "domcontentloaded",
timeout: 30000,
});
// N-24:page.goto 不对 404/500 抛错,而 Next 的 not-found 页只有一个 h1、无层级跳跃
// ⇒ 路由消失时本门禁会安静地判「层级正常」。必须显式断言状态码。
const httpStatus = response?.status() ?? 0;
if (httpStatus >= 400) {
totalIssues++;
results.push({
name,
url,
passed: false,
headings: [],
issues: [
{
type: "http_error",
message: `HTTP ${httpStatus} —— 页面未正常渲染(路由缺失/服务端错误)`,
detail: "标题层级检查未执行",
},
],
});
console.log(` ❌ ${name} (${pagePath}): HTTP ${httpStatus}`);
continue;
}
await page.waitForTimeout(1500);
const headings = await page.evaluate(() => {
const elements = Array.from(
document.querySelectorAll("h1, h2, h3, h4, h5, h6"),
);
return elements.map((el) => ({
level: parseInt(el.tagName[1]!, 10),
text: el.textContent?.trim() ?? "",
}));
});
const issues = checkHeadings(headings);
totalIssues += issues.length;
const result: PageResult = {
name,
url,
passed: issues.length === 0,
headings,
issues,
};
results.push(result);
const status = issues.length === 0 ? "✅" : "❌";
console.log(`${status} ${name} (${issues.length} 个问题)`);
for (const issue of issues) {
console.log(
` • ${issue.message}${issue.detail ? ` (${issue.detail})` : ""}`,
);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`❌ ${name} 检查失败:`, message);
results.push({
name,
url,
passed: false,
headings: [],
issues: [{ type: "missing_h1", message: `页面加载失败: ${message}` }],
});
}
}
await browser.close();
console.log("\n📊 检查摘要");
console.log(` 扫描页面: ${results.length}`);
console.log(` 通过页面: ${results.filter((r) => r.passed).length}`);
console.log(` 失败页面: ${results.filter((r) => !r.passed).length}`);
console.log(` 问题总数: ${totalIssues}`);
const reportPath = path.resolve(
__dirname,
"../../heading-hierarchy-report.json",
);
require("fs").writeFileSync(reportPath, JSON.stringify(results, null, 2));
console.log(`\n📝 详细报告已保存: ${reportPath}`);
// process.exit() 不会执行 finally,所以两处出口都得自己收服服务再退出。
stopServer(server);
process.exit(totalIssues > 0 ? 1 : 0);
} catch (error) {
console.error("检查执行失败:", error);
stopServer(server);
process.exit(1);
} finally {
stopServer(server);
}
}
runCheck();