Files
FreeCADWasmDev/web/tools/teaching-console/build-inapp-data.mjs
Claude fd37b92fd9 teaching: run lessons in-app through an iframe-driven console
The teaching console now lives inside Web FreeCAD: web/teaching-console.html
hosts the workbench in a same-origin iframe and drives its DOM directly, with
no Node server and no spawned Chrome. The driver modules run in the framed
page's own realm (bridge.ts publishes window.__teaching), so the proven
driver/assembly code is reused unchanged and the CSP without 'unsafe-eval' is
never crossed.

- steps.ts globs both courses' ui-steps records (skipping their index.json
  manifests) so each lesson downloads only its own chunk
- runner.ts checks prerequisites in dependency order, then runs part or
  assembly lessons; a pass stores the FCStd in OPFS freecad-documents under
  the course document name, which is what assembly lessons consume
- assembly lessons insert, joint, solve and save through lib/assembly.mjs;
  insertLink falls back to UI-suffixed object names (Body1 for Body)
- check-inapp-console.mjs (npm run check:console-inapp) is green: preflight,
  P01 volume within 6e-13, OPFS evidence, both viewports
- run-inapp-lessons.mjs runs a whole course in one browser; reducer 23 parts
  + assembly and carrier 20 parts + assembly all pass in-browser

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

151 lines
6.3 KiB
JavaScript

#!/usr/bin/env node
// Generate the small data files the in-app teaching console bundles.
//
// The console runs inside the browser, so it cannot read `tools/**/out/**` or
// the 9.4 MB replays at run time. Everything it needs to *name* and *judge* a
// lesson -- which document, how many steps, the reference volume after each
// step, and the assembly placement numbers -- is extracted here into two
// committed JSON files under `src/teaching/generated/`.
//
// The step files are not copied: `src/teaching/steps.ts` globs them straight
// out of the course directories, so they keep exactly one home in the repo.
//
// Usage: node tools/teaching-console/build-inapp-data.mjs [--check]
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadCatalog } from "./catalog.mjs";
import { buildLessons } from "./lessons.mjs";
import { loadProject, replayPath } from "../cad-ui-rebuild/manifest.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const generatedDir = path.join(webRoot, "src/teaching/generated");
/** Lesson kinds the browser can run. Everything else needs Node (suites). */
const IN_APP_KINDS = new Set(["preflight", "carrier-part", "carrier-assembly", "reducer-part", "reducer-assembly"]);
const PROJECTS = {
carrier: "tools/carrier-partdesign-course",
reducer: "tools/reducer-parts-course",
};
function readJson(file) {
return JSON.parse(fs.readFileSync(file, "utf8"));
}
/** The volumes the replay recorded after each step: the reference to judge against. */
function stepVolumes(replayFile) {
const replay = readJson(replayFile);
return replay.steps.map(step => (typeof step?.volume === "number" ? step.volume : null));
}
/**
* One lesson, as the console needs it at run time.
*
* `document` and `steps` are what the runner loads and how many rows to expect;
* `volumes` is the per-step reference. A `null` entry means the replay recorded
* no volume for that step, so the runner compares nothing there.
*/
function resolveJob(job, projects) {
if (job.kind === "preflight") return { kind: "preflight" };
const project = projects[job.kind.startsWith("carrier") ? "carrier" : "reducer"];
if (job.kind.endsWith("-part")) {
const part = project.parts.find(item => item.id === job.partId);
if (!part) throw new Error(`${project.name} has no part ${job.partId}`);
const stepsFile = path.join(project.paths.stepsDir, `${part.document}.json`);
if (!fs.existsSync(stepsFile)) throw new Error(`missing ui-steps ${stepsFile}`);
const uiSteps = readJson(stepsFile);
return {
kind: job.kind,
partId: part.id,
document: part.document,
title: part.title,
page: uiSteps.steps[0]?.page ?? "partdesign.html",
steps: uiSteps.steps.length,
volumes: stepVolumes(replayPath(project, part.document)),
};
}
// Assembly: the runner inserts what the replay recorded, in replay order.
const assembly = project.assembly;
if (!assembly) throw new Error(`${project.name} has no assembly block`);
const replay = readJson(replayPath(project, assembly.document, { assembly: true }));
const inserts = replay.steps.filter(step => step.insert).map(step => step.insert);
if (!inserts.length) throw new Error(`${project.name} assembly replay has no insertions`);
return {
kind: job.kind,
document: assembly.document,
title: assembly.label ?? assembly.document,
page: project.pages.assembly,
groundDocument: assembly.groundDocument ?? inserts[0]?.sourceDocument ?? null,
saveBundle: Boolean(assembly.saveBundle),
sourceDocuments: [...new Set(inserts.map(item => item.sourceDocument))],
inserts,
joints: replay.steps
.filter(step => typeof step.action === "string" && step.action.startsWith("Assembly_CreateJoint"))
.map(step => ({ action: step.action, args: step.args ?? null })),
solves: replay.steps
.filter(step => step.action === "Assembly_SolveAssembly")
.map(step => ({ action: step.action, args: step.args ?? null })),
bom: replay.steps
.filter(step => step.action === "Assembly_CreateBom")
.map(step => ({ action: step.action, args: step.args ?? null })),
};
}
function build() {
const projects = Object.fromEntries(Object.entries(PROJECTS)
.map(([name, dir]) => [name, loadProject(path.join(webRoot, dir), { requireParts: true })]));
const curriculum = buildLessons(loadCatalog());
const groups = curriculum.groups.filter(group => ["basics", "carrier", "reducer"].includes(group.id));
const lessons = curriculum.lessons
.filter(lesson => IN_APP_KINDS.has(lesson.job?.kind))
.map(lesson => ({
id: lesson.id,
groupId: lesson.groupId,
title: lesson.title,
level: lesson.level,
durationMin: lesson.durationMin,
summary: lesson.summary,
sees: lesson.sees ?? [],
expect: lesson.expect,
job: resolveJob(lesson.job, projects),
}));
// Both preflight lessons point at the same check; the console keeps one.
const preflight = lessons.find(lesson => lesson.job.kind === "preflight");
const kept = [preflight, ...lessons.filter(lesson => lesson !== preflight)].filter(Boolean);
return {
schema: "freecad-web/teaching-console/in-app/v1",
groups,
lessons: kept,
counts: {
lessons: kept.length,
parts: kept.filter(lesson => lesson.job.kind.endsWith("-part")).length,
assemblies: kept.filter(lesson => lesson.job.kind.endsWith("-assembly")).length,
steps: kept.reduce((sum, lesson) => sum + (lesson.job.steps ?? 0), 0),
},
};
}
function serialize(value) {
return `${JSON.stringify(value, null, 1)}\n`;
}
const data = build();
const file = path.join(generatedDir, "lessons.json");
const text = serialize(data);
if (process.argv.includes("--check")) {
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
if (current !== text) {
console.error(`in-app lesson data is stale: ${path.relative(webRoot, file)}`);
console.error("run: node tools/teaching-console/build-inapp-data.mjs");
process.exit(1);
}
console.log(`in-app lesson data is current (${data.counts.lessons} lessons, ${data.counts.steps} steps)`);
} else {
fs.mkdirSync(generatedDir, { recursive: true });
fs.writeFileSync(file, text);
console.log(JSON.stringify({ file: path.relative(webRoot, file), ...data.counts }));
}