feat(web): deployed functional suite, outliner expansion fix and local-first runs
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Outliner: react-accessible-treeview's controlled expandedIds sync expands a
node together with its parent, then the next pass treats that extra parent id
as removed from the controlled set and collapses the whole branch. Reproduced
as a collapsed tree after ch11 -> ch12 (scene rows complete in React, one
collapsed row in the DOM). Keep OUTLINER_ROOT_ID in the controlled set so both
passes agree, and drop the rows-digest memo that regressed the normal path.
Also arm a bounded post-open OUTLINER_REFRESH loop so the tree settles on rows
of the newly opened Main instead of the previous one.

Tests: web/playwright.deployed.config.ts + web/tests/deployed walk the 31
manual chapters and the 31 capability rows headed against a deployed origin,
and tools/web/run-deployed-functional-tests.mjs preflights, runs and reports.
--local serves the production bundle from web/dist on loopback with the same
COOP/COEP/CORP/CSP headers, so a case costs compile time instead of a 300 MB
download: full local suite 60/60 in 10.3 min, also 60/60 against the deployed
release. Report dirs are resolved absolute and [ch28a]-style tags map to their
chapter.

Area layout: split from the clamped source rect and keep the area switcher
inside a narrow header.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-24 16:12:26 +08:00
parent 570aa2dd54
commit a5f772e18f
162 changed files with 9341 additions and 8 deletions

View File

@@ -0,0 +1,25 @@
# tests/deployed — 线上功能测试用例
运行入口不在本目录,而是仓库根的 `tools/web/run-deployed-functional-tests.mjs`(它做预检、生成报告)。直接跑 Playwright 也可以:
```bash
cd web
DISPLAY=:1 WEB_ORIGIN=https://49.232.250.35:58014 \
npx playwright test --config playwright.deployed.config.ts --workers=1 tests/deployed/01-files.spec.ts
```
## 写作规范
- 标题形如 `"[ch07] …"`:方括号里的 `chNN` 会进入报告的章节覆盖统计;`manual-page`、`preflight-http`、`cap-layout` 等自定义标签同理。
- 每条用例必须至少一个**用户可见**断言:对象数、面数、状态栏文本、下载文件名、OPFS 内容、渲染像素宽度。禁止只断言「元素被点击」。
- 结束前调用 `receipt(testInfo, {...})` 写入 `{status, screenshot, …}`;`shot(page, testInfo, name)` 存关键截图。
- 需要打开工程时用 `openProject(page, path)`(内含启动等待 + `SceneIR` 等待),不要自己写 `waitForTimeout`。
- 默认入口(`gotoApp(page, "native")`)有原生覆盖层,指针点击会被吞掉,须用 `element.click()`。
## 辅助文件
| 文件 | 内容 |
| --- | --- |
| `support/deployed.ts` | `gotoApp`、`waitEngineBoot`、`waitEngineReady`、`openProject`、`openBlend`、`waitForObjects`、`shot`、`receipt`、`opfsProjectIds`、`FIXTURES` |
| `support/chapters.ts` | 手册 31 章的 `CHAPTERS` / `chapter(id)` |
| `support/matrix.ts` | 能力矩阵 31 行的 `CAPABILITIES` |

View File

@@ -0,0 +1,43 @@
import { execFileSync } from "node:child_process";
import path from "node:path";
/**
* Launch parameters shared by the Playwright config and the shared-session
* fixture, so both modes (isolated and reused context) drive the same browser.
*/
export const DEPLOYED_ORIGIN = (process.env.WEB_ORIGIN ?? "https://49.232.250.35:58014").replace(/\/+$/, "");
export const DEPLOYED_VIEWPORT = { width: 1600, height: 900 };
export function chromePath(): string | undefined {
if (process.env.CHROME_PATH) return process.env.CHROME_PATH;
try { return execFileSync("which", ["google-chrome"], { encoding: "utf8" }).trim() || undefined; }
catch { return undefined; }
}
const hardwareArgs = [
"--no-sandbox",
"--use-gl=angle",
"--use-angle=gl",
"--ignore-gpu-blocklist",
"--enable-gpu-rasterization",
"--enable-zero-copy",
"--enable-unsafe-webgpu",
];
const swiftshaderArgs = [
"--no-sandbox",
"--use-gl=swiftshader",
"--enable-unsafe-swiftshader",
"--enable-unsafe-webgpu",
"--enable-dawn-features=allow_unsafe_apis",
"--use-webgpu-adapter=swiftshader",
];
export function browserArgs(): string[] {
const mode = process.env.GPU_MODE ?? (process.env.DISPLAY ? "hardware" : "swiftshader");
return mode === "hardware" ? hardwareArgs : swiftshaderArgs;
}
/** Chromium profile kept between runs: the 300 MB engine is revalidated, not re-downloaded. */
export function profileDir(repoRoot: string): string {
return process.env.DEPLOYED_PROFILE ?? path.join(repoRoot, "web/.cache/deployed-profile");
}

View File

@@ -0,0 +1,46 @@
import fs from "node:fs";
import path from "node:path";
import { REPO_ROOT } from "./deployed";
/**
* The user manual is the coverage yardstick for this suite: every chapter has
* objectives and `checks`, but no selectors, so it is used for grouping and
* acceptance wording, not executed as a script.
*/
export interface ChapterInfo {
id: string;
number: number;
title: string;
part: string;
workspace: string;
checks: string[];
}
interface ManualChapter { id: string; number: number; title: string; workspace: string; checks?: string[] }
interface ManualPart { id: string; title: string; chapterIds: string[] }
interface Manual { chapters: ManualChapter[]; parts: ManualPart[] }
const MANUAL_PATH = path.join(REPO_ROOT, "user-manual/WEB_Blender_Web_Manual_20261113/manual.json");
function load(): ChapterInfo[] {
if (!fs.existsSync(MANUAL_PATH)) throw new Error(`user manual not found: ${MANUAL_PATH}`);
const manual = JSON.parse(fs.readFileSync(MANUAL_PATH, "utf8")) as Manual;
const partOf = new Map<string, string>();
for (const part of manual.parts) for (const id of part.chapterIds) partOf.set(id, part.title);
return manual.chapters.map((chapter) => ({
id: chapter.id,
number: chapter.number,
title: chapter.title,
part: partOf.get(chapter.id) ?? "",
workspace: chapter.workspace,
checks: chapter.checks ?? [],
}));
}
export const CHAPTERS: ChapterInfo[] = load();
export function chapter(id: string): ChapterInfo {
const found = CHAPTERS.find((item) => item.id === id);
if (!found) throw new Error(`manual chapter not found: ${id}`);
return found;
}

View File

@@ -0,0 +1,121 @@
import { test as base, expect, chromium, type BrowserContext, type Page } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";
import { DEPLOYED_ORIGIN, DEPLOYED_VIEWPORT, browserArgs, chromePath, profileDir } from "./browser-options";
import { REPO_ROOT, normalizeApp } from "./deployed";
/**
* Test entry point for the deployed suite.
*
* Loading the deployed bundle costs ~3 minutes per browser context: a 300 MB
* wasm module is downloaded and compiled for every fresh context. Re-running
* that for each of ~60 cases is what made the suite impractically slow, so the
* default mode launches ONE persistent context per worker (Chrome profile on
* disk, so repeat runs only revalidate the wasm with a 304) and every test
* shares its page. Cases reset their own state by opening the project they need.
*
* `DEPLOYED_ISOLATE=1` restores per-test contexts and video capture for the
* rare case where a full recording is worth the reload cost.
*/
const isolated = process.env.DEPLOYED_ISOLATE === "1";
interface Session {
context: BrowserContext;
page: Page;
bootMs: number;
loads: number;
pageErrors: string[];
/** Spec file whose case currently owns the page; a new file reloads it. */
lastFile: string | null;
reloads: number[];
}
/** Worker-scoped: the whole file (and run, with workers=1) reuses one page. */
const sharedSession = base.extend<{ session: Session }, { session: Session }>({
session: [async ({}, use) => {
const context = await chromium.launchPersistentContext(profileDir(REPO_ROOT), {
headless: false,
executablePath: chromePath(),
args: browserArgs(),
viewport: DEPLOYED_VIEWPORT,
baseURL: DEPLOYED_ORIGIN,
acceptDownloads: true,
ignoreHTTPSErrors: process.env.DEPLOYED_IGNORE_HTTPS === "1",
locale: "zh-CN",
});
const page = context.pages()[0] ?? await context.newPage();
const started = Date.now();
await page.goto("/?ui=web", { waitUntil: "domcontentloaded", timeout: 20_000 });
await page.locator("main.blender-app").waitFor({ timeout: 20_000 });
await page.waitForFunction(() => document.body.innerText.includes("WASM ABI: ready"), undefined, { timeout: 30_000 });
const bootMs = Date.now() - started;
/* A crash in a shared page otherwise shows up as a mysterious missing
* element; keep the browser's own errors next to the case. */
const pageErrors: string[] = [];
page.on("pageerror", (error) => { if (pageErrors.length < 20) pageErrors.push(`pageerror: ${error.message}`); });
page.on("console", (message) => { if (message.type() === "error" && pageErrors.length < 20) pageErrors.push(`console: ${message.text()}`); });
const session: Session = { context, page, bootMs, loads: 1, pageErrors, lastFile: null, reloads: [] };
/* The runner reads this to report how much the reuse saved. */
const reportDir = process.env.DEPLOYED_REPORT_DIR;
if (reportDir) {
try {
fs.mkdirSync(reportDir, { recursive: true });
fs.writeFileSync(path.join(reportDir, "session.json"), JSON.stringify({
schemaVersion: 1, mode: "shared-persistent", origin: DEPLOYED_ORIGIN, bootMs, loads: 1,
profile: profileDir(REPO_ROOT), startedAt: new Date().toISOString(),
}, null, 2));
}
catch { /* the report directory is the runner's business */ }
}
await use(session);
await context.close();
}, { scope: "worker" }],
/* Same context, same page: no reload, no recompile between cases. */
page: async ({ session }, use) => { await use(session.page); },
context: async ({ session }, use) => { await use(session.context); },
/* A case inherits layout/preferences from the previous one; put the shell back
* into a known state before it runs.
*
* The first case of each spec file also reloads the page. Sharing one page
* for the whole run is what keeps the suite fast, but area DOM state carries
* across files: in a full run ch12/ch15 waited forever for `treeitem
* BasicCube` even though the same files passed when run alone. A warm reload
* (~2 s, wasm served from the disk profile) restores file-boundary
* conditions without paying for a new context. */
normalize: [async ({ session }, use, testInfo) => {
if (session.lastFile !== testInfo.file) {
const started = Date.now();
await session.page.goto("/?ui=web", { waitUntil: "domcontentloaded", timeout: 30_000 });
await session.page.locator("main.blender-app").waitFor({ timeout: 20_000 });
await session.page.waitForFunction(() => document.body.innerText.includes("WASM ABI: ready"), undefined, { timeout: 30_000 });
session.reloads.push(Date.now() - started);
session.lastFile = testInfo.file;
}
await normalizeApp(session.page);
await use();
}, { auto: true }],
/* Playwright's built-in `trace` fixture already records this context per test
* and keeps the archive only on failure (config: retain-on-failure). Starting
* a second trace here fails with "Tracing has been already started". */
/* Failure screenshot from the shared page, which the runner cannot take itself. */
evidence: [async ({ session }, use, testInfo) => {
await use();
if (testInfo.status !== testInfo.expectedStatus) {
const file = testInfo.outputPath("failure.png");
await session.page.screenshot({ path: file }).catch(() => undefined);
await testInfo.attach("failure-screenshot", { path: file, contentType: "image/png" }).catch(() => undefined);
if (session.pageErrors.length) {
const log = testInfo.outputPath("page-errors.txt");
fs.writeFileSync(log, session.pageErrors.join("\n"));
await testInfo.attach("page-errors", { path: log, contentType: "text/plain" }).catch(() => undefined);
}
}
}, { auto: true }],
});
export const test = isolated ? base : sharedSession;
export { expect };

View File

@@ -0,0 +1,288 @@
import { expect, type Page, type TestInfo } from "@playwright/test";
import fs from "node:fs";
import path from "node:path";
/**
* Shared helpers for the deployed-site functional suite.
*
* Everything here asserts through the DOM and the engine's public status
* elements, so the specs run against the built bundle (no `import("/src/...")`,
* which only exists on a Vite dev server).
*/
export const REPO_ROOT = path.resolve(import.meta.dirname, "../../../..");
export function reportDir(): string {
const explicit = process.env.DEPLOYED_REPORT_DIR;
if (explicit) return explicit;
const day = new Date().toISOString().slice(0, 10).replaceAll("-", "");
return path.join(REPO_ROOT, `tests/golden/DEPLOYED-FUNCTIONAL-${day}`);
}
/** `[ch07] ...` in the test title is the manual chapter a case walks. */
export function caseId(testInfo: TestInfo): string {
const tag = /\[([a-z0-9][a-z0-9-]*)\]/.exec(testInfo.title);
return tag?.[1] ?? testInfo.title.replace(/[^\w.-]+/g, "-").replace(/^-|-$/g, "").slice(0, 72);
}
export async function gotoApp(page: Page, mode: "web" | "native" = "web"): Promise<void> {
/* The shared page already holds the compiled engine. Re-navigating restarts
* it (and left the engine status empty while it came back), so only navigate
* when the entry actually changes. */
const current = new URL(page.url());
const origin = new URL(process.env.WEB_ORIGIN ?? "https://49.232.250.35:58014").origin;
const modeMatches = mode === "web" ? current.searchParams.get("ui") === "web" : !current.searchParams.has("ui");
const hasApp = await page.locator("main.blender-app").count() > 0;
if (current.origin === origin && modeMatches && hasApp) return;
await page.goto(mode === "web" ? "/?ui=web" : "/", { waitUntil: "domcontentloaded", timeout: 20_000 });
await page.locator("main.blender-app").waitFor({ timeout: 20_000 });
}
/**
* The first load of the deployed bundle pulls a ~300 MB wasm module; the
* repository's own deployed checks wait up to 300 s for the same state.
*
* Boot and scene are two different states: at startup the engine opens the
* built-in General template and reports `new General project`; `SceneIR rN`
* appears once a project is actually opened. Waiting for SceneIR right after
* boot blocks forever.
*/
export async function waitEngineBoot(page: Page, timeout = 30_000): Promise<string> {
await page.waitForFunction(() => document.body.innerText.includes("WASM ABI: ready"), undefined, { timeout });
await expect(page.getByTestId("engine-status")).not.toHaveText(/starting/i, { timeout });
return (await page.getByTestId("engine-status").innerText()).trim();
}
export async function waitEngineReady(page: Page, timeout = 30_000): Promise<string> {
await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout });
return (await page.getByTestId("engine-status").innerText()).trim();
}
/**
* The deployed app opens a built-in "General" template on startup, and that
* open can land AFTER the file the user picked, silently replacing it with the
* 3-object template. Waiting for an object count alone is therefore a race; a
* project is considered open only once its active object and object count stay
* put for a couple of polls.
*/
export async function waitSceneStable(
page: Page,
expected: { objects: number; active?: RegExp },
timeout = 30_000,
): Promise<string> {
let last = "";
let streak = 0;
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const text = await page.getByTestId("scene-stats").innerText().catch(() => "");
const objects = Number(text.match(/Objects (\d+)/)?.[1] ?? -1);
const active = /Active ([^·]+?) ·/.exec(text)?.[1]?.trim() ?? "";
const matches = objects === expected.objects && (!expected.active || expected.active.test(active));
streak = matches && text === last ? streak + 1 : matches ? 1 : 0;
last = text;
if (streak >= 4) return text.trim();
await page.waitForTimeout(500);
}
throw new Error(`scene did not settle at Objects ${expected.objects}${expected.active ? ` / ${expected.active}` : ""}; last was "${last}"`);
}
/** The 保存当前工程的修改? prompt blocks scripted opens; open it discarded. */
export async function dismissReplacementPrompt(page: Page): Promise<void> {
const discard = page.getByRole("button", { name: "不保存,继续", exact: true });
const save = page.getByRole("button", { name: "保存后继续", exact: true });
for (let attempt = 0; attempt < 20; attempt += 1) {
if (await discard.isVisible().catch(() => false)) { await discard.click(); return; }
if (await save.isVisible().catch(() => false)) { await save.click(); return; }
await page.waitForTimeout(250);
}
}
/** Boot, then open a project and wait until its scene has settled. */
export async function openProject(
page: Page,
absolutePath: string,
expected?: { objects: number; active?: RegExp },
timeout = 30_000,
): Promise<string> {
await waitEngineBoot(page, timeout);
await openBlend(page, absolutePath);
await dismissReplacementPrompt(page).catch(() => undefined);
/* engine-status also carries transient mode/error text ("模式:Object",
* "Command failed"), so `SceneIR rN` there is not a stable proof that the
* project opened. When the caller states the expected scene, the settled
* scene-stats line is the stronger evidence; keep SceneIR only as the
* fallback for callers that do not. */
if (expected) await waitSceneStable(page, expected, timeout);
else await waitEngineReady(page, timeout);
await recoverOutlinerRows(page);
return (await page.getByTestId("engine-status").innerText()).trim();
}
/**
* Opening a project right after an edit-mode session can leave the native
* Outliner with an empty row list although the scene has objects (diagnosed
* with ch11 -> ch12; the scene-stats line shows the fresh project while the
* tree only carries the collection row). The product ships a 「刷新大纲树」
* entry for exactly this context; use it once, and record whether it recovered
* the rows instead of silently waiting on a tree that will never fill.
*/
export async function recoverOutlinerRows(page: Page, timeout = 8_000): Promise<number> {
/* The product-side fix (an OUTLINER_REFRESH after a successful open) was
* proven with ch11 -> ch12 on release …-uifix2, so the workaround is off by
* default: a missing row list must fail loudly. Opt in only when pinning an
* older release that predates the fix. */
if (process.env.DEPLOYED_OUTLINER_RECOVERY !== "1") return 0;
const rows = page.locator('.outliner-area [role="tree"][aria-label="场景层级"] [role="treeitem"]');
const count = await rows.count().catch(() => 0);
if (count > 1) return count;
const refresh = page.locator('.outliner-area [aria-label="刷新大纲树"]');
if (await refresh.count() === 0) return count;
await refresh.first().dispatchEvent("click").catch(() => undefined);
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const next = await rows.count().catch(() => 0);
if (next > 1) return next;
await page.waitForTimeout(250);
}
return await rows.count().catch(() => 0);
}
export async function openBlend(page: Page, absolutePath: string): Promise<void> {
await page.getByTestId("blend-file-input").setInputFiles(absolutePath);
}
/** Object count must also hold still, so a late template open cannot satisfy it. */
export async function waitForObjects(page: Page, count: number, timeout = 20_000): Promise<void> {
await waitSceneStable(page, { objects: count }, timeout);
}
export async function sceneStats(page: Page): Promise<string> {
return (await page.getByTestId("scene-stats").innerText()).trim();
}
/** Named evidence image, kept beside the report it belongs to. */
export async function shot(page: Page, testInfo: TestInfo, name: string): Promise<string> {
const dir = path.join(reportDir(), "screenshots");
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, `${caseId(testInfo)}-${name}.png`);
await page.screenshot({ path: file, fullPage: false });
return path.relative(REPO_ROOT, file);
}
/** One JSON receipt per case: what was walked, what was seen, where the images are. */
export function receipt(testInfo: TestInfo, data: Record<string, unknown>): void {
const dir = path.join(reportDir(), "receipts");
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, `${caseId(testInfo)}.json`);
fs.writeFileSync(file, JSON.stringify({
schemaVersion: 1,
browser: "chromium-headed",
storage: "OPFS",
caseId: caseId(testInfo),
title: testInfo.title,
origin: process.env.WEB_ORIGIN ?? "https://49.232.250.35:58014",
acceptance: "NOT_CLAIMED",
...data,
}, null, 2));
}
/**
* Browser-mode saves go to OPFS and nowhere else. Returns the project ids the
* origin currently stores, so a case can prove a save happened without
* downloading anything.
*/
export async function opfsProjectIds(page: Page): Promise<string[]> {
return page.evaluate(async () => {
try {
const root = await navigator.storage.getDirectory();
const projects = await root.getDirectoryHandle("projects");
const ids: string[] = [];
for await (const [name] of (projects as unknown as AsyncIterable<[string, FileSystemHandle]>)) ids.push(name);
return ids.sort();
}
catch { return []; }
});
}
export async function clearOPFS(page: Page): Promise<void> {
await page.evaluate(async () => {
try {
const root = await navigator.storage.getDirectory();
for await (const [name] of (root as unknown as AsyncIterable<[string, FileSystemHandle]>)) {
await root.removeEntry(name, { recursive: true });
}
}
catch { /* a fresh context has nothing to clear */ }
});
}
/**
* Bring the app back to a neutral state before a case runs.
*
* The suite shares one persistent browser profile, so layout and preference
* changes survive between cases (that is what makes it fast). A case that walks
* area splitting must therefore start from the built-in layout, and any dialog
* left open by a previous, interrupted case must not swallow its clicks.
*/
export async function normalizeApp(page: Page): Promise<void> {
const app = page.locator("main.blender-app");
if (await app.count() === 0) return;
await page.keyboard.press("Escape").catch(() => undefined);
const preferences = page.getByTestId("preferences-window");
if (await preferences.isVisible().catch(() => false)) {
await page.getByRole("button", { name: "关闭偏好设置", exact: true }).click().catch(() => undefined);
}
/* Test-scoped: keep it well inside the one-minute case budget. */
await ensureDefaultLayout(page, 10_000).catch(() => undefined);
}
/**
* The saved layout is restored from OPFS a moment after boot, so a check that
* runs immediately can still see `default` and then watch it turn `custom`.
* Wait for the built-in four-area grid, resetting a custom layout if one is
* actually applied.
*/
export async function ensureDefaultLayout(page: Page, timeout = 20_000): Promise<void> {
const app = page.locator("main.blender-app");
const grid = page.locator(".workspace-grid");
const deadline = Date.now() + timeout;
let custom = false;
let frames = 0;
while (Date.now() < deadline) {
custom = (await app.getAttribute("data-area-layout")) === "custom";
frames = await grid.locator(":scope > .area-frame").count();
if (!custom && frames === 4) return;
if (custom) await resetAreaLayout(page).catch(() => undefined);
await page.waitForTimeout(400);
}
throw new Error(`layout did not settle to the built-in four areas (custom=${custom}, frames=${frames})`);
}
/**
* 区域 ⋮ → 重置工作区布局.
*
* In the deployed build some area switchers are overlapped by neighbouring
* chrome, and a split can place a frame partly off-screen, so the trigger is
* activated through the DOM (the same handler the button runs) instead of
* relying on hit-testing. Recorded as a UI gap in the status doc.
*/
export async function resetAreaLayout(page: Page, timeout = 15_000): Promise<void> {
const triggers = page.locator(".workspace-grid .area-type-switch .area-menu button");
const count = await triggers.count();
for (let index = 0; index < count; index += 1) {
await triggers.nth(index).dispatchEvent("click").catch(() => undefined);
const reset = page.getByRole("menuitem", { name: "重置工作区布局", exact: true });
if (await reset.count()) { await reset.click({ force: true, timeout }); return; }
await page.keyboard.press("Escape").catch(() => undefined);
}
throw new Error("no area menu exposed 重置工作区布局");
}
export const FIXTURES = {
studio: path.join(REPO_ROOT, "web/app/public/tutorial/pbr/studio.blend"),
basic: path.join(REPO_ROOT, "tests/files/web/basic_scene.blend"),
monkey: path.join(REPO_ROOT, "re/猴头.glb"),
empty: path.join(REPO_ROOT, "tests/files/web/empty.blend"),
nla: path.join(REPO_ROOT, "tests/files/web/nla_time_mapping_scene.blend"),
};

View File

@@ -0,0 +1,30 @@
import fs from "node:fs";
import path from "node:path";
import { REPO_ROOT } from "./deployed";
/** The 31 capability rows that the manual generation and parity checks share. */
export interface CapabilityRow {
area: string;
feature: string;
status: string;
note?: string;
chapter?: string;
}
const MATRIX_PATH = path.join(REPO_ROOT, "tools/web/manual/feature-matrix.json");
function load(): CapabilityRow[] {
if (!fs.existsSync(MATRIX_PATH)) throw new Error(`feature matrix not found: ${MATRIX_PATH}`);
/* The file is an object with metadata (schemaVersion, legend, …) and a
* `capabilities` array; older copies were a bare array. */
const parsed = JSON.parse(fs.readFileSync(MATRIX_PATH, "utf8")) as CapabilityRow[] | { capabilities?: CapabilityRow[] };
const rows = Array.isArray(parsed) ? parsed : parsed.capabilities ?? [];
if (!Array.isArray(rows) || rows.length === 0) throw new Error(`feature matrix has no capabilities: ${MATRIX_PATH}`);
return rows;
}
export const CAPABILITIES: CapabilityRow[] = load();
export function capabilitySlug(row: CapabilityRow): string {
return `${row.area}-${row.feature}`.replace(/[^\w一-龥]+/g, "-").replace(/^-|-$/g, "").slice(0, 48);
}