Files
novalon-website/scripts/acceptance/sweep-routes.mjs
T
zhangxiang 763e159ac4 docs(acceptance): 两轮全站验收读数 + 复现脚本 + 企微资产包入库(OPEN-12)
按「这条结论怎么来的必须入库,排查当时的截图只服务当时」的既有口径,
把此前一直悬在 git status 里、归属未定的产物逐组落定:

入库(7.2MB):
- docs/acceptance/2026-10-21-full-qa/、2026-10-24-full-qa/ 的文字与结构化读数
  (README / defects*.json / sweep/summary.json / axe evidence / lighthouse /
  report.json 逐 run 原始读数 / tools 复现脚本)
- docs/acceptance/2026-11-26-axe/ 本轮 axe 复跑证据(35 路由 × 4 组合 140 rows 全 0)
- scripts/acceptance/{sweep-routes,contact-sheet}.mjs —— 两轮 README 里被引用的
  复现脚本,不提交则结论不可复算
- deliverables/.../wecom-pack.cjs + check-wecom.py + WECOM-MANIFEST.md +
  assets-wecom/pack-report.json(生成器/校验器/清单;18 张 PNG 可由脚本从已入库
  SVG 重新栅格化,故仍按既有规则忽略)

忽略(不提交,已写进 .gitignore 并注明归属):
- 两轮验收的逐页截图(172MB):只在排查当时有用
- infra/cicd/gitea{,-custom}/ + 2026-10-22-gitea-branding/(340KB):
  归 feature/gitea-branding,逐文件 sha256 与该分支 50/50 完全一致,
  在本分支提交会造成同一批文件的两份历史

判据:提交后 git status -uall 只剩被忽略项;每条 ?? 都能回答「归谁、为什么在这里」。
2026-11-26 20:03:46 +08:00

701 lines
29 KiB
JavaScript
Raw 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.
// 2026-10-21 全路由 UI/UE/UX 验收 sweep
//
// 用法:
// BASE=http://127.0.0.1:3100 ROUTES=/tmp/qa-routes.xml OUT=docs/acceptance/2026-10-21-full-qa \
// node scripts/acceptance/sweep-routes.mjs
// MODE=admin ...(只跑后台) / MODE=both(先前台再后台)
// ONLY=/about,/contact LIMIT=3 用于冒烟
//
// 判据不是「截图看着对」:每条运行都落不变量读数(祖先链 opacity 乘积、横向溢出、破图、
// 同源失败请求、pageerror、文本裁切、触控目标、品牌红触达、圆角/字阶/动效时长),
// 截图只作为定性评审与缺陷证据。
import { chromium, firefox, webkit } from 'playwright';
import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
const BASE = (process.env.BASE || 'http://127.0.0.1:3100').replace(/\/$/, '');
const OUT = process.env.OUT || 'docs/acceptance/2026-10-21-full-qa';
const ROUTES_FILE = process.env.ROUTES;
const ONLY = process.env.ONLY ? process.env.ONLY.split(',').map((s) => s.trim()).filter(Boolean) : null;
const LIMIT = Number(process.env.LIMIT || 0);
const MODE = process.env.MODE || 'public';
const ADMIN_USER = process.env.ADMIN_USER || 'admin';
const ADMIN_PASS = process.env.ADMIN_PASS || 'admin123';
const EDITOR_USER = process.env.EDITOR_USER || 'e2e_editor';
const EDITOR_PASS = process.env.EDITOR_PASS || 'editor123';
const SHOT_DIR = path.join(OUT, 'screenshots');
const TMP_DIR = path.join(OUT, '.tmp');
fs.mkdirSync(path.join(SHOT_DIR, 'public'), { recursive: true });
fs.mkdirSync(path.join(SHOT_DIR, 'admin'), { recursive: true });
fs.mkdirSync(TMP_DIR, { recursive: true });
const VIEWPORTS = {
'1440': { width: 1440, height: 900, mobile: false },
'834': { width: 834, height: 1194, mobile: false },
'390': { width: 390, height: 844, mobile: true },
};
const MATRIX = [
{ vp: '1440', theme: 'light' },
{ vp: '1440', theme: 'dark' },
{ vp: '834', theme: 'light' },
{ vp: '390', theme: 'light' },
{ vp: '390', theme: 'dark' },
];
const REPORT = {
meta: { base: BASE, startedAt: new Date().toISOString(), routesFile: ROUTES_FILE || null, matrix: MATRIX },
runs: [],
adminRuns: [],
notes: [],
};
const slugOf = (p) => (p === '/' ? 'home' : p.replace(/^\//, '').replace(/[^a-zA-Z0-9._-]+/g, '_'));
const isNoiseHost = (url) => {
try {
const host = new URL(url).hostname;
return !['127.0.0.1', 'localhost'].includes(host) && !url.startsWith(BASE);
} catch {
return true;
}
};
const flush = () => {
REPORT.meta.finishedAt = new Date().toISOString();
fs.writeFileSync(path.join(OUT, 'report.json'), JSON.stringify(REPORT, null, 2));
};
async function loadRoutes() {
let raw = '';
if (ROUTES_FILE) raw = fs.readFileSync(ROUTES_FILE, 'utf8');
else {
const res = await fetch(`${BASE}/sitemap.xml`);
raw = await res.text();
}
let routes;
if (/<loc>/.test(raw)) {
routes = [...raw.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => {
try { return new URL(m[1]).pathname; } catch { return null; }
}).filter(Boolean);
} else {
routes = raw.split(/\r?\n/)
.map((s) => s.trim())
.filter((s) => s && !s.startsWith('#'))
.map((s) => (s.startsWith('http') ? new URL(s).pathname : s));
}
routes = [...new Set(routes)].filter((r) => !ONLY || ONLY.includes(r));
if (LIMIT) routes = routes.slice(0, LIMIT);
return routes;
}
async function settle(page) {
await page.waitForLoadState('load').catch(() => {});
await page.waitForFunction(() => {
const main = document.querySelector('main');
if (!main) return true;
let el = main;
let product = 1;
while (el) {
product *= parseFloat(getComputedStyle(el).opacity || '1');
el = el.parentElement;
}
return product > 0.99;
}, { timeout: 10000 }).catch(() => {});
await page.evaluate(() => document.querySelectorAll('img').forEach((img) => { img.loading = 'eager'; }));
await page.evaluate(async () => {
const step = Math.max(400, Math.floor(window.innerHeight * 0.8));
for (let y = 0; y <= document.body.scrollHeight; y += step) {
window.scrollTo(0, y);
await new Promise((r) => setTimeout(r, 120));
}
window.scrollTo(0, 0);
await new Promise((r) => setTimeout(r, 250));
});
await page.waitForFunction(
() => [...document.images].every((img) => img.complete),
{ timeout: 15000 },
).catch(() => {});
await page.evaluate(() => document.fonts?.ready).catch(() => {});
await page.waitForTimeout(500);
}
async function measure(page) {
return page.evaluate(() => {
const visible = (el) => {
if (!el) return false;
const r = el.getBoundingClientRect();
const s = getComputedStyle(el);
return r.width > 0 && r.height > 0 && s.display !== 'none' && s.visibility !== 'hidden'
&& parseFloat(s.opacity || '1') > 0.01;
};
let el = document.querySelector('main');
let opacityProduct = 1;
const opacityChain = [];
while (el) {
const o = parseFloat(getComputedStyle(el).opacity || '1');
opacityProduct *= o;
if (opacityChain.length < 8) opacityChain.push({ tag: el.tagName, opacity: o });
el = el.parentElement;
}
const iw = window.innerWidth;
const offenders = [];
for (const node of document.querySelectorAll('body *')) {
if (!visible(node)) continue;
const r = node.getBoundingClientRect();
if (r.right > iw + 1 || r.left < -1) {
offenders.push({
tag: node.tagName,
cls: String(node.className || '').slice(0, 80),
left: Math.round(r.left),
right: Math.round(r.right),
});
if (offenders.length >= 8) break;
}
}
const images = [...document.images]
.filter((img) => img.currentSrc || img.src)
.map((img) => ({ src: (img.currentSrc || img.src).split('/').pop(), complete: img.complete, nw: img.naturalWidth }));
const broken = images.filter((img) => !img.complete || img.nw === 0);
const clipping = [];
for (const node of document.querySelectorAll('h1,h2,h3,h4,p,span,a,li,dt,dd,label,button')) {
if (!visible(node)) continue;
const s = getComputedStyle(node);
if (!/hidden|clip/.test(`${s.overflow}${s.overflowX}${s.overflowY}`)) continue;
if (node.scrollHeight > node.clientHeight + 1 || node.scrollWidth > node.clientWidth + 1) {
clipping.push({
tag: node.tagName,
text: (node.innerText || '').trim().slice(0, 60),
sh: node.scrollHeight, ch: node.clientHeight, sw: node.scrollWidth, cw: node.clientWidth,
});
}
if (clipping.length >= 8) break;
}
const tinyText = [];
for (const node of document.querySelectorAll('p,span,a,li,label,button,small,em')) {
if (!visible(node)) continue;
const fs = parseFloat(getComputedStyle(node).fontSize);
if (fs < 10 && (node.innerText || '').trim()) {
tinyText.push({ tag: node.tagName, fs: +fs.toFixed(1), text: (node.innerText || '').trim().slice(0, 40) });
}
if (tinyText.length >= 8) break;
}
const touchTargets = [];
for (const node of document.querySelectorAll('button,a,input,select,textarea,[role="button"]')) {
if (!visible(node)) continue;
const r = node.getBoundingClientRect();
if (r.width < 44 || r.height < 44) {
touchTargets.push({
tag: node.tagName, w: Math.round(r.width), h: Math.round(r.height),
text: (node.innerText || node.getAttribute('aria-label') || '').trim().slice(0, 40),
});
}
if (touchTargets.length >= 12) break;
}
const redTouches = [];
for (const node of document.querySelectorAll('body *')) {
if (!visible(node)) continue;
const s = getComputedStyle(node);
const hit = [s.color, s.backgroundColor, s.borderTopColor, s.borderLeftColor, s.borderRightColor, s.borderBottomColor]
.some((v) => String(v || '').replace(/\s/g, '').includes('196,30,58'));
if (hit) {
redTouches.push({ tag: node.tagName, cls: String(node.className || '').slice(0, 70), text: (node.innerText || '').trim().slice(0, 30) });
}
if (redTouches.length >= 80) break;
}
const radii = {};
for (const node of document.querySelectorAll('button,a[role="button"],a[class*="bg-"]')) {
if (!visible(node)) continue;
const r = parseFloat(getComputedStyle(node).borderTopLeftRadius) || 0;
radii[r] = (radii[r] || 0) + 1;
}
// 大数字被容器挤到第二行(如「40%」+「+」、「99.2」+「%」)
const wrappedNumbers = [];
for (const node of document.querySelectorAll('.text-3xl,.text-4xl,.text-5xl,.text-6xl,[class*="tabular-nums"]')) {
if (!visible(node)) continue;
const text = (node.innerText || '').trim();
if (!text || text.length > 24) continue;
const s = getComputedStyle(node);
const lh = parseFloat(s.lineHeight);
const rect = node.getBoundingClientRect();
if (lh && rect.height > lh * 1.6 && /^[\d.,%+×xX\-–—\s个月年月天周倍]+$/.test(text)) {
wrappedNumbers.push({ text, w: Math.round(rect.width), h: Math.round(rect.height), lh: Math.round(lh), fs: s.fontSize });
}
if (wrappedNumbers.length >= 10) break;
}
// 多列 grid 的某一行没排满(如 5 项塞进 4 列、3 项指标放进 4 列、2 张卡放进 5 列)。
// 按每行 col-span 求和判断,避免把「12 栏非对称构图」这类有意的留白当成缺陷。
const gridGaps = [];
for (const grid of document.querySelectorAll('.grid')) {
if (!visible(grid)) continue;
const cs0 = getComputedStyle(grid);
const cols = cs0.gridTemplateColumns.split(' ').filter(Boolean).length;
// 只判「有底色」的网格:空列会变成一整块可见灰底;透明网格的留白多为有意构图。
if (cols < 2 || cs0.backgroundColor === 'rgba(0, 0, 0, 0)') continue;
const kids = [...grid.children].filter(visible);
if (!kids.length) continue;
const parseSpan = (value) => {
const span = /^span\s+(\d+)/.exec(value || '');
if (span) return Number(span[1]);
if (/^\d+$/.test(value || '')) return Number(value);
return null;
};
const rows = new Map();
for (const kid of kids) {
const cs = getComputedStyle(kid);
const start = parseSpan(cs.gridColumnStart);
const end = parseSpan(cs.gridColumnEnd);
const explicit = /^\d+$/.test(cs.gridColumnStart) && /^\d+$/.test(cs.gridColumnEnd);
const span = explicit && start && end ? Math.max(1, end - start) : Math.max(start || 1, end || 1);
const top = Math.round(kid.getBoundingClientRect().top);
if (!rows.has(top)) rows.set(top, { sum: 0, count: 0 });
const row = rows.get(top);
row.sum += span;
row.count += 1;
}
const underfilled = [...rows.entries()]
.filter(([, row]) => row.sum < cols)
.map(([top, row]) => ({ top, sum: row.sum, count: row.count }));
if (underfilled.length) {
gridGaps.push({
cls: String(grid.className || '').slice(0, 90),
cols,
kids: kids.length,
bg: cs0.backgroundColor,
underfilled,
});
}
if (gridGaps.length >= 8) break;
}
// col-span-* 挂在非 grid 父级的元素上 ⇒ 分栏意图失效(套件组合区的已知形状)
const orphanColSpans = [];
for (const node of document.querySelectorAll('[class*="col-span-"]')) {
if (!visible(node)) continue;
const parentDisplay = getComputedStyle(node.parentElement).display;
if (parentDisplay !== 'grid' && parentDisplay !== 'inline-grid') {
orphanColSpans.push({
tag: node.tagName,
cls: String(node.className || '').slice(0, 100),
parentDisplay,
text: (node.innerText || '').trim().slice(0, 40),
});
}
if (orphanColSpans.length >= 8) break;
}
const typography = {};
for (const sel of ['h1', 'h2', 'h3', 'p']) {
const node = document.querySelector(sel);
if (!node) continue;
const s = getComputedStyle(node);
typography[sel] = {
text: (node.innerText || '').trim().slice(0, 50),
size: s.fontSize, weight: s.fontWeight, lineHeight: s.lineHeight,
letterSpacing: s.letterSpacing, color: s.color,
};
}
let maxTransitionMs = 0;
let maxAnimationMs = 0;
for (const node of document.querySelectorAll('body *')) {
const s = getComputedStyle(node);
for (const v of s.transitionDuration.split(',')) {
const n = parseFloat(v) || 0;
maxTransitionMs = Math.max(maxTransitionMs, String(v).includes('ms') ? n : n * 1000);
}
for (const v of s.animationDuration.split(',')) {
const n = parseFloat(v) || 0;
maxAnimationMs = Math.max(maxAnimationMs, String(v).includes('ms') ? n : n * 1000);
}
}
const hero = document.querySelector('[data-testid*="hero"], main section');
const h1 = document.querySelector('h1');
const tabBar = document.querySelector('[data-testid="mobile-tab-bar"]');
const cta = [...document.querySelectorAll('a,button')]
.find((node) => visible(node) && (node.innerText || '').includes('预约咨询'));
const form = document.querySelector('form');
return {
path: location.pathname,
title: document.title,
opacityProduct: +opacityProduct.toFixed(3),
opacityChain,
innerWidth: iw,
scrollWidth: document.documentElement.scrollWidth,
overflowX: document.documentElement.scrollWidth > iw + 1,
offenders,
images: images.length,
broken,
clippingCount: clipping.length,
clipping,
tinyTextCount: tinyText.length,
tinyText,
touchTargetCount: touchTargets.length,
touchTargets,
redTouches: redTouches.length,
redSample: redTouches.slice(0, 15),
radii,
wrappedNumbers,
orphanColSpans,
gridGaps,
typography,
maxTransitionMs: Math.round(maxTransitionMs),
maxAnimationMs: Math.round(maxAnimationMs),
heroHeight: hero ? Math.round(hero.getBoundingClientRect().height) : null,
primaryCta: cta ? {
top: Math.round(cta.getBoundingClientRect().top + window.scrollY),
inFirstViewport: cta.getBoundingClientRect().top < window.innerHeight,
} : null,
form: form ? {
top: Math.round(form.getBoundingClientRect().top + window.scrollY),
inFirstViewport: form.getBoundingClientRect().top < window.innerHeight,
fields: form.querySelectorAll('input,textarea,select').length,
} : null,
h1Text: h1 ? (h1.innerText || '').trim().slice(0, 120) : null,
h1Count: document.querySelectorAll('h1').length,
docHeight: document.documentElement.scrollHeight,
mobileTabBar: tabBar ? visible(tabBar) : false,
bodyTextLength: (document.body.innerText || '').trim().length,
};
});
}
async function redPixelRatio(pngPath) {
const { data, info } = await sharp(pngPath).resize({ width: 300 }).raw().toBuffer({ resolveWithObject: true });
let red = 0;
const total = info.width * info.height;
for (let i = 0; i < data.length; i += info.channels) {
if (Math.abs(data[i] - 196) <= 28 && Math.abs(data[i + 1] - 30) <= 28 && Math.abs(data[i + 2] - 58) <= 28) red += 1;
}
return +(red / total).toFixed(4);
}
async function saveShots(page, dir, baseName, viewport) {
await page.screenshot({
path: path.join(dir, `${baseName}__hero.jpg`), type: 'jpeg', quality: 80,
animations: 'disabled', caret: 'hide', timeout: 30000,
});
const tmp = path.join(TMP_DIR, `${baseName}.png`);
await page.screenshot({
path: tmp, fullPage: true, animations: 'disabled', caret: 'hide', timeout: 60000,
});
const meta = await sharp(tmp).metadata();
const files = [];
if (meta.height > 15000) {
for (let y = 0, i = 1; y < meta.height; y += 8000, i += 1) {
const height = Math.min(8000, meta.height - y);
const file = path.join(dir, `${baseName}__full-p${i}.webp`);
await sharp(tmp).extract({ left: 0, top: y, width: meta.width, height }).webp({ quality: 78 }).toFile(file);
files.push(path.basename(file));
}
} else {
const file = path.join(dir, `${baseName}__full.webp`);
await sharp(tmp).webp({ quality: 78 }).toFile(file);
files.push(path.basename(file));
}
const ratio = await redPixelRatio(tmp);
fs.unlinkSync(tmp);
return { files, redPixelRatio: ratio, width: meta.width, height: meta.height };
}
async function runOne(browser, engine, route, vpName, theme) {
const vp = VIEWPORTS[vpName];
const context = await browser.newContext({
viewport: { width: vp.width, height: vp.height },
colorScheme: theme === 'dark' ? 'dark' : 'light',
reducedMotion: 'reduce',
...(vp.mobile && engine === 'chromium' ? { isMobile: true, hasTouch: true, deviceScaleFactor: 2 } : {}),
});
const page = await context.newPage();
await page.addInitScript(() => {
localStorage.setItem('novalon-cookie-preferences', JSON.stringify({
necessary: true, analytics: false, marketing: false, functionality: true, timestamp: 1784284000000,
}));
});
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const thirdParty = [];
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 240)); });
page.on('pageerror', (e) => pageErrors.push(String(e).slice(0, 240)));
page.on('requestfailed', (req) => {
const item = { url: req.url().slice(0, 180), error: req.failure()?.errorText };
(isNoiseHost(req.url()) ? thirdParty : failedRequests).push(item);
});
page.on('response', (res) => {
if (res.status() >= 400) {
const item = { url: res.url().slice(0, 180), status: res.status() };
(isNoiseHost(res.url()) ? thirdParty : failedRequests).push(item);
}
});
const started = Date.now();
let metrics = null;
let shots = null;
let error = null;
try {
await page.goto(BASE + route, { waitUntil: 'domcontentloaded', timeout: 45000 });
await settle(page);
if (theme === 'dark') {
await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));
await page.waitForTimeout(300);
}
metrics = await measure(page);
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForTimeout(200);
const baseName = `${slugOf(route)}__${vpName}__${theme}__${engine}`;
shots = await saveShots(page, path.join(SHOT_DIR, 'public'), baseName, vp);
} catch (err) {
error = String(err).slice(0, 300);
}
await context.close();
// `/_not-found` 是 404 哨兵页:文档自身 404 是契约,不是失败;其余 4xx/5xx 仍判红。
const expected404 = route === '/_not-found';
const httpErrors = failedRequests.filter((r) => r.status >= 400);
const unexpectedHttp = expected404
? httpErrors.filter((r) => {
try { return new URL(r.url).pathname !== '/_not-found'; } catch { return true; }
})
: httpErrors;
const hard = Boolean(error) || !metrics
|| metrics.opacityProduct < 0.99
|| metrics.overflowX
|| metrics.broken.length > 0
|| pageErrors.length > 0
|| unexpectedHttp.length > 0;
return {
kind: 'public', engine, route, viewport: vpName, theme,
durationMs: Date.now() - started,
...(metrics || {}),
shots,
consoleErrors,
pageErrors,
failedRequests,
thirdParty,
expected404,
hardFailure: hard,
error,
};
}
async function loginAndState(browser, viewport, username, password, colorScheme) {
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
colorScheme, reducedMotion: 'reduce',
...(viewport.mobile ? { isMobile: true, hasTouch: true, deviceScaleFactor: 2 } : {}),
});
const page = await context.newPage();
await page.goto(`${BASE}/admin/login`, { waitUntil: 'networkidle', timeout: 45000 }).catch(() => {});
// 表单是客户端组件:水合前点击不会触发 React handler(native submit 停在原页)。
await page.waitForTimeout(1200);
await page.fill('#admin-login-username', username);
await page.fill('#admin-login-password', password);
await page.click('button[type="submit"]');
await page.waitForURL((url) => !url.pathname.includes('/admin/login'), { timeout: 20000 }).catch(() => {});
await page.waitForTimeout(1500);
const loggedIn = !page.url().includes('/admin/login');
const state = loggedIn ? await context.storageState() : null;
return { context, page, loggedIn, state };
}
async function captureAdminPage(browser, state, route, vpName, theme, dir) {
const vp = VIEWPORTS[vpName];
const context = await browser.newContext({
viewport: { width: vp.width, height: vp.height },
storageState: state,
colorScheme: theme === 'dark' ? 'dark' : 'light',
reducedMotion: 'reduce',
...(vp.mobile ? { isMobile: true, hasTouch: true, deviceScaleFactor: 2 } : {}),
});
const page = await context.newPage();
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 240)); });
page.on('pageerror', (e) => pageErrors.push(String(e).slice(0, 240)));
page.on('response', (res) => {
if (res.status() >= 400 && !isNoiseHost(res.url())) failedRequests.push({ url: res.url().slice(0, 180), status: res.status() });
});
let metrics = null;
let shots = null;
let error = null;
try {
await page.goto(BASE + route, { waitUntil: 'networkidle', timeout: 45000 }).catch(() => {});
await page.waitForTimeout(1500);
if (theme === 'dark') {
await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));
await page.waitForTimeout(400);
}
metrics = await measure(page);
const baseName = `admin-${slugOf(route.replace('/admin', '')) || 'root'}__${vpName}__${theme}__chromium`;
shots = await saveShots(page, dir, baseName, vp);
} catch (err) {
error = String(err).slice(0, 300);
}
const url = page.url();
await context.close();
return {
kind: 'admin', route, url, viewport: vpName, theme,
...(metrics || {}), shots, consoleErrors, pageErrors, failedRequests,
hardFailure: Boolean(error) || failedRequests.filter((r) => r.status >= 500).length > 0,
error,
};
}
async function runAdmin(browser) {
const dir = path.join(SHOT_DIR, 'admin');
const desktop = VIEWPORTS['1440'];
// 登录页自身也要进视觉验收(未登录上下文)
for (const combo of MATRIX) {
const run = await captureAdminPage(browser, undefined, '/admin/login', combo.vp, combo.theme, dir);
REPORT.adminRuns.push(run);
flush();
console.log(`[admin] /admin/login ${combo.vp}/${combo.theme} hard=${run.hardFailure} ${run.durationMs || ''}ms`);
}
const login = await loginAndState(browser, desktop, ADMIN_USER, ADMIN_PASS, 'light');
const loginUrl = login.page.url();
const loginBody = (await login.page.locator('body').innerText().catch(() => '')).slice(0, 500);
await login.context.close();
REPORT.notes.push({ adminLogin: { loggedIn: login.loggedIn, url: loginUrl, bodySnippet: loginBody } });
if (!login.loggedIn || !login.state) {
REPORT.notes.push({ adminSweep: 'skipped: admin login failed' });
return;
}
// 登录失败态(错误密码)
const bad = await browser.newContext({ viewport: desktop, reducedMotion: 'reduce' });
const badPage = await bad.newPage();
await badPage.goto(`${BASE}/admin/login`, { waitUntil: 'networkidle' });
await badPage.waitForTimeout(1200);
await badPage.fill('#admin-login-username', ADMIN_USER);
await badPage.fill('#admin-login-password', 'definitely-wrong-password');
await badPage.click('button[type="submit"]');
await badPage.waitForTimeout(2500);
await badPage.screenshot({ path: path.join(dir, 'admin-login-error__1440__light__chromium__full.webp'), fullPage: true }).catch(() => {});
REPORT.notes.push({ adminLoginErrorText: (await badPage.locator('body').innerText().catch(() => '')).slice(0, 300) });
await bad.close();
// 取得的条目 id(用于编辑器页面);取不到就用 new
const probeContext = await browser.newContext({ viewport: desktop, storageState: login.state, reducedMotion: 'reduce' });
const probe = await probeContext.newPage();
await probe.goto(`${BASE}/admin/content/news`, { waitUntil: 'networkidle' }).catch(() => {});
await probe.waitForTimeout(1200);
const itemHref = await probe.evaluate(() => {
const link = [...document.querySelectorAll('a[href*="/admin/content/news/"]')]
.find((a) => !a.getAttribute('href').endsWith('/new'));
return link ? link.getAttribute('href') : null;
});
await probeContext.close();
REPORT.notes.push({ adminNewsItemHref: itemHref });
const adminPages = [
'/admin',
'/admin/content/news',
itemHref || '/admin/content/news/new',
'/admin/media',
'/admin/notifications',
'/admin/roles',
'/admin/users',
'/admin/zones',
];
if (ONLY) {
const filtered = adminPages.filter((p) => ONLY.some((o) => p.includes(o)));
adminPages.length = 0;
adminPages.push(...filtered);
}
for (const route of adminPages) {
for (const combo of MATRIX) {
const run = await captureAdminPage(browser, login.state, route, combo.vp, combo.theme, dir);
REPORT.adminRuns.push(run);
flush();
console.log(`[admin] ${route} ${combo.vp}/${combo.theme} hard=${run.hardFailure} ${run.durationMs || ''}ms`);
}
}
// 删除确认弹窗(打开后取消,不写库)
const dialogContext = await browser.newContext({ viewport: desktop, storageState: login.state, reducedMotion: 'reduce' });
const dialogPage = await dialogContext.newPage();
await dialogPage.goto(`${BASE}/admin/content/news`, { waitUntil: 'networkidle' }).catch(() => {});
await dialogPage.waitForTimeout(1200);
const deleteButton = dialogPage.locator('button[title="删除"]').first();
const hasDelete = await deleteButton.count();
if (hasDelete) {
await deleteButton.click().catch(() => {});
await dialogPage.waitForTimeout(800);
await dialogPage.screenshot({ path: path.join(dir, 'admin-delete-dialog__1440__light__chromium__full.webp'), fullPage: true }).catch(() => {});
const cancel = dialogPage.getByRole('button', { name: /取消/ }).first();
await cancel.click().catch(() => {});
REPORT.notes.push({ adminDeleteDialog: 'opened and cancelled' });
} else {
REPORT.notes.push({ adminDeleteDialog: 'delete button not found on /admin/content/news' });
}
await dialogContext.close();
// 权限拒绝态(content_editor 直访 /admin/users)
const editor = await loginAndState(browser, desktop, EDITOR_USER, EDITOR_PASS, 'light');
if (editor.loggedIn && editor.state) {
const ctx = await browser.newContext({ viewport: desktop, storageState: editor.state, reducedMotion: 'reduce' });
const page = await ctx.newPage();
await page.goto(`${BASE}/admin/users`, { waitUntil: 'networkidle' }).catch(() => {});
await page.waitForTimeout(1500);
await page.screenshot({ path: path.join(dir, 'admin-permission-denied__1440__light__chromium__full.webp'), fullPage: true }).catch(() => {});
REPORT.notes.push({ adminPermissionDenied: { url: page.url(), body: (await page.locator('body').innerText().catch(() => '')).slice(0, 300) } });
await ctx.close();
} else {
REPORT.notes.push({ adminPermissionDenied: 'skipped: editor login failed' });
}
await editor.context.close();
}
const routes = await loadRoutes();
REPORT.meta.routes = routes;
REPORT.meta.routeCount = routes.length;
flush();
console.log(`routes=${routes.length} mode=${MODE}`);
const browsers = { chromium: await chromium.launch(), firefox: await firefox.launch(), webkit: await webkit.launch() };
try {
if (MODE === 'public' || MODE === 'both') {
for (const route of routes) {
for (const combo of MATRIX) {
const run = await runOne(browsers.chromium, 'chromium', route, combo.vp, combo.theme);
REPORT.runs.push(run);
flush();
console.log(`[public] ${route} ${combo.vp}/${combo.theme} hard=${run.hardFailure} ${run.durationMs}ms`);
}
}
const detail = routes.find((r) => r.split('/').filter(Boolean).length >= 2 && !['/about/brand', '/products/erp-upgrade', '/products/erp-upgrade-v3', '/news/company-founded'].includes(r));
const crossRoutes = ['/', '/about', '/contact', '/products', ...(detail ? [detail] : [])];
for (const engine of ['firefox', 'webkit']) {
for (const route of crossRoutes) {
for (const combo of [{ vp: '1440', theme: 'light' }, { vp: '390', theme: 'light' }]) {
const run = await runOne(browsers[engine], engine, route, combo.vp, combo.theme);
REPORT.runs.push(run);
flush();
console.log(`[public:${engine}] ${route} ${combo.vp}/${combo.theme} hard=${run.hardFailure} ${run.durationMs}ms`);
}
}
}
}
if (MODE === 'admin' || MODE === 'both') {
await runAdmin(browsers.chromium);
flush();
}
} finally {
await browsers.chromium.close();
await browsers.firefox.close();
await browsers.webkit.close();
flush();
}
const hard = REPORT.runs.filter((r) => r.hardFailure).length + REPORT.adminRuns.filter((r) => r.hardFailure).length;
console.log(`DONE runs=${REPORT.runs.length} adminRuns=${REPORT.adminRuns.length} hardFailures=${hard} -> ${path.join(OUT, 'report.json')}`);
process.exit(hard > 0 ? 1 : 0);