Files
FreeCADWasmDev/web/tools/cad-ui-rebuild/build-steps.mjs
wangdequan 87b2a6cb8a feat(carrier): 航空母舰 PartDesign 有头创建工具包与初学者教学
- 新数据链 web/teaching/cases/carrier-partdesign:20 件零件(spec.json 唯一来源)、
  内核建造器 parts/*.mjs、traces/FCStd/replay 全量产物;装配 20 插入 + 19 关节。
- 工具包 tools/carrier:catalog / preflight / create-part / create-assembly /
  create-all / list / self-test / README,按零件与装配拆分为独立工具。
- 共享驱动扩展 web/tools/cad-ui-rebuild:Loft/Pipe/Hole/Fillet/Chamfer/Mirrored/
  LinearPattern 交互,Reversed 复选框补齐;装配 saveAssemblyBundle 先 Accept 再保存。
- 教学:lessons.mjs 新增 carrier 组(环境课 + 20 件 + 装配),suite-runner 增加
  carrier-part/carrier-assembly,生成 carrier-toolkit.html 并接入 index 与控制台证据。

验证:20 件 210 步全部有头通过(P05 修复后 39640 m³;P06 回归 8/8);
装配 20/20 插入、19/19 关节、20 组件 0 畸形、0 mismatch;check:carrier、
check:reducer、check-console --live 全绿。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:46:27 +08:00

130 lines
5.5 KiB
JavaScript

#!/usr/bin/env node
// Generate the per-step UI operation list for every part in a project.
//
// Reads each part's replay (the scripted build) plus one snapshot of the
// finished FCStd to recover the sketch coordinates the replay compacted away.
// Output: <outDir>/ui-steps/<document>.json and index.json
//
// Usage: node build-steps.mjs --project <dir> [partId ...]
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadProject, projectFromArgv, readJson, replayPath } from "./manifest.mjs";
import { uiStepsFor } from "./lib/steps.mjs";
import { readReplay } from "./lib/replay.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const repoRoot = path.resolve(webRoot, "..");
const projectDir = projectFromArgv();
const project = loadProject(projectDir, { requireParts: true });
const projectArg = process.argv.slice(2)[process.argv.slice(2).indexOf("--project") + 1];
const wanted = process.argv.slice(2).filter(value => !value.startsWith("--") && value !== projectArg
&& process.argv.slice(2)[process.argv.indexOf(value) - 1] !== "--project");
const { loadWasmProbe } = await import(path.join(repoRoot, "tools", "wasm-probe-runtime.mjs"));
fs.mkdirSync(project.paths.stepsDir, { recursive: true });
const results = [];
const failures = [];
const selected = wanted.length
? project.parts.filter(part => wanted.includes(part.id) || wanted.includes(part.document))
: project.parts;
// One probe instance serves every part: the module import is cached but each
// loadWasmProbe() call instantiates a fresh kernel (and pthread workers), which
// is the leak behind long full-catalog runs.
let probe = null;
const kernelFor = async () => {
if (!probe) probe = await loadWasmProbe(path.join(webRoot, "public", "kernel"), "FreeCADWebPartDesignRuntimeProbe");
return probe.kernel;
};
for (const part of selected) {
const replayFile = replayPath(project, part.document);
const sampleFile = project.paths.sampleDir ? path.join(project.paths.sampleDir, `${part.document}.FCStd`) : null;
if (!fs.existsSync(replayFile)) { failures.push(`${part.document}: missing replay ${replayFile}`); continue; }
if (!sampleFile || !fs.existsSync(sampleFile)) { failures.push(`${part.document}: missing sample FCStd`); continue; }
const replay = readReplay(replayFile);
const kernel = await kernelFor();
const send = (action, args = {}) => JSON.parse(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify({
cmd: "partdesign.document",
args: { schema: "freecad-web-partdesign-document/v1", module: "PartDesign",
document: part.document, action, includeMesh: false, ...args },
})]));
let snapshot;
try {
// The probe's open action restores from a path inside the WASM filesystem;
// it does not decode a `bytes` argument. The FCStd has to be written into
// Emscripten's /tmp first, exactly as the browser build does.
const stagedPath = `/tmp/${part.document}.FCStd`;
kernel.FS.writeFile(stagedPath, fs.readFileSync(sampleFile));
const opened = send("open", { path: stagedPath });
if (!opened.ok) throw new Error(`open failed: ${String(opened.error).slice(0, 200)}`);
const snap = send("snapshot");
if (!snap.ok) throw new Error(`snapshot failed: ${String(snap.error).slice(0, 200)}`);
snapshot = snap.result?.objects ?? [];
} catch (error) {
failures.push(`${part.document}: ${error.message}`);
send("close");
continue;
}
const { steps, failures: local } = uiStepsFor(part.document, replay, snapshot, {
pages: project.pages, featureCommands: project.featureCommands,
});
failures.push(...local);
if (steps.length !== replay.steps.length) {
failures.push(`${part.document}: ${steps.length} ui steps but the replay has ${replay.steps.length}`);
}
const record = {
schema: "freecad-web-cad-ui-rebuild/ui-steps/v1",
generatedAt: new Date().toISOString(),
project: project.name,
document: part.document,
episode: part.id,
title: part.title,
steps,
};
fs.writeFileSync(path.join(project.paths.stepsDir, `${part.document}.json`), `${JSON.stringify(record, null, 2)}\n`);
results.push({ id: part.id, document: part.document, steps: steps.length });
send("close");
}
// A subset run must not drop the other parts from the index: regenerate the
// entries it touched and keep whatever an earlier full run recorded.
const indexFile = path.join(project.paths.stepsDir, "index.json");
const previous = [];
if (wanted.length && fs.existsSync(indexFile)) {
try {
previous.push(...(JSON.parse(fs.readFileSync(indexFile, "utf8")).documents ?? []));
} catch {
// A corrupt index is rebuilt from this run only.
}
}
const merged = new Map(previous.map(item => [item.document, item]));
for (const item of results) merged.set(item.document, item);
const index = {
schema: "freecad-web-cad-ui-rebuild/ui-steps-index/v1",
generatedAt: new Date().toISOString(),
project: project.name,
documents: [...merged.values()],
failures,
};
fs.writeFileSync(indexFile, `${JSON.stringify(index, null, 2)}\n`);
// Write to fd 1 synchronously: process.exit() below would otherwise race the
// async pipe write. The probe's pthread worker keeps the event loop alive, so
// a finished run has to exit explicitly or it looks hung after the summary.
fs.writeFileSync(1, `${JSON.stringify({
documents: results.length,
steps: results.reduce((sum, item) => sum + item.steps, 0),
failures,
}, null, 2)}\n`);
process.exit(failures.length ? 1 : 0);