test(闸门): 常驻探针补两只新闸与凭据口径,14 道全绿
`scripts/**` 是本项目对 NEX 10「阶段 5 质量门禁」的现成实现,跟着呈现层一起落地。 - 新增 `scripts/ui/projectswitchcheck.py`:第 14 道常驻探针——改了项目数据生命周期 (详情 store/切换与轮询)才跑。判据是换项目不残留、404 认错、静置不闪; 读数落盘默认 `/tmp/nex_ui_projectswitch`,优先级 `NEX_JSON` > `NEX_OUT` > 默认目录(阶段 37 把「跑一次就在版本树里留一个未跟踪文件」这条收掉)。 `README.md` 的探针清单同步补这一行。 - 新增 `scripts/ui/chunkbudget.mjs`:产物级 chunk 预算闸,配 `frontend/chunk-budget.json` 的在册上限,超预算即非零退出。 - 八只常驻探针的登录口令默认值 `admin1234 → admin@123`,跟 `.env.example` 对齐; 只改凭据默认值,判据与豁免一字未动,因此不触发 `gateprobe` 的 29 条自证。 - `classaudit.mjs`:子闸从 9 条扩到 12 族(+附/附二/附三:图标型控件命名 ICNN、 两级表边界、图标出口形状),末尾新增机器可读的 `FAMILY` 族账行——它同时是 `gateprobe` ㉖ 的判据凭据,退出码 = 任一族非零。 - `gateprobe.py` 补到 29 条闸门自证;`visualcheck.py`、`gridcheck.py`、`tableaudit.py`、 `rhythmcheck.py`、`aligncheck.py`、`symmetrycheck.py`、`tagcheck.py`、`footercheck.py`、 `semanticcheck.py`、`feedbackcheck.py`、`btnrowcheck.py`、`btnclustercheck.py` 按各阶段 咬出的缺陷补判据(`footercheck` 的 CASES 改成环节资产页的真实触发器)。 落地前实跑:`node scripts/ui/classaudit.mjs` 退出码 0、12 族全 0; `.venv/bin/python scripts/ui/gateprobe.py` → `GATEPROBE_OK 29/29`、`^OK` 205 条、 `FAIL` 0 条、退出码 0(与阶段 35 起的基线逐字相同)。14 道活体探针沿用阶段 44 收工(2026-11-11 22:02)的全绿读数——本轮零业务代码改动,R12 全量回归不触发。 同一批 `scripts/**` 里的非探针部分(一起提交,同属质量与部署工装): - `scripts/seed.py` 补 `--reset-password`:`install` **默认不改已存在账号的口令** (这台机器可能早就改过,覆盖成开发机的口令是反直觉的倒退),只有显式加这条 才让部署包里的口令生效;`scripts/seed/users.json`/`model_specs.json` 跟着真实 初始口令与模型配置更新。 - `scripts/dev.sh`/`server.sh`/`e2e_selfcheck.py` 里那几处初始口令与提示同步; `server.sh install` 在没有 `scripts/seed/` 时明确告知「服务器将用 mock 模型 + admin/admin@123 起步」。main
parent
ee17358182
commit
83ed9622ec
|
|
@ -303,7 +303,7 @@ try:
|
|||
call("/api/auth/login", {
|
||||
"username": os.environ.get("NEX_USER")
|
||||
or (state.get("login_hint") or {}).get("username") or "admin",
|
||||
"password": os.environ.get("NEX_PASS") or "admin1234"})
|
||||
"password": os.environ.get("NEX_PASS") or "admin@123"})
|
||||
providers = call("/api/providers")["providers"]
|
||||
except Exception as exc:
|
||||
print(f" 模型注册表读取失败:{type(exc).__name__}: {exc}")
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ def login():
|
|||
if st.get("authenticated"):
|
||||
return
|
||||
user = os.environ.get("NEX_USER") or (st.get("login_hint") or {}).get("username") or "admin"
|
||||
pwd = os.environ.get("NEX_PASS") or "admin1234"
|
||||
pwd = os.environ.get("NEX_PASS") or "admin@123"
|
||||
r = CLIENT.post("/api/auth/login", json={"username": user, "password": pwd})
|
||||
if r.status_code != 200:
|
||||
print(" XX 登录失败 %s -> %s\n%s\n 换个账号试试:NEX_USER=xxx NEX_PASS=xxx %s"
|
||||
|
|
|
|||
|
|
@ -88,7 +88,13 @@ def row_to_dict(obj) -> dict:
|
|||
def write_json(path: Path, payload) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(f" 写出 {path.relative_to(ROOT)}")
|
||||
# --out 可以指到仓库外(比对导出内容、CI 里落产物),这时 relative_to 会抛
|
||||
# ValueError,把整个 export 打断在半路上:只有第一个文件写了出去。
|
||||
try:
|
||||
shown = path.relative_to(ROOT)
|
||||
except ValueError:
|
||||
shown = path
|
||||
print(f" 写出 {shown}")
|
||||
|
||||
|
||||
def read_json(src: Path, name: str):
|
||||
|
|
@ -614,7 +620,7 @@ def _install_specs(db, rows, *, dry: bool, only_missing: bool = False) -> None:
|
|||
+ ("" if not updated or only_missing else "(更新=用部署包的值覆盖服务器上的同名模型)"))
|
||||
|
||||
|
||||
def _install_users(db, rows, *, dry: bool) -> None:
|
||||
def _install_users(db, rows, *, dry: bool, reset_password: bool = False) -> None:
|
||||
for data in rows:
|
||||
row = db.scalars(select(User).where(User.username == data["username"])).first()
|
||||
if row is None:
|
||||
|
|
@ -627,11 +633,22 @@ def _install_users(db, rows, *, dry: bool) -> None:
|
|||
else:
|
||||
# 已存在的账号不重置口令:这台机器可能早改过密码,
|
||||
# 覆盖成开发机的口令是个反直觉的倒退。
|
||||
_apply(row, data, skip=("id", "created_at", "updated_at", "password_hash",
|
||||
"must_change_password"))
|
||||
# 先比再写:_apply 之后两边必然一致,"要不要提醒口令不同"就量不出来了
|
||||
diff = (data.get("password_hash") or "") != row.password_hash
|
||||
print(f" · 管理员 {row.username} 已存在:只同步角色/显示名,不改口令"
|
||||
+ ("(注意:它的口令与部署包不同,登录请用这台机器的口令)" if diff else ""))
|
||||
keep = ("must_change_password",) if reset_password else ("password_hash",
|
||||
"must_change_password")
|
||||
_apply(row, data, skip=("id", "created_at", "updated_at") + keep)
|
||||
if reset_password:
|
||||
row.must_change_password = False
|
||||
if reset_password and diff:
|
||||
print(f" ✓ 管理员 {row.username} 口令已按部署包重置(开发机导出的那一次登录口令)")
|
||||
elif diff:
|
||||
print(f" · 管理员 {row.username} 已存在:只同步角色/显示名,不改口令"
|
||||
f"(注意:它的口令与部署包不同,登录请用这台机器的口令;"
|
||||
f"要让部署包的口令生效加 --reset-password)")
|
||||
else:
|
||||
print(f" · 管理员 {row.username} 已存在:口令与部署包一致"
|
||||
f"(角色/显示名已同步)")
|
||||
if not dry:
|
||||
db.commit()
|
||||
|
||||
|
|
@ -694,7 +711,8 @@ def do_install(args) -> None:
|
|||
print("安装部署数据集(幂等,可反复执行)")
|
||||
_install_master_key(db, keys, dry=args.dry_run, force=args.force_master_key)
|
||||
_install_specs(db, specs, dry=args.dry_run, only_missing=args.only_missing)
|
||||
_install_users(db, users, dry=args.dry_run)
|
||||
_install_users(db, users, dry=args.dry_run,
|
||||
reset_password=args.reset_password)
|
||||
if lib is not None:
|
||||
_install_platform(db, lib, dry=args.dry_run)
|
||||
if args.dry_run:
|
||||
|
|
@ -824,6 +842,9 @@ def main() -> None:
|
|||
i.add_argument("--only-missing", action="store_true",
|
||||
help="模型配置只补缺,不覆盖服务器上已有的同名模型")
|
||||
i.add_argument("--allow-drift", action="store_true", help="体检有 error 也照样导入")
|
||||
i.add_argument("--reset-password", action="store_true",
|
||||
help="管理员口令也按部署包重置(默认不改:这台机器可能早改过密码)。"
|
||||
"开发机换过管理口令并重新 export 后,服务器上用它对齐")
|
||||
i.set_defaults(func=do_install)
|
||||
|
||||
d = sub.add_parser("doctor", help="体检:量开发库(默认)或量部署包(--src),不改数据")
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
"tts=comfyui/indextts2",
|
||||
"video=comfyui/minimax-h3"
|
||||
],
|
||||
"exported_at": "2026-11-06T16:42:16"
|
||||
"exported_at": "2026-11-10T14:53:55"
|
||||
},
|
||||
"rows": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@
|
|||
"username": "admin",
|
||||
"display_name": "平台管理员",
|
||||
"email": "",
|
||||
"password_hash": "pbkdf2_sha256$180000$qaixn-FvRZ9-KfxxeskdUQ$f47df46b72273583ec549869e454ad22e31d56c4f4f288d8e16962b47add494b",
|
||||
"password_hash": "pbkdf2_sha256$180000$ZghwyAPJYAZX8HRjQl_2ug$8670f47313bb914be276da20aec41fc15b99dfca98b84adfb9d7df13c5c9ba78",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"must_change_password": false,
|
||||
|
|
@ -18,7 +18,7 @@
|
|||
"prefs_json": {},
|
||||
"created_by_id": null,
|
||||
"created_at": "2026-10-27 08:56:53.524106",
|
||||
"updated_at": "2026-11-05 17:13:26.239575"
|
||||
"updated_at": "2026-11-10 06:53:30.965457"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -170,8 +170,8 @@ seed_data() {
|
|||
head2 "表结构与初始数据"
|
||||
if [ ! -d "$ROOT/scripts/seed" ]; then
|
||||
# 从 git 克隆(而不是从部署包解压)时没有这个目录:不是错误,
|
||||
# 应用首启会自己建表、播 mock、建 admin/admin1234,只是要在模型管理中心重配一遍。
|
||||
warn "没有 scripts/seed/:跳过数据导入,服务器将用 mock 模型 + admin/admin1234 起步"
|
||||
# 应用首启会自己建表、播 mock、建 admin/admin@123,只是要在模型管理中心重配一遍。
|
||||
warn "没有 scripts/seed/:跳过数据导入,服务器将用 mock 模型 + admin/admin@123 起步"
|
||||
return 0
|
||||
fi
|
||||
# 体检不在这层重复实现:seed.py install 自己会先量包(列 / 适配器 / 能力位 /
|
||||
|
|
@ -332,7 +332,7 @@ try:
|
|||
if st.get("auth_enabled") and not st.get("authenticated"):
|
||||
r = c.post("/api/auth/login", json={
|
||||
"username": os.environ.get("NEX_USER") or (st.get("login_hint") or {}).get("username") or "admin",
|
||||
"password": os.environ.get("NEX_PASS") or "admin1234"})
|
||||
"password": os.environ.get("NEX_PASS") or "admin@123"})
|
||||
if r.status_code != 200:
|
||||
# 登录不进去多半是首登强制改密没走界面,这里只提示,不阻塞 status
|
||||
print(f" 模型注册表跳过:登录失败 {r.status_code}(改 NEX_USER/NEX_PASS 后重试)")
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ with sync_playwright() as pw:
|
|||
pg = b.new_page(viewport={'width': WIDTH, 'height': 1000})
|
||||
pg.goto(BASE + '/login', wait_until='networkidle')
|
||||
if pg.locator('#login-user').count():
|
||||
pg.fill('#login-user', 'admin'); pg.fill('#login-pass', 'admin1234')
|
||||
pg.fill('#login-user', 'admin'); pg.fill('#login-pass', 'admin@123')
|
||||
pg.click('button[type=submit]'); pg.wait_for_timeout(1200)
|
||||
pg.evaluate('t => localStorage.setItem("nex-the", t)', THEME)
|
||||
for name, route in PAGES:
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ from playwright.sync_api import sync_playwright
|
|||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
|
||||
WIDTHS = [int(x) for x in os.environ.get("NEX_WIDTHS", "1440,992,768,576,430").split(",")]
|
||||
THEMES = os.environ.get("NEX_THEMES", "light").split(",")
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin1234")
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin@123")
|
||||
ROUTES = os.environ.get("NEX_ROUTES",
|
||||
"/,/assets,/models,/users,/account,/projects/10/overview,/projects/10/library,"
|
||||
"/projects/10/storyboard,/projects/10/dispatch,/projects/10/timeline,"
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ ROUTES = [r for r in os.environ.get(
|
|||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||||
"/projects/{id}/timeline,/projects/{id}/delivery,"
|
||||
"/account,/users,/help").split(",") if r]
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin1234")
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin@123")
|
||||
|
||||
# 项目子页量「镜头最多」的项目:空项目全是空态,按钮组根本不渲染(同 visualcheck)
|
||||
PROJECT_JS = r"""async () => {
|
||||
|
|
|
|||
|
|
@ -32,7 +32,10 @@ THEMES = ["dark", "light"] if os.environ.get("NEX_THEME", "both") == "both" else
|
|||
OUT = os.environ.get("NEX_CENSUS_OUT", "/tmp/nex_census")
|
||||
ROOT = str(pathlib.Path(__file__).resolve().parents[2])
|
||||
|
||||
src = open(ROOT + "/frontend/src/components/icons/index.ts", encoding="utf8").read()
|
||||
# 2026-11-09 阶段 25:登记表拆成 core.ts / extra.ts 两张表(外加 _kit.ts / index.ts),
|
||||
# 词汇表读整个目录,否则普查会少掉 extra 那 24 只。
|
||||
src = "\n".join(open(ROOT + "/frontend/src/components/icons/" + f, encoding="utf8").read()
|
||||
for f in sorted(os.listdir(ROOT + "/frontend/src/components/icons")) if f.endswith(".ts"))
|
||||
pairs = []
|
||||
for glyph, alias in re.findall(r"export\s*\{\s*(\w+)\s+as\s+(Icon\w+)\s*\}", src):
|
||||
pairs.append((glyph, alias))
|
||||
|
|
@ -108,7 +111,7 @@ def main():
|
|||
page.add_init_script("try{localStorage.setItem('nex-the','%s')}catch(e){}" % theme)
|
||||
page.goto(BASE + "/login", wait_until="networkidle")
|
||||
if page.locator("#login-user").count():
|
||||
page.fill("#login-user", "admin"); page.fill("#login-pass", "admin1234")
|
||||
page.fill("#login-user", "admin"); page.fill("#login-pass", "admin@123")
|
||||
page.click("button[type=submit]"); page.wait_for_timeout(1500)
|
||||
pid = page.evaluate("""async () => { const r = await fetch('/api/projects').then(x=>x.json()).catch(()=>null);
|
||||
const l = Array.isArray(r) ? r : (r && (r.items||r.projects||r.data)) || []; return l.length ? l[0].id : null; }""")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,281 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* 产物预算闸(阶段 16 · 任务 3):给构建产物一条**会响**的体积上限。
|
||||
*
|
||||
* 症状:`vite.config.ts` 的 `chunkSizeWarningLimit: 1200` 从阶段 8.5 起常驻一条
|
||||
* `(!) Some chunks are larger than 1200 kB after minification`——它只是构建器
|
||||
* 打印的一行字,**退出码永远是 0**。于是两件事被悄悄做掉了:谁把首屏 chunk 从
|
||||
* 1 246 kB 抬到 1 280 kB、1 300 kB,构建照样绿;而那条警告因为「一直在那儿」
|
||||
* 被当成噪音划走。阶段 9/14/15 的结论是「不改分包」——**不改更需要一把尺子**:
|
||||
* 不改 = 现状是基线,任何往上的漂移必须有人拦,不能靠谁偶然瞄一眼构建日志。
|
||||
*
|
||||
* 做法:上限按三层来源取,**先登记的、后兜底**,命中哪一层就打印哪一层的文件与字节:
|
||||
* A) 显式 `--config <file>`:只认这一份(判据 ㉒ 的反向验证靠它喂夹具,
|
||||
* 显式指定的来源不许被项目默认值污染,所以它没 budget 就是 DEGRADED,不往下兜)。
|
||||
* B) 构建器落盘配置 `output.budget`(`<dist>/.vite/rollup.config.json`)。
|
||||
* 本项目长期走不到这一层:vite 8.3.4 + rolldown 1.2.13 既不落那份配置
|
||||
* (实测 `dist/` 只有 assets/help/index.html),`OutputOptions` 里也没有
|
||||
* `budget` 字段(grep 过 rolldown 的 d.mts)。
|
||||
* C) 项目自己登记的预算文件 `frontend/chunk-budget.json`(阶段 24 补的来源,
|
||||
* `--budget-file` 可显式指定)。B 读不出上限时才读它;它坏了 / 没 budget 键 /
|
||||
* 原值读不出正数 ⇒ **点名响**,不冒充「没有预算」也不悄悄兜底。
|
||||
* 三层都没有时**退化到 1 500 kB 并显式打印 `DEGRADED`**。
|
||||
* 退化必须看得见,不许把兜底数字伪装成「配置里写的」;退化也不许放宽判定。
|
||||
* 然后逐个量 `dist` 里的 `.js`/`.css`,超限就点名 + 退出码非零。
|
||||
*
|
||||
* 为什么不「把 chunkSizeWarningLimit 调到 1300 让警告消失」:那是**加阈值**,本次禁止
|
||||
* (阶段 8.5 §6.3:抬阈值捂警告仍然禁止)。这把闸的语义是「产物不得越过预算」,
|
||||
* 与那条 >1 200 kB 的**警告**互不干涉:警告继续如实报,闸门在真越界时才阻断。
|
||||
* 兜底 1 500 kB = 阶段 15 基线(`chunk-after.txt`:`ui-*.js` 1 275.93 kB)之上
|
||||
* 留 17.5 % 余量——够一次正常的功能增量,不够一次无声的重依赖引入。
|
||||
*
|
||||
* 大小口径:raw(磁盘字节),**kB = 1000 B(十进制)**——与 vite 控制台同一把尺。
|
||||
* 这是实测钉的,不是猜的:`ui-DsRXK1XH.js` 落盘 1 275 933 B,vite 打印 `1,275.93 kB`,
|
||||
* `chunkSizeWarningLimit` 按同一把尺比较,阶段 15 基线(首屏 1 559.97 / 全部 1 963.80)
|
||||
* 也是十进制——本脚本对同一份产物报「合计 1 963.80 kB」,与 `chunk-after.txt` 逐位吻合。
|
||||
* ⚠ 仓库里另有两把尺:`chunkinfo.mjs` 用 n/1024 却标 kB(同一个文件它报 1 246.03),
|
||||
* 与这里差 2.4 %;跨脚本比大小先认尺子(已登记阶段 16 报告 §7,本轮不动它)。
|
||||
* gzip/brotli 只进明细不参与判定:传输看压缩、parse 看 raw,判定挑最严的那一个。
|
||||
*
|
||||
* 四条「不许沉默」的守卫:
|
||||
* 1) `dist` 不存在 / 没有 assets / 一个 .js|.css 都没有 → 红(没构建等于没量);
|
||||
* 2) 配置文件 / 预算文件存在但不是合法 JSON → 红(配置坏了不能当成「没有 budget」混成 DEGRADED);
|
||||
* 显式 `--config` / `--budget-file` 指不到文件 → 红(夹具前提变了就是错);
|
||||
* 预算文件在却没有 budget 键 / 原值读不出正数 → 红(文件在而读不出上限,等于没有预算);
|
||||
* 3) 读到了 budget → 打印来源文件 + 原始字节 + 换算后的 kB,数字可回溯;
|
||||
* 4) 没读到 → 打印 `DEGRADED` + 原因,并按兜底值照判(退化≠放宽)。
|
||||
*
|
||||
* budget 支持的形状(构建器今天不产这份配置,所以形状按「能宽就宽、但不猜单位」处理,
|
||||
* 每一条都原样打印以便人工复核;单位一律**字节**,与 rollup/rolldown 的尺寸类选项一致):
|
||||
* · `output.budget = 1500000` → 全量上限
|
||||
* · `output.budget = { maximumSize: 1500000 }`(或 maxSize/limit/max)→ 同上
|
||||
* · `output.budget = [ {maximumSize, name?, type?}, … ]` → 逐条作用域:
|
||||
* `type:'chunk'` 只管 `.js`,`type:'asset'` 只管非 `.js`(css 等),不写 = 都管;
|
||||
* `name` 是 glob(`assets/ui-*.js`),不写 = 全部文件;
|
||||
* 一个文件命中多条时取**最具体**的那条(name > type > 全局),同层取更小的上限;
|
||||
* · `outputs[].output.budget` 也读(多 output 配置)。
|
||||
* 一条都读不出来 → 与「没有该键」同样处理:DEGRADED + 兜底。
|
||||
*
|
||||
* 用法:
|
||||
* node scripts/ui/chunkbudget.mjs # 默认 frontend/dist + frontend/chunk-budget.json
|
||||
* node scripts/ui/chunkbudget.mjs --dist DIR # 指定产物目录
|
||||
* node scripts/ui/chunkbudget.mjs --budget-file F.json # 指定项目预算文件(阶段 24 的来源 C)
|
||||
* node scripts/ui/chunkbudget.mjs --dist D --config C.json # 反向验证:喂一份带 budget 的配置
|
||||
* node scripts/ui/chunkbudget.mjs --json # 机读(gateprobe 用)
|
||||
* 退出码:0 全部在预算内;1 有越界 / 产物或配置不可信。
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import zlib from 'node:zlib'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const FALLBACK_KB = 1500 // 没读到 budget 时的兜底上限(依据见文件头「为什么不抬阈值」)
|
||||
const CONFIG_REL = path.join('.vite', 'rollup.config.json') // 构建器落盘配置相对 dist 的位置
|
||||
const VITE_WARN_KB = 1200 // 只用来标注「vite 已警告」,判定不看它(调大数字 ≠ 整改)
|
||||
const kb = (n) => n / 1000 // 十进制:与 vite 控制台 / chunkSizeWarningLimit / 阶段 15 基线同尺
|
||||
const fmt = (n) => kb(n).toFixed(2).padStart(9)
|
||||
|
||||
/* ---------- 参数 ---------- */
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, dflt) => {
|
||||
const i = argv.indexOf('--' + name)
|
||||
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : dflt
|
||||
}
|
||||
const JSON_OUT = argv.includes('--json')
|
||||
const DIST = path.resolve(arg('dist', path.join(HERE, '../../frontend/dist')))
|
||||
const CONFIG_GIVEN = arg('config', null)
|
||||
// 项目自己登记的预算文件(阶段 24):构建器不落盘 rollup.config.json,唯一来源等于长期 DEGRADED。
|
||||
const BUDGET_FILE_GIVEN = arg('budget-file', null)
|
||||
const BUDGET_FILE = path.resolve(BUDGET_FILE_GIVEN ?? path.join(HERE, '../../frontend/chunk-budget.json'))
|
||||
|
||||
const fails = []
|
||||
const die = (msg) => fails.push(msg)
|
||||
|
||||
/* ---------- 1. 上限从哪来 ---------- */
|
||||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null)
|
||||
function readEntries(budget) {
|
||||
const list = Array.isArray(budget) ? budget : [budget]
|
||||
const out = []
|
||||
for (const item of list) {
|
||||
const max = num(item) ?? (item && typeof item === 'object'
|
||||
? (num(item.maximumSize) ?? num(item.maxSize) ?? num(item.limit) ?? num(item.max)) : null)
|
||||
if (max == null) continue
|
||||
const name = item && typeof item === 'object' ? (item.name || item.pattern || null) : null
|
||||
const type = item && typeof item === 'object' ? (item.type || null) : null
|
||||
if (type && !['chunk', 'asset'].includes(type)) { // 认不出的作用域不猜,直接响
|
||||
die(`BUDGET-TYPE budget.type=${JSON.stringify(type)} 不在册(只认 chunk / asset) → 猜错作用域等于把上限悄悄放宽`)
|
||||
continue
|
||||
}
|
||||
out.push({ max, name, type })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/* 来源字符串:文件 + 原值字节 + 换算 kB + 作用域,数字可回溯(守卫 3) */
|
||||
const entriesText = (src, es) => `${src} = ${es.map((e) => `${e.max} B=${kb(e.max).toFixed(2)} kB${e.name || e.type ? `(${[e.type, e.name].filter(Boolean).join(' ')}→${e.name || '全部'})` : ''}`).join(' · ')}`
|
||||
|
||||
/* 从一份 JSON 文档里抓 budget 原值(顶层 output.budget / budget / outputs[].output.budget) */
|
||||
function grabRaws(doc) {
|
||||
const raws = []
|
||||
const grab = (o) => {
|
||||
if (!o || typeof o !== 'object') return
|
||||
if (o.output && o.output.budget !== undefined) raws.push(o.output.budget)
|
||||
else if (o.budget !== undefined) raws.push(o.budget)
|
||||
}
|
||||
grab(doc)
|
||||
if (Array.isArray(doc.outputs)) for (const o of doc.outputs) grab(o)
|
||||
return raws
|
||||
}
|
||||
|
||||
const configPath = CONFIG_GIVEN ? path.resolve(CONFIG_GIVEN) : path.join(DIST, CONFIG_REL)
|
||||
let configUntrusted = false // CONFIG-BAD / CONFIG-MISSING:这种情况**不许**冒充 DEGRADED
|
||||
const configFound = fs.existsSync(configPath)
|
||||
let entries = []
|
||||
let budgetSource = null
|
||||
let degraded = null
|
||||
let configRaw = null
|
||||
|
||||
if (CONFIG_GIVEN && !configFound) {
|
||||
die(`CONFIG-MISSING 指定的配置不存在:${configPath} → 反向验证的夹具前提变了,不许退化成兜底继续跑`)
|
||||
degraded = '指定的配置文件不存在'; configUntrusted = true
|
||||
} else if (configFound) {
|
||||
try {
|
||||
configRaw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
|
||||
} catch (e) {
|
||||
die(`CONFIG-BAD 配置不是合法 JSON:${configPath} —— ${e.message} → 配置坏了必须响,不许混成 DEGRADED 用兜底蒙过去`)
|
||||
degraded = '配置解析失败(见 CONFIG-BAD)'; configUntrusted = true
|
||||
}
|
||||
if (configRaw) {
|
||||
const raws = grabRaws(configRaw)
|
||||
if (!raws.length) {
|
||||
degraded = `配置里没有 output.budget(${configPath})`
|
||||
} else {
|
||||
entries = raws.flatMap(readEntries)
|
||||
if (!entries.length) degraded = `output.budget 读不出可用上限(原值 ${JSON.stringify(raws[0]).slice(0, 120)})`
|
||||
else budgetSource = entriesText(configPath + ' · output.budget', entries)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
degraded = `构建器未落盘配置(找不到 ${path.join(DIST, CONFIG_REL)})`
|
||||
}
|
||||
/* 来源 C(阶段 24):项目自己登记的预算文件。
|
||||
* 什么时候才读它:没显式 --config(显式 = 反向验证夹具,不许被默认值污染)、
|
||||
* 且构建器那一份没给出上限(不落盘 / 没 budget 键)。
|
||||
* 三条红线照旧:读到了就打印来源与字节;坏了就响,不冒充「没有预算」;
|
||||
* 缺文件在没显式指定时才算「没有这一层」,显式 --budget-file 指不到就是错。 */
|
||||
let budgetFileUsed = null
|
||||
if (!CONFIG_GIVEN && !entries.length) {
|
||||
if (!fs.existsSync(BUDGET_FILE)) {
|
||||
if (BUDGET_FILE_GIVEN) {
|
||||
die(`BUDGET-FILE-MISSING 指定的预算文件不存在:${BUDGET_FILE} → 显式指定的来源找不到就是错,不许退到兜底继续跑`)
|
||||
degraded = '指定的预算文件不存在'; configUntrusted = true
|
||||
} else {
|
||||
degraded = (degraded ? degraded + ';' : '') + `项目预算文件也不存在(${BUDGET_FILE})`
|
||||
}
|
||||
} else {
|
||||
let doc = null
|
||||
try {
|
||||
doc = JSON.parse(fs.readFileSync(BUDGET_FILE, 'utf8'))
|
||||
} catch (e) {
|
||||
die(`BUDGET-FILE-BAD 预算文件不是合法 JSON:${BUDGET_FILE} —— ${e.message} → 配置坏了必须响,不许混成 DEGRADED 用兜底蒙过去`)
|
||||
degraded = '预算文件解析失败(见 BUDGET-FILE-BAD)'; configUntrusted = true
|
||||
}
|
||||
if (doc !== null) {
|
||||
const raws = grabRaws(doc)
|
||||
if (!raws.length) {
|
||||
die(`BUDGET-FILE-EMPTY ${BUDGET_FILE} 里没有 budget / output.budget 键 → 文件在却读不出上限,等于没有预算,不许静默兜底`)
|
||||
degraded = '预算文件里没有 budget 键(见 BUDGET-FILE-EMPTY)'; configUntrusted = true
|
||||
} else {
|
||||
const es = raws.flatMap(readEntries)
|
||||
if (!es.length) {
|
||||
die(`BUDGET-FILE-SHAPE budget 原值 ${JSON.stringify(raws[0]).slice(0, 120)} 读不出正数上限 → 猜单位等于把上限悄悄放宽`)
|
||||
degraded = 'budget 原值读不出可用上限(见 BUDGET-FILE-SHAPE)'; configUntrusted = true
|
||||
} else {
|
||||
entries = es // 上限真正生效的一条:只记来源不装 entries = 空转
|
||||
budgetFileUsed = BUDGET_FILE
|
||||
budgetSource = entriesText(BUDGET_FILE + ' · budget', es)
|
||||
degraded = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const fallbackKB = FALLBACK_KB
|
||||
if (degraded) entries = []
|
||||
|
||||
/* 一个文件适用哪条上限:name 命中 > type 命中 > 全局;同层取更小的;都没有 → 兜底 */
|
||||
const glob = (p) => new RegExp('^' + p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
|
||||
function limitFor(rel) {
|
||||
const isJs = rel.endsWith('.js')
|
||||
let best = null
|
||||
for (const e of entries) {
|
||||
if (e.type === 'chunk' && !isJs) continue
|
||||
if (e.type === 'asset' && isJs) continue
|
||||
if (e.name && !glob(e.name).test(rel) && !glob(e.name).test(path.basename(rel))) continue
|
||||
const spec = (e.name ? 2 : 0) + (e.type ? 1 : 0)
|
||||
if (!best || spec > best.spec || (spec === best.spec && e.max < best.max)) best = { max: e.max, spec }
|
||||
}
|
||||
return best ? best.max : (degraded ? fallbackKB * 1000 : entries.length ? Math.min(...entries.map((e) => e.max)) : fallbackKB * 1000)
|
||||
}
|
||||
|
||||
/* ---------- 2. 逐个量产物 ---------- */
|
||||
const ASSETS = path.join(DIST, 'assets')
|
||||
let files = []
|
||||
if (!fs.existsSync(DIST)) {
|
||||
die(`NO-DIST 产物目录不存在:${DIST} → 先 cd frontend && npm run build,没构建等于没量,不能算通过`)
|
||||
} else if (!fs.existsSync(ASSETS)) {
|
||||
die(`NO-ASSETS 产物里没有 assets:${ASSETS} → 空产物不能算通过`)
|
||||
} else {
|
||||
const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {
|
||||
const p = path.join(d, e.name)
|
||||
if (e.isDirectory()) return e.name === '.vite' ? [] : walk(p)
|
||||
return /\.(js|css)$/.test(e.name) && !e.name.endsWith('.map') ? [p] : []
|
||||
})
|
||||
files = walk(DIST)
|
||||
if (!files.length) die(`EMPTY 产物里没有任何 .js/.css:${DIST} → 空产物不能算通过`)
|
||||
}
|
||||
|
||||
const rows = files.map((f) => {
|
||||
const buf = fs.readFileSync(f)
|
||||
const rel = path.relative(DIST, f)
|
||||
const limit = limitFor(rel)
|
||||
return { rel, raw: buf.length, gzip: zlib.gzipSync(buf, { level: 9 }).length,
|
||||
brotli: zlib.brotliCompressSync(buf).length, limit, over: buf.length > limit }
|
||||
}).sort((a, b) => b.raw - a.raw)
|
||||
|
||||
for (const r of rows) {
|
||||
if (r.over) die(`OVER ${r.rel} raw ${kb(r.raw).toFixed(2)} kB > 预算 ${kb(r.limit).toFixed(2)} kB(超 ${kb(r.raw - r.limit).toFixed(2)} kB · gzip ${kb(r.gzip).toFixed(2)} kB)`)
|
||||
}
|
||||
|
||||
/* ---------- 3. 输出 ---------- */
|
||||
const verdict = fails.length ? 'FAIL' : 'OK'
|
||||
const total = rows.reduce((a, r) => a + r.raw, 0)
|
||||
const totalBytes = rows.reduce((a, r) => a + r.raw, 0)
|
||||
const degradedText = configUntrusted
|
||||
? `不可信 —— 配置/预算文件读坏了(见 CONFIG-BAD / CONFIG-MISSING / BUDGET-FILE-*),不冒充 DEGRADED 也不假装按兜底量过`
|
||||
: (degraded ? `DEGRADED —— ${degraded};退化到兜底 ${fallbackKB} kB(兜底≠放宽,判定照旧)` : null)
|
||||
if (JSON_OUT) {
|
||||
console.log(JSON.stringify({
|
||||
verdict, dist: DIST, configPath, configFound, budgetSource,
|
||||
degraded: !!degraded && !configUntrusted, configUntrusted, degradedReason: degraded, fallbackKB,
|
||||
files: rows.map((r) => ({ rel: r.rel, rawKB: +kb(r.raw).toFixed(2), gzipKB: +kb(r.gzip).toFixed(2),
|
||||
brotliKB: +kb(r.brotli).toFixed(2), limitKB: +kb(r.limit).toFixed(2), over: r.over })),
|
||||
totalKB: +kb(totalBytes).toFixed(2), fails,
|
||||
}))
|
||||
} else {
|
||||
console.log(`CHUNKBUDGET ${verdict}`)
|
||||
console.log(` 产物目录 : ${DIST}`)
|
||||
console.log(` 预算来源 : ${budgetSource || degradedText}`)
|
||||
console.log(` 判定口径 : raw(磁盘字节)· kB = 1000 B(与 vite 控制台 / chunkSizeWarningLimit / 阶段 15 基线同尺)`)
|
||||
console.log(` 产物 : ${rows.length} 个 .js/.css · 合计 raw ${fmt(totalBytes)} kB` + (degraded ? `(逐文件预算 ${fallbackKB} kB = 兜底,非登记值)` : budgetFileUsed ? '(逐文件预算见来源行)' : ''))
|
||||
const widest = Math.max(...rows.map((r) => r.rel.length), 4)
|
||||
console.log(' ' + '文件'.padEnd(widest + 3) + ' raw gzip brotli 预算 判定')
|
||||
for (const r of rows) {
|
||||
console.log(' ' + r.rel.padEnd(widest + 3) + fmt(r.raw) + fmt(r.gzip) + fmt(r.brotli) + fmt(r.limit)
|
||||
+ (r.over ? ' OVER' : (kb(r.raw) > VITE_WARN_KB ? ' 慢(vite 已在警告,不参与判定)' : ' ok')))
|
||||
}
|
||||
for (const l of fails) console.log(' ' + l)
|
||||
if (fails.length) console.log(' → 先查是不是新依赖进了首屏(node scripts/ui/chunkinfo.mjs 看成分),不许调大数字把它捂住')
|
||||
}
|
||||
process.exit(fails.length ? 1 : 0)
|
||||
|
|
@ -16,6 +16,16 @@
|
|||
* 再按 node_modules 包名 / src 路径聚合。列 ≈ 字节(产物是 ASCII 压缩代码),
|
||||
* 这是近似值,但足够定位大头。没有 .map 时只出尺寸表。
|
||||
*
|
||||
* ⚠ 阶段 31 修正了这把尺本身的缺陷(详见 §3 注释与
|
||||
* `reports/NEX阶段31-Bundle模块级结案与chunkinfo归属修正-2026-11-09.md`):
|
||||
* 旧实现把「每行最后一个映射点之后的全部列」回填给那个源,在**预压缩 CJS 透传段**
|
||||
* (`react` / `scheduler` / `@babel/runtime` 的 `*.production.min.js` 这类磁盘几 kB、
|
||||
* 产物里只有一两行且 mappings 覆盖不全的源)上会凭空造出几百 kB。
|
||||
* 现在空档超过 `GAP_LIMIT` 一律记为「无主字节」单列,并把每个源的归属字节
|
||||
* 与它在磁盘上的真实大小对账,超出 `SOURCE_TOLERANCE` 倍直接点名。
|
||||
* 想看「谁真的占了多少」的精确口径,用模块级的 `renderedLength`:
|
||||
* `node reports/ui_evidence/nex-p31/eagergraph.mjs`。
|
||||
*
|
||||
* 用法:
|
||||
* node scripts/ui/chunkinfo.mjs [dist 目录] # 默认 frontend/dist
|
||||
* node scripts/ui/chunkinfo.mjs frontend/dist-sm # 带 --sourcemap 的产物做归属分析
|
||||
|
|
@ -96,62 +106,147 @@ for (const r of rows.sort((a, b) => b.raw - a.raw)) {
|
|||
}
|
||||
|
||||
/* ---------- 3. 归属分析(需要 .map) ---------- */
|
||||
/* source-map VLQ 解码:只需要 generated line / column → source index。 */
|
||||
/* source-map VLQ 解码:只需要 generated line / column → source index。
|
||||
*
|
||||
* ⚠ 阶段 31 修掉了这把尺子真正的病灶(不是行尾回填,是这个解码器):
|
||||
* source map v3 里 **generated column 每行归零**,但
|
||||
* **source index / source line / source column 是整串 mappings 累积的**。
|
||||
* 旧实现 `decode(line)` 把 `sidx` 也放在行内归零,于是从第 2 行起
|
||||
* 每一段都拿「本行累计的源下标」去查 `sources[]`,整张归属表被打乱:
|
||||
* 实测同一份 `WarningOutlined-*.js.map`,错的解码器报
|
||||
* `npm:react` 234.5 kB(该文件磁盘只有 6.8 kB)、
|
||||
* 指向 react 的段有 51 990 个、源切换 5 万多次;
|
||||
* 按规范累积的解码器报同一个包几个连续区间、全文件源切换只有 1 011 次
|
||||
* (拼接产物的正常形态)。
|
||||
* ⇒ 阶段 24 报告里「react 306 / @babel-runtime 217 / rc-util 170 kB」是伪像,
|
||||
* 本轮更正;`renderedLength` 口径(`eagergraph.mjs`,不读 sourcemap)不受影响。
|
||||
* 修法:跨行累积 `sidx`,`gcol` 每行归零;并保留行尾/空档不回填 + 磁盘对账两道自证。 */
|
||||
const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||||
const VAL = new Int8Array(128).fill(-64)
|
||||
CHARS.split('').forEach((c, i) => { VAL[c.charCodeAt(0)] = i })
|
||||
|
||||
function decode(line) {
|
||||
const segs = []
|
||||
let gcol = 0, sidx = 0
|
||||
for (const seg of line.split(',')) {
|
||||
if (!seg) continue
|
||||
const fields = []
|
||||
let i = 0
|
||||
while (i < seg.length && fields.length < 5) {
|
||||
let shift = 0, result = 0, cont = true
|
||||
while (cont) {
|
||||
const d = VAL[seg.charCodeAt(i++)]
|
||||
if (d < 0) { cont = false; break }
|
||||
cont = !!(d & 32)
|
||||
result |= (d & 31) << shift
|
||||
shift += 5
|
||||
/* 返回 Array<线>[generatedLine] = [[gcol, sourceIndex], …];sidx 跨行累积 */
|
||||
function decodeMappings(mappings) {
|
||||
const byLine = []
|
||||
let sidx = 0
|
||||
for (const line of String(mappings || '').split(';')) {
|
||||
let gcol = 0
|
||||
const segs = []
|
||||
for (const seg of line.split(',')) {
|
||||
if (!seg) continue
|
||||
const fields = []
|
||||
let i = 0
|
||||
while (i < seg.length && fields.length < 5) {
|
||||
let shift = 0, result = 0, cont = true
|
||||
while (cont) {
|
||||
const d = VAL[seg.charCodeAt(i++)]
|
||||
if (d < 0) { cont = false; break }
|
||||
cont = !!(d & 32)
|
||||
result |= (d & 31) << shift
|
||||
shift += 5
|
||||
}
|
||||
const neg = result & 1
|
||||
result >>= 1
|
||||
fields.push(neg ? -result : result)
|
||||
}
|
||||
const neg = result & 1
|
||||
result >>= 1
|
||||
fields.push(neg ? -result : result)
|
||||
gcol += fields[0] || 0
|
||||
if (fields.length >= 4) { sidx += fields[1]; segs.push([gcol, sidx]) }
|
||||
}
|
||||
gcol += fields[0]
|
||||
if (fields.length >= 4) { sidx += fields[1]; segs.push([gcol, sidx]) }
|
||||
byLine.push(segs)
|
||||
}
|
||||
return segs
|
||||
return byLine
|
||||
}
|
||||
|
||||
|
||||
const TOPN = Number(process.env.NEX_TOP || 15) /* 想看某包落在第几名时调大,不改默认口径 */
|
||||
const GAP_LIMIT = Number(process.env.GAP_LIMIT || 2048)
|
||||
const SOURCE_TOLERANCE = Number(process.env.SOURCE_TOLERANCE || 1.5)
|
||||
const COV_MIN = Number(process.env.SOURCE_CHECK_MIN_COVERAGE || 60) /* 覆盖率低于此 ⇒ 自证空转,不许宣称「没有伪像」 */
|
||||
const SOURCE_CHECK_STRICT = process.env.SOURCE_CHECK_STRICT === '1' /* 可选:把自证判定升级成退出码 */
|
||||
const ORPHAN = '(无主字节:map 未覆盖的列区间)'
|
||||
|
||||
const withMaps = rows.filter((r) => r.f.endsWith('.js') && exists(path.join(ASSETS, r.f + '.map')))
|
||||
if (!withMaps.length) {
|
||||
console.log('\n(产物没有 .map:跳过归属分析。用 `npx vite build --sourcemap --outDir dist-sm` 再跑一次。)')
|
||||
} else {
|
||||
const agg = new Map()
|
||||
const aggByChunk = new Map()
|
||||
const orphanByChunk = new Map()
|
||||
const orphans = []
|
||||
const diskCache = new Map()
|
||||
const add = (map, k, w) => map.set(k, (map.get(k) || 0) + w)
|
||||
/* 源文件在磁盘上的真实大小:归属字节不可能显著超过它,超了就是尺子在造数。
|
||||
⚠ 阶段 31 翻自己的案:旧实现只认「.map 所在目录」一个基准。产物在项目树内时
|
||||
`dist/assets/../../node_modules/…` 恰好等于 `frontend/node_modules/…`,看着没毛病;
|
||||
产物一旦复制到树外(`/tmp/nex-p31-dist-sm`)全部解析失败,对账覆盖率 0/1177,
|
||||
判定行仍打印「(无)⇒ 没有伪像」⇒ 尺子的自证自己空转了(假绿)。
|
||||
现在按顺序退让多个基准,并记录每个源命中哪个基准 + 给覆盖率设门槛:
|
||||
覆盖率不达标时判定必须自称空转,不许冒充证据。 */
|
||||
const PROJECT_ROOT = path.resolve(HERE, '../..')
|
||||
const BASES = [...new Set([
|
||||
ASSETS, /* 规范口径:sources 相对 .map 所在目录 */
|
||||
DIST, PROJECT_ROOT, path.join(PROJECT_ROOT, 'frontend'), process.cwd(),
|
||||
])].filter((p) => exists(p))
|
||||
const BASE_LABELS = BASES.map((p) => {
|
||||
const rel = path.relative(PROJECT_ROOT, p)
|
||||
return rel && !rel.startsWith('..') ? rel || '.' : p
|
||||
})
|
||||
const isFile = (p) => { try { return fs.statSync(p).isFile() } catch { return false } }
|
||||
const hits = BASES.map(() => 0)
|
||||
let unresolved = 0
|
||||
const diskOf = (mapDir, src) => {
|
||||
const key = mapDir + '\u0000' + src
|
||||
if (diskCache.has(key)) return diskCache.get(key)
|
||||
let hit = { disk: -1, base: -1 }
|
||||
try {
|
||||
const clean = decodeURIComponent(src.split('?')[0].split('#')[0])
|
||||
const stripped = clean.replace(/^(?:\.\.(?:\/|$)|\.(?:\/|$))+/, '')
|
||||
const nm = clean.lastIndexOf('node_modules/')
|
||||
const cands = []
|
||||
if (path.isAbsolute(clean)) cands.push([0, clean])
|
||||
else BASES.forEach((b, bi) => {
|
||||
cands.push([bi, path.resolve(b, clean)])
|
||||
if (stripped !== clean) cands.push([bi, path.join(b, stripped)])
|
||||
if (nm >= 0) cands.push([bi, path.join(b, clean.slice(nm))]) /* 多处 node_modules 时兜住 */
|
||||
})
|
||||
for (const [bi, abs] of cands) {
|
||||
if (!isFile(abs)) continue
|
||||
hit = { disk: fs.statSync(abs).size, base: bi }
|
||||
hits[bi]++
|
||||
break
|
||||
}
|
||||
if (hit.base < 0) unresolved++
|
||||
} catch { hit = { disk: -1, base: -1 } }
|
||||
diskCache.set(key, hit)
|
||||
return hit
|
||||
}
|
||||
|
||||
for (const r of withMaps) {
|
||||
const map = JSON.parse(fs.readFileSync(path.join(ASSETS, r.f + '.map'), 'utf8'))
|
||||
const srcs = map.sources || []
|
||||
const lines = map.mappings.split(';')
|
||||
/* 按行取每行最后一个有源的文件,把该行剩余列归给它:
|
||||
压缩产物一行常常混了多个源,段级更准但抖动大;行级足够定位大头。 */
|
||||
const mapLines = decodeMappings(map.mappings)
|
||||
const code = r.buf.toString('utf8').split('\n')
|
||||
const mapDir = ASSETS /* sources 是相对 .map 所在目录的路径,基准必须是目录本身 */
|
||||
const own = new Map()
|
||||
for (let li = 0; li < lines.length; li++) {
|
||||
const segs = decode(lines[li])
|
||||
if (!segs.length) { continue }
|
||||
let orphan = 0
|
||||
/* 逐行:段间空档与行尾空档 > GAP_LIMIT 记无主;mappings 没覆盖到的行整行无主。
|
||||
不回填给邻居 ⇒ 归属 Σ + 无主 === 文件大小(可自证)。 */
|
||||
const nLines = Math.max(mapLines.length, code.length)
|
||||
for (let li = 0; li < nLines; li++) {
|
||||
const lineLen = Buffer.byteLength(code[li] ?? '', 'utf8') + 1
|
||||
let prev = null
|
||||
for (const s of segs) {
|
||||
if (prev) { const w = Math.max(0, s[0] - prev[0]); own.set(srcs[prev[1]] || '?', (own.get(srcs[prev[1]] || '?') || 0) + w) }
|
||||
prev = s
|
||||
const segs = li < mapLines.length ? mapLines[li] : []
|
||||
if (!segs.length) { orphan += lineLen; continue }
|
||||
for (let si = 0; si + 1 < segs.length; si++) {
|
||||
const w = segs[si + 1][0] - segs[si][0]
|
||||
if (w <= 0) continue
|
||||
if (w > GAP_LIMIT) { orphan += w; continue }
|
||||
add(own, srcs[segs[si][1]] || '?', w)
|
||||
}
|
||||
const tail = lineLen - segs[segs.length - 1][0]
|
||||
if (tail > 0) {
|
||||
if (tail > GAP_LIMIT) orphan += tail
|
||||
else add(own, srcs[segs[segs.length - 1][1]] || '?', tail)
|
||||
}
|
||||
if (prev) { const w = Math.max(0, lineLen - prev[0]); own.set(srcs[prev[1]] || '?', (own.get(srcs[prev[1]] || '?') || 0) + w) }
|
||||
}
|
||||
const per = new Map()
|
||||
for (const [src, w] of own) {
|
||||
|
|
@ -159,18 +254,73 @@ if (!withMaps.length) {
|
|||
const key = src.includes('node_modules/')
|
||||
? 'npm:' + rel.split('/').slice(0, rel.startsWith('@') ? 2 : 1).join('/')
|
||||
: 'src:' + src.split('/src/').pop()
|
||||
agg.set(key, (agg.get(key) || 0) + w)
|
||||
per.set(key, (per.get(key) || 0) + w)
|
||||
add(agg, key, w)
|
||||
add(per, key, w)
|
||||
orphans.push({ chunk: r.f, src, w, ...diskOf(mapDir, src) })
|
||||
}
|
||||
const accounted = [...own.values()].reduce((a, b) => a + b, 0)
|
||||
orphanByChunk.set(r.f, { orphan, raw: r.raw, accounted })
|
||||
aggByChunk.set(r.f, per)
|
||||
}
|
||||
|
||||
const top = (map, n) => [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, n)
|
||||
console.log('\n=== 全站前 15 大来源(按压缩产物字节近似归属)===')
|
||||
for (const [k, v] of top(agg, 15)) console.log(kb(v), 'kB', k)
|
||||
const mapRaw = withMaps.reduce((a, r) => a + r.raw, 0)
|
||||
const orphanTotal = [...orphanByChunk.values()].reduce((a, v) => a + v.orphan, 0)
|
||||
const ownedTotal = [...orphanByChunk.values()].reduce((a, v) => a + v.accounted, 0)
|
||||
const mapHead = (label) => {
|
||||
console.log('\n' + label)
|
||||
console.log(` 对账:归属 ${kb(ownedTotal)} + 无主 ${kb(orphanTotal)} = ${kb(ownedTotal + orphanTotal)} kB,带 map 产物 ${kb(mapRaw)} kB` +
|
||||
` ⇒ 无主占 ${(100 * orphanTotal / mapRaw).toFixed(1)} %(gap>${GAP_LIMIT}B 不回填)`)
|
||||
}
|
||||
|
||||
mapHead(`=== 全站前 ${TOPN} 大来源(压缩产物字节近似归属 · map 空档单列不回填)===`)
|
||||
for (const [k, v] of top(agg, TOPN)) console.log(kb(v), 'kB', k)
|
||||
console.log(kb(orphanTotal), 'kB', ORPHAN)
|
||||
|
||||
for (const [chunk, per] of aggByChunk) {
|
||||
if (!eagerAll.has(chunk)) continue
|
||||
if (per.size < 8) continue
|
||||
console.log(`\n=== 首屏 chunk ${chunk} 前 15 大来源 ===`)
|
||||
for (const [k, v] of top(per, 15)) console.log(kb(v), 'kB', k)
|
||||
const st = orphanByChunk.get(chunk)
|
||||
console.log(`\n=== 首屏 chunk ${chunk} 前 ${TOPN} 大来源 ===`)
|
||||
console.log(` 对账:归属 ${kb(st.accounted)} + 无主 ${kb(st.orphan)} = ${kb(st.accounted + st.orphan)} kB,文件 ${kb(st.raw)} kB` +
|
||||
` ⇒ 无主占 ${(100 * st.orphan / st.raw).toFixed(1)} %`)
|
||||
for (const [k, v] of top(per, TOPN)) console.log(kb(v), 'kB', k)
|
||||
if (st.orphan) console.log(kb(st.orphan), 'kB', ORPHAN)
|
||||
}
|
||||
|
||||
/* 自证:归属字节显著超过源文件磁盘大小 ⇒ 尺子伪像(或该源在块内被复制)。
|
||||
⚠ 判定有两个前提必须同时成立才有资格说「没有伪像」:
|
||||
a) 覆盖率达标(源能在磁盘上找到,否则整条对账根本没在看东西);b) 点名 0 条。
|
||||
缺 a 就是阶段 31 踩过的那条假绿。 */
|
||||
const bad = orphans
|
||||
.filter((o) => o.disk > 0 && o.w > o.disk * SOURCE_TOLERANCE)
|
||||
.map((o) => ({ ...o, over: o.w - o.disk, ratio: o.w / o.disk }))
|
||||
.sort((a, b) => b.over - a.over)
|
||||
const resolved = orphans.filter((o) => o.disk > 0).length
|
||||
const cov = orphans.length ? (100 * resolved) / orphans.length : 0
|
||||
const idle = cov < COV_MIN
|
||||
const verdict = idle ? 'IDLE' : bad.length ? 'SUSPECT' : 'OK'
|
||||
console.log('\n=== 尺子自证:归属 > 磁盘源文件 × ' + SOURCE_TOLERANCE + ' 的源(应当为 0 条)===')
|
||||
console.log(` 对账覆盖 ${resolved}/${orphans.length} 个源(${cov.toFixed(1)} %,其余是磁盘上不存在或无权限的虚拟源,不参与判定)`)
|
||||
console.log(' 解析口径 ' + BASE_LABELS.map((l, i) => `${l}:${hits[i]}`).join(' ') + ` 未解析:${unresolved}` +
|
||||
`(规范基准=mapDir;其余是产物被移到项目树外时的退让,命中越多说明 map 与磁盘越脱节)`)
|
||||
console.log(`ATTRIB_COVERAGE=${resolved}/${orphans.length} (${cov.toFixed(1)}%)`)
|
||||
console.log(`ATTRIB_SUSPECT=${bad.length}`)
|
||||
console.log(`ATTRIB_VERDICT=${verdict}`)
|
||||
if (idle) {
|
||||
console.log(` !! 覆盖率 ${cov.toFixed(1)} % < 门槛 ${COV_MIN} % ⇒ **本条自证空转,不作证据**` +
|
||||
`(多半是产物不在项目树内或 node_modules 不在原位)。把产物放回 frontend/dist-sm 重跑,别引用本轮归属读数。`)
|
||||
} else if (!bad.length) {
|
||||
console.log(' (无)⇒ 本轮归属读数没有「源文件装不下」的伪像')
|
||||
} else {
|
||||
for (const o of bad.slice(0, 10)) {
|
||||
console.log(` ${kb(o.w)} kB 记给 ${o.src.split('node_modules/').pop()},磁盘只有 ${kb(o.disk)} kB(×${o.ratio.toFixed(1)})in ${o.chunk}〔磁盘基准 ${o.base >= 0 ? BASE_LABELS[o.base] : '?'}〕`)
|
||||
}
|
||||
console.log(` 共 ${bad.length} 条,合计虚高 ${kb(bad.reduce((a, o) => a + o.over, 0))} kB` +
|
||||
` ⇒ 这些数字只能当「产物列区间」读,不能当「该依赖的体积」引用`)
|
||||
}
|
||||
if (SOURCE_CHECK_STRICT && (idle || bad.length)) {
|
||||
console.log(`\n!! SOURCE_CHECK_STRICT=1:自证判定 ${verdict} ⇒ 退出码 1(不设该变量时本尺恒退出 0,见 nex.config.yaml)`)
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@
|
|||
* 判定用的是构建时同一套配置(@theme 语义色、自定义断点、@utility),不会误报。
|
||||
*
|
||||
* 第二道检查(2026-11 图标重设计加的):图标只许从 components/icons 取。
|
||||
* 全站唯一允许 `from '@ant-design/icons'` 的文件是那张登记表。
|
||||
* 全站唯一允许 `from '@ant-design/icons'` 的地方是那张登记表——阶段 25 起它是一个目录、
|
||||
* 两张表(core.ts 首屏 / extra.ts 懒页面)加一个桶与一件公共件,放行按**目录**不按文件名。
|
||||
* 为什么必须钉住:页面一旦直接 import 字形名(AppstoreOutlined),
|
||||
* 「这个位置到底是网格视图还是资产库」就又只有读代码的人才知道,
|
||||
* 换图标也又变成全站搜索替换——登记表当天就废掉。
|
||||
|
|
@ -171,24 +172,49 @@ for (const [tok, where] of dead) console.log(`DEAD ${tok.padEnd(26)} ${where.jo
|
|||
console.log(`\n${dead.length} 个死类名 / ${cands.size} 个候选`)
|
||||
|
||||
/* ── 第 2 条:图标出口唯一 ───────────────────────────────────────────────
|
||||
登记表自己是唯一可以 import 字形名的文件;其余文件一律写语义别名
|
||||
(IconGrid / IconWarn / IconTimeline),要新图形先在登记表登记一行。 */
|
||||
const REGISTRY = path.join(SRC, 'components/icons/index.ts')
|
||||
登记表**目录**是唯一可以 import 字形名的地方;其余文件一律写语义别名
|
||||
(IconGrid / IconWarn / IconTimeline),要新图形先在登记表登记一行。
|
||||
为什么必须钉住:页面一旦直接 import 字形名(AppstoreOutlined),
|
||||
「这个位置到底是网格视图还是资产库」就又只有读代码的人才知道,
|
||||
换图标也又变成全站搜索替换——登记表当天就废掉。
|
||||
|
||||
2026-11-09 阶段 25:这张登记表从「一个文件」变成**一个目录**(两级表)——
|
||||
· `core.ts` 首屏外壳用得上的 54 只,由 `index.ts` 桶对外;
|
||||
· `extra.ts` 只有懒加载页面用得上的 24 只,调用方深 import `icons/extra`;
|
||||
· `_kit.ts` `decorative()` 与两个图标类型,**不导出任何图形**;
|
||||
· `index.ts` 桶,只 re-export core(见下面第 2 条·附三:它不许碰 extra)。
|
||||
所以放行范围跟着从「一个文件」改成「这个目录」:两张表各自 import 自己要用的字形,
|
||||
`_kit.ts` 里那条 `import type { ProjectOutlined }` 只是取它的属性类型,
|
||||
`import type` 编译期整条抹掉、不上产物(这也是它不算绕过口径的原因:
|
||||
它渲染不出任何东西,字形名也就漏不进辅助技术树)。
|
||||
扫描前先剥注释:登记表文件头里有一句散文写着
|
||||
`import { XOutlined } from '@ant-design/icons'`,不剥就是注释自己被当成一次绕过
|
||||
(§13.11 已把「import 正则先剥注释」立成通则)。 */
|
||||
const REG_DIR = path.join(SRC, 'components/icons')
|
||||
/** 读一个源文件并剥掉全部注释(保留行号:返回按行切开的数组,注释位置留空行)。 */
|
||||
function codeLines(file) {
|
||||
let inBlock = false
|
||||
return fs.readFileSync(file, 'utf8').split('\n').map((raw) => {
|
||||
const [line, block] = stripComments(raw, () => inBlock)
|
||||
inBlock = block
|
||||
return line
|
||||
})
|
||||
}
|
||||
const inRegistryDir = (p) => p === REG_DIR || p.startsWith(REG_DIR + path.sep)
|
||||
const stray = []
|
||||
const walkIcons = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walkIcons(p); continue }
|
||||
if (!/\.(tsx|ts)$/.test(ent.name) || p === REGISTRY) continue
|
||||
fs.readFileSync(p, 'utf8').split('\n').forEach((line, i) => {
|
||||
if (!/\.(tsx|ts)$/.test(ent.name) || inRegistryDir(p)) continue
|
||||
codeLines(p).forEach((line, i) => {
|
||||
if (/from '@ant-design\/icons'/.test(line)) stray.push(`${path.relative(FRONTEND, p)}:${i + 1}: ${line.trim()}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
walkIcons(SRC)
|
||||
for (const hit of stray) console.log(`ICON ${hit}`)
|
||||
console.log(`${stray.length} 处绕过登记表的图标 import(只许 ${path.relative(FRONTEND, REGISTRY)})`)
|
||||
|
||||
console.log(`${stray.length} 处绕过登记表目录的图标 import(只许 ${path.relative(FRONTEND, REG_DIR)}/ 里的两张表)`)
|
||||
/* ── 第 2 条·附:登记表自身的辅助技术口径(2026-11-08 · S-2)───────────────
|
||||
上面那条只管「别人不许 import 字形」,管不到登记表自己怎么写出口。
|
||||
`decorative()` 把「图标默认是装饰」写死在唯一的出口上(登记表顶部规则 5);
|
||||
|
|
@ -200,8 +226,15 @@ console.log(`${stray.length} 处绕过登记表的图标 import(只许 ${path.
|
|||
对账逐条匹配固定形状 `export const IconX = decorative(Glyph, 'IconX')`:
|
||||
加图标的人只会复制旁边一行,不会先读注释,所以形状不对就红。
|
||||
反例由 scripts/ui/gateprobe.py 注入验证(改一条注释不会把这条闸改成恒绿)。 */
|
||||
const REG_NAME = path.relative(FRONTEND, REGISTRY)
|
||||
const regSrc = fs.readFileSync(REGISTRY, 'utf8')
|
||||
/** 登记表的全部出口所在文件:目录里除桶与公共件之外的那几张表。
|
||||
写成「扫目录」而不是写死 `['core.ts','extra.ts']`,是为了让这条判据对
|
||||
单文件旧布局和两级新布局**同样有效**——gateprobe ⑰ 的夹具只写一份 index.ts,
|
||||
它必须继续量得出东西(放行但采不到 = 空转,这是本项目栽过的跟头)。 */
|
||||
const TABLES = fs.existsSync(REG_DIR)
|
||||
? fs.readdirSync(REG_DIR).filter((f) => /\.ts$/.test(f)).map((f) => path.join(REG_DIR, f))
|
||||
: []
|
||||
const REG_NAME = path.relative(FRONTEND, REG_DIR) + '/'
|
||||
const regSrc = TABLES.map((f) => codeLines(f).join('\n')).join('\n')
|
||||
const regHits = []
|
||||
for (const m of regSrc.matchAll(/^export\s*\{([^}]*)\}/gm)) {
|
||||
if (/\bIcon[A-Z]\w*\b|Outlined|Filled|TwoTone/.test(m[1]))
|
||||
|
|
@ -216,7 +249,424 @@ for (const [, name, rhs] of regIcons) {
|
|||
}
|
||||
if (!regIcons.length) regHits.push(`${REG_NAME}: 一条 decorative() 图标出口都没匹配到 —— 登记表结构变了,这道闸要跟着改`)
|
||||
for (const hit of regHits) console.log(`ICONA ${hit}`)
|
||||
console.log(`${regHits.length} 处图标出口未走 decorative()(登记表 ${regIcons.length} 条出口 / ${stray.length} 处外部 import)`)
|
||||
console.log(`${regHits.length} 处图标出口未走 decorative()(登记表 ${REG_NAME} 共 ${regIcons.length} 条出口 / 目录外 ${stray.length} 处 import)`)
|
||||
/* ── 第 2 条·附二:图标型控件的名字从哪儿来(2026-11-09 · S-2 复扫)──────────
|
||||
decorative() 把字形名从辅助技术树里撤掉之后,「一颗只画图标的按钮」剩下的命名
|
||||
通道只有两条:调用方自己写的 aria-label / title,或者整颗没有名字。
|
||||
浏览器口径的闸门(semanticcheck 的 NAME / GLYPH)量不到这一族的大本营:抽屉、
|
||||
模态、灯箱、录音面板里的图标钮要**先点开浮层**才在 DOM 里,而常驻探针跑的是
|
||||
15 条路由的关闭态(阶段 10 的普查 census-icons.py 同样只走关闭态)。
|
||||
两个实测数(2026-11-09 · 阶段 17,口径可复现,别再抄口头数):
|
||||
· 源码面:全站 **46 颗**自关闭的图标型控件,分布在 18 个文件(Storyboard 7 /
|
||||
Library 6 / Timeline 6 / AssetLibrary 5 / MediaLightbox 4 / UserAdmin 4 …),
|
||||
43 颗同时写了 aria-label + title、2 颗只有 aria-label、1 颗只有 title,
|
||||
缺名字的 **0 颗** ⇒ 这条闸今天立案 0 处,它是**立案起点**而不是缺陷清单;
|
||||
· 浏览器面:reports/ui_evidence/nex-p17/s2overlay.py 把 8 个浮层逐个点开
|
||||
(概况抽屉 / 删除确认模态 / 平台动态 / 430 导航抽屉 / 新建账号 / 编辑母版 /
|
||||
素材灯箱 / 分镜检查器),明暗各量一遍:**每个主题 16 颗**图标型控件
|
||||
是关闭态探针根本量不到的(最多一处 = 分镜检查器 8 颗),命名缺陷 0 颗。
|
||||
⇒ 「15 条路由关闭态全绿」离「全站图标控件都有名字」还差 16 颗的可见面,
|
||||
而没有任何东西挡得住下一个人在新抽屉里顺手加一颗没名字的 ✕。
|
||||
判据敢用静态,靠的是一个结构事实:**自闭合的 JSX 元素不可能有 children**,
|
||||
所以「这颗控件没有文字」不需要渲染就能确定;有 icon 槽又没有 aria-label / title,
|
||||
就等于把命名托付给了一只默认 aria-hidden 的图标 = 托付给空气。
|
||||
三条子判据:
|
||||
① `<Button|LinkButton|button|a … icon={<Icon…/>} … />` 自关闭 + 无 aria-label
|
||||
且无 title ⇒ 立案(宿主只有图标,却没有名字);
|
||||
② `<Icon… aria-label="字面量">` 的字面量里没有汉字 ⇒ 立案。图标自己承担语义
|
||||
是 decorative() 的第二条通道,写进去的就是 AT 念到的全部;今天 4 处出口
|
||||
全部是中文(「更多页签」「清空搜索」+ SecretInput 的两态 hint),
|
||||
一旦有人图省事写回 `aria-label="upload"`,S-2 就原地复活。
|
||||
③ **antd 把 onClick 克隆到图标本体上的那些槽位**(closeIcon / clearIcon /
|
||||
removeIcon / prevIcon / nextIcon / sortIcon / filterIcon / expandIcon /
|
||||
menuItemSelectedIcon / dropIcon)里的 `<Icon…/>` 必须自带非空中文 aria-label。
|
||||
为什么 ① 管不到它们:① 认的是「宿主只画图标」,而这些槽位的宿主(Tag、Select、
|
||||
Table 表头……)**本来就有文字或有自己的名字**,图标是宿主里另一颗独立操作
|
||||
——胶囊 `人物·俊杰` 有名字,那颗 ✕ 仍然要自己的名字。
|
||||
为什么不看渲染结果:静态就能定死。`antd/es/tag/index.js:81-93` 的
|
||||
`closeIconRender` + `rc-util/replaceElement` 把 `onClick` 与
|
||||
`ant-tag-close-icon` **克隆到我们那颗图标节点上**,antd 不再包一层壳
|
||||
⇒ 图标自己就是那颗可点的东西;而 `decorative()` 默认 `aria-hidden`
|
||||
⇒ 不写名字 = 这条操作在辅助技术树里不存在。
|
||||
「antd 会自己兜一个名字」不算数:`_util/hooks/useClosable.js` 从 5.29 起
|
||||
才用 `locale.global.close`(现网实测念「关闭」)兜这一族,5.20 没有这一段,
|
||||
而且 `clearIcon` 那一族 antd **从来不兜**——把命名托付给依赖库的版本实现细节,
|
||||
升级那天静默失效,量都量不到。
|
||||
这一族现网的真实调用面(grep 实测 2026-11-09):`Ctlbar.tsx:338`(胶囊 ✕,
|
||||
本轮补「移除」)、`Input.tsx:183`(`clearIcon` 已带「清空搜索」),其余两处
|
||||
只在注释里(注释已剥掉,不参与匹配)⇒ 真文件必须静音。
|
||||
④ **图标当 children 的图标钮**(2026-11-10 · 阶段 32 · S-2 复扫补的第四支):
|
||||
`<Button … onClick={f}><IconClose /></Button>` 这种写法 ① 看不见——它既不自关闭、
|
||||
也没有 icon 槽,① 的两条前提一条都不成立,可结论一模一样:`decorative()` 一隐藏,
|
||||
这颗控件在辅助技术树里没有名字。DOM 侧的 NAME 闸认得它,但常驻探针跑的是
|
||||
15 条路由的**关闭态**,浮层里那一半(抽屉 / 模态 / 灯箱 / 录音面板)结构上量不到,
|
||||
所以这一族仍须钉在源码上。
|
||||
判据保守到只咬一种形状:**非自关闭 + 开标签没有 aria-label / aria-labelledby / title
|
||||
+ children 里出现的每一个开标签都是登记表图标 + 没有任何裸文字 + 没有任何「可能出字」的
|
||||
表达式**。表达式由 `exprIconOnly()` 判定,只认四种形状:整段就是一只 `<Icon… />`、
|
||||
外面套圆括号、`cond ? 图标 : 图标`、`cond && 图标`(假值渲染成空,不出字);
|
||||
`cond` 那一段随便写,两个**分支**必须逐条递归过这条判据。
|
||||
children 里有别的元素(`<span>` 包的文字)、表达式里有字符串字面量或 `{row.label}`
|
||||
这类认得出的标识符、或是函数调用 ⇒ 跳过:「看不出有没有名字」不是「没有名字」,
|
||||
误报的代价和漏报一样是这条闸被关掉。
|
||||
顺带打印覆盖率行 `ICNN-COVER childIcon=N named=M missing=K`(N = 全站「children 只有
|
||||
图标」的交互标签颗数,M = 其中报了名的):这一族闸门的失败方式从来不是响错,
|
||||
而是安静地什么都没看见(§15.1 通则),N=0 就说明采集形状变了、闸该跟着改而不是继续绿。
|
||||
反例由 scripts/ui/gateprobe.py ㉓ 注入验证(改一条注释不会把这条闸改成恒绿)。 */
|
||||
const ICON_NAMELESS = []
|
||||
const CHILD_ICON_MISSING = []
|
||||
let CHILD_ICON_TOTAL = 0, CHILD_ICON_NAMED = 0
|
||||
/** 从 `<Tag` 的开括号扫到配对的 `>`,返回开标签原文与自关闭标记。
|
||||
JSX 表达式里的 > 在 `{}` 内,字符串/模板字面量整段跳过。 */
|
||||
function jsxOpenTag(src, from) {
|
||||
let depth = 0, q = null
|
||||
for (let i = from; i < src.length; i++) {
|
||||
const c = src[i]
|
||||
if (q) {
|
||||
if (c === '\\') { i++; continue }
|
||||
if (c === q) q = null
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') { q = c; continue }
|
||||
if (c === '{') { depth++; continue }
|
||||
if (c === '}') { depth--; continue }
|
||||
if (c === '>' && depth === 0) return { head: src.slice(from, i + 1), end: i }
|
||||
}
|
||||
return null
|
||||
}
|
||||
/** 从 src[i](必须是 `{`)扫到配对的那个 `}`,返回它的下标;找不到返回 -1。
|
||||
字符串与模板字面量整段跳过——里面的括号不算数。给 ③ 取 `xxxIcon={…}` 的原文用。 */
|
||||
function braceAt(src, i) {
|
||||
let depth = 0, q = null
|
||||
for (let j = i; j < src.length; j++) {
|
||||
const c = src[j]
|
||||
if (q) {
|
||||
if (c === '\\') { j++; continue }
|
||||
if (c === q) q = null
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') { q = c; continue }
|
||||
if (c === '{') depth++
|
||||
else if (c === '}' && --depth === 0) return j
|
||||
}
|
||||
return -1
|
||||
}
|
||||
/** 从 `<X` 取到与之配对的 `</X>`:返回开标签原文 head 与 children 原文。
|
||||
自关闭时 children 是空串;扫不到配对(模板残缺 / 解析不了)返回 null,调用方按「不判」处理。 */
|
||||
function jsxElement(src, from) {
|
||||
const t = jsxOpenTag(src, from)
|
||||
if (!t) return null
|
||||
const nm = /^<\s*([A-Za-z][\w.]*)/.exec(src.slice(from))
|
||||
if (!nm) return null
|
||||
const name = nm[1]
|
||||
if (t.head.replace(/\s+$/, '').endsWith('/>')) return { head: t.head, children: '', selfClosing: true, end: t.end + 1 }
|
||||
const tagRe = new RegExp('<\\s*/?\\s*' + name.replace('.', '\\.') + '(?=[\\s/>])', 'g')
|
||||
tagRe.lastIndex = t.end + 1
|
||||
let m, depth = 0
|
||||
while ((m = tagRe.exec(src))) {
|
||||
const closing = /^<\s*\//.test(m[0])
|
||||
if (closing) {
|
||||
if (depth === 0) {
|
||||
const gt = src.indexOf('>', m.index) // 闭合标签没有属性,第一个 > 就是它结尾
|
||||
return { head: t.head, children: src.slice(t.end + 1, m.index), selfClosing: false,
|
||||
end: gt < 0 ? m.index : gt + 1 }
|
||||
}
|
||||
depth--
|
||||
continue
|
||||
}
|
||||
const inner = jsxOpenTag(src, m.index)
|
||||
if (inner && inner.head.replace(/\s+$/, '').endsWith('/>')) continue // 自关闭的同名标签不进栈
|
||||
depth++
|
||||
}
|
||||
return null
|
||||
}
|
||||
/** 拆一段 JSX children:返回开标签名、`{}` 表达式原文、去掉标签与表达式之后的裸文字。
|
||||
扫描靠 jsxOpenTag / braceAt,所以 `onClick={() => a > b}` 那种表达式里的 `>` 不会截断标签。 */
|
||||
function kidsShape(src) {
|
||||
const tags = [], exprs = []
|
||||
let text = '', i = 0
|
||||
while (i < src.length) {
|
||||
const c = src[i]
|
||||
if (c === '<') {
|
||||
const t = jsxOpenTag(src, i)
|
||||
if (!t) { i++; continue }
|
||||
const nm = /^<\s*(\/?)([A-Za-z][\w.]*)/.exec(src.slice(i))
|
||||
if (nm && !nm[1]) tags.push(nm[2]) // 闭合标签不算「内容」
|
||||
i = t.end + 1
|
||||
continue
|
||||
}
|
||||
if (c === '{') {
|
||||
const e = braceAt(src, i)
|
||||
if (e < 0) break
|
||||
const body = src.slice(i + 1, e).trim()
|
||||
if (body) exprs.push(body)
|
||||
i = e + 1
|
||||
continue
|
||||
}
|
||||
if (!/\s/.test(c)) text += c
|
||||
i++
|
||||
}
|
||||
return { tags, exprs, text: text.replace(/&[a-z]+;/g, '').trim() }
|
||||
}
|
||||
/** 找一段表达式里**顶层**的 `? : && ||` 切点:圆括号 / 方括号 / 花括号 / 字符串 /
|
||||
模板字面量内部都不算,整段 JSX 元素直接跳过——属性值里的 `?`、`:` 与箭头函数的 `=>`
|
||||
都不是外层运算符(`onClick={() => a ? b : c}` 曾被当成三元拆过一遍)。 */
|
||||
function topCuts(s) {
|
||||
const cuts = []
|
||||
let depth = 0, q = null
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i]
|
||||
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue }
|
||||
if (c === '"' || c === "'" || c === '`') { q = c; continue }
|
||||
if (c === '(' || c === '[' || c === '{') { depth++; continue }
|
||||
if (c === ')' || c === ']' || c === '}') { depth--; continue }
|
||||
if (c === '<') {
|
||||
const el = jsxElement(s, i)
|
||||
if (el && el.end > i) { i = el.end - 1; continue }
|
||||
const t = jsxOpenTag(s, i) // 解析不了的残缺 JSX 也要跳过,别把里面的字符当运算符
|
||||
if (t) i = t.end
|
||||
continue
|
||||
}
|
||||
if (depth) continue
|
||||
if (c === '?' || c === ':') { cuts.push({ i, kind: c }); continue }
|
||||
if (c === '&' && s[i + 1] === '&') { cuts.push({ i, kind: '&&' }); i++; continue }
|
||||
if (c === '|' && s[i + 1] === '|') { cuts.push({ i, kind: '||' }); i++; continue }
|
||||
}
|
||||
return cuts
|
||||
}
|
||||
/** 这段表达式的返回值会不会「出字」——④ 的表达式守卫,保守到只放行四种形状:
|
||||
· 整段就是一只登记表图标 `<Icon… />`(且自己没有 children);
|
||||
· 外面套一层或多层**成对**圆括号(`(on ? <IconA /> : <IconB />)`);
|
||||
· `cond ? 分支 : 分支`,两个分支各自递归过这条判据,cond 随便写;
|
||||
· `cond && 图标`(假值渲染成空,不出字);`a || 图标` 则两侧都要过。
|
||||
其余一律 false:字符串字面量、`{row.label}` 这种标识符、函数调用、包了 `<span>`——
|
||||
这些是「看不出会不会出字」,④ 放过那颗控件不猜(放过 = 不计数,不是判它合规)。 */
|
||||
function exprIconOnly(raw) {
|
||||
let s = String(raw || '').trim()
|
||||
for (;;) { // 只剥「与末尾配对」的外层圆括号
|
||||
if (!s.startsWith('(')) break
|
||||
let d = 0, q = null, closed = -1
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i]
|
||||
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue }
|
||||
if (c === '"' || c === "'" || c === '`') { q = c; continue }
|
||||
if (c === '(') d++
|
||||
else if (c === ')' && --d === 0) { closed = i; break }
|
||||
}
|
||||
if (closed !== s.length - 1) break
|
||||
s = s.slice(1, -1).trim()
|
||||
}
|
||||
if (!s) return false
|
||||
const cuts = topCuts(s)
|
||||
const tern = cuts.find((c) => c.kind === '?')
|
||||
const colon = tern && cuts.find((c) => c.kind === ':' && c.i > tern.i)
|
||||
if (tern && colon) {
|
||||
return exprIconOnly(s.slice(tern.i + 1, colon.i)) && exprIconOnly(s.slice(colon.i + 1))
|
||||
}
|
||||
const and = cuts.find((c) => c.kind === '&&')
|
||||
if (and) return exprIconOnly(s.slice(and.i + 2))
|
||||
const or = cuts.find((c) => c.kind === '||')
|
||||
if (or) return exprIconOnly(s.slice(0, or.i)) && exprIconOnly(s.slice(or.i + 2))
|
||||
if (!/^<Icon[A-Za-z0-9]*[\s/>]/.test(s)) return false
|
||||
const el = jsxElement(s, 0)
|
||||
return !!el && String(el.children).trim() === ''
|
||||
}
|
||||
/** 取一个开标签里的 `aria-label` 字面量:`="文"`、`={"文"}` 两种写法都认;
|
||||
写成表达式(`aria-label={n}`)认不出 → 返回 null,由调用方按「没有名字」处理。 */
|
||||
function ariaLit(head) {
|
||||
const m = head.match(/\baria-label\s*=\s*(?:\{\s*)?(["'])((?:[^\\]|\\.)*?)\1(?:\s*\})?/)
|
||||
return m ? m[2] : null
|
||||
}
|
||||
const lineOf = (code, idx) => code.slice(0, idx).split('\n').length
|
||||
const tsxFiles = []
|
||||
{
|
||||
const collect = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const q = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { collect(q); continue }
|
||||
if (/\.(tsx|jsx)$/.test(ent.name)) tsxFiles.push({ rel: path.relative(SRC, q), abs: q })
|
||||
}
|
||||
}
|
||||
collect(SRC)
|
||||
}
|
||||
tsxFiles.sort()
|
||||
for (const { rel, abs } of tsxFiles) {
|
||||
const raw = fs.readFileSync(abs, 'utf8')
|
||||
let inBlock = false
|
||||
const code = raw.split('\n').map((l) => {
|
||||
const [c, b] = stripComments(l, () => inBlock)
|
||||
inBlock = b
|
||||
return c
|
||||
}).join('\n')
|
||||
/* ① 只有图标、又没有名字的控件 */
|
||||
for (const m of code.matchAll(/<(Button|LinkButton|button|a)([\s>])/g)) {
|
||||
const tag = jsxOpenTag(code, m.index)
|
||||
if (!tag || !tag.head.replace(/\s+$/, '').endsWith('/>')) continue
|
||||
if (!/icon=\{[^}]*<Icon[A-Za-z]*\s*\/?>/.test(tag.head)) continue
|
||||
if (/\baria-label\s*=|\btitle\s*=/.test(tag.head)) continue
|
||||
ICON_NAMELESS.push(`${rel}:${lineOf(code, m.index)} — <${m[1]}> 只画图标却既无 aria-label 也无 title`
|
||||
+ `(图标默认 aria-hidden,这颗控件对辅助技术没有名字):${tag.head.replace(/\s+/g, ' ').trim().slice(0, 76)}`)
|
||||
}
|
||||
/* ② 图标自己报名,报名内容必须是自然语言 */
|
||||
for (const m of code.matchAll(/<Icon[A-Za-z]*\b/g)) {
|
||||
const tag = jsxOpenTag(code, m.index)
|
||||
if (!tag) continue
|
||||
const lit = tag.head.match(/\baria-label\s*=\s*(["'])((?:[^\\]|\\.)*?)\1/
|
||||
|| tag.head.match(/\baria-label\s*=\s*\{\s*(["'])((?:[^\\]|\\.)*?)\1\s*\}/))
|
||||
if (!lit) continue
|
||||
const val = lit[2]
|
||||
if (!val) {
|
||||
ICON_NAMELESS.push(`${rel}:${lineOf(code, m.index)} — <${m[0].slice(1)}> 的 aria-label 是空串(图标自称有语义却什么都没写)`)
|
||||
} else if (!/[一-龥]/.test(val)) {
|
||||
ICON_NAMELESS.push(`${rel}:${lineOf(code, m.index)} — <${m[0].slice(1)} aria-label="${val.slice(0, 24)}"> 没有中文`
|
||||
+ `:这只图标自己承担语义,写什么读屏就念什么,字形码(upload / eye-invisible)不许当名字`)
|
||||
}
|
||||
}
|
||||
/* ③ antd 把 onClick 克隆到图标本体上的槽位:那颗图标就是那颗操作 */
|
||||
for (const m of code.matchAll(/\b(?:closeIcon|clearIcon|removeIcon|prevIcon|nextIcon|sortIcon|filterIcon|expandIcon|menuItemSelectedIcon|dropIcon)\s*[=:]\s*/g)) {
|
||||
const at = m.index + m[0].length
|
||||
let seg
|
||||
if (code[at] === '{') { const close = braceAt(code, at); seg = close < 0 ? '' : code.slice(at + 1, close) }
|
||||
else { const nl = code.indexOf('\n', at); seg = code.slice(at, nl < 0 ? code.length : nl) }
|
||||
if (!seg.includes('<Icon')) continue
|
||||
for (const im of seg.matchAll(/<Icon[A-Za-z]*\b/g)) {
|
||||
const tag = jsxOpenTag(seg, im.index)
|
||||
if (!tag) continue
|
||||
const val = ariaLit(tag.head)
|
||||
const at2 = `${rel}:${lineOf(code, m.index)}`
|
||||
if (val === null) {
|
||||
ICON_NAMELESS.push(`${at2} — ${m[0].replace(/\s+/g, ' ').trim()} 里的 <${im[0].slice(1)}> 没写 aria-label`
|
||||
+ `:antd 把 onClick 克隆在这颗图标上,它就是那颗操作,而图标默认 aria-hidden`
|
||||
+ ` ⇒ 辅助技术树里没有这条操作(antd 顺手兜的「关闭」是 5.29 起的实现细节,不算名字):`
|
||||
+ `${tag.head.replace(/\s+/g, ' ').trim().slice(0, 76)}`)
|
||||
} else if (!/[\u4e00-\u9fa5]/.test(val)) {
|
||||
ICON_NAMELESS.push(`${at2} — ${m[0].replace(/\s+/g, ' ').trim()} 里的 <${im[0].slice(1)} aria-label="${val.slice(0, 24)}"> 没有中文`
|
||||
+ `:这颗图标自己就是那颗操作,写什么读屏就念什么,字形码不许当名字`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ④ 图标当 children 的图标钮(2026-11-10 · 阶段 32 · S-2 复扫)*/
|
||||
for (const m of code.matchAll(/<(Button|LinkButton|button|a)([\s>])/g)) {
|
||||
const el = jsxElement(code, m.index)
|
||||
if (!el || el.selfClosing || !el.children.trim()) continue
|
||||
const kids = kidsShape(el.children)
|
||||
if (kids.text) continue // children 里有裸文字 ⇒ 有名字来源
|
||||
if (kids.tags.some((t) => !/^Icon[A-Za-z0-9]*$/.test(t))) continue // 混了别的标签 ⇒ 可能出字
|
||||
if (!kids.exprs.every(exprIconOnly)) continue // 表达式可能出字 ⇒ 不判
|
||||
if (!kids.tags.length && !kids.exprs.length) continue // 只有空白 / 注释:不属这一族
|
||||
CHILD_ICON_TOTAL++
|
||||
const at = `${rel}:${lineOf(code, m.index)}`
|
||||
if (/\baria-label\s*=|\baria-labelledby\s*=|\btitle\s*=/.test(el.head)) { CHILD_ICON_NAMED++; continue }
|
||||
CHILD_ICON_MISSING.push(`${at} — <${m[1]}> 的 children 只有图标却既无 aria-label 也无 title`
|
||||
+ `(图标默认 aria-hidden,这颗控件对辅助技术没有名字):`
|
||||
+ `${el.head.replace(/\s+/g, ' ').trim().slice(0, 76)}`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const hit of ICON_NAMELESS) console.log(`ICNN ${hit}`)
|
||||
for (const hit of CHILD_ICON_MISSING) console.log(`ICNN ${hit}`)
|
||||
console.log(`${ICON_NAMELESS.length + CHILD_ICON_MISSING.length} 处图标型控件缺自然语言名称(第 2 条·附二:① 自关闭 + icon 槽 + 无 aria-label/title;`
|
||||
+ `② 图标自带 aria-label 必须是中文;③ closeIcon/clearIcon 这类「onClick 克隆到图标上」的槽位必须自带中文名字;`
|
||||
+ `④ children 只有图标且无 aria-label/title)`)
|
||||
// 覆盖率行:不是缺陷,是「这支闸今天到底看见了多少颗」的凭据(N=0 = 采集形状变了,闸在空转)
|
||||
console.log(`ICNN-COVER childIcon=${CHILD_ICON_TOTAL} named=${CHILD_ICON_NAMED} missing=${CHILD_ICON_MISSING.length}`)
|
||||
|
||||
/* ── 第 2 条·附三:两级表的边界(2026-11-09 · 阶段 25 · Bundle)───────────────
|
||||
拆表换的是**首屏字节**,同一条 `scripts/ui/chunkinfo.mjs` 前后配对实测
|
||||
(`reports/ui_evidence/nex-p25/bundle-landing.log`):
|
||||
首屏 raw 1 513.38 → 1 492.44 kB / gzip 460.51 → 455.77 kB(−4.74,−1.03 %)/
|
||||
brotli 377.02 → 373.46 kB;全部产物 gzip 593.70 → 594.69 kB(+0.99,新块边界的 interop 成本);
|
||||
第三方大块 `WarningOutlined-*` 1 217.16 → 1 195.84 kB(十进制 kB,与 `chunk-budget.json` 同一把尺),
|
||||
sourcemap 归因:里面 111 只字形 → 87 只,请出去的正是 extra 那 24 只,
|
||||
react / @babel/runtime / rc-util 逐模块字节一字不差。
|
||||
这笔收益**没有任何编译器会替你守着**,两条静默回退路径都在 typecheck 下活得很好:
|
||||
a) 桶里补一句 `export * from './extra'`(看着最无害、IDE 还会自动补全成它)——
|
||||
外壳立刻又能按名字引用到那 24 只,`kit` 分组按目录 `src/components/**` 收拢,
|
||||
整张 extra.ts 连字形一起焊回首屏。实测这一条 `export *` 值 Δgzip −0.08 kB,
|
||||
拆表当场白做(`bundle-icons-split.log` 的 D1)。
|
||||
b) 首屏外壳里的某个组件(`app/` · `components/ui/` · `lib/` …)为了一个新按钮
|
||||
深 import `icons/extra` —— extra 又回首屏,页面照样绿。
|
||||
⇒ 判据三条:① 桶不许 re-export `./extra`;② 从 `main.tsx` 出发**只走静态 import**
|
||||
(撞到 `import()` 动态边界就停,与打包器的切块口径一致)可达的文件里,
|
||||
谁都不许引用 `icons/extra`;③ 同一个语义名不许同时躺在两张表里
|
||||
(同名双出口时「页面拿到的到底是哪一只」取决于打包顺序,肉眼查不出来)。
|
||||
另外两个数是「这条闸采到了东西」的证据,不是缺陷:外壳静态闭包的模块数、
|
||||
extra 里没有任何调用方的死出口数(今天 0 只——24 只全有真实调用方,逐条 grep 过)。
|
||||
反例由 scripts/ui/gateprobe.py ㉖ 注入验证:临时树里把桶改成 `export * from './extra'`、
|
||||
把某个外壳文件改成深 import extra,两种都必须点名;整棵树只有 core 时必须静音。 */
|
||||
const SPLIT_DEFECTS = []
|
||||
{
|
||||
const CORE = path.join(REG_DIR, 'core.ts')
|
||||
const EXTRA = path.join(REG_DIR, 'extra.ts')
|
||||
const BUCKET = path.join(REG_DIR, 'index.ts')
|
||||
if (fs.existsSync(CORE) && fs.existsSync(EXTRA)) {
|
||||
/** 临时树里跑的时候 `path.relative(FRONTEND, …)` 会吐出一长串 ../..,
|
||||
看不见是哪个文件;越界就退回按 src 目录算(gateprobe ㉖ 的点名行靠这个才可读)。 */
|
||||
const rel = (f) => { const r = path.relative(FRONTEND, f); return r.startsWith('..') ? path.relative(SRC, f) : r }
|
||||
const code = (f) => codeLines(f).join('\n')
|
||||
const namesOf = (f) => [...code(f).matchAll(/^export const (Icon\w+)/gm)].map((m) => m[1])
|
||||
const coreNames = new Set(namesOf(CORE))
|
||||
const extraNames = new Set(namesOf(EXTRA))
|
||||
/* ① 桶 */
|
||||
if (fs.existsSync(BUCKET) && /from\s+'\.\/extra'/.test(code(BUCKET)))
|
||||
SPLIT_DEFECTS.push(`${rel(BUCKET)}: 桶 re-export 了 ./extra —— 那 ${extraNames.size} 只字形会整块焊回首屏`
|
||||
+ `(实测这一条 export * 值 Δgzip −0.08 kB,等于白拆);懒页面专属出口请在调用方写全路径 '…/icons/extra'`)
|
||||
/* ③ 同名双出口 */
|
||||
for (const n of extraNames) if (coreNames.has(n))
|
||||
SPLIT_DEFECTS.push(`${n} 同时在 core.ts 与 extra.ts 里登记 —— 桶与深路径会给出两只不同的出口`)
|
||||
/* ② 外壳静态闭包 */
|
||||
const RESOLVE_EXT = ['', '.ts', '.tsx', '/index.ts', '/index.tsx']
|
||||
const RE_STATIC = /(?:^|[\s;}])(?:import|export)\s+(?:[\w*{},\s$]*?\s+from\s*)?["']([^"']+)["']/g
|
||||
const resolveSpec = (spec, from) => {
|
||||
let base = null
|
||||
if (spec.startsWith('@/')) base = path.join(SRC, spec.slice(2))
|
||||
else if (spec.startsWith('.')) base = path.resolve(path.dirname(from), spec)
|
||||
else return null // 第三方包不是我们的模块,闭包到此为止
|
||||
for (const e of RESOLVE_EXT) { const q = base + e; if (fs.existsSync(q) && fs.statSync(q).isFile()) return q }
|
||||
return null // CSS / 资源 / 解析不到:不是图标表,跳过
|
||||
}
|
||||
const MAIN = path.join(SRC, 'main.tsx')
|
||||
const closure = new Set()
|
||||
if (fs.existsSync(MAIN)) {
|
||||
const queue = [MAIN]
|
||||
while (queue.length) {
|
||||
const f = queue.pop()
|
||||
if (closure.has(f)) continue
|
||||
closure.add(f)
|
||||
const text = code(f)
|
||||
// 只沿**静态** import 走;`import()` 是切块边界,对面那一坨不在首屏里,不进闭包
|
||||
for (const m of text.matchAll(RE_STATIC)) { const r = resolveSpec(m[1], f); if (r && !closure.has(r)) queue.push(r) }
|
||||
}
|
||||
for (const f of closure) {
|
||||
for (const m of code(f).matchAll(RE_STATIC)) {
|
||||
if (resolveSpec(m[1], f) === EXTRA)
|
||||
SPLIT_DEFECTS.push(`${rel(f)} 在**首屏静态闭包**里引用 icons/extra —— extra 的字形会跟着回到首屏`
|
||||
+ `(收益 −4.74 kB gzip 当场作废)。要么这只图形本来就属于外壳(挪进 core.ts 并同步这里),`
|
||||
+ `要么调用方本身该是懒加载的`)
|
||||
}
|
||||
}
|
||||
}
|
||||
/* 证据计数:extra 里没人用的出口 */
|
||||
const outside = []
|
||||
const walkAll = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const q = path.join(dir, ent.name)
|
||||
if (ent.isDirectory()) { walkAll(q); continue }
|
||||
if (/\.(tsx|ts)$/.test(ent.name) && !inRegistryDir(q)) outside.push(code(q))
|
||||
}
|
||||
}
|
||||
walkAll(SRC)
|
||||
const allCode = outside.join('\n')
|
||||
const deadExtra = [...extraNames].filter((n) => !new RegExp(`\\b${n}\\b`).test(allCode))
|
||||
for (const n of deadExtra) SPLIT_DEFECTS.push(`extra.ts 的 ${n} 没有任何调用方 —— 删掉它,别留着当摆设`)
|
||||
for (const hit of SPLIT_DEFECTS) console.log(`ICONS ${hit}`)
|
||||
console.log(`${SPLIT_DEFECTS.length} 处两级表边界问题(第 2 条·附三:core ${coreNames.size} 只 / extra ${extraNames.size} 只 ·`
|
||||
+ ` 首屏静态闭包 ${closure.size} 个模块 · extra 死出口 ${deadExtra.length} 只)`)
|
||||
} else {
|
||||
console.log(`两级表结构不完整(缺 ${fs.existsSync(CORE) ? 'extra.ts' : 'core.ts'})—— 第 2 条·附三这条闸今天没东西可量,请确认是布局变了还是文件被误删`)
|
||||
}
|
||||
}
|
||||
|
||||
/* ── 第 3 条:裸 <button> 收口到自定义表面族 ──────────────────────────────
|
||||
每条都要写清「为什么不是 antd Button」;新增文件先进这张表,别先写裸按钮。
|
||||
|
|
@ -229,6 +679,14 @@ const CUSTOM_SURFACES = {
|
|||
'src/components/media/MediaLightbox.tsx': '灯箱左右翻页:压在媒体上的 40px 玻璃圆钮 + 悬停位移',
|
||||
'src/components/media/VersionPanel.tsx': '版本封面缩略:图块本身是热区,光标是 zoom-in',
|
||||
'src/pages/project/Storyboard.tsx': '注释里解释「卡片为什么不是 button」——命中数为 0 时删条目',
|
||||
/* 2026-11-10 · 阶段 35 · T1-N4:「显示密码」那颗从 <span role=img tabindex=-1> 换成
|
||||
真 <button>(Tab 到得了 + `aria-pressed` 报明文/密文状态)。为什么不是 kit <Button>:
|
||||
antd `Input.Password` 用 `cloneElement(icon, { className: 'ant-input-password-icon', … })`
|
||||
把 className **整个覆盖**(`antd/es/input/Password.js:64-83`)⇒ 自定义类留不住,
|
||||
归零只能靠内联;换 antd Button 会带进自己的 32px 盒与悬停底,输入框后缀就变形了。
|
||||
下面那条 `nex-*` 标记检查在本文件里由取证路径 `nex-p35/vo/eye-geom-*.json` 满足
|
||||
(清注释时注意:真被撞掉就把标记补到 `.ant-input-password-icon` 的局部样式上)。 */
|
||||
'src/components/forms/SecretInput.tsx': '显示密码开关:antd 后缀槽里的零皮肤命中区,className 会被 antd cloneElement 覆盖',
|
||||
}
|
||||
|
||||
/** 宿主元素不是字面量 <button> 的文件:Tile 用 <As>,As 可以是 button。
|
||||
|
|
@ -737,6 +1195,20 @@ console.log(`${bpHits.length} 处断点越界(第 9 闸:${bpTable.size} 档
|
|||
+ ` / 裸 max-[…] 与未登记名与文档-探针失同步)`)
|
||||
|
||||
|
||||
process.exit(dead.length + stray.length + regHits.length + bare.length + footerViolations.length + antdStray.length
|
||||
+ fbHits.length + headHits.length + tagSkinHits.length + bpHits.length ? 1 : 0)
|
||||
/* ── 收尾:一个族一张账,退出码由这张表算出来 ─────────────────────────────
|
||||
为什么要把表打出来:退出码是布尔的,「第 2 条·附三」刚落地那天就漏在这张表外面——
|
||||
它照常打印 `ICONS …` 与「N 处两级表边界问题」,却进不了 process.exit,
|
||||
于是真仓库里有人把桶改回 `export * from './extra'`(首屏收益 −4.74 kB gzip 当场作废)
|
||||
时,闸门数得清清楚楚、退出码却仍是 0,链子上看是「全绿」。
|
||||
现在族的名单与退出码同源,`FAMILY` 这一行也给 gateprobe ㉖ 一个能区分
|
||||
「采到了」与「响了」的机器可读标记(临时树里第 9 闸永远会响 5 下——它量的是全局登记表,
|
||||
所以退出码本身在夹具里不具区分度,只能靠这一行)。 */
|
||||
const FAMILIES = [
|
||||
['死类名', dead], ['图标外部import', stray], ['图标出口', regHits], ['图标型控件缺名', ICON_NAMELESS],
|
||||
['两级表', SPLIT_DEFECTS], ['裸button', bare], ['footer', footerViolations], ['antd越界', antdStray],
|
||||
['反馈四级', fbHits], ['门牌图形', headHits], ['标签皮肤类', tagSkinHits], ['断点越界', bpHits],
|
||||
]
|
||||
console.log(`FAMILY ${FAMILIES.map(([n, a]) => `${n}=${a.length}`).join(' ')}`
|
||||
+ ` —— 退出码 = 任一族非零;这条行是 gateprobe ㉖ 的机器可读凭据`)
|
||||
process.exit(FAMILIES.reduce((s, [, a]) => s + a.length, 0) ? 1 : 0)
|
||||
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ def login(pg, theme):
|
|||
pg.goto(BASE + "/login", wait_until="networkidle")
|
||||
if pg.locator("#login-user").count():
|
||||
pg.fill("#login-user", "admin")
|
||||
pg.fill("#login-pass", "admin1234")
|
||||
pg.fill("#login-pass", "admin@123")
|
||||
pg.click("button[type=submit]")
|
||||
pg.wait_for_timeout(1200)
|
||||
pg.evaluate("t => localStorage.setItem('nex-the', t)", theme)
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ from playwright.sync_api import sync_playwright
|
|||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
|
||||
WIDTHS = [int(x) for x in os.environ.get("NEX_WIDTHS", "1440,576,430").split(",")]
|
||||
THEMES = os.environ.get("NEX_THEMES", "light").split(",")
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin1234")
|
||||
USER, PWD = os.environ.get("NEX_USER", "admin"), os.environ.get("NEX_PASS", "admin@123")
|
||||
MIN_PROBED = int(os.environ.get("NEX_MIN_PROBED", "8"))
|
||||
|
||||
# (路线, 是否先勾一行, [打开浮层的按钮]) —— 覆盖 Overlay.Drawer / Modal 的全部底部形态:
|
||||
|
|
@ -43,7 +43,10 @@ CASES = [
|
|||
("/assets", False, ["编辑", "新建人物", "引入项目"]),
|
||||
("/assets", True, ["打标签", "批量", "删除"]),
|
||||
("/users", False, ["新建账号", "@编辑账号", "@重置密码"]),
|
||||
("/projects/10/library", False, ["新建人物", "新建场景", "新建声线", "打开生成台", "编辑"]),
|
||||
# 项目资产管理(2026-11-11 与平台资产库对齐后):页头只留当前面板的一颗「新建X」,
|
||||
# 生成入口的可见文案也从「打开生成台」改成平台同款「AI 生成」。
|
||||
# 「新建场景 / 新建声线」是抽屉标题而不是按钮,从来没被点中过,一并清掉。
|
||||
("/projects/10/library", False, ["新建人物", "AI 生成", "编辑"]),
|
||||
("/models", False, ["添加大模型", "配置"]),
|
||||
("/projects/10/storyboard", False, ["导入脚本 / 关键帧"]),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""反向验证:证明八道闸门的十七条判据「坏了会响、好了不响」(2026-11 第七轮起常驻)。
|
||||
"""反向验证:证明九道闸门的每一条判据「坏了会响、好了不响」(2026-11 第七轮起常驻)。
|
||||
条数别写死在标题里——它随夹具增减,实数以末行 `GATEPROBE_OK N/N` 为准(2026-11-08 阶段 12 起为 21 条,
|
||||
2026-11-09 阶段 16 加了产物预算闸的静态反向验证 = 22 条、阶段 17 加图标命名闸 ㉓ = 23 条、
|
||||
阶段 23 加 AT 图形中文名闸 ㉔ = 24 条、阶段 25 加图标登记表两级表闸 ㉖ = 25 条、
|
||||
阶段 31 加归属尺自证空转闸 ㉗ = 26 条、阶段 33 加项目切换探测器自证闸 ㉘ = 27 条、
|
||||
阶段 34 加 S-2 宿主级缺名闸 ㉙ = 28 条、阶段 35 加原生文件控件文案闸 ㉚ = 29 条)。
|
||||
|
||||
`gridcheck` / `rhythmcheck` / `tagcheck` / `btnrowcheck` / `footercheck` / `btnclustercheck` /
|
||||
`tableaudit` 量像素,`semanticcheck` 量辅助技术语义与真实按键——八道闸门自己也需要被体检一次:豁免写宽一格、阈值调松一档,
|
||||
|
|
@ -20,7 +25,7 @@
|
|||
(三条都是 semanticcheck 管的那一族)、
|
||||
只装了一颗 `aria-label=upload` 图标的裸按钮——它的辅助技术名称整个
|
||||
就是英文字形码(S-2 管的那一族)
|
||||
——十七条缺陷,每条判据必须**点名**到它;
|
||||
——十七种页面夹具缺陷,每条判据必须**点名**到它;
|
||||
· `pg-*`(good):故意造出二十二种**合法**形态(卡底 mt-auto 钉底、整块居中的排版、
|
||||
正文 max-w-[72ch] 栏宽、.nex-chipbar 胶囊流、
|
||||
容器自适应的流程条、让位后与字段同行的复选框、
|
||||
|
|
@ -36,18 +41,59 @@
|
|||
同一只图标改成 `aria-hidden=true`(登记表的修法)、图标被显式给了
|
||||
中文名「清空搜索」(后两种必须连候选都不进,S-2)。
|
||||
|
||||
· 判据 ⑱(`TABKBD`):**这一条种不出 div 夹具**。被裁的页签在 DOM 里 rect 完整、AX 树照读,
|
||||
临时 fixture 复现不出「窗口太窄、rc-tabs 自己把页签收进溢出菜单」;假造的
|
||||
`.ant-tabs-nav-more` 又不会响应 ↓/Enter/Esc,正例永远过不了。所以它开一个真 430
|
||||
的窗口走 `/models`,在**真触发器**上改坏五次(tabindex=-1 / 抹掉名称来源 /
|
||||
名称换成字形码 ellipsis / aria-expanded 写死 true / 整颗触发器删掉),
|
||||
五种必须逐条点名;原样那一遍除了静音还要求 `lists>=1 且 picked>=1`
|
||||
——它必须真的用键盘选中过一颗被裁页签,读数取不到溢出就直接停。
|
||||
|
||||
· 判据 ⑲(`semanticcheck.GLYPH-whole`):**也不是靠页面夹具**。它是「整条可读名称
|
||||
恰好等于一个登记表字形码」这一支的全部逻辑,本质是一个字符串函数
|
||||
(DOM 侧与 AX 侧共用),所以直接喂名称表:五个坏名称必须逐条认出,
|
||||
八个好名称必须逐条放行——`/api/meta`(正文里的路径,撞中的是 `api`)
|
||||
和 `upload 导入脚本`(半中半英,归 DOM 侧那条管)放行了才算这条没写宽。
|
||||
|
||||
· 判据 ⑳(`semanticcheck.LOCALE` / `-seen`,阶段 12 · S-3 根因):语言包静默回落 enUS 时
|
||||
只有 antd 内置件自己写的文案会变英文(分页 `Previous Page`、空态 `No data`)。
|
||||
夹具种在 `.ant-pagination` / `.ant-empty` / `.ant-input-number` 三个真作用域里:
|
||||
三条坏形状必须点名(`Previous Page`、`No data`、步进器的 `Increase Value`——
|
||||
最后那条 2026-11-09 阶段 18 起在册豁免已清空,kit 改名一失效它就该响);
|
||||
`上一页`、`暂无数据`、`增加数值` 三条好形状必须放行,
|
||||
**而且必须仍然被采集面点名**——采不到就等于判据瞎了,
|
||||
「放行」是空转(GLYPH 那对 seen/verdict 的教训,别再犯一次)。
|
||||
|
||||
任何一条对不上就退出 1——说明闸门瞎了或者过敏,先修闸门再谈页面。
|
||||
同一块夹具会被几条判据分别评,所以夹具种数(17 个 `pb-*` + 22 个 `pg-*`,按类名实数)
|
||||
与判据条数(17)本来就对不上:末行 `GATEPROBE_OK 17/17` 数的是**判据**,别拿它去核对 fixture 个数。
|
||||
最后一条判据(`classaudit.GATE2-*`)不在页面上:**静态闸门读的是源文件,页面上种不出反例**,
|
||||
同一块夹具会被几条判据分别评,所以夹具种数(`pb-*` 坏形状 / `pg-*` 好形状,按类名实数会随判据增减,
|
||||
另外 5 种是判据 ⑱ 在真页面上改出来的坏形状,判据 ⑲ 喂的是名称表不是夹具)
|
||||
与判据条数本来就对不上:末行 `GATEPROBE_OK N/N` 数的是**判据**(`len(checks) + 11`:
|
||||
页面 18 条 + TABKBD ⑱ + 整名 ⑲ + classaudit 第 2 闸 ⑰ + 产物预算闸 ㉒ + 图标命名闸 ㉓
|
||||
+ AT 图形中文名闸 ㉔(阶段 23 · S-2 收口,静态喂形状表)
|
||||
+ 图标登记表两级表闸 ㉖(阶段 25 · Bundle 收口,四棵临时树喂 classaudit)
|
||||
+ 归属尺自证空转闸 ㉗(阶段 31 · Bundle 结案,三棵临时 dist 喂 chunkinfo:点名 / 静音 / 空转必须各就各位)
|
||||
+ 项目切换探测器自证闸 ㉘(阶段 33 · 第 14 道常驻探针,喂合成读数给 `matches()`:命中与不命中必须各就各位)
|
||||
+ S-2 宿主级缺名闸 ㉙(阶段 34 · 喂「名称已为空的宿主」形状表给 `nameless_icon_host`:七坏五好各就各位)
|
||||
+ 原生文件控件文案闸 ㉚(阶段 35 · S-3 · 喂 `<input type=file>` 的**算完名称表**给 `file_name_defect`:三坏四好各就各位 —— 这一族的英文活在影子 DOM 里,LOCALE 与 GLYPH 五支都量不到,只能钉名称表:没有 aria-label、纯英文 aria-label 必须点名,中文名称与「动作 + 选择文件」这种带上下文的长名必须放行)= 29 条),
|
||||
别拿它去核对 fixture 个数。
|
||||
判据 ⑰(`classaudit.GATE2-*`)不在页面上:**静态闸门读的是源文件,页面上种不出反例**,
|
||||
所以把真登记表抄进临时目录、改出三种绕过 `decorative()` 的写法喂给 classaudit——
|
||||
坏形状必须逐条点名、真登记表必须全程静音,锚点在登记表里找不到时直接停(不许退化成恒真)。
|
||||
再一条同理不吃页面:`classaudit.GATE2B-*`(阶段 17 · S-2 复扫)读源码,喂的是临时目录里的
|
||||
一份夹具 + 两份**真页面文件**(抽屉 ✕、分镜行内图标钮)——坏形状三条点名、好形状整片静音、
|
||||
真文件也必须静音,这条闸管的是「图标被藏起来之后控件彻底没名字」,占这一族一半的浮层控件
|
||||
只有源码闸量得到。
|
||||
最后一条判据(`chunkbudget.*` · 阶段 16)同理不吃页面:它读的是**构建产物**,所以喂临时 dist——
|
||||
七种坏/好形状 + 真产物必须静音,其中「没 budget 要喊 DEGRADED」与「DEGRADED 仍按 1 500 kB 判」
|
||||
两条钉的是同一个退化路径的两面(只钉一面,工具可以永远走兜底 / 永远把兜底当放宽)。
|
||||
用法:
|
||||
.venv/bin/python scripts/ui/gateprobe.py
|
||||
"""
|
||||
import importlib.util
|
||||
import os
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
|
@ -57,11 +103,35 @@ from playwright.sync_api import sync_playwright
|
|||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
|
||||
|
||||
CLASSAUDIT = HERE / "classaudit.mjs"
|
||||
REGISTRY = HERE.parents[1] / "frontend" / "src" / "components" / "icons" / "index.ts"
|
||||
CHUNKBUDGET = HERE / "chunkbudget.mjs"
|
||||
REAL_DIST = HERE.parents[1] / "frontend" / "dist"
|
||||
REAL_DIST_SM = HERE.parents[1] / "frontend" / "dist-sm" # 带 map 的产物;没有就退到 dist(归属段自动跳过)
|
||||
CHUNKINFO = HERE / "chunkinfo.mjs"
|
||||
REGISTRY = HERE.parents[1] / "frontend" / "src" / "components" / "icons" # 阶段 25 起是目录(core.ts / extra.ts / index.ts / _kit.ts)
|
||||
|
||||
|
||||
def registry_files():
|
||||
"""登记表目录里的全部 .ts —— 反向验证的锚点必须在**整个目录**里找。
|
||||
|
||||
只读 `index.ts` 的话,拆表后 `IconUpload` 搬进 `extra.ts`,锚点找不到,
|
||||
这条判据会当场停(而不是退化成恒真):房规「登记一把尺必须当场试一次这把尺」。
|
||||
"""
|
||||
out = {p.name: p.read_text(encoding="utf8") for p in sorted(REGISTRY.glob("*.ts"))}
|
||||
if not out:
|
||||
raise SystemExit(f"GATEPROBE_FAIL —— 登记表目录里一个 .ts 都没有:{REGISTRY}")
|
||||
return out
|
||||
|
||||
|
||||
def write_registry(d, files):
|
||||
"""把一份登记表原样落到临时源码树里(保持多文件形状,别摊成一个 index.ts)。"""
|
||||
(d / "components" / "icons").mkdir(parents=True, exist_ok=True)
|
||||
for name, text in files.items():
|
||||
(d / "components" / "icons" / name).write_text(text, encoding="utf8")
|
||||
return d
|
||||
|
||||
# 判据 ⑰ 的反例:登记表里**真实存在**的三行,逐行换成三种「绕过 decorative()」的写法。
|
||||
# 锚点找不到就直接停——登记表改名时这条反向验证会先喊,而不是悄悄退化成恒真。
|
||||
|
|
@ -73,6 +143,78 @@ BAD_SHAPES = [
|
|||
]
|
||||
|
||||
|
||||
# ── 判据 ⑱(TABKBD · 阶段 9 · S-3)的反例:窄屏溢出页签那颗「更多」触发器。
|
||||
# 这一条**种不出 div 夹具**:被裁的那几颗页签在 DOM 里 rect 完整、AX 树照读得到,
|
||||
# 源码字符串与临时 fixture 都造不出「窗口太窄、rc-tabs 把页签收进溢出菜单」这个前提——
|
||||
# 只有真的把窗口收到 430、让组件自己溢出,判据才有东西可看。所以这段直接在真页面上
|
||||
# **改真东西**(每改一种坏形状重新加载一次,页面自己复位,不留残留):
|
||||
# 五反一正。正例除了「静音」还要求 `picked>=1`——它必须在 430 的溢出条带上真的用键盘
|
||||
# 选中过一颗被裁页签,才算这条判据没有空转(它历史上空转过一次:恒 0 看着像全绿)。
|
||||
# · pb-tkbd-unfocusable:给那颗真 button 铺 tabindex=-1 → 键盘到不了(判据①)
|
||||
# · pb-tkbd-nameless :抹掉名称来源(内层图标的 aria-label)→ AT 读作未命名按钮(判据②)
|
||||
# · pb-tkbd-glyph :名称换成字形码 ellipsis → S-2 那族缺陷换个位置复发(判据②)
|
||||
# · pb-tkbd-stuckopen :aria-expanded 写死 true 不翻 → 声明与行为不一致(判据③)
|
||||
# · pb-tkbd-nowmore :触发器整颗没了但页签仍被裁 → 窄屏把页签弄丢了(前置检查)
|
||||
TKBD_ROUTE = "/models"
|
||||
TKBD_DEFECTS = [
|
||||
("pb-tkbd-unfocusable",
|
||||
"() => { const m = document.querySelector('.ant-tabs-nav-more');"
|
||||
" m.tabIndex = -1; return 1 }",
|
||||
"不可聚焦"),
|
||||
("pb-tkbd-nameless",
|
||||
"() => { const m = document.querySelector('.ant-tabs-nav-more');"
|
||||
" const s = m.querySelector('[role=img],.anticon');"
|
||||
" if (s) { s.removeAttribute('aria-label'); s.setAttribute('aria-hidden','true'); } return 1 }",
|
||||
"没有名字"),
|
||||
("pb-tkbd-glyph",
|
||||
"() => { const m = document.querySelector('.ant-tabs-nav-more');"
|
||||
" const s = m.querySelector('[role=img],.anticon');"
|
||||
" if (s) s.setAttribute('aria-label','ellipsis'); return 1 }",
|
||||
"混进字形码"),
|
||||
("pb-tkbd-stuckopen",
|
||||
"() => { document.querySelector('.ant-tabs-nav-more')"
|
||||
".setAttribute('aria-expanded','true'); return 1 }",
|
||||
"aria-expanded=true"),
|
||||
("pb-tkbd-nowmore",
|
||||
"() => { document.querySelector('.ant-tabs-nav-more').remove(); return 1 }",
|
||||
"找不到「更多」触发器"),
|
||||
]
|
||||
|
||||
|
||||
def tabkbd_negative(pw):
|
||||
"""在真实窄屏溢出的那一页上把 TABKBD 跑六遍:原样必须静音且真选中过,五种坏形状必须逐条点名。
|
||||
|
||||
返回 [(marker, 必须点名的半句话 | None, offenders 摊平串, 覆盖读数)],交给主循环逐条 verdict。
|
||||
锚点(430 的 /models 会溢出)读不到溢出时**直接停**:前提变了就别退化成恒真。
|
||||
"""
|
||||
out = []
|
||||
b = pw.chromium.launch()
|
||||
ctx = b.new_context(viewport={"width": 430, "height": 900})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(20000)
|
||||
cdp = ctx.new_cdp_session(pg)
|
||||
cdp.send("DOM.enable")
|
||||
cdp.send("Accessibility.enable")
|
||||
semanticcheck.login(pg)
|
||||
for marker, inject, expect in ([("<原样>", None, None)]
|
||||
+ [(m, j, e) for m, j, e in TKBD_DEFECTS]):
|
||||
pg.goto(BASE + TKBD_ROUTE, wait_until="networkidle")
|
||||
pg.wait_for_timeout(1600)
|
||||
if inject:
|
||||
pg.evaluate(inject)
|
||||
off, cov = [], []
|
||||
stat = semanticcheck.tab_kbd_check(pg, cdp, "gateprobe/" + marker, off, cov)
|
||||
out.append((marker, expect, " | ".join(off), stat))
|
||||
b.close()
|
||||
first = out[0][3]
|
||||
if first["lists"] < 1 or first["picked"] < 1:
|
||||
raise SystemExit(
|
||||
"GATEPROBE_FAIL semanticcheck.TABKBD —— 反向验证的前提没了:%s 在 430 档"
|
||||
"读不到溢出页签(lists=%s picked=%s)。要么这一页的页签变少了/变窄了,"
|
||||
"要么 rc-tabs 换了溢出实现 → 先换夹具页,别让这条判据悄悄空转。"
|
||||
% (TKBD_ROUTE, first["lists"], first["picked"]))
|
||||
return out
|
||||
|
||||
def load(mod_name: str):
|
||||
"""按路径加载闸门模块,直接复用它们的探针 JS,避免同一份判据写两遍。"""
|
||||
spec = importlib.util.spec_from_file_location(mod_name, HERE / f"{mod_name}.py")
|
||||
|
|
@ -89,6 +231,11 @@ footercheck = load("footercheck")
|
|||
btnclustercheck = load("btnclustercheck")
|
||||
tableaudit = load("tableaudit")
|
||||
semanticcheck = load("semanticcheck")
|
||||
projectswitchcheck = load("projectswitchcheck")
|
||||
# 反向验证必须和被测闸门指向**同一个**前端:两个脚本的默认 BASE 都是 :5173
|
||||
# (与 `nex.config.yaml` 的 `dev_base_url` 同一口径),但这里仍然显式覆盖 —— 各自读 env 的话,
|
||||
# 只给 gateprobe 传 NEX_BASE 会让 TABKBD 那一段去一个没人服务的地址上找溢出页签,然后抱怨「锚点找不到」。
|
||||
semanticcheck.BASE, semanticcheck.USER, semanticcheck.PWD = BASE, USER, PWD
|
||||
|
||||
FIXTURE = r"""() => {
|
||||
const old = document.getElementById('nex-gateprobe'); if (old) old.remove();
|
||||
|
|
@ -322,6 +469,31 @@ FIXTURE = r"""() => {
|
|||
<div class="pb-semt" role="tab" tabindex="0" style="cursor:pointer;height:28px;line-height:28px">我们的页签</div>
|
||||
<div class="pg-semt ant-tabs-tab-btn" role="tab" tabindex="0"
|
||||
style="cursor:pointer;height:28px;line-height:28px">antd 的页签</div>
|
||||
<!-- ⑪ S-3 根因(阶段 12):antd 中文语言包没生效时**静默**回落 enUS,
|
||||
只有它家自己写的文案会变英文。作用域靠 ant- 类认,所以夹具必须种进真作用域,
|
||||
而 marker 类名要打在**被读的那个节点自己身上**(sig() 会剥掉 ant- 类,
|
||||
打在包裹层上就点不出名)。类名两两不互为前缀:hay 是子串匹配。 -->
|
||||
<ul class="ant-pagination" style="list-style:none;padding:0;margin:0;display:flex;gap:4px">
|
||||
<li class="pb-locprev ant-pagination-item-link" title="Previous Page"
|
||||
style="display:block;width:24px;height:24px">‹</li>
|
||||
<li class="pg-loczh ant-pagination-item-link" title="上一页"
|
||||
style="display:block;width:24px;height:24px">‹</li>
|
||||
</ul>
|
||||
<div class="ant-empty" style="display:block;width:160px;height:40px">
|
||||
<span class="pb-locdata ant-empty-description"
|
||||
style="display:block;width:80px;height:16px">No data</span>
|
||||
<span class="pg-loctxt ant-empty-description"
|
||||
style="display:block;width:80px;height:16px">暂无数据</span>
|
||||
</div>
|
||||
<!-- 步进器那颗(阶段 18 语义翻转):kit 的改名收口之前它是「在册豁免唯一的真住户」,
|
||||
豁免表清空之后英文名就是违规;中文那颗是好形状必须放行——两条一起才量得出
|
||||
「改名生效」与「改名没把中文误判成英文」两个方向。 -->
|
||||
<div class="ant-input-number" style="display:block;width:80px;height:32px">
|
||||
<span class="pb-locnum ant-input-number-handler ant-input-number-handler-up"
|
||||
aria-label="Increase Value" style="display:block;width:16px;height:16px"></span>
|
||||
<span class="pg-locnumzh ant-input-number-handler ant-input-number-handler-down"
|
||||
aria-label="增加数值" style="display:block;width:16px;height:16px"></span>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(host2);
|
||||
return [...host.querySelectorAll('[class]'), ...host2.querySelectorAll('[class]')].length;
|
||||
|
|
@ -357,32 +529,345 @@ def run_classaudit(src: pathlib.Path):
|
|||
|
||||
|
||||
def gate2_static():
|
||||
"""把真登记表抄进临时目录,喂给 classaudit 跑「好形状 / 坏形状」各一遍。"""
|
||||
reg = REGISTRY.read_text(encoding="utf8")
|
||||
"""把真登记表**整目录**抄进临时目录,喂 classaudit 跑「好形状 / 坏形状」各一遍。"""
|
||||
reg = registry_files()
|
||||
with tempfile.TemporaryDirectory(prefix="nex-gate2-") as td:
|
||||
root = pathlib.Path(td)
|
||||
bad_src = reg
|
||||
bad_src = dict(reg)
|
||||
for old, new in BAD_SHAPES:
|
||||
if bad_src.count(old) != 1:
|
||||
raise SystemExit(f"GATEPROBE_FAIL classaudit.GATE2 —— 反向验证的锚点在登记表里找不到:{old}"
|
||||
" → 登记表那行改名/删除时,先同步这里的 fixture,别让这条判据变成空转")
|
||||
bad_src = bad_src.replace(old, new, 1)
|
||||
hit = [n for n, t in bad_src.items() if t.count(old) == 1]
|
||||
if len(hit) != 1:
|
||||
raise SystemExit(f"GATEPROBE_FAIL classaudit.GATE2 —— 反向验证的锚点在登记表目录里找不到或不止一处"
|
||||
f"(命中 {hit}):{old}"
|
||||
" → 登记表那行改名/删除/挪表时,先同步这里的 fixture,别让这条判据变成空转")
|
||||
bad_src[hit[0]] = bad_src[hit[0]].replace(old, new, 1)
|
||||
shapes = {}
|
||||
for tag, text, extra in (("good", reg, "import { IconUpload } from './components/icons'\n"),
|
||||
("bad", bad_src, "import { StarOutlined } from '@ant-design/icons'\n")):
|
||||
for tag, files, extra in (("good", reg, "import { IconUpload } from './components/icons'\n"),
|
||||
("bad", bad_src, "import { StarOutlined } from '@ant-design/icons'\n")):
|
||||
d = root / tag
|
||||
(d / "components" / "icons").mkdir(parents=True)
|
||||
(d / "components" / "icons" / "index.ts").write_text(text, encoding="utf8")
|
||||
write_registry(d, files)
|
||||
(d / "Probe.tsx").write_text(extra, encoding="utf8")
|
||||
shapes[tag] = " || ".join(run_classaudit(d))
|
||||
return shapes
|
||||
|
||||
|
||||
PROBE_BAD = """\
|
||||
import { Button } from './components/ui/Button'
|
||||
import { IconClose, IconDelete, IconMore } from './components/icons'
|
||||
export const A = () => <Button icon={<IconClose />} onClick={() => {}} />
|
||||
export const B = () => <Button icon={<IconClose />} aria-label="关闭" onClick={() => {}} />
|
||||
export const C = () => <Button icon={<IconClose />} title="关闭" onClick={() => {}} />
|
||||
export const D = () => <Button icon={<IconDelete />} danger>删除</Button>
|
||||
export const E = () => (
|
||||
<Button
|
||||
type="text"
|
||||
icon={<IconClose />}
|
||||
aria-label="多行也要认"
|
||||
/>
|
||||
)
|
||||
export const F = () => <IconMore aria-label="more" />
|
||||
export const G = () => <IconMore aria-label="更多页签" />
|
||||
export const H = () => <IconMore aria-label="" />
|
||||
// export const I = () => <Button icon={<IconClose />} />
|
||||
/* export const J = () => <Button icon={<IconClose />} /> */
|
||||
export const K = () => <Button icon={on ? <IconClose /> : <IconDelete />} onClick={go} />
|
||||
export const L = () => <Button icon={on ? <IconClose /> : <IconDelete />} aria-label="切换" onClick={go} />
|
||||
export const M = () => <Tag closable closeIcon={<IconClose />} />
|
||||
// ④(阶段 32 · S-2 复扫):图标写在 children 里的图标钮——① 的两条前提都不成立
|
||||
export const N = () => <button type="button" onClick={go}><IconClose /></button>
|
||||
export const O = () => <Button onClick={go}>{on ? <IconClose /> : <IconDelete />}</Button>
|
||||
"""
|
||||
|
||||
# ③ 那一支的**好形状**(阶段 23 · S-2 收口):槽位里的图标自带中文名字、三元写法、
|
||||
# 表达式(认不出就不判)、以及「图标在宿主的 icon 槽里而宿主自己报名」——四种都不许连坐。
|
||||
# 这一族今天全站只有两处真调用(`Ctlbar.tsx:338` 胶囊 ✕、`Input.tsx:183` 清空搜索),
|
||||
# 好形状一旦误报,被改写的就是那两句刚补上的中文名字。
|
||||
PROBE_GOOD = """\
|
||||
import { Button } from './components/ui/Button'
|
||||
import { IconChevronLeft, IconClear, IconClose, IconDelete, IconUpload } from './components/icons'
|
||||
export const P = () => <Tag closable closeIcon={<IconClose aria-label="移除" />} />
|
||||
export const Q = () => <Tag closable closeIcon={onRemove ? <IconClose aria-label="移除" /> : undefined} />
|
||||
export const R = () => <Search allowClear={{ clearIcon: <IconClear aria-label="清空搜索" /> }} />
|
||||
export const S = () => <Button icon={<IconClose />} aria-label="关闭抽屉" />
|
||||
export const T = () => <Tag closable closeIcon={myIcon} />
|
||||
// ④ 的好形状(阶段 32):U / V / W 三颗**必须被覆盖率行采到并放行**(children 只有图标、名字写在宿主上),
|
||||
// X / Y / Z / AA 四颗**必须整个跳过**(children 里出了字或看不出会不会出字)——
|
||||
// 前者证明这支闸真的在看东西,后者证明它没有宽到把有文字的按钮也拖进来点名。
|
||||
export const U = () => <Button onClick={go} aria-label="关闭"><IconClose /></Button>
|
||||
export const V = () => (
|
||||
<Button
|
||||
type="text"
|
||||
onClick={go}
|
||||
aria-label="多行写名字的图标钮"
|
||||
>
|
||||
<IconClose />
|
||||
</Button>
|
||||
)
|
||||
export const W = () => <Button onClick={go} title="上一个"><IconChevronLeft /></Button>
|
||||
export const X = () => <Button onClick={go}><IconUpload />导入脚本</Button>
|
||||
export const Y = () => <Button onClick={go}><IconClose /><span>关闭这一层</span></Button>
|
||||
export const Z = () => <Button onClick={go}>{row.label}</Button>
|
||||
export const AA = () => <Button onClick={go}>{on ? <IconClose /> : '删除'}</Button>
|
||||
"""
|
||||
|
||||
PROBE_REAL = ["frontend/src/components/ui/Overlay.tsx", "frontend/src/pages/project/Storyboard.tsx"]
|
||||
|
||||
|
||||
def gate2b_static():
|
||||
"""判据 ㉓(阶段 17 · S-2 复扫):classaudit 第 2 条·附二「图标型控件必须报名」的反向验证。
|
||||
|
||||
这条闸量的是「一颗只画图标的按钮 / 链接,有没有对辅助技术报出自己的名字」。
|
||||
和 ⑰ 一样喂临时目录:静态闸读源文件,页面上种不出反例。
|
||||
七种坏形状必须逐条点名(少一颗名字 / 名字写成英文字形码 / 名字写成空串 /
|
||||
closeIcon 槽里那颗没报名 / children 只有图标的 <button> / children 是换图形三元表达式的
|
||||
<Button>),十二种好形状必须静音——其中「有 children」「多行写 aria-label」「注释里那一颗」
|
||||
「换图标的三元表达式」四条是这条闸最容易写宽的地方,误报的下场和漏报一样:被关掉。
|
||||
阶段 23 起这一条多了第三支(classaudit 第 2 条·附二 ③:`closeIcon=` / `clearIcon=`
|
||||
这类「antd 把 onClick 克隆到图标本体」的槽位),夹具同步:坏形状加 `M`(胶囊 ✕ 不写名字),
|
||||
好形状另开一份 `PROBE_GOOD`(自带中文名 / 三元 / 表达式 / 宿主报名四种),
|
||||
它和真页面文件一起写进 good 目录——good 目录必须整片静音。
|
||||
阶段 32 起这一条还有第四支(classaudit 第 2 条·附二 ④:`<Button …><IconClose /></Button>`
|
||||
这种把图标写在 children 里的图标钮,① 的「自关闭 + icon 槽」两条前提一条都不成立),
|
||||
夹具同步:坏形状加 `N`(裸 children 图标)与 `O`(children 是三元换图形),
|
||||
好形状加 `U`/`V`/`W`(名字写在宿主上:aria-label / 多行 aria-label / title,必须被
|
||||
`ICNN-COVER` 采到)与 `X`/`Y`/`Z`/`AA`(children 里有裸文字 / 有 `<span>` 包的字 /
|
||||
是 `{row.label}` / 三元的一个分支是字符串——四种都必须整片跳过)。
|
||||
另外拿**真页面文件**(Overlay.tsx 的抽屉 ✕、Storyboard.tsx 的 8 颗行内图标钮)
|
||||
跑一遍要求静音:这一族控件一半活在浮层里(探针点开不到),真文件静音才算
|
||||
这条闸站在现网代码上量得出对的结果,而不是只在自家夹具里自证。
|
||||
"""
|
||||
root_dir = HERE.parents[1] # 仓库根:PROBE_REAL 按 frontend/src/... 取真文件
|
||||
with tempfile.TemporaryDirectory(prefix="nex-gate2b-") as td:
|
||||
root = pathlib.Path(td)
|
||||
shapes = {}
|
||||
for tag in ("bad", "good"):
|
||||
d = root / tag
|
||||
write_registry(d, registry_files())
|
||||
if tag == "bad":
|
||||
(d / "Probe.tsx").write_text(PROBE_BAD, encoding="utf8")
|
||||
else:
|
||||
(d / "ProbeGood.tsx").write_text(PROBE_GOOD, encoding="utf8")
|
||||
for rel in PROBE_REAL:
|
||||
f = d / pathlib.Path(rel).name
|
||||
f.write_text((root_dir / rel).read_text(encoding="utf8"), encoding="utf8")
|
||||
out = subprocess.run(["node", str(CLASSAUDIT), str(d)],
|
||||
capture_output=True, text=True, timeout=300)
|
||||
lines = (out.stdout or "").splitlines()
|
||||
# 点名行 + 那行计数都要留下:计数行是「好的一面必须静音」唯一的证据
|
||||
# (只有点名行时,好形状与「这条闸根本没跑」在输出里长得一模一样)。
|
||||
shapes[tag] = " || ".join(ln for ln in lines
|
||||
if ln.startswith("ICNN ") or ln.startswith("ICNN-COVER ")
|
||||
or "处图标型控件缺自然语言名称" in ln)
|
||||
return shapes
|
||||
|
||||
|
||||
def split_static():
|
||||
"""判据 ㉖(阶段 25 · Bundle):classaudit 第 2 条·附三「两级表边界」的反向验证。
|
||||
|
||||
这条闸守的是**已实测兑现的首屏收益**(首屏 gzip −4.74 kB / −1.03 %,
|
||||
`reports/ui_evidence/nex-p25/bundle-landing.log`),而它的两条回退路径都骗得过 tsc:
|
||||
桶里多一句 `export * from \'./extra\'`、或外壳文件深 import 一次 `icons/extra`
|
||||
——两种都编译通过、页面照常、产物里 extra 悄悄回到首屏。所以必须在这里种反例。
|
||||
|
||||
临时树刻意搭成**两级表**的最小形状(main → App 静态、App → Lazy 动态),
|
||||
因为这条闸的判定对象就是「静态闭包」:动态边界两侧的结论必须相反,
|
||||
把 `Lazy.tsx` 改成静态 import 就是 bad-shell 那一腿,夹具里不用另搭一棵树。
|
||||
四个变体:good(extra 只被动态边界那边引用)/ bad-bucket / bad-shell / bad-dup。
|
||||
good 一面除了「ICONS 点名行必须为空」还要求计数行里真的写着 `core 1 只 / extra 1 只`
|
||||
——放行但采不到 = 空转,这条规矩本项目栽过两次(阶段 12 的 GLYPH、阶段 18 的 TABKBD)。
|
||||
"""
|
||||
KIT = ("import { createElement, forwardRef } from 'react'\n"
|
||||
"export function decorative(Glyph: any, alias: string) {\n"
|
||||
" const Icon = forwardRef<HTMLSpanElement, any>(function IconDecorative(props: any, ref: any) {\n"
|
||||
" const { \'aria-hidden\': ah, \'aria-label\': al, ...rest } = props\n"
|
||||
" const named = typeof al === \'string\' && al.trim() !== \'\'\n"
|
||||
" return createElement(Glyph, { ...rest, ref, \'aria-label\': named ? al : undefined,\n"
|
||||
" \'aria-hidden\': named ? (ah ?? false) : (ah ?? true) })\n"
|
||||
" })\n"
|
||||
" Icon.displayName = alias\n"
|
||||
" return Icon\n}\n")
|
||||
CORE = ("import { PlusOutlined } from \'@ant-design/icons\'\nimport { decorative } from \'./_kit\'\n\n"
|
||||
"export const IconAdd = decorative(PlusOutlined, \'IconAdd\')\n")
|
||||
EXTRA = ("import { EditOutlined } from \'@ant-design/icons\'\nimport { decorative } from \'./_kit\'\n\n"
|
||||
"export const IconEdit = decorative(EditOutlined, \'IconEdit\')\n")
|
||||
SHELL = ("import { IconAdd } from \'./components/icons\'\n"
|
||||
"export const App = () => <div>{\'{}\'}</div>\n")
|
||||
SHELL_BAD = ("import { IconAdd } from \'./components/icons\'\n"
|
||||
"import { IconEdit } from \'./components/icons/extra\'\n"
|
||||
"export const App = () => <div>{\'{}\'}</div>\n")
|
||||
LAZY = ("import { IconEdit } from \'./components/icons/extra\'\n"
|
||||
"export default () => <div>{\'{}\'}</div>\n")
|
||||
MAIN = ("import { createRoot } from \'react-dom/client\'\nimport { App } from \'./App\'\n"
|
||||
"const Lazy = lazy(() => import(\'./pages/Lazy\'))\n"
|
||||
"createRoot(document.getElementById(\'root\')!).render(<App />)\n")
|
||||
# 第 9 闸(断点越界)在任何临时树里都天然响 5 下:尺子来自真仓库的 @theme 登记表,
|
||||
# 而五把登记尺子(insp-lg / board / insp-md / insp-sm / agent)在夹具里没有使用者
|
||||
# ⇒「登记了却 0 个使用者」。那 5 下会把退出码永久占住(good 也恒 EXIT=1),
|
||||
# 于是「两级表这一族到底进不进 process.exit」在夹具里根本证明不了。
|
||||
# 本轮补的正是这个洞,所以顺手给夹具补上五把尺子的使用者——全写在同一个文件里,
|
||||
# 满足 §4 口径 ①「一把尺子只服务一个表面」。这样 good 的 12 族全 0 且 EXIT=0,
|
||||
# 三种坏形状只有 `两级表` 非 0 且 EXIT=1:退出码从此只由这一族说了算。
|
||||
BPFIX = ("export const Bp = () => (\n"
|
||||
" <div className=\"min-insp-lg:w-full min-board:grid min-insp-md:flex \"\n"
|
||||
" \"min-insp-sm:hidden min-agent:block\" />\n)\n")
|
||||
with tempfile.TemporaryDirectory(prefix="nex-gate2c-") as td:
|
||||
root = pathlib.Path(td)
|
||||
out = {}
|
||||
for tag in ("good", "bad-bucket", "bad-shell", "bad-dup"):
|
||||
d = root / tag / "src"
|
||||
(d / "components" / "icons").mkdir(parents=True)
|
||||
(d / "pages").mkdir(parents=True)
|
||||
(d / "components" / "icons" / "_kit.ts").write_text(KIT, encoding="utf8")
|
||||
(d / "components" / "icons" / "core.ts").write_text(
|
||||
CORE + ("export const IconEdit = decorative(EditOutlined, \'IconEdit\')\n"
|
||||
if tag == "bad-dup" else ""), encoding="utf8")
|
||||
(d / "components" / "icons" / "extra.ts").write_text(EXTRA, encoding="utf8")
|
||||
(d / "components" / "icons" / "index.ts").write_text(
|
||||
"export * from \'./core\'\n"
|
||||
+ ("export * from \'./extra\'\n" if tag == "bad-bucket" else ""), encoding="utf8")
|
||||
(d / "App.tsx").write_text(SHELL_BAD if tag == "bad-shell" else SHELL, encoding="utf8")
|
||||
(d / "pages" / "Lazy.tsx").write_text(LAZY, encoding="utf8")
|
||||
(d / "Bp.tsx").write_text(BPFIX, encoding="utf8")
|
||||
(d / "main.tsx").write_text(MAIN, encoding="utf8")
|
||||
proc = subprocess.run(["node", str(CLASSAUDIT), str(d)],
|
||||
capture_output=True, text=True, timeout=300)
|
||||
lines = (proc.stdout or "").splitlines()
|
||||
keep = [ln for ln in lines
|
||||
if ln.startswith("ICONS ") or ln.startswith("FAMILY ")
|
||||
or "处两级表边界问题" in ln or "两级表结构不完整" in ln]
|
||||
# 闸门自己的退出码也进夹具:FAMILY 行是「采到了」的凭据,EXIT 行是「响了」的凭据
|
||||
out[tag] = " || ".join(keep + [f"EXIT={proc.returncode}"])
|
||||
return out
|
||||
|
||||
|
||||
def chunkbudget_static():
|
||||
"""判据 ㉒(阶段 16 · 任务 3):产物预算闸 `chunkbudget.mjs` 的反向验证。
|
||||
|
||||
这一条闸吃的是**构建产物**,页面上种不出反例,所以照 `gate2_static` 的姿势喂临时目录。
|
||||
七种形状,坏的一面必须逐条点名、好的一面必须静音——尤其这两面:
|
||||
· 「读到 budget 就按 budget 判」与「没读到 budget 必须喊 DEGRADED」是同一把尺子的两面:
|
||||
只钉后一面,工具可以永远走兜底;只钉前一面,兜底那条路坏了没人知道。
|
||||
· DEGRADED 那一腿还要拿一颗 1 501 kB 的文件证明**退化没有放宽判定**
|
||||
(阶段 12 的 GLYPH「放行但采不到 = 空转」是同一类错误,别再犯第三次)。
|
||||
阶段 24 加了来源 C(项目登记的 `frontend/chunk-budget.json`)之后,这里多钉三件事,
|
||||
一条都不能少:① C 真被读到并参与判定(`proj` 那腿按 10 kB 点名);
|
||||
② C 坏了 / 缺键 / 单位读不出 / 显式指定却找不到 ⇒ 一律响,不许冒充「没有预算」悄悄兜底;
|
||||
③ 显式 `--config` 的优先级没被 C 污染(`degraded` 那腿现在才是真判据:
|
||||
项目预算文件就在默认路径上,一旦「显式配置没 budget 也往下兜」,DEGRADED 就不见了);
|
||||
外加真产物必须报出 C 的文件名、且不再挂 DEGRADED(挂账③ 的销账凭据)。
|
||||
"""
|
||||
out = {}
|
||||
|
||||
def run(*a):
|
||||
r = subprocess.run(["node", str(CHUNKBUDGET), *[str(x) for x in a]],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
return f"exit={r.returncode} " + (r.stdout or "") + (r.stderr or "")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="nex-chunkbudget-") as td:
|
||||
root = pathlib.Path(td)
|
||||
d = root / "dist" / "assets"
|
||||
d.mkdir(parents=True)
|
||||
(root / "dist-empty" / "assets").mkdir(parents=True)
|
||||
hd = root / "dist-huge" / "assets"
|
||||
hd.mkdir(parents=True)
|
||||
(d / "ok.js").write_bytes(b"x" * 2_000) # 任何一条预算都该放过它
|
||||
(d / "big.js").write_bytes(b"y" * 20_000) # 全局 10 kB 时越界,chunk 档 30 kB 时合法
|
||||
(d / "big.css").write_bytes(b"z" * 4_000) # asset 档 5 kB 时合法
|
||||
(hd / "huge.js").write_bytes(b"w" * 1_501_000) # 兜底 1 500 kB 之上 1 kB
|
||||
(root / "cfg-budget.json").write_text('{"output":{"budget":10000}}', encoding="utf8")
|
||||
(root / "cfg-scoped.json").write_text(
|
||||
'{"output":{"budget":[{"type":"asset","name":"assets/big*","maximumSize":5000},'
|
||||
'{"type":"chunk","maximumSize":30000}]}}', encoding="utf8")
|
||||
(root / "cfg-nobudget.json").write_text('{"output":{"format":"es"}}', encoding="utf8")
|
||||
(root / "cfg-broken.json").write_text("{ not json", encoding="utf8")
|
||||
# 来源 C(阶段 24 · 项目自己登记的预算文件)——五种形状各留一份夹具
|
||||
(root / "proj-good.json").write_text('{"budget":10000}', encoding="utf8")
|
||||
(root / "proj-broken.json").write_text("{ not json", encoding="utf8")
|
||||
(root / "proj-empty.json").write_text('{"_what":"没有 budget 键"}', encoding="utf8")
|
||||
(root / "proj-shape.json").write_text('{"budget":"1500"}', encoding="utf8")
|
||||
out["good"] = run("--dist", root / "dist", "--config", root / "cfg-scoped.json")
|
||||
out["bad"] = run("--dist", root / "dist", "--config", root / "cfg-budget.json")
|
||||
out["degraded"] = run("--dist", root / "dist", "--config", root / "cfg-nobudget.json")
|
||||
out["degraded-limit"] = run("--dist", root / "dist-huge")
|
||||
out["broken"] = run("--dist", root / "dist", "--config", root / "cfg-broken.json")
|
||||
out["nodist"] = run("--dist", root / "nope")
|
||||
out["empty"] = run("--dist", root / "dist-empty")
|
||||
out["proj"] = run("--dist", root / "dist", "--budget-file", root / "proj-good.json")
|
||||
out["proj-broken"] = run("--dist", root / "dist", "--budget-file", root / "proj-broken.json")
|
||||
out["proj-missing"] = run("--dist", root / "dist", "--budget-file", root / "nope.json")
|
||||
out["proj-empty"] = run("--dist", root / "dist", "--budget-file", root / "proj-empty.json")
|
||||
out["proj-shape"] = run("--dist", root / "dist", "--budget-file", root / "proj-shape.json")
|
||||
out["real"] = run("--dist", REAL_DIST)
|
||||
return out
|
||||
|
||||
|
||||
def chunkinfo_static():
|
||||
"""判据 ㉗(阶段 31 · Bundle 结案时翻自己的案):归属尺 `chunkinfo.mjs` §3
|
||||
「磁盘对账自证」的反向验证。
|
||||
|
||||
为什么要有这一条:阶段 31 把 VLQ 解码器修完之后,给归属读数加了一道自证
|
||||
(某源归属字节 > 磁盘源文件 × 1.5 ⇒ 点名)。它落地当天就把我们把我们骗了——
|
||||
把带 map 的产物复制到 `/tmp` 再跑,`sources` 里的 `../../node_modules/…`
|
||||
全部解析失败,对账覆盖率 **0/1177**,而判定行照样打印
|
||||
「(无)⇒ 本轮归属读数没有「源文件装不下」的伪像」。
|
||||
**自证空转比没有自证更危险**:它长得像证据。
|
||||
(规范基准 = .map 所在目录,产物在项目树内时恰好等价,所以同一把尺在
|
||||
`frontend/dist-sm` 上是 1177/1177、真在看着东西;移到树外就瞎了还在喊安静。)
|
||||
|
||||
三种形状,钉的是「自证必须真的在看」:
|
||||
· `suspect`:一个 12 B 的真源被记了 401 B ⇒ 必须点名、必须挂 SUSPECT;
|
||||
· `good`:同一个源只被记 9 B ⇒ 必须静音且必须仍说「没有伪像」
|
||||
(恒红 = 噪音,这条闸的宿命就是被关掉);
|
||||
· `idle`:源在磁盘上不存在(模拟产物脱离项目树)⇒ 覆盖率 0 %
|
||||
必须挂 `ATTRIB_VERDICT=IDLE`、必须**闭嘴**——「没有伪像」那一句一个字节都不许出现。
|
||||
外加退出码契约:默认恒 0(只读尺,nex.config.yaml 写着),
|
||||
只有显式 `SOURCE_CHECK_STRICT=1` 才把 IDLE / SUSPECT 升级成退出码 1。
|
||||
"""
|
||||
out = {}
|
||||
|
||||
def run(dist, strict=False):
|
||||
env = dict(os.environ)
|
||||
if strict:
|
||||
env["SOURCE_CHECK_STRICT"] = "1"
|
||||
r = subprocess.run(["node", str(CHUNKINFO), str(dist)],
|
||||
capture_output=True, text=True, timeout=180, env=env)
|
||||
return f"exit={r.returncode} " + (r.stdout or "") + (r.stderr or "")
|
||||
|
||||
def dist_fixture(root, name, gen_len, src_len, src_rel):
|
||||
"""一份最小可用产物:index.html → assets/a.js(一行 gen_len 字节)+ 它的 map。"""
|
||||
d = root / name
|
||||
(d / "assets").mkdir(parents=True)
|
||||
(d / "src").mkdir(parents=True)
|
||||
(d / "index.html").write_text('<script type="module" src="/assets/a.js"></script>', encoding="utf8")
|
||||
(d / "assets" / "a.js").write_text("x" * gen_len, encoding="utf8")
|
||||
(d / "src" / "tiny.js").write_text("y" * src_len, encoding="utf8")
|
||||
# mappings="AAAA" = 第 1 行 1 段 [gcol 0, sidx 0, src line 0, col 0]
|
||||
(d / "assets" / "a.js.map").write_text(json.dumps(
|
||||
{"version": 3, "file": "a.js", "sources": [src_rel], "names": [], "mappings": "AAAA"}),
|
||||
encoding="utf8")
|
||||
return d
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="nex-chunkinfo-") as td:
|
||||
root = pathlib.Path(td)
|
||||
sus = dist_fixture(root, "dist-suspect", 400, 12, "../src/tiny.js")
|
||||
good = dist_fixture(root, "dist-good", 8, 12, "../src/tiny.js")
|
||||
idle = dist_fixture(root, "dist-idle", 400, 12, "../../ghost/tiny-ghost.js")
|
||||
out["suspect"] = run(sus)
|
||||
out["suspect-strict"] = run(sus, True)
|
||||
out["good"] = run(good)
|
||||
out["good-strict"] = run(good, True)
|
||||
out["idle"] = run(idle)
|
||||
out["idle-strict"] = run(idle, True)
|
||||
out["real"] = run(REAL_DIST_SM if REAL_DIST_SM.exists() else REAL_DIST)
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
fails = []
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.launch()
|
||||
pg = b.new_context(viewport={"width": 1440, "height": 1600}).new_page()
|
||||
ctx = b.new_context(viewport={"width": 1440, "height": 1600})
|
||||
pg = ctx.new_page()
|
||||
pg.set_default_timeout(20000)
|
||||
pg.goto(BASE + "/login")
|
||||
pg.wait_for_selector("#login-user")
|
||||
|
|
@ -478,6 +963,21 @@ def main() -> int:
|
|||
(lambda r: [g["host"] for g in r.get("glyphs", [])]),
|
||||
[("pb-glyph", True), ("pg-glyph", True),
|
||||
("pg-glyph2", False), ("pg-glyph3", False)]),
|
||||
# S-3 根因(2026-11-08 · 阶段 12 起常驻):语言包静默回落 enUS。
|
||||
# 坏形状三条必须逐条点名(分页 title / 空态文字 / 步进器 aria-label),
|
||||
# 好形状三条必须放行。阶段 18 把豁免表清空后,步进器那颗英文从「放行」
|
||||
# 翻成「点名」——豁免写宽一格就会把真缺陷一起放过,这条正是那三格之一。
|
||||
("semanticcheck.LOCALE", semanticcheck.COLLECT,
|
||||
(lambda r: semanticcheck.locale_offenders(r.get("builtins", []))),
|
||||
[("pb-locprev", True), ("pb-locdata", True), ("pb-locnum", True),
|
||||
("pg-loczh", False), ("pg-loctxt", False), ("pg-locnumzh", False)]),
|
||||
# 同一条判据的**采集面**:六条夹具必须全部仍然被采到。少了这一条,
|
||||
# 上面那三个「必须放行」在作用域写错时也会全绿(没采到 ≠ 采到了但判为合法)。
|
||||
("semanticcheck.LOCALE-seen", semanticcheck.COLLECT,
|
||||
(lambda r: ["%s %s %s" % (b["kind"], b["sig"], b["v"])
|
||||
for b in r.get("builtins", [])]),
|
||||
[("pb-locprev", True), ("pb-locdata", True), ("pb-locnum", True),
|
||||
("pg-loczh", True), ("pg-loctxt", True), ("pg-locnumzh", True)]),
|
||||
]
|
||||
def verdict(label, marker, should_fire, hay):
|
||||
hit = marker in hay
|
||||
|
|
@ -494,8 +994,88 @@ def main() -> int:
|
|||
hay = names(rows, key)
|
||||
for marker, should_fire in expectations:
|
||||
verdict(label, marker, should_fire, hay)
|
||||
|
||||
# ── 判据 ⑲ 的**第二腿**(阶段 10 · S-2 收尾):名称表钉的是字符串,
|
||||
# 而这条判据真正跑在浏览器里(DOM 采集 5b + CDP AX 树两支)。只测字符串那一层
|
||||
# 等于自反了 §15.12 立下的规矩——「判据写在哪一层,反例就得造在哪一层」:
|
||||
# 采集 JS 的正则写坏了(比如整条名称匹配不上 `^[a-z][a-z0-9-]{1,24}$`),
|
||||
# 名称表那条腿照样全绿。所以在真页面(登录后 /assets)上拿**真按钮**改三种形状:
|
||||
# 原样必须一个字都不点(点了就是页面缺陷或闸门过敏)、
|
||||
# `aria-label=ellipsis`(登记表在册字形码)两支都必须点名、
|
||||
# `aria-label=/api/meta`(正文里那种拉丁词,撞中的是 `api`)必须只打印不点名。
|
||||
# 前提:先摘掉自家夹具——上面那 17 块 `pb-*` 里就有 `pb-glyph`(只装一颗
|
||||
# `aria-label=upload` 图标的裸按钮),它本来就是这一族缺陷的坏形状,
|
||||
# 夹具还挂着就量「真页面原样必须静」,等于自己抓自己:阶段 10 第一跑就是这样红的
|
||||
# (`必须放行 → 点名了 upload`),这条 FAIL 反过来证明第二腿确实在读名称。
|
||||
# 摘完必须回到 checks 之前的状态没有意义(后面 ⑱/⑰ 各开各的页面与临时目录),
|
||||
# 所以在这里摘是安全的;摘不到两个 host 就直接停,别让「静」来自空页面。
|
||||
cdp = ctx.new_cdp_session(pg)
|
||||
cdp.send("Accessibility.enable")
|
||||
|
||||
def whole_hits():
|
||||
"""把这条判据的两支各跑一遍,返回「被点名的整条名称」拼串(空串 = 全静)。"""
|
||||
d = pg.evaluate(semanticcheck.COLLECT)
|
||||
hits = [c["tok"] for c in d.get("nameOnly", [])
|
||||
if semanticcheck.whole_glyph_name(c["tok"])]
|
||||
hits += [n["name"] for n in (semanticcheck.ax_names(cdp) or [])
|
||||
if semanticcheck.whole_glyph_name(n["name"])]
|
||||
return "|".join(hits)
|
||||
|
||||
gone = pg.evaluate("""() => {
|
||||
let n = 0;
|
||||
for (const id of ['nex-gateprobe', 'nex-gateprobe-sem']) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) { el.remove(); n++; }
|
||||
}
|
||||
const left = document.querySelectorAll('[class^="pb-"],[class*=" pb-"]').length;
|
||||
return { n, left };
|
||||
}""")
|
||||
if gone["n"] != 2:
|
||||
print("FAIL 摘不掉自家夹具:", gone)
|
||||
fails.append("semanticcheck.GLYPH-whole-live/夹具没摘干净")
|
||||
b.close()
|
||||
print("GATEPROBE_FAIL", " ".join(fails))
|
||||
return 1
|
||||
print(" 摘掉自家夹具 2 个 → 剩余 pb-* 节点 %d(应为 0)" % gone["left"])
|
||||
pg.wait_for_timeout(200)
|
||||
|
||||
raw = whole_hits()
|
||||
if raw:
|
||||
fails.append("semanticcheck.GLYPH-whole-live/真页面原样")
|
||||
print("FAIL semanticcheck.GLYPH-whole-live 真页面原样 "
|
||||
"必须放行 → 点名了:", raw[:300])
|
||||
else:
|
||||
print("OK semanticcheck.GLYPH-whole-live 真页面原样 "
|
||||
"必须放行 → 没点名")
|
||||
for tok, fire in (("ellipsis", True), # 在册字形码:两支都必须点名
|
||||
("/api/meta", False)): # 正文里那种拉丁词:只能打印,不许点名
|
||||
pg.evaluate("""(t) => {
|
||||
const b = [...document.querySelectorAll('button')]
|
||||
.find(x => x.offsetWidth > 0 && !x.getAttribute('aria-label'));
|
||||
if (!b) throw new Error('页面上找不到一颗没写过 aria-label 的可见按钮(夹具前提变了)');
|
||||
b.setAttribute('aria-label', t); window.__gpBtn = b; return 1;
|
||||
}""", tok)
|
||||
pg.wait_for_timeout(200)
|
||||
hits = whole_hits()
|
||||
# 「点名」= 两支里任何一支给出了整条名称。好形状要求一支都不给(不是「别的那个词被点名」)
|
||||
ok = bool(hits) == fire
|
||||
print(f"{'OK ' if ok else 'FAIL'} semanticcheck.GLYPH-whole-live "
|
||||
f"aria-label={tok:<12} {'必须点名' if fire else '必须放行'} → "
|
||||
f"{'点名了 ' + hits[:120] if hits else '没点名'}")
|
||||
if not ok:
|
||||
fails.append("semanticcheck.GLYPH-whole-live/" + tok)
|
||||
pg.evaluate("() => { window.__gpBtn.removeAttribute('aria-label'); return 1 }")
|
||||
b.close()
|
||||
|
||||
# ── 判据 ⑱(TABKBD):不吃 div 夹具,直接开一个 430 的真窗口跑六遍
|
||||
for marker, expect, hay, stat in tabkbd_negative(pw):
|
||||
if expect is None:
|
||||
verdict("semanticcheck.TABKBD-good", "TABKBD", False, hay)
|
||||
print(" 原样跑通:溢出条带 %d 处 · 被裁 %d 颗 · 纯键盘选中成功 %d 颗"
|
||||
% (stat["lists"], stat["clipped"], stat["picked"]))
|
||||
else:
|
||||
verdict("semanticcheck.TABKBD", expect, True, hay)
|
||||
|
||||
# ── 判据 ⑰(不吃页面、不触发 HMR):classaudit 第 2 闸的静态反向验证
|
||||
# 这条闸读的是一份**源文件**,页面上种不出反例,只能喂临时目录:
|
||||
# 真登记表必须全程静音(否则它就是恒红),三种绕过 decorative() 的写法必须逐条点名
|
||||
|
|
@ -507,11 +1087,269 @@ def main() -> int:
|
|||
verdict("classaudit.GATE2-bad", "StarOutlined", True, shapes["bad"])
|
||||
verdict("classaudit.GATE2-good", "ICON", False, shapes["good"])
|
||||
|
||||
# ── 判据 ㉓(阶段 17 · S-2 复扫):classaudit 第 2 条·附二「图标型控件必须报名」。
|
||||
# 与 ⑰ 同一姿势喂临时目录,但钉的是另一族缺陷:不是「图标自己把英文字形名漏出去」,
|
||||
# 而是「图标被 decorative() 藏起来之后,那颗控件彻底没有名字」——
|
||||
# 抽屉 / 模态 / 灯箱里的图标钮占这一族的一半,常驻的浏览器探针量不到(浮层没点开)。
|
||||
# 所以坏形状三条逐条点名、好形状整片静音、真页面文件也必须静音。
|
||||
shapes2b = gate2b_static()
|
||||
verdict("classaudit.GATE2B-bad", "<Button> 只画图标却既无 aria-label 也无 title", True, shapes2b["bad"])
|
||||
verdict("classaudit.GATE2B-bad", 'aria-label="more"', True, shapes2b["bad"])
|
||||
verdict("classaudit.GATE2B-bad", "aria-label 是空串", True, shapes2b["bad"])
|
||||
# 好形状不许连坐:有文字的按钮 / aria-label 在下一行的多行写法 / 注释里那一颗 /
|
||||
# 带名字的三元换图形,四条都不许出现在点名行里。
|
||||
for marker in ('aria-label="关闭"', 'aria-label="多行也要认"', '>删除</Button>',
|
||||
'aria-label="切换"', "export const I", "更多页签"):
|
||||
verdict("classaudit.GATE2B-good", marker, False, shapes2b["bad"])
|
||||
# ③(阶段 23):`closeIcon={<IconClose />}` 这种「antd 把 onClick 克隆到图标上」的槽位,
|
||||
# 闸必须用「没写 aria-label」这句话点名(这句话只有 ③ 的空名分支会打,① ② 都打不出)。
|
||||
verdict("classaudit.GATE2B-bad", "closeIcon= 里的 <IconClose> 没写 aria-label", True, shapes2b["bad"])
|
||||
for marker in ('closeIcon={<IconClose aria-label="移除" />}', 'aria-label="清空搜索"',
|
||||
'closeIcon={myIcon}', 'aria-label="关闭抽屉"'):
|
||||
verdict("classaudit.GATE2B-goodshape", marker, False, shapes2b["bad"])
|
||||
verdict("classaudit.GATE2B-goodshape", marker, False, shapes2b["good"])
|
||||
# 标记必须是「ICNN + 两颗空格」这句**点名行前缀**(classaudit 567/568 两行的打印形状)。
|
||||
# 阶段 32 第一版这里写的是裸 "ICNN",被新增的 `ICNN-COVER` 覆盖率行撞中,
|
||||
# 于是「真文件必须静音」这条腿在好面上永远红——红的是探针自己,不是页面(§15.12 ㉓)。
|
||||
verdict("classaudit.GATE2B-real", "ICNN ", False, shapes2b["good"])
|
||||
verdict("classaudit.GATE2B-real", "处图标型控件缺自然语言名称", True, shapes2b["good"])
|
||||
# ④(阶段 32 · S-2 复扫):children 只有图标的图标钮。必须用「children 只有图标」这句原话点名——
|
||||
# 这句话只有 ④ 会打,① ② ③ 打不出来,钉它才证明这第四支在跑(钉「缺自然语言名称」会撞 ① 的计数行)。
|
||||
for marker in ("<button> 的 children 只有图标却既无 aria-label 也无 title",
|
||||
"<Button> 的 children 只有图标却既无 aria-label 也无 title"):
|
||||
verdict("classaudit.GATE2B-bad", marker, True, shapes2b["bad"])
|
||||
# 采到证明(§15.1 通则:放行但采不到 = 空转;这条闸自己的覆盖率行就是它的采到凭据):
|
||||
# · 坏面必须**恰好**数到那两颗(2 采到 / 0 具名 / 2 未命名),少一颗就是采集形状又变了;
|
||||
# · 好面未命名必须 0,且夹具那三颗具名图标钮必须真被数进去(childIcon≥3 且 named≥3)。
|
||||
# 颗数只钉下限不钉死:good 目录里还抄了 Overlay.tsx / Storyboard.tsx 两份真文件,
|
||||
# 它们哪天多一颗具名图标钮是正常的,不该把别人的正常改动变成这条闸的红。
|
||||
cov_bad = re.search(r"ICNN-COVER childIcon=(\d+) named=(\d+) missing=(\d+)", shapes2b["bad"])
|
||||
cov_good = re.search(r"ICNN-COVER childIcon=(\d+) named=(\d+) missing=(\d+)", shapes2b["good"])
|
||||
hay_bad = shapes2b["bad"] if cov_bad and cov_bad.groups() == ("2", "0", "2") else ""
|
||||
verdict("classaudit.GATE2B-cover-bad", "ICNN-COVER childIcon=2 named=0 missing=2", True, hay_bad)
|
||||
# verdict() 是 `marker in hay` 的字面子串匹配 ⇒ 标记必须写成**输出里真会长出来的那半句话**。
|
||||
# 阶段 32 第一版把「childIcon>=3 且 named>=3 且 missing=0」这句**口径说明**当成标记,
|
||||
# 它永远不可能出现在 classaudit 的输出里,于是好面越健康这条腿越必红。
|
||||
# 现在钉的是覆盖率行本身(实测 `ICNN-COVER childIcon=3 named=3 missing=0`):
|
||||
# 行在且达到下限 → 点名;行在但没达到下限 → hay 置空,判 FAIL(不是放宽);
|
||||
# 整行缺失(采集形状又变了)→ 标记退化成「ICNN-COVER 行缺失」,仍在 hay 里找不到 → FAIL。
|
||||
good_line = cov_good.group(0) if cov_good else "ICNN-COVER 行缺失(④ 没采到任何图标钮)"
|
||||
hay_good = (shapes2b["good"] if cov_good
|
||||
and int(cov_good.group(1)) >= 3 and int(cov_good.group(2)) >= 3
|
||||
and int(cov_good.group(3)) == 0 else "")
|
||||
verdict("classaudit.GATE2B-cover-good", good_line, True, hay_good)
|
||||
|
||||
|
||||
# ── 判据 ㉖(阶段 25 · Bundle):classaudit 第 2 条·附三「两级表边界」。
|
||||
# 拆表换来的是实测的首屏收益,而两条回退路径(桶 re-export extra / 外壳深 import extra)
|
||||
# tsc 与页面都看不出来 ⇒ 这一族的反例只能在源码层喂临时目录。
|
||||
shapes2c = split_static()
|
||||
verdict("classaudit.GATE2C-bucket", "桶 re-export 了 ./extra", True, shapes2c["bad-bucket"])
|
||||
verdict("classaudit.GATE2C-shell", "在**首屏静态闭包**里引用 icons/extra", True, shapes2c["bad-shell"])
|
||||
verdict("classaudit.GATE2C-dup", "同时在 core.ts 与 extra.ts", True, shapes2c["bad-dup"])
|
||||
# good 那一面:三条点名都必须没有,但计数行必须真的数到 1 只 / 1 只(采到了才叫放过)。
|
||||
# ⚠ 标记必须是**违规行原话**,不能截取其中一段裸词:计数行是恒打印的测量值,
|
||||
# 里面天然写着「首屏静态闭包 N 个模块」,拿「首屏静态闭包」当放行标记必然自己撞自己。
|
||||
# ㉖ 落地当天真响过一次(GATEPROBE_FAIL classaudit.GATE2C-good/首屏静态闭包,
|
||||
# 闸门与产物都没错,错在探针的字符串太宽);同一条教训见 ㉔ 的注释。
|
||||
for marker in ("桶 re-export 了 ./extra", "在**首屏静态闭包**里引用 icons/extra",
|
||||
"同时在 core.ts 与 extra.ts 里登记"):
|
||||
verdict("classaudit.GATE2C-good", marker, False, shapes2c["good"])
|
||||
# ── 退出码接线(本轮补的洞):附三刚落地时只 print、不进 process.exit,
|
||||
# 真仓库里有人把收益改回去时,日志写着「1 处两级表边界问题」、链子上仍是 CLASSAUDIT=0。
|
||||
# 现在族的名单与退出码同源(classaudit 末尾的 FAMILIES 表 → FAMILY 行 → 同一个 reduce)。
|
||||
# ⚠ 只钉 FAMILY 行证明的是「采到了」,不是「响了」。这一版断言刚写下时钉的是
|
||||
# 「坏形状 EXIT=1」,可那个 1 是被第 9 闸白占住的(夹具里没有断点使用者)——
|
||||
# 把两级表从退出码里摘掉,断言照样绿,正是这条闸自己要说的那种空转。
|
||||
# 夹具补上五把登记尺子的使用者之后:good = 12 族全 0 且 EXIT=0、
|
||||
# 坏形状 = 只有两级表非 0 且 EXIT=1,退出码成了这一族的单变量函数。
|
||||
for tag in ("good", "bad-bucket", "bad-shell", "bad-dup"):
|
||||
verdict(f"classaudit.GATE2C-ledger-{tag}", "FAMILY ", True, shapes2c[tag])
|
||||
verdict("classaudit.GATE2C-good", "两级表=0", True, shapes2c["good"])
|
||||
verdict("classaudit.GATE2C-good", "断点越界=0", True, shapes2c["good"])
|
||||
verdict("classaudit.GATE2C-good-exit", "EXIT=0", True, shapes2c["good"])
|
||||
for tag in ("bad-bucket", "bad-shell", "bad-dup"):
|
||||
verdict(f"classaudit.GATE2C-{tag}", "两级表=0", False, shapes2c[tag])
|
||||
for tag in ("bad-bucket", "bad-shell", "bad-dup"):
|
||||
verdict(f"classaudit.GATE2C-{tag}-exit", "EXIT=1", True, shapes2c[tag])
|
||||
verdict("classaudit.GATE2C-seen", "core 1 只 / extra 1 只", True, shapes2c["good"])
|
||||
# 真产物必须静音(恒红 = 噪音),且必须报得出真实的两级表读数
|
||||
verdict("classaudit.GATE2C-real", "ICONS ", False, shapes2c["good"])
|
||||
|
||||
# ── 判据 ㉔(阶段 23 · S-2 收口):`semanticcheck` GLYPH **第四支** `ax_graphic_zh_defect`
|
||||
# 的反向验证。这一支的输入是两个字符串(AX 算完的整条名称 + 那颗图形的 outerHTML),
|
||||
# 在页面上种不出一颗「AT 看得见、名字是英文字形码」的真图形——种出来就是恒真,
|
||||
# 所以照 ⑲ / ⑳ 的姿势直接喂形状表。五坏五好,好形状钉的是这条闸最容易写宽的三个地方:
|
||||
# · 「名字含汉字」不是「名字撞中字形名单」——`移除` / `清空搜索` 必须是好形状;
|
||||
# · 「只管 anticon」——素材封面那颗 `<img alt="Chart">` 与自绘的 `.nex-brief-mark`
|
||||
# 名字里全是英文,那是**内容**不是控件属性,立案就是假阳性(下场是这条闸被关掉);
|
||||
# · 名称为空的图形归 NAME / C 支,这一支不许重复立案。
|
||||
# ⚠ 阶段 17 的教训同样适用:标记用行 id(`b-up` / `g-nonanticon`),**不用名称本身**
|
||||
# ——`up` 既是坏形状的名字,也可能出现在别的名字里,裸子串匹配会自己撞自己。
|
||||
GLYPH5C = [
|
||||
("b-up", "up", '<span role="img" aria-label="up" class="anticon anticon-up">'),
|
||||
("b-down", "down", '<span role="img" aria-label="down" class="anticon anticon-down">'),
|
||||
("b-left", "left", '<span role="img" aria-label="left" class="anticon anticon-left">'),
|
||||
("b-right", "right", '<span role="img" aria-label="right" class="anticon anticon-right">'),
|
||||
("b-closecircle", "close-circle", '<span role="img" aria-label="close-circle" class="anticon anticon-close-circle">'),
|
||||
("g-zh-remove", "移除", '<span role="img" aria-label="移除" class="anticon anticon-close ant-tag-close-icon">'),
|
||||
("g-zh-clear", "清空搜索", '<span role="img" aria-label="清空搜索" class="anticon anticon-close-circle">'),
|
||||
("g-nonanticon", "Chart", '<img alt="Chart" src="/api/meta.png">'),
|
||||
("g-mark", "PrevPageGlyph", '<span class="nex-brief-mark">'),
|
||||
("g-empty", "", '<span role="img" aria-label="up" class="anticon anticon-up">'),
|
||||
]
|
||||
fired5c = "||".join("%s|%s" % (mid, semanticcheck.ax_graphic_zh_defect(nm, html))
|
||||
for mid, nm, html in GLYPH5C if semanticcheck.ax_graphic_zh_defect(nm, html))
|
||||
for mid, _, _ in GLYPH5C:
|
||||
verdict("semanticcheck.GLYPH-5c", mid, mid.startswith("b-"), fired5c)
|
||||
|
||||
# ── 判据 ㉙(阶段 34 · 2026-11-10 · S-2 宿主级收口):`semanticcheck` GLYPH **第五支**
|
||||
# `nameless_icon_host` 的反向验证。这一支的输入只有「名称已经为空的宿主 outerHTML」,
|
||||
# 判的是「里面还有没有图标」这一层——在页面上种一颗「AT 看得见、整条名称为空、
|
||||
# 里面只有图标」的真控件等于自己喂自己(种下去名字就没了/或者恒真),
|
||||
# 所以照 ㉔ / ⑲ 的姿势直接喂形状表。七坏五好,好形状钉的是这条闸最容易写宽的几处:
|
||||
# · 真 `<img>` 的 alt 与自绘圆点是**内容**,不是图标控件属性(与 5c 同一把尺子);
|
||||
# · `<input type=file>` 的名称是浏览器自带文案(Choose File),与图标无关,
|
||||
# 不在这一支立案;它自己的名字归阶段 35 的 FILE 闸(判据 ㉚)。
|
||||
# 2026-11-10 之前这条口径写的是「归英文宿主名一族在册豁免」,S-3 修好后
|
||||
# 真页面上原生英文已经读不到了,豁免的说法随之作废;
|
||||
# · 纯文字按钮 / 只有 SVG 文本的按钮:名称为空是 NAME 闸的活,不许重复立案。
|
||||
# 坏形状里 `anticon-loading` 是**加载态**那颗:类名带 anticon 却没有名字,
|
||||
# 读屏同样什么都念不到 ⇒ 立案是对的,不是假阳性(这条刻意钉成坏形状)。
|
||||
GLYPH5D = [
|
||||
("b-upload", '<button class="ant-btn ant-btn-text"><span class="anticon anticon-upload" aria-hidden="true"><svg data-icon="upload"></svg></span></button>'),
|
||||
("b-eye", '<span role="button" tabindex="0" class="ant-input-password-icon"><span class="anticon anticon-eye-invisible" aria-hidden="true"></span></span>'),
|
||||
("b-previewclose", '<button class="ant-image-preview-close"><span class="anticon anticon-close" aria-hidden="true"></span></button>'),
|
||||
("b-selectclear", '<span class="ant-select-clear"><span class="anticon anticon-close-circle" aria-hidden="true"></span></span>'),
|
||||
("b-stepup", '<span class="ant-input-number-handler-up"><span class="anticon anticon-up"><svg data-icon="up"></svg></span></span>'),
|
||||
("b-combobox", '<div class="ant-select ant-select-single" role="combobox" tabindex="0"><span class="ant-select-arrow"><span class="anticon anticon-down" aria-hidden="true"></span></span></div>'),
|
||||
("b-loading", '<button class="ant-btn"><span class="anticon-loading anticon-spin"></span></button>'),
|
||||
("g-text", '<button class="ant-btn"><span>导入脚本</span></button>'),
|
||||
("g-fileinput", '<input type="file" class="nex-file-input">'),
|
||||
("g-cover", '<div class="nex-cover"><img alt="Chart" src="/api/meta.png"></div>'),
|
||||
("g-dot", '<button class="ant-btn"><i class="nex-dot"></i></button>'),
|
||||
("g-svgtext", '<button class="ant-btn"><svg viewBox="0 0 16 16"><text>OK</text></svg></button>'),
|
||||
]
|
||||
fired5d = "||".join("%s|%s" % (mid, semanticcheck.nameless_icon_host(html))
|
||||
for mid, html in GLYPH5D if semanticcheck.nameless_icon_host(html))
|
||||
for mid, _ in GLYPH5D:
|
||||
verdict("semanticcheck.GLYPH-5d", mid, mid.startswith("b-"), fired5d)
|
||||
|
||||
# ── 判据 ㉚(阶段 35 · 2026-11-10 · S-3):`semanticcheck` **FILE** 那一支。
|
||||
# 症状不是「图标」也不是「antd 语言包回落」,而是**浏览器原生控件文案**渗进
|
||||
# 辅助技术名称:`<input type=file>` 的 `Choose File` / `No file chosen` 活在影子 DOM 里,
|
||||
# DOM 侧一条属性都读不到,所以 LOCALE 那把尺子量不到它,GLYPH 那五支也与它无关。
|
||||
# 页面上种夹具只能种真组件渲染出来的形状(FilePick 一旦改名整族一起改,
|
||||
# 种不出「只坏一颗」的对照),所以照 ⑲ / ㉙ 的姿势直接喂名称表:
|
||||
# · 坏形状必须点名:没有 aria-label(原生英文 inevitable)、纯英文 aria-label
|
||||
# (把原生文案抄进名字里,读屏照样念英文);
|
||||
# · 好形状必须放行:中文名称、以及「动作 + 选择文件」这种带上下文的长名
|
||||
# ——按「含汉字」判,不按英文名单判,换宿主语言也不空转。
|
||||
FILE_NAMES = [
|
||||
("b-empty", ""),
|
||||
("b-blank", " "),
|
||||
("b-native", "Choose File"),
|
||||
("b-nativefull", "No file chosen"),
|
||||
("g-zh", "选择文件"),
|
||||
("g-zh-ctx", "定妆图,选择文件"),
|
||||
("g-zh-mix", "上传 v2 参考图"),
|
||||
]
|
||||
firedFile = "||".join("%s|%s" % (mid, semanticcheck.file_name_defect(nm))
|
||||
for mid, nm in FILE_NAMES if semanticcheck.file_name_defect(nm))
|
||||
for mid, _ in FILE_NAMES:
|
||||
verdict("semanticcheck.FILE", mid, mid.startswith("b-"), firedFile)
|
||||
|
||||
|
||||
# ── 判据 ⑲(semanticcheck.GLYPH 的「整条名称=字形码」那一支 · 阶段 10 · S-2 收尾):
|
||||
# 这一支的全部逻辑就是一个字符串函数(DOM 侧与 AX 侧共用 `whole_glyph_name`),
|
||||
# 页面上种不出一颗「名称正好是字形码」的控件——种出来就是恒真(我们自己喂的名字),
|
||||
# 所以直接喂名称表。两头都要钉:
|
||||
# · 认不出坏形状 = 这条判据恒绿,`ellipsis` 那种「读屏只念一个英文单词」能重新进来;
|
||||
# · 把好名称也认成字形码 = 假阳性,下场是这条闸被以噪音为由关掉。
|
||||
# `/api/meta`(撞中 api)与 `upload 导入脚本`(归 DOM 侧那条管)就是现成的两个陷阱。
|
||||
WHOLE_IN = ["upload", "down", "ellipsis", "api", " close "]
|
||||
WHOLE_OUT = ["upload 导入脚本", "导入脚本", "更多页签", "/api/meta", "Esc", "OK", "全部展开", "导出"]
|
||||
fired = "|".join(n for n in WHOLE_IN + WHOLE_OUT if semanticcheck.whole_glyph_name(n))
|
||||
for n in WHOLE_IN:
|
||||
verdict("semanticcheck.GLYPH-whole", n.strip(), True, fired)
|
||||
for n in WHOLE_OUT:
|
||||
verdict("semanticcheck.GLYPH-whole-out", n, False, fired)
|
||||
|
||||
# ── 判据 ㉒(阶段 16 · 任务 3 · chunkbudget):产物预算闸的静态反向验证。
|
||||
# 编号说明:⑰ classaudit 第 2 闸、⑲ 整名(含浏览器第二腿)、⑱ TABKBD、⑳ LOCALE 都在上面;
|
||||
# 这一条不占上面那 18 条页面判据里的任何一格,是**新增的一条判据**,末行计数随之 +1
|
||||
# (计数式 `len(checks) + 6`:⑰/⑱/⑲静态/⑳/㉑/㉒/㉓/㉔ 里的离线支……
|
||||
# 简言之 18 条页面 + 6 条离线 = 24,阶段 23 起)。
|
||||
#
|
||||
# ⚠ 阶段 17 的教训(判据 ㉒ 第一次跑红就是这个原因,别再犯):`verdict` 是**裸子串匹配**,
|
||||
# 所以标记必须钉在闸的**结构化字段**上,不能钉在它自己的解释散文里。
|
||||
# 原来这两腿写的是裸 `DEGRADED`:坏配置那条路(CONFIG-BAD)本应「不许冒充退化」而放行,
|
||||
# 可闸在 `预算来源` 那行和 die() 提示里各有一句**散文**写着「不冒充 DEGRADED」
|
||||
# 「不许混成 DEGRADED 用兜底蒙过去」——字面量撞中,好形状被误判成误报,
|
||||
# 表现是 `chunkbudget.broken DEGRADED 必须放行 → 点名了`。
|
||||
# 修法是把两腿一起钉到字段前缀 `预算来源 : ` 上(退化 = `预算来源 : DEGRADED —— …`,
|
||||
# 坏配置 = `预算来源 : 不可信 —— …`),判定语义一条都没放宽,散文想怎么写怎么写。
|
||||
cb = chunkbudget_static()
|
||||
verdict("chunkbudget.bad", "OVER assets/big.js", True, cb["bad"]) # 越界必须点名
|
||||
verdict("chunkbudget.bad", "OVER assets/ok.js", False, cb["bad"]) # 没越界的不许连坐(明细表里它本来就在)
|
||||
verdict("chunkbudget.good", "OVER", False, cb["good"]) # 作用域 budget 命中时必须放过
|
||||
verdict("chunkbudget.good", "output.budget = 5000", True, cb["good"]) # 且必须说清上限是从配置读的
|
||||
verdict("chunkbudget.degraded", "预算来源 : DEGRADED", True, cb["degraded"]) # 没 budget 必须自报退化(钉字段,不钉散文)
|
||||
verdict("chunkbudget.degraded", "OVER", False, cb["degraded"]) # 兜底之下小文件仍要放过
|
||||
verdict("chunkbudget.degraded-limit", "OVER assets/huge.js", True, cb["degraded-limit"]) # 退化≠放宽
|
||||
verdict("chunkbudget.broken", "CONFIG-BAD", True, cb["broken"]) # 配置坏了要响
|
||||
verdict("chunkbudget.broken", "预算来源 : DEGRADED", False, cb["broken"]) # 且不许冒充「没有 budget」——阶段 17 锚定,见上方 ⚠
|
||||
verdict("chunkbudget.nodist", "NO-DIST", True, cb["nodist"]) # 没构建等于没量
|
||||
verdict("chunkbudget.empty", "EMPTY", True, cb["empty"]) # 空产物不许算过
|
||||
verdict("chunkbudget-real", "OVER", False, cb["real"]) # 真产物必须静音(恒红=噪音)
|
||||
verdict("chunkbudget-real", "CHUNKBUDGET OK", True, cb["real"])
|
||||
# ↓ 来源 C(阶段 24):登记文件必须真的被读到、真的参与判定、坏了真的会响
|
||||
verdict("chunkbudget.proj", "OVER assets/big.js", True, cb["proj"]) # 10 kB 预算下必须越界
|
||||
verdict("chunkbudget.proj", "proj-good.json · budget = 10000 B=10.00 kB", True, cb["proj"]) # 来源行必须点名登记文件(钉字段)
|
||||
verdict("chunkbudget.proj", "预算来源 : DEGRADED", False, cb["proj"]) # 读到登记值就不许再挂退化
|
||||
verdict("chunkbudget.proj-broken", "BUDGET-FILE-BAD", True, cb["proj-broken"]) # 登记文件坏了要响
|
||||
verdict("chunkbudget.proj-broken", "预算来源 : DEGRADED", False, cb["proj-broken"]) # 不许冒充「没有预算」
|
||||
verdict("chunkbudget.proj-missing", "BUDGET-FILE-MISSING", True, cb["proj-missing"]) # 显式指定却找不到 = 错,不是退化
|
||||
verdict("chunkbudget.proj-empty", "BUDGET-FILE-EMPTY", True, cb["proj-empty"]) # 文件在而没 budget 键 = 没有预算,必须响
|
||||
verdict("chunkbudget.proj-shape", "BUDGET-FILE-SHAPE", True, cb["proj-shape"]) # 原值读不出正数 = 不猜单位,必须响
|
||||
verdict("chunkbudget-real", "chunk-budget.json · budget", True, cb["real"]) # 真产物走来源 C(挂账③ 销账)
|
||||
verdict("chunkbudget-real", "预算来源 : DEGRADED", False, cb["real"]) # 且不再退化到脚本常数
|
||||
|
||||
# ── 判据 ㉗(阶段 31 · Bundle 结案):归属尺的「磁盘对账自证」必须真的在看东西。
|
||||
# 全部钉在尺子的机器可读行(`ATTRIB_*`)与判定语上,不钉散文(阶段 17 的教训)。
|
||||
ci = chunkinfo_static()
|
||||
verdict("chunkinfo.suspect", "ATTRIB_SUSPECT=1", True, ci["suspect"]) # 12 B 源被记 401 B 必须点名
|
||||
verdict("chunkinfo.suspect", "ATTRIB_VERDICT=SUSPECT", True, ci["suspect"])
|
||||
verdict("chunkinfo.suspect", "ATTRIB_COVERAGE=1/1 (100.0%)", True, ci["suspect"]) # 覆盖率本身要能读出来
|
||||
verdict("chunkinfo.suspect-strict", "exit=1", True, ci["suspect-strict"]) # 显式 strict 才升级退出码
|
||||
verdict("chunkinfo.good", "ATTRIB_SUSPECT=0", True, ci["good"])
|
||||
verdict("chunkinfo.good", "没有「源文件装不下」的伪像", True, ci["good"]) # 好形状必须仍敢下结论
|
||||
verdict("chunkinfo.good", "ATTRIB_VERDICT=SUSPECT", False, ci["good"])
|
||||
verdict("chunkinfo.good-strict", "exit=0", True, ci["good-strict"])
|
||||
# ↓ 这一组才是本轮翻案的正主:覆盖率塌了必须自称空转,不许冒充「没有伪像」
|
||||
verdict("chunkinfo.idle", "ATTRIB_VERDICT=IDLE", True, ci["idle"])
|
||||
verdict("chunkinfo.idle", "ATTRIB_COVERAGE=0/1", True, ci["idle"])
|
||||
verdict("chunkinfo.idle", "没有「源文件装不下」的伪像", False, ci["idle"])
|
||||
verdict("chunkinfo.idle", "本条自证空转", True, ci["idle"])
|
||||
verdict("chunkinfo.idle-strict", "exit=1", True, ci["idle-strict"])
|
||||
verdict("chunkinfo.real-idle", "ATTRIB_VERDICT=IDLE", False, ci["real"]) # 真产物不许空转
|
||||
verdict("chunkinfo.real-idle", "本条自证空转", False, ci["real"])
|
||||
|
||||
# ── 判据 ㉘(阶段 33 · 第 14 道常驻探针 `projectswitchcheck`):
|
||||
# 这条闸门的三条判据全部站在同一个探测器 `matches()` 上——它要退化成长驻 True
|
||||
# (把上一个项目的残留判成正常)或恒 False(三条判据一起空转,页面怎么改都绿),
|
||||
# 常驻探针就只剩「跑了一遍」这个外观。探测器是纯函数,喂合成读数即可,
|
||||
# 不吃页面、不吃数据库,因此两头都能钉死:命中面必须命中、不命中面必须不命中。
|
||||
ps_ok, ps_line = projectswitchcheck.selftest()
|
||||
verdict("projectswitchcheck.matches", "SELFTEST OK", True, ps_line)
|
||||
verdict("projectswitchcheck.matches", "SELFTEST FAIL", False, ps_line)
|
||||
print(f" 探测器自证 9 例(命中/不命中/骨架/半挂载/整行多余列/空指纹/状态变了)→ {ps_line}")
|
||||
|
||||
if fails:
|
||||
print("GATEPROBE_FAIL", " ".join(fails))
|
||||
print("→ 闸门本身出问题:不是漏检(豁免写宽了)就是误报(豁免没生效),先修闸门")
|
||||
return 1
|
||||
print(f"GATEPROBE_OK {len(checks) + 1}/{len(checks) + 1} 闸门坏了会响、好了不响")
|
||||
print(f"GATEPROBE_OK {len(checks) + 11}/{len(checks) + 11} 闸门坏了会响、好了不响")
|
||||
return 0
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ ROUTES = [r for r in os.environ.get(
|
|||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||||
"/projects/{id}/timeline,/projects/{id}/delivery,/account,/users,/help").split(",") if r]
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
OUT = pathlib.Path(os.environ.get("NEX_SHOTS", "/tmp/nex_ui_grid")); OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
PROJECT_JS = r"""async () => {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
|
||||
用法:`.venv/bin/python scripts/ui/helpshots.py [输出目录]`
|
||||
默认直写 `frontend/public/help/`;给一个目录就落在那儿,先人工过一眼再覆盖。
|
||||
前置:dev `vite :5173` + 后端 `:8000` 在跑,账号 admin/admin1234。
|
||||
前置:dev `vite :5173` + 后端 `:8000` 在跑,账号 admin/admin@123。
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
|
|
@ -79,7 +79,7 @@ def login(pg) -> None:
|
|||
pg.evaluate("() => localStorage.setItem('nex-the','light')")
|
||||
pg.goto(BASE + "/login", wait_until="networkidle")
|
||||
pg.fill("#login-user", "admin")
|
||||
pg.fill("#login-pass", "admin1234")
|
||||
pg.fill("#login-pass", "admin@123")
|
||||
pg.click("button[type=submit]")
|
||||
pg.wait_for_url(BASE + "/")
|
||||
pg.wait_for_timeout(800)
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ from playwright.async_api import async_playwright # noqa: E402
|
|||
import metrics as M # noqa: E402
|
||||
|
||||
BASE = os.environ.get("NEX_UI_BASE", "http://localhost:5173")
|
||||
LOGIN = ("admin", "admin1234")
|
||||
LOGIN = ("admin", "admin@123")
|
||||
# 样例项目:有分镜、有素材、有流程数据,量出来的才是有内容的页面
|
||||
PROJ = os.environ.get("NEX_UI_PROJECT", "10")
|
||||
|
||||
|
|
|
|||
|
|
@ -235,7 +235,7 @@ async def login(pg):
|
|||
"""真登录一次(拿 localStorage 里的 token),后面所有路由都按登录态量。"""
|
||||
await pg.goto("/login")
|
||||
await pg.fill("#login-user", "admin")
|
||||
await pg.fill("#login-pass", "admin1234")
|
||||
await pg.fill("#login-pass", "admin@123")
|
||||
async with pg.expect_response(lambda r: "/api/auth/login" in r.url, timeout=180000) as info:
|
||||
await pg.click(".ant-btn-primary")
|
||||
await info.value
|
||||
|
|
|
|||
|
|
@ -0,0 +1,415 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""项目切换的数据生命周期(第 14 道常驻探针 · 2026-11-10 · NEX 阶段 33 · 用户第 2 条)。
|
||||
|
||||
为什么要有这一道(真缺陷,不是假想敌):
|
||||
store 里「路由现在是哪个项目」和「手上这份数据属于哪个项目」以前是**同一个字段**。
|
||||
同一次会话里从 A 切到 B(点项目列表的链接、点平台动态里的那条、点概况抽屉里的七站跳转,
|
||||
走的都是 react-router 的 in-app transition,不重载页面):`id` 立刻变成 B,
|
||||
而 `project` / `workflow` / `stats` 还是 A —— 概览页于是把上一个项目的 12 个节点
|
||||
顶在 B 的地址下面(改前实测命中 +40 / +80 ms 两次)。
|
||||
更糟的是 B 已经被别处删掉:详情 404 只写 `error`,`project` 永远停在 A,
|
||||
「未找到项目」永远出不来。这不是理论——项目列表 20 秒自刷
|
||||
(`pages/Dashboard.tsx` 的 `useAutoRefresh`),另一个标签页删掉项目之后,
|
||||
这一行的链接最多 20 秒内还在,点下去就是这一条。
|
||||
改前读数:`reports/ui_evidence/nex-p33/projspa_before.log`(缺陷 2 条)。
|
||||
修法:`stores/project.ts` 增加 `loadedId`(只在拉成功时与数据同写、同清),
|
||||
非 silent 换项目先清(由 `ProjectDetail.tsx` 既有的骨架态接管),
|
||||
消费方比 `loadedId` 而不是 `project?.id`;再加请求序号,旧响应不许盖新数据。
|
||||
|
||||
没有常驻闸,「先清」这一句会在下一次重构里被静默删掉:它不影响任何单页首次载入,
|
||||
只有**换项目**才看得出来,而换项目恰好没人截图。
|
||||
|
||||
三条判据(退出码 = 缺陷条数,0 = 全绿):
|
||||
|
||||
① 换项目不残留 路由已经在 B,页面节点表就不许等于 A 的节点指纹。
|
||||
中途允许的是「这份数据还不可用」的形态(骨架 / 空表),不是 A 的旧数据。
|
||||
落定必须是 B 的真值(`SETTLE_MS` 内等不到才算缺陷,避免慢机器假红)。
|
||||
② 404 必须认错 切到一个详情 404 的项目:必须出现「未找到项目」的 Empty,
|
||||
节点表必须清空,顶栏胶囊必须退成「项目 #<路由号>」而不是上一个项目的名字;
|
||||
并且**切回真项目要能恢复**(证明 store 没被一次失败永久污染)。
|
||||
③ 静置不许闪 停在同一个项目上跨过一整轮 6 秒轮询(`IDLE_MS`,默认 8 秒):
|
||||
节点表必须一直在,不许出现骨架。这条钉的是反向退化——
|
||||
有人把「清」加到 silent 通道上,就会变成每 6 秒整屏闪一次骨架。
|
||||
|
||||
判据用的探测器 `matches()` 是纯函数,夹具与自证在同文件的 `selftest()`,
|
||||
由 `scripts/ui/gateprobe.py` 判据 ㉘ 反向验证(它退化成长驻 True / 恒 False 时自证必须红)。
|
||||
|
||||
环境要求:一台跑着的前端(默认 :5173)+ 库里至少两个「节点指纹不同」的项目。
|
||||
凑不齐时直接 EXIT=2 并说明原因,不伪装成绿(§15.1「恒 0 也要说出来」的反面:没量到要说没量到)。
|
||||
切换用 pushState + popstate:react-router 就是靠 popstate 走 in-app transition,
|
||||
与点内链走的是同一条路径,不新增 Tab 停靠点、不改任何业务操作。
|
||||
|
||||
NEX_BASE=http://127.0.0.1:5173 .venv/bin/python scripts/ui/projectswitchcheck.py
|
||||
NEX_SHOTS=/tmp/p34 NEX_THEME=dark … # 顺手落三张过程截图(切换途中 / 落定 / 404)。
|
||||
「切换途中」那张是三条判据跑完之后的**证据补拍**:重新走一遍 A→B、在 +80 ms 处读一次并截图,
|
||||
不参与任何判据(采样窗口只有几十毫秒,截图本身比窗口长,量了就不准)。它的作用是让人眼直接看到
|
||||
「清空期显示的是骨架 / 空表,不是上一个项目的节点」——把这条突变回改前行为,同一张图就变成残留。
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[1]
|
||||
|
||||
|
||||
def _load(name, rel):
|
||||
spec = importlib.util.spec_from_file_location(name, str(ROOT / rel))
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
sc = _load("nex_semanticcheck_for_login", "scripts/ui/semanticcheck.py")
|
||||
|
||||
BASE = os.environ.get("NEX_BASE", sc.BASE)
|
||||
WIDTH = int(os.environ.get("NEX_WIDTH", "1440"))
|
||||
IDLE_MS = int(os.environ.get("NEX_IDLE_MS", "8000"))
|
||||
SETTLE_MS = int(os.environ.get("NEX_SETTLE_MS", "8000"))
|
||||
SHOTS = pathlib.Path(os.environ["NEX_SHOTS"]) if os.environ.get("NEX_SHOTS") else None
|
||||
THEME = os.environ.get("NEX_THEME", "") # light / dark;只影响截图,判据与主题无关
|
||||
GHOST = os.environ.get("NEX_GHOST_ID", "999999") # 详情必然 404 的项目号
|
||||
|
||||
# 概览页节点表每行的「状态 | 名字 key」前缀 = 这个项目的节点指纹。
|
||||
# 认 key(`import_script` 这类稳定英文标识)而不是认中文状态,是为了让「同一批节点、
|
||||
# 状态变了」也算换了指纹——那正是「显示的是不是这一份数据」要看的东西。
|
||||
STATE_CN = {"done": "已完成", "active": "进行中", "failed": "需处理", "pending": "待处理"}
|
||||
|
||||
READ = r"""() => {
|
||||
const tx = (e) => (e && e.innerText || '').replace(/\s+/g, ' ').trim();
|
||||
const rows = [...document.querySelectorAll('.nex-table tbody tr')]
|
||||
.map(tr => [...tr.querySelectorAll('td')].map(tx)).filter(r => r.length);
|
||||
// 概览页的「流程节点明细」表:认「名字 key」那一列,别的表不算
|
||||
const nodes = rows.map(r => r.join(' | ')).filter(s => /[a-z_]{4,}/.test(s));
|
||||
return {
|
||||
url: location.pathname,
|
||||
rows: rows.length,
|
||||
nodes: nodes,
|
||||
firstCells: (rows[0] || []).slice(0, 4),
|
||||
skeleton: !!document.querySelector('.ant-skeleton'),
|
||||
notFound: document.body.innerText.includes('未找到项目'),
|
||||
hdr: tx(document.querySelector('header')).slice(0, 160),
|
||||
obs: window.__nexObs ? { removedTR: window.__nexObs.removedTR,
|
||||
batches: window.__nexObs.batches } : null
|
||||
};
|
||||
}"""
|
||||
|
||||
LIST = r"""async () => {
|
||||
const j = await (await fetch('/api/projects')).json();
|
||||
const list = j.projects || (j.result || {}).projects || [];
|
||||
// 列表接口自带 workflow(与详情接口同源);取 state/label/key 三样拼指纹
|
||||
return list.map(p => ({ id: String(p.id), name: p.name,
|
||||
workflow: (p.workflow || []).map(n => ({ state: n.state, label: n.label, key: n.key })) }));
|
||||
}"""
|
||||
|
||||
NAV = r"""(path) => { history.pushState({}, '', path); dispatchEvent(new PopStateEvent('popstate')); }"""
|
||||
|
||||
# 为什么要有观察器:本地接口一次往返只有几毫秒,「清 → 立刻填回来」的窗口比任何
|
||||
# 轮询采样都短——实测把「清」错加到 silent 通道上(每 6 秒清一次),400 ms 采一次
|
||||
# 采 20 次一次都没抓到(`/tmp/p34/mutB.log` 缺陷 0),③ 于是成了一条看不见的闸。
|
||||
# MutationObserver 不吃采样运气:行被摘掉一次就记一次。
|
||||
# 只数「被摘掉的 <tr>」,不数文字变化——轮询把相对时间从「4 分钟前」刷成「5 分钟前」
|
||||
# 是 characterData,不是重挂载,那是正常行为,不能算闪。
|
||||
ARM = r"""() => {
|
||||
// 只数「和节点表那一族有关的移除」:被摘掉的整行 <tr>,或装着它的更大块
|
||||
// (ProjectDetail 换骨架时会把整个内容子树一起摘走——那是一次 childList
|
||||
// 变化,发生在被观察节点的**祖先**上;MutationObserver 不看祖先,
|
||||
// 所以观察面必须直接铺在 body 上,否则「清空」这件事恰好看不见)。
|
||||
const isNodeRow = (tr) => /[a-z_]{4,}/.test(tr.textContent || '');
|
||||
const rowish = (n) => {
|
||||
if (!n || n.nodeType !== 1) return false;
|
||||
if (n.tagName === 'TR') return isNodeRow(n);
|
||||
if (!n.querySelector) return false;
|
||||
return [...n.querySelectorAll('tr')].some(isNodeRow);
|
||||
};
|
||||
const bodies = [...document.querySelectorAll('.nex-table tbody')]
|
||||
.filter(tb => [...tb.querySelectorAll('tr')].some(isNodeRow));
|
||||
if (!bodies.length) return { armed: false, why: '页面上找不到节点表 tbody' };
|
||||
window.__nexObs = { removedTR: 0, batches: 0, bodies: bodies.length };
|
||||
window.__nexConn && window.__nexConn.disconnect();
|
||||
window.__nexConn = new MutationObserver((list) => {
|
||||
for (const m of list) {
|
||||
let hit = 0;
|
||||
for (const n of m.removedNodes) if (rowish(n)) hit++;
|
||||
if (hit) { window.__nexObs.batches++; window.__nexObs.removedTR += hit; }
|
||||
}
|
||||
});
|
||||
window.__nexConn.observe(document.body, { childList: true, subtree: true });
|
||||
return { armed: true, bodies: bodies.length };
|
||||
}"""
|
||||
|
||||
SET_THEME = r"""(mode) => {
|
||||
if (!mode) return document.documentElement.getAttribute('data-theme');
|
||||
localStorage.setItem('nex-the', mode);
|
||||
document.documentElement.setAttribute('data-theme', mode);
|
||||
return mode;
|
||||
}"""
|
||||
|
||||
|
||||
def fingerprint(workflow):
|
||||
"""节点指纹:逐项「<中文状态> | <label> <key>」,只取前两列能拼出来的部分。"""
|
||||
return [f"{STATE_CN.get(n['state'], n['state'])} | {n['label']} {n['key']}" for n in workflow]
|
||||
|
||||
|
||||
def matches(read, fp):
|
||||
"""页面读数是否就是这份节点指纹(按「状态 | 名字 key」前缀逐行比)。
|
||||
|
||||
口径两条,都是被假阳性教出来的:
|
||||
· `len(nodes) < len(fp)` 直接 False —— 骨架 / 半挂载时 nodes 是空的,
|
||||
它「不等于 A」也「不等于 B」,是「数据还不可用」的第三种形态,不许算命中任何一方;
|
||||
· 只比**前缀**不比整行 —— 行里第三列往后是产出物计数、时间戳(相对时间会自己走字),
|
||||
拿整行比会把自己走的时间读成「换了一个项目」。
|
||||
"""
|
||||
if not fp or len(read.get("nodes") or []) < len(fp):
|
||||
return False
|
||||
for got, want in zip(read["nodes"], fp):
|
||||
if not got.startswith(want):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def selftest():
|
||||
"""探测器两头都要灵:恒 True(把残留当正常)与恒 False(三条判据全空转)都必须被抓到。"""
|
||||
a = ["已完成 | 导入脚本 import_script", "进行中 | 分镜生成 storyboard"]
|
||||
b = ["待处理 | 导入脚本 import_script"]
|
||||
rd = lambda rows: {"nodes": rows}
|
||||
cases = [
|
||||
("A面相等→命中", matches(rd(a), a) is True),
|
||||
("B面相等→命中", matches(rd(b), b) is True),
|
||||
("显示A时不算B→不命中", matches(rd(a), b) is False),
|
||||
("显示B时不算A→不命中", matches(rd(b), a) is False),
|
||||
("骨架(空表)→谁都不命中", matches(rd([]), a) is False and matches(rd([]), b) is False),
|
||||
("半挂载(行数不够)→不命中", matches(rd([a[0]]), a) is False),
|
||||
("整行多出来的列不影响→命中", matches(rd([x + " | 3 个 | 4 分钟前" for x in a]), a) is True),
|
||||
("空指纹不许命中任何东西→不命中", matches(rd(a), []) is False),
|
||||
("某一行状态变了→不命中", matches(rd([b[0], a[1]]), a) is False),
|
||||
]
|
||||
bad = [n for n, ok in cases if not ok]
|
||||
line = (f"SELFTEST OK {len(cases)}/{len(cases)}" if not bad
|
||||
else f"SELFTEST FAIL {len(bad)}/{len(cases)} " + ",".join(bad))
|
||||
return (not bad), line
|
||||
|
||||
|
||||
def pick(truth):
|
||||
"""挑两个节点指纹真的不同的项目——指纹相同就等于页面分不出显示的是谁的数。"""
|
||||
ids = [i for i, t in truth.items() if t["fp"]]
|
||||
for i in ids:
|
||||
for j in ids:
|
||||
if i != j and truth[i]["fp"] != truth[j]["fp"]:
|
||||
return i, j
|
||||
return None, None
|
||||
|
||||
|
||||
def shot(page, name):
|
||||
if not SHOTS:
|
||||
return
|
||||
SHOTS.mkdir(parents=True, exist_ok=True)
|
||||
p = SHOTS / f"{name}-{WIDTH}{('-' + THEME) if THEME else ''}.png"
|
||||
page.screenshot(path=str(p))
|
||||
print(f" 截图 {p}")
|
||||
|
||||
|
||||
def main():
|
||||
defects, ev = [], {"base": BASE, "width": WIDTH, "idle_ms": IDLE_MS, "settle_ms": SETTLE_MS}
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.launch()
|
||||
ctx = b.new_context(viewport={"width": WIDTH, "height": 1000})
|
||||
page = ctx.new_page()
|
||||
sc.login(page)
|
||||
if THEME:
|
||||
page.goto(BASE + "/", wait_until="domcontentloaded")
|
||||
page.evaluate(SET_THEME, THEME)
|
||||
page.goto(BASE + "/", wait_until="networkidle")
|
||||
page.wait_for_timeout(1500)
|
||||
raw = page.evaluate(LIST)
|
||||
truth = {t["id"]: {**t, "fp": fingerprint(t["workflow"])} for t in raw}
|
||||
A, B = pick(truth)
|
||||
if not A:
|
||||
print(f"没有两个节点指纹不同的项目(共 {len(raw)} 个项目)⇒ 页面分不出显示的是谁的数,无法判定")
|
||||
print("SUMMARY 项目数=%d 缺陷=? 判定=无法判定" % len(raw))
|
||||
return 2
|
||||
na, nb = truth[A]["name"], truth[B]["name"]
|
||||
print(f"项目切换的数据生命周期 | A=#{A}「{na}」节点 {len(truth[A]['fp'])} 个"
|
||||
f" | B=#{B}「{nb}」节点 {len(truth[B]['fp'])} 个 | base {BASE} · {WIDTH}px"
|
||||
f"{' · ' + THEME if THEME else ''}")
|
||||
|
||||
# ── ③ 静置不许闪:停在 A 上跨过一整轮轮询 ─────────────────────────────
|
||||
page.goto(f"{BASE}/projects/{A}/overview", wait_until="networkidle")
|
||||
page.wait_for_timeout(1500)
|
||||
armed3 = page.evaluate(ARM)
|
||||
if not armed3.get("armed"):
|
||||
defects.append(f"③ 观察器布不下去({armed3.get('why')})⇒ 静置判据是空转")
|
||||
print(f"③ 观察器:{armed3}")
|
||||
stable = page.evaluate(READ)
|
||||
ok_stable = matches(stable, truth[A]["fp"])
|
||||
flick = []
|
||||
n_idle = max(int(IDLE_MS / 400), 4)
|
||||
for _ in range(n_idle):
|
||||
page.wait_for_timeout(400)
|
||||
r = page.evaluate(READ)
|
||||
if r["skeleton"] or not matches(r, truth[A]["fp"]):
|
||||
flick.append((r["skeleton"], len(r["nodes"])))
|
||||
after3 = page.evaluate(READ)
|
||||
dropped = (after3["obs"] or {}).get("removedTR", 0) if armed3.get("armed") else None
|
||||
ok_final3 = matches(after3, truth[A]["fp"])
|
||||
print(f"\n③ 停在 A 不动 {IDLE_MS} ms(覆盖一轮 6 s 轮询,采样 {n_idle} 次):"
|
||||
f"起始节点表 {len(stable['nodes'])} 行 | 与 A 真值一致={ok_stable}"
|
||||
f" | 采样抓到骨架/换数据={len(flick)} 次"
|
||||
f" | 观察器数到「节点行被摘掉」={dropped} 次(批 {after3['obs']['batches'] if after3['obs'] else '-'})")
|
||||
if dropped and ok_final3:
|
||||
defects.append(f"③ 静置期间节点表被重挂载 {dropped} 次(轮询把数据清了又填回来,"
|
||||
f"采样窗口太短看不见,只有观察器抓得到)")
|
||||
elif dropped:
|
||||
print(f" 观察器数到 {dropped} 次摘行,但结束时数据已不等于 A ⇒ 期间项目本身变了,不立案")
|
||||
if not ok_stable:
|
||||
print(f" 页面首行:{stable['firstCells']}\n 真值首行:{truth[A]['fp'][:1]}")
|
||||
defects.append("③ 停在项目概览时节点表与该项目真值不符(基线就不对,后面无法判)")
|
||||
if flick:
|
||||
defects.append(f"③ 静置期间节点表被轮询打断(骨架/换数据){len(flick)} 次:{flick[:3]}")
|
||||
ev["idle"] = {"stable_rows": len(stable["nodes"]), "samples": n_idle, "flicker": flick,
|
||||
"armed": armed3, "removedTR": dropped, "batches": (after3["obs"] or {}).get("batches")}
|
||||
|
||||
# ── ① SPA 内 A→B:细粒度采样找残留 ──────────────────────────────────
|
||||
page.goto(f"{BASE}/projects/{A}/overview", wait_until="networkidle")
|
||||
page.wait_for_timeout(1500)
|
||||
armed1 = page.evaluate(ARM)
|
||||
page.evaluate(NAV, f"/projects/{B}/overview")
|
||||
seen = []
|
||||
tms = [40, 80, 120, 180, 260, 360, 500, 700, 1000, 1500]
|
||||
prev = 0
|
||||
for ms in tms:
|
||||
page.wait_for_timeout(max(ms - prev, 10))
|
||||
prev = ms
|
||||
r = page.evaluate(READ)
|
||||
seen.append((ms, r))
|
||||
print(f"\n① +{ms:>4}ms url={r['url']:<26} 行{len(r['nodes']):>3} 骨架={str(r['skeleton']):<5}"
|
||||
f" A的数据={str(matches(r, truth[A]['fp'])):<5} B的数据={matches(r, truth[B]['fp'])}")
|
||||
settled_at = None
|
||||
if not matches(seen[-1][1], truth[B]["fp"]):
|
||||
extra = 250
|
||||
waited = prev
|
||||
while waited < SETTLE_MS:
|
||||
page.wait_for_timeout(extra)
|
||||
waited += extra
|
||||
r = page.evaluate(READ)
|
||||
if matches(r, truth[B]["fp"]):
|
||||
settled_at = waited
|
||||
seen.append((waited, r))
|
||||
print(f"① 追加等待 +{waited} ms 后落定是 B(慢机器兜底,上限 {SETTLE_MS} ms)")
|
||||
break
|
||||
stale = [ms for ms, r in seen if r["url"] == f"/projects/{B}/overview" and matches(r, truth[A]["fp"])]
|
||||
final = seen[-1][1]
|
||||
saw_clear = [ms for ms, r in seen if r["url"] == f"/projects/{B}/overview" and r["skeleton"]]
|
||||
print(f"\n① 路由已在 B 却显示 A 的节点:{len(stale)} 次 {stale}"
|
||||
f" | 落定是 B={matches(final, truth[B]['fp'])}"
|
||||
f" | 中途看到「数据不可用」形态(骨架):{len(saw_clear)} 次 {saw_clear[:4]}"
|
||||
+ ("" if saw_clear else "(一次都没采到 ⇒ 清空窗口短于采样粒度,不作为缺陷)"))
|
||||
if stale:
|
||||
print(f" 首个残留样本首行:{seen[tms.index(stale[0])][1]['firstCells']}")
|
||||
defects.append(f"① SPA 内已切到 B 但概览仍显示 A 的节点,命中 {len(stale)} 次:+{stale}ms")
|
||||
if not matches(final, truth[B]["fp"]):
|
||||
print(f" 落定首行:{final['firstCells']}\n B 真值首行:{truth[B]['fp'][:1]}")
|
||||
defects.append(f"① SPA 切换落定后概览不是 B 的节点(等满 {SETTLE_MS} ms 仍不是)")
|
||||
obs1 = final.get("obs") or {}
|
||||
print(f"① 观察器正对照:切换途中数到「节点行被摘掉」{obs1.get('removedTR')} 次"
|
||||
f" | 采样看到骨架 {len(saw_clear)} 次 | 观察器布上={armed1.get('armed')}")
|
||||
if armed1.get("armed") and not obs1.get("removedTR") and not saw_clear:
|
||||
defects.append("① 切换途中既没采到骨架、观察器也没数到摘行 ⇒ 观察器是瞎的,"
|
||||
"③ 那条「静置不许闪」从此不可信(先修取证,别信绿灯)")
|
||||
shot(page, "switch-settled")
|
||||
# 顶栏胶囊:换项目途中不许还写着上一个项目的名字
|
||||
# (阶段 33 把总控台 / 概况抽屉两处 `project?.id === id` 收敛成 `loadedId === id`,这条钉住它)
|
||||
comparable = bool(na) and na not in nb and nb not in na
|
||||
pill_bad = ([ms for ms, r in seen if comparable and r["url"] == f"/projects/{B}/overview"
|
||||
and na in r["hdr"]] if comparable else [])
|
||||
if not comparable:
|
||||
print(f"① 顶栏胶囊检查跳过:A「{na}」与 B「{nb}」互为子串,分不出写的是谁的名字")
|
||||
else:
|
||||
print(f"① 顶栏胶囊仍写着 A 的项目名:{len(pill_bad)} 次 {pill_bad[:4]}"
|
||||
f" | 落定顶栏「{final['hdr'][:60]}」")
|
||||
if pill_bad:
|
||||
defects.append(f"① 路由已在 B,顶栏胶囊仍显示 A「{na}」,命中 {len(pill_bad)} 次:+{pill_bad[:4]}ms")
|
||||
ev["switch"] = {
|
||||
"samples": [{"ms": ms, "url": r["url"], "rows": len(r["nodes"]), "skeleton": r["skeleton"],
|
||||
"isA": matches(r, truth[A]["fp"]), "isB": matches(r, truth[B]["fp"]),
|
||||
"hdr": r["hdr"]} for ms, r in seen],
|
||||
"settled_at_ms": settled_at if settled_at else prev,
|
||||
"clear_window_samples": saw_clear,
|
||||
"comparable_names": comparable,
|
||||
"pill_stale_samples": pill_bad,
|
||||
"observer_control": {"armed": armed1, **obs1}}
|
||||
|
||||
# ── ② 切到详情 404 的项目,再切回真项目 ─────────────────────────────
|
||||
page.goto(f"{BASE}/projects/{B}/overview", wait_until="networkidle")
|
||||
page.wait_for_timeout(1500)
|
||||
before = page.evaluate(READ)
|
||||
page.evaluate(NAV, f"/projects/{GHOST}/overview")
|
||||
page.wait_for_timeout(2500)
|
||||
r404 = page.evaluate(READ)
|
||||
stale404 = matches(r404, truth[B]["fp"])
|
||||
print(f"\n② SPA 内切到详情 404 的 #{GHOST}:报「未找到项目」={r404['notFound']}"
|
||||
f" | 骨架={r404['skeleton']} | 节点表 {len(r404['nodes'])} 行"
|
||||
f" | 仍是 B 的节点={stale404}")
|
||||
print(f" 该页顶栏:{r404['hdr']}")
|
||||
print(f" 节点表首行:{r404['firstCells']}")
|
||||
if stale404 and not r404["notFound"]:
|
||||
defects.append("② SPA 内切到不存在的项目后,概览永久停留在上一个项目(B)的节点,且不报「未找到项目」")
|
||||
if not r404["notFound"]:
|
||||
defects.append(f"② 切到详情 404 的 #{GHOST} 没有落到「未找到项目」的 Empty")
|
||||
shot(page, "404-ghost")
|
||||
page.evaluate(NAV, f"/projects/{B}/overview")
|
||||
page.wait_for_timeout(2500)
|
||||
back = page.evaluate(READ)
|
||||
ok_back = matches(back, truth[B]["fp"])
|
||||
print(f"② 从 404 页切回 #{B}:节点表恢复={ok_back}({len(back['nodes'])} 行)")
|
||||
if not ok_back:
|
||||
print(f" 恢复后首行:{back['firstCells']}")
|
||||
defects.append("② 从 404 的项目切回真项目后,概览没有恢复成该项目的节点(一次失败污染了 store)")
|
||||
ev["notfound"] = {"ghost": GHOST, "before_rows": len(before["nodes"]),
|
||||
"read": r404, "recovered": ok_back, "back_rows": len(back["nodes"])}
|
||||
|
||||
# ── 证据补拍(只在 NEX_SHOTS 下跑,不参与判据):切换途中的可见形态 ──
|
||||
if SHOTS:
|
||||
page.goto(f"{BASE}/projects/{A}/overview", wait_until="networkidle")
|
||||
page.wait_for_timeout(1500)
|
||||
page.evaluate(NAV, f"/projects/{B}/overview")
|
||||
page.wait_for_timeout(80)
|
||||
mid = page.evaluate(READ)
|
||||
isA, isB = matches(mid, truth[A]["fp"]), matches(mid, truth[B]["fp"])
|
||||
shot(page, "switch-clear")
|
||||
print(f"\n证据补拍 +80ms(不参与判据)url={mid['url']} 行{len(mid['nodes']):>3}"
|
||||
f" 骨架={mid['skeleton']} A的数据={isA} B的数据={isB}")
|
||||
ev["evidence_clear"] = {"url": mid["url"], "rows": len(mid["nodes"]),
|
||||
"skeleton": mid["skeleton"], "isA": isA, "isB": isB}
|
||||
b.close()
|
||||
|
||||
print(f"\n=== 缺陷 {len(defects)} 条 ===")
|
||||
for d in defects:
|
||||
print(" ✗", d)
|
||||
stale_hits = sum(1 for s in ev["switch"]["samples"] if s["isA"])
|
||||
print(f"SUMMARY 项目数={len(raw)} A=#{A} B=#{B} 采样={len(ev['switch']['samples'])} 残留命中={stale_hits} "
|
||||
f"落定是B={matches(final, truth[B]['fp'])} 404未找到={r404['notFound']} "
|
||||
f"404恢复={ok_back} 静置闪={len(flick)} 缺陷={len(defects)}")
|
||||
# 读数落盘(阶段 36 收口):默认 /tmp/nex_ui_projectswitch,与其余常驻探针的
|
||||
# NEX_SHOTS 口径一致。阶段 33 落地时默认写 HERE —— 跑一次就在 scripts/ui/ 里
|
||||
# 留一个未跟踪的 JSON,白污染一次工作树(阶段 36 实测多出的那一条 ??)。
|
||||
# 优先级:NEX_JSON(整条路径)> NEX_OUT(文件名,可绝对)> 默认目录 + 默认文件名。
|
||||
art = pathlib.Path(os.environ.get("NEX_OUT", f"projectswitchcheck-{WIDTH}.json"))
|
||||
if os.environ.get("NEX_JSON"):
|
||||
out = pathlib.Path(os.environ["NEX_JSON"])
|
||||
elif art.is_absolute():
|
||||
out = art
|
||||
else:
|
||||
out = pathlib.Path(os.environ.get("NEX_SHOTS", "/tmp/nex_ui_projectswitch")) / art
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(ev, ensure_ascii=False, indent=1))
|
||||
print(f"读数落盘 {out}")
|
||||
return len(defects)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -41,7 +41,7 @@ ROUTES = [r for r in os.environ.get(
|
|||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||||
"/projects/{id}/timeline,/projects/{id}/delivery,/account,/users,/help").split(",") if r]
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
OUT = pathlib.Path(os.environ.get("NEX_SHOTS", "/tmp/nex_ui_rhythm")); OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
PROJECT_JS = r"""async () => {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -82,7 +82,7 @@ with sync_playwright() as pw:
|
|||
pg = b.new_page(viewport={'width': WIDTH, 'height': 1000})
|
||||
pg.goto(BASE + '/login', wait_until='networkidle')
|
||||
if pg.locator('#login-user').count():
|
||||
pg.fill('#login-user', 'admin'); pg.fill('#login-pass', 'admin1234')
|
||||
pg.fill('#login-user', 'admin'); pg.fill('#login-pass', 'admin@123')
|
||||
pg.click('button[type=submit]'); pg.wait_for_timeout(1200)
|
||||
pg.evaluate('t => localStorage.setItem("nex-the", t)', THEME)
|
||||
for name, route in PAGES:
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ from playwright.sync_api import sync_playwright
|
|||
BASE = os.environ.get("NEX_BASE", "http://127.0.0.1:5173")
|
||||
WIDTH = int(os.environ.get("NEX_WIDTH", "1440"))
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
ROW_H_MAX = int(os.environ.get("NEX_ROW_H_MAX", "84"))
|
||||
SCROLL_SLACK = int(os.environ.get("NEX_SCROLL_SLACK", "40"))
|
||||
ROUTES = [r for r in os.environ.get(
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ ROUTES = [r for r in os.environ.get(
|
|||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||||
"/projects/{id}/timeline,/projects/{id}/delivery,/account,/users,/help").split(",") if r]
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
|
||||
PROJECT_JS = r"""async () => {
|
||||
const t = localStorage.getItem('nex-auth');
|
||||
|
|
|
|||
|
|
@ -41,6 +41,12 @@ ROUTES = [r for r in os.environ.get(
|
|||
"/projects/{id}/storyboard,/projects/{id}/dispatch,/projects/{id}/review,"
|
||||
"/projects/{id}/timeline,/projects/{id}/delivery,"
|
||||
"/account,/users,/help,/login," + NOT_FOUND_ROUTE).split(",") if r]
|
||||
# 本轮实际出了哪些状态图 / 哪些状态被跳过 —— 收尾自报 STATES=<n> 的账本。
|
||||
# 为什么要记在尺子里:stdout 只打第一档宽度的逐行明细(下面 shot_prefix),
|
||||
# 光看日志数不清状态数,判「几态通过」只能去数 PNG(阶段 22 就是这么写错过结论)。
|
||||
SHOT_LOG: list[str] = []
|
||||
SKIP_LOG: list[str] = []
|
||||
|
||||
# 侧栏导航覆盖到的路由:这些必须有选中项,否则 selectedKeys 断了。
|
||||
# 登录页不在导航里(chromeless),主循环也不跑它——见下面登录前的专用一趟。
|
||||
# 404 也不算:地址压根不在菜单里,侧栏没有选中项才是对的。
|
||||
|
|
@ -59,7 +65,7 @@ def in_nav(path: str, pid: str) -> bool:
|
|||
|
||||
USER = os.environ.get("NEX_USER", "admin")
|
||||
FORCED_PID = os.environ.get("NEX_PROJECT_ID", "")
|
||||
PWD = os.environ.get("NEX_PASS", "admin1234")
|
||||
PWD = os.environ.get("NEX_PASS", "admin@123")
|
||||
# 项目子页一律量「镜头最多」的那个项目:列表第一个往往是刚建的空项目,
|
||||
# 空项目的分镜墙 / 调度清单 / 审核表全是空态,溢出与截断这两类断言等于没测。
|
||||
# 需要指定项目时用 NEX_PROJECT_ID。
|
||||
|
|
@ -510,6 +516,7 @@ def audit(page, route: str, width: int, theme: str, problems: list[str], *,
|
|||
slug = route.strip("/").replace("/", "-") or "home"
|
||||
name = f"{width}-{theme}-{slug}.png"
|
||||
page.screenshot(path=str(SHOTS / name))
|
||||
SHOT_LOG.append(name)
|
||||
if shot_prefix and width == WIDTHS[0]:
|
||||
print(f"shot {name:38} menu={probe['menu']} header={probe['header']}")
|
||||
|
||||
|
|
@ -553,6 +560,7 @@ def main() -> int:
|
|||
page.wait_for_timeout(500)
|
||||
if not page.locator("#login-user").count():
|
||||
problems.append(f"{width}/{theme}/login: 登录表单没渲染(#login-user 不在)")
|
||||
SKIP_LOG.append(f"{width}/{theme}/login 登录表单没渲染")
|
||||
continue
|
||||
audit(page, "/login", width, theme, problems)
|
||||
|
||||
|
|
@ -581,6 +589,7 @@ def main() -> int:
|
|||
pid = page.evaluate(PROJECT_JS)
|
||||
if not pid:
|
||||
print("!! 拿不到项目 id,跳过", r)
|
||||
SKIP_LOG.append(f"{width}/{theme}{r} 拿不到项目 id")
|
||||
continue
|
||||
r = r.replace("{id}", str(pid))
|
||||
page.goto(BASE + r, wait_until="networkidle")
|
||||
|
|
@ -588,6 +597,7 @@ def main() -> int:
|
|||
# 比对 URL:页面自己乱跳(含回潮成「静默重定向回首页」)时别白测一页
|
||||
if not page.url.rstrip("/").endswith(r.rstrip("/")):
|
||||
problems.append(f"{width}/{theme}{r}: 路由不存在,实际落在 {page.url}")
|
||||
SKIP_LOG.append(f"{width}/{theme}{r} 路由不存在")
|
||||
continue
|
||||
if r == NOT_FOUND_ROUTE and not page.get_by_text("页面不存在").count():
|
||||
# 兜底页必须真的说话:只剩空壳或换回跳首页,都算这条兜底没了
|
||||
|
|
@ -595,6 +605,22 @@ def main() -> int:
|
|||
audit(page, r, width, theme, problems, menu_required=in_nav(r, pid))
|
||||
browser.close()
|
||||
|
||||
# ── 状态覆盖自报:日志自己说清这轮量了几态,别再靠人数 PNG ──
|
||||
expected = len(WIDTHS) * len(THEMES) * len(ROUTES)
|
||||
print("\n=== 状态覆盖 ===")
|
||||
print(f"STATES={len(SHOT_LOG)} 档位 {len(WIDTHS)}宽 × {len(THEMES)}色 × "
|
||||
f"{len(ROUTES)}路由 = 期望 {expected} 出图目录 {SHOTS}")
|
||||
for width in WIDTHS:
|
||||
for theme in THEMES:
|
||||
n = sum(1 for x in SHOT_LOG if x.startswith(f"{width}-{theme}-"))
|
||||
flag = "" if n == len(ROUTES) else f" ✗ 少 {len(ROUTES) - n} 态"
|
||||
print(f" {width:>4}/{theme:<5} {n}/{len(ROUTES)}{flag}")
|
||||
for x in dict.fromkeys(SKIP_LOG):
|
||||
print(f" 跳过 {x}")
|
||||
if len(SHOT_LOG) != expected:
|
||||
print(f" !! 状态数不等于期望值({len(SHOT_LOG)}/{expected})⇒ 上面「跳过」逐条核对,"
|
||||
f"缺态的结论不能签")
|
||||
|
||||
print("\n=== :root 尺子 ===")
|
||||
print("(见上方逐行 menu/header)")
|
||||
# 「Failed to load resource」不带 URL,是素材还是接口上面已经分诊过了,这里不再重复计数
|
||||
|
|
|
|||
Loading…
Reference in New Issue