#!/usr/bin/env node // Runs a manual scenario in the real app, asserts UI state and captures // full-page / element screenshots. Usage: // node capture.mjs --scenario ../../manual/scenarios/ch01-ui.json [--headed] import fs from "node:fs"; import path from "node:path"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { listOpfsFiles, readOpfsFile } from "../carrier-course/lib/opfs.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const webRoot = path.resolve(here, "../.."); const require = createRequire(path.join(webRoot, "package.json")); const { chromium } = require("playwright"); const args = process.argv.slice(2); const option = (name, fallback = "") => { const index = args.indexOf(name); return index < 0 ? fallback : args[index + 1] ?? fallback; }; const scenarioPath = path.resolve(option("--scenario")); if (!fs.existsSync(scenarioPath)) throw new Error(`missing scenario ${scenarioPath}`); const scenario = JSON.parse(fs.readFileSync(scenarioPath, "utf8")); const origin = option("--origin", "http://127.0.0.1:5181"); const headed = args.includes("--headed"); const chapter = scenario.chapter; const workflow = scenario.workflow; const shotDir = path.join(webRoot, "manual", "assets", chapter, workflow); const reportDir = path.join(webRoot, "manual", "data", "capture"); fs.mkdirSync(shotDir, { recursive: true }); fs.mkdirSync(reportDir, { recursive: true }); const sha256 = file => createHash("sha256").update(fs.readFileSync(file)).digest("hex"); async function runOnce() { const browser = await chromium.launch({ executablePath: "/usr/bin/google-chrome", headless: !headed, args: ["--no-sandbox", "--disable-dev-shm-usage", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader", "--window-size=1600,900"], }); const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); const pageErrors = []; const consoleErrors = []; page.on("pageerror", error => pageErrors.push(String(error))); page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); }); const trace = []; const shots = []; const record = entry => trace.push({ at: new Date().toISOString(), ...entry }); const click = async action => { let locator; if (action.role) locator = page.getByRole(action.role, { name: action.name, exact: action.exact }); else { locator = page.locator(action.selector); if (action.hasText) locator = locator.filter({ hasText: action.hasText }); if (action.target) locator = locator.locator(action.target); } if (action.nth !== undefined) locator = locator.nth(action.nth); else if (!action.all) locator = locator.first(); if (action.optional && (await locator.count()) === 0) return; if (action.all) { const count = await locator.count(); for (let index = 0; index < count; index++) await locator.nth(index).click(); } else await locator.click({ timeout: action.timeout ?? 30000 }); }; const shot = async action => { const file = path.join(shotDir, `${action.name}.png`); if (action.selector) { const target = page.locator(action.selector).first(); await target.waitFor({ state: "visible", timeout: 30000 }); await target.screenshot({ path: file }); } else { await page.screenshot({ path: file, fullPage: Boolean(action.fullPage) }); } const stat = fs.statSync(file); if (stat.size < 1024) throw new Error(`screenshot too small: ${file}`); shots.push({ id: `${chapter}/${workflow}/${action.name}`, file: path.relative(webRoot, file), bytes: stat.size, sha256: sha256(file), fullPage: Boolean(action.fullPage), selector: action.selector ?? null }); record({ action: "shot", name: action.name, bytes: stat.size }); }; const save = async action => { await page.evaluate(() => { const details = document.querySelector(".file-tools"); if (details) details.open = true; }); await page.waitForTimeout(400); const before = await listOpfsFiles(page); await page.locator('button:has-text("保存 FCStd 到 OPFS")').first().click(); let after = before; let status = ""; for (let attempt = 0; attempt < 40; attempt++) { await page.waitForTimeout(750); after = await listOpfsFiles(page); status = await page.locator("p.status").first().textContent().catch(() => ""); if (after.some(name => !before.includes(name) && /\.FCStd$/i.test(name)) || /Saved\s+\S+\.FCStd\s+to OPFS/i.test(status ?? "")) break; } const match = /Saved\s+(\S+\.FCStd)\s+to OPFS/i.exec(status ?? ""); const name = match?.[1] ?? after.find(item => !before.includes(item) && /\.FCStd$/i.test(item)); if (!name) throw new Error(`save produced no FCStd; status=${status}`); const bytes = (await readOpfsFile(page, name)).bytes; const fixture = path.join(webRoot, "manual", "fixtures", `${chapter}-${workflow}.FCStd`); fs.mkdirSync(path.dirname(fixture), { recursive: true }); fs.writeFileSync(fixture, Buffer.from(bytes)); record({ action: "save", name, bytes: bytes.length, status }); }; try { for (const action of scenario.actions) { switch (action.type) { case "goto": await page.goto(`${origin}${action.url}`, { waitUntil: "domcontentloaded", timeout: 120000 }); record({ action: "goto", url: action.url }); break; case "waitFor": if (action.selector) await page.waitForSelector(action.selector, { timeout: action.timeout ?? 120000 }); if (action.text) await page.getByText(action.text, { exact: action.exact ?? false }).first() .waitFor({ state: "visible", timeout: action.timeout ?? 120000 }); record({ action: "waitFor", selector: action.selector ?? null, text: action.text ?? null }); break; case "click": await click(action); record({ action: "click", selector: action.selector ?? action.name }); break; case "fill": await page.locator(action.selector).first().fill(String(action.value)); record({ action: "fill", selector: action.selector, value: action.value }); break; case "select": await page.locator(action.selector).first().selectOption(action.label ? { label: action.label } : action.value); record({ action: "select", selector: action.selector, label: action.label ?? action.value }); break; case "press": await page.keyboard.press(action.key); record({ action: "press", key: action.key }); break; case "clickCanvas": { const target = page.locator(action.selector).first(); await target.scrollIntoViewIfNeeded(); await page.waitForTimeout(200); const box = await target.boundingBox(); if (!box) throw new Error(`canvas missing: ${action.selector}`); await page.mouse.click(box.x + box.width * action.fx, box.y + box.height * action.fy); await page.waitForTimeout(action.wait ?? 250); record({ action: "clickCanvas", selector: action.selector, fx: action.fx, fy: action.fy }); break; } case "assertAnyText": { const texts = await page.locator(action.selector).allTextContents(); if (!texts.some(text => String(text).includes(action.contains))) throw new Error(`assertAnyText failed: ${action.contains} in ${JSON.stringify(texts.slice(0, 5))}`); record({ action: "assertAnyText", selector: action.selector, contains: action.contains }); break; } case "drag": { const box = await page.locator(action.selector).first().boundingBox(); if (!box) throw new Error(`drag target missing: ${action.selector}`); const x = box.x + box.width / 2; const y = box.y + box.height / 2; await page.mouse.move(x, y); await page.mouse.down(); await page.mouse.move(x + (action.dx ?? 0), y + (action.dy ?? 0), { steps: 18 }); await page.mouse.up(); await page.waitForTimeout(400); record({ action: "drag", selector: action.selector, dx: action.dx, dy: action.dy }); break; } case "eval": await page.evaluate(action.script); record({ action: "eval" }); break; case "shot": await shot(action); break; case "save": await save(action); break; case "assertText": { const text = await page.locator(action.selector).first().textContent(); if (!String(text ?? "").includes(action.contains)) throw new Error(`assertText failed: ${action.selector} ${text}`); record({ action: "assertText", selector: action.selector, contains: action.contains }); break; } case "assertVisible": await page.locator(action.selector).first().waitFor({ state: "visible", timeout: 30000 }); record({ action: "assertVisible", selector: action.selector }); break; case "assertValue": { const value = await page.locator(action.selector).first().inputValue(); if (String(value) !== String(action.value)) throw new Error(`assertValue failed: ${action.selector} ${value} != ${action.value}`); record({ action: "assertValue", selector: action.selector, value }); break; } case "wait": await page.waitForTimeout(action.ms ?? 500); break; default: throw new Error(`unknown action ${action.type}`); } } if (pageErrors.length || consoleErrors.length) throw new Error(`page errors: ${JSON.stringify({ pageErrors, consoleErrors })}`); const report = { schema: "freecad-web-manual/capture/v1", generatedAt: new Date().toISOString(), chapter, workflow, scenario: path.relative(webRoot, scenarioPath), origin, ok: true, trace, shots, pageErrors, consoleErrors, }; fs.writeFileSync(path.join(reportDir, `${chapter}-${workflow}.json`), `${JSON.stringify(report, null, 2)}\n`); return report; } finally { await browser.close(); } } try { const report = await runOnce(); console.log(JSON.stringify({ ok: true, chapter, workflow, shots: report.shots.length })); } catch (error) { console.error(JSON.stringify({ ok: false, error: String(error?.stack ?? error) })); process.exitCode = 1; }