/** * Prerequisites for a headed carrier rebuild. * * Iron law: a missing dist, kernel, Chrome, DISPLAY, playwright, engine or UI * step list is a prerequisite failure, never a product failure. `create-*` * exits 2 for these and only ever exits 1 after the browser actually ran. */ import fs from "node:fs"; import path from "node:path"; import { createRequire } from "node:module"; import { REPO_ROOT, PROJECT_DIR, parts, projectManifest, stats } from "./catalog.mjs"; import { findChrome, startStaticHost } from "../static-host.mjs"; const require = createRequire(path.join(REPO_ROOT, "web/package.json")); function originPort(origin) { try { const url = new URL(origin); return Number(url.port || (url.protocol === "https:" ? 443 : 80)); } catch { return 0; } } async function originReachable(origin, timeoutMs = 1500) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const response = await fetch(`${origin}/index.html`, { signal: controller.signal, cache: "no-store" }); return response.ok; } catch { return false; } finally { clearTimeout(timer); } } const BUILD_STEPS = "node web/tools/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course"; const REPLAY_GEN = "node web/tools/cad-ui-rebuild/capture-replay.mjs --trace-dir web/teaching/cases/carrier-partdesign/out/traces --sample-dir web/teaching/cases/carrier-partdesign/out/FCStd --out-dir web/teaching/cases/carrier-partdesign/out/replay --source-prefix web/teaching/cases/carrier-partdesign/out/FCStd"; /** * @param {{ part?: object | null }} [options] * `part` narrows the catalog check to that one part: `create-part` only needs * its own ui-steps and build record, so the other 19 parts must not block it. * Without it (create-all, self-test) the check is the whole catalog. */ export async function preflight(options = {}) { const part = options.part ?? null; const checks = []; const add = (id, ok, detail, fix) => checks.push({ id, ok, detail, fix }); const manifest = projectManifest(); const origin = manifest.appOrigin; const distIndex = path.join(REPO_ROOT, "web/dist/index.html"); add("dist", fs.existsSync(distIndex), fs.existsSync(distIndex) ? "web/dist/index.html 已就绪" : "web/dist/index.html 不存在", "cd web && npx vite build"); const wasm = ["web/dist/kernel", "web/public/kernel"].flatMap(rel => { try { return fs.readdirSync(path.join(REPO_ROOT, rel)).filter(name => name.endsWith(".wasm")); } catch { return []; } }); add("kernel", wasm.length > 0, wasm.length ? `内核产物 ${wasm.length} 个 .wasm` : "未找到内核 .wasm 产物", "cd web && node ../tools/sync-assets.mjs"); let chrome = null; try { chrome = findChrome(); } catch { chrome = null; } add("chrome", Boolean(chrome), chrome || "未找到 Chrome/Chromium", "export FREECAD_CHROME=/usr/bin/google-chrome"); const display = process.env.DISPLAY || ""; add("display", Boolean(display), display ? `DISPLAY=${display}` : "DISPLAY 未设置(有头运行需要)", "DISPLAY=:1 node tools/carrier/create-part.mjs P02"); let playwright = null; try { playwright = require.resolve("playwright"); } catch { playwright = null; } add("playwright", Boolean(playwright), playwright ? "web/node_modules 可解析 playwright" : "web/node_modules 中找不到 playwright", "cd web && npm install"); const engine = [ "web/tools/cad-ui-rebuild/drive.mjs", "web/tools/cad-ui-rebuild/assemble.mjs", "web/tools/cad-ui-rebuild/manifest.mjs", "web/tools/cad-ui-rebuild/build-steps.mjs", ]; const missingEngine = engine.filter(rel => !fs.existsSync(path.join(REPO_ROOT, rel))); add("engine", missingEngine.length === 0, missingEngine.length ? `缺少共享引擎:${missingEngine.join(", ")}` : "界面重建引擎完整", "git status web/tools/cad-ui-rebuild"); const summary = stats(); const withoutReplay = parts().filter(item => item.volume == null).map(item => item.id); const withoutSteps = parts().filter(item => item.steps === 0).map(item => item.id); if (part) { add("parts", Boolean(part.reconstructable), part.reconstructable ? `${part.id} ${part.document}:${part.steps} 步,构建记录体积 ${part.volume ?? "—"}` + `(目录共 ${summary.reconstructable}/${summary.parts} 件具备步骤)` : `${part.id} ${part.document} 缺少界面步骤或构建记录(该件 ${part.steps} 步,体积 ${part.volume ?? "—"})`, `node web/tools/cad-ui-rebuild/build-steps.mjs --project web/tools/carrier-partdesign-course ${part.id} # 若缺构建记录:${REPLAY_GEN}`); } else { add("parts", summary.reconstructable === summary.parts, `${summary.reconstructable}/${summary.parts} 件具备界面步骤与构建记录(共 ${summary.steps} 步)` + (withoutSteps.length ? `;缺界面步骤:${withoutSteps.join(",")}` : "") + (withoutReplay.length ? `;缺构建记录:${withoutReplay.join(",")}` : ""), `${BUILD_STEPS} # 或先生成 replay:${REPLAY_GEN}`); } const originOk = await originReachable(origin); add("app", originOk, originOk ? `应用入口可达:${origin}` : `应用入口不可达:${origin}(create-part 会自动起静态服务)`, `cd web && npx vite build && node ../tools/static-host.mjs --root dist --port ${originPort(origin) || 5183}`); return { ok: checks.every(check => check.ok || check.id === "app"), checks, origin, projectDir: PROJECT_DIR, stats: summary, }; } /** * Write a one-off project manifest that keeps the real paths but points at a * different app origin. The driver reads appOrigin from project.json only, so * this is the least invasive way to run it without touching the checked-in * manifest. */ function derivedProject(originMW) { const raw = projectManifest(); const base = { ...raw, appOrigin: originMW, paths: Object.fromEntries(Object.entries(raw.paths ?? {}).map(([key, value]) => [key, path.resolve(PROJECT_DIR, value)])), }; const dir = path.join(REPO_ROOT, "docs/current/carrier-partdesign-toolkit/runtimes", new Date().toISOString().replace(/[:.]/g, "-")); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, "project.json"), `${JSON.stringify(base, null, 2)}\n`); return dir; } /** * Make sure something serves the built app, reusing tools/static-host.mjs. * * Returns the project directory the driver should use: the checked-in one when * its appOrigin already serves the app, otherwise a derived manifest in the run * evidence tree that points at the ephemeral host we just started. */ export async function ensureOrigin(origin = projectManifest().appOrigin) { if (await originReachable(origin)) return { origin, started: false, projectDir: PROJECT_DIR, close: async () => {} }; const dist = path.join(REPO_ROOT, "web/dist"); if (!fs.existsSync(path.join(dist, "index.html"))) { throw Object.assign(new Error(`web/dist/index.html 不存在,无法为 ${origin} 起服务`), { code: "E_PREFLIGHT" }); } const port = originPort(origin) || 5183; try { const host = await startStaticHost(dist, "index.html", port); if (host.origin === origin) { return { origin: host.origin, started: true, projectDir: PROJECT_DIR, close: () => host.close() }; } await host.close(); } catch { /* port busy (or refused) — fall through to an ephemeral host */ } const host = await startStaticHost(dist, "index.html", 0); return { origin: host.origin, started: true, projectDir: derivedProject(host.origin), close: () => host.close() }; } export { parts };