Files
FreeCADWasmDev/tools/run_p6_sketcher_regular_polygon_method_gate.mjs
wangdequan 9a7c4f0335 Save FreeCAD Web workspace sources and user validation evidence
IFC native binding remains incomplete; preserve accurate test results.
2026-09-15 22:01:58 +08:00

108 lines
11 KiB
JavaScript

#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { Worker } from "node:worker_threads";
import { fileURLToPath, pathToFileURL } from "node:url";
import { execFileSync } from "node:child_process";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const build = path.resolve(process.argv[2] ?? path.join(root, "freecad-source/build-web/configure/bin"));
const out = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-sketcher-regular-polygon-"));
const hash = (value) => crypto.createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex");
const fileHash = (file) => hash(fs.readFileSync(file));
execFileSync(path.join(root, "web/node_modules/.bin/tsc"), ["--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", "--strict", "--skipLibCheck", "--outDir", out, "--declaration", "false", "--noEmit", "false", "web/src/facade-envelope.ts", "web/src/sketcher-python-method-facade.ts"], { cwd: root, stdio: "inherit" });
globalThis.__dirname = `${build}${path.sep}`;
globalThis.require = createRequire(import.meta.url);
const loader = await import(pathToFileURL(path.join(build, "FreeCADWebSketcherProbe.js")));
const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebSketcherProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {} });
const facade = await import(pathToFileURL(path.join(out, "sketcher-python-method-facade.js")));
const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js")));
const invoke = (request) => JSON.parse(String(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify(request)])));
const request = facade.createSketcherMakeRegularPolygonRequest("sketcher-regular-success");
const queue = new envelope.FacadeSerialQueue();
const success = await facade.dispatchSketcherPythonMethod(queue, request, kernel);
const repeat = await facade.dispatchSketcherPythonMethod(queue, facade.createSketcherMakeRegularPolygonRequest("sketcher-regular-repeat"), kernel);
const malformed = await facade.dispatchSketcherPythonMethod(queue, { ...request, requestId: "sketcher-regular-malformed", payload: { ...request.payload, family: "geometry-value" } }, kernel);
const duplicateRequest = facade.createSketcherMakeRegularPolygonRequest("sketcher-regular-duplicate");
const delayed = facade.dispatchSketcherPythonMethod(queue, duplicateRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
const duplicate = await facade.dispatchSketcherPythonMethod(queue, duplicateRequest, kernel);
const duplicateResult = await delayed;
const cancelRequest = facade.createSketcherMakeRegularPolygonRequest("sketcher-regular-cancel");
const cancelledPromise = facade.dispatchSketcherPythonMethod(queue, cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
const cancelAccepted = queue.cancel(envelope.createCancel("sketcher-regular-cancel-control", cancelRequest.requestId, "sketcher-python-method"));
const cancelled = await cancelledPromise;
const direct = invoke({ cmd: "sketcher.pythonMethod", args: request.payload });
const directRepeat = invoke({ cmd: "sketcher.pythonMethod", args: request.payload });
const crossModule = invoke({ cmd: "sketcher.pythonMethod", args: { ...request.payload, module: "Part", apiId: "py:Part:function:makeRegularPolygon" } });
const unsupported = invoke({ cmd: "sketcher.unknown", args: {} });
if (success.kind !== "result" || success.result.result.sides !== 5 || success.result.result.geometryCount !== 6 || success.result.result.constraintCount !== 14 || success.result.result.recomputeHasError !== false || success.result.resourcesReleased !== true) throw new Error(`native Sketcher regular polygon method failed: ${JSON.stringify(success)}`);
if (repeat.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeat.result)) throw new Error("Sketcher regular polygon replay changed");
if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error(`invalid Sketcher regular polygon envelope was accepted: ${JSON.stringify(malformed)}`);
if (duplicate.kind !== "error" || duplicate.error.code !== "duplicate_request" || duplicateResult.kind !== "result") throw new Error(`Sketcher regular polygon duplicate sequencing failed: ${JSON.stringify({ duplicate, duplicateResult })}`);
if (!cancelAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error(`Sketcher regular polygon cancellation failed: ${JSON.stringify(cancelled)}`);
if (direct.ok !== true || direct.result.sides !== 5 || direct.result.geometryCount !== 6 || direct.result.constraintCount !== 14 || directRepeat.ok !== true || JSON.stringify(direct) !== JSON.stringify(directRepeat)) throw new Error(`direct Sketcher regular polygon dispatch failed: ${JSON.stringify({ direct, directRepeat })}`);
if (crossModule.ok !== false || crossModule.code !== "unmatched_source_record" || unsupported.ok !== false || unsupported.code !== "unsupported_command") throw new Error(`Sketcher regular polygon boundaries failed: ${JSON.stringify({ crossModule, unsupported })}`);
const worker = new Worker(path.join(root, "tools/sketcher-python-method-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(out, "sketcher-python-method-facade.js")).href, envelopePath: pathToFileURL(path.join(out, "facade-envelope.js")).href } });
const receive = () => new Promise((resolve, reject) => { const onMessage = (value) => { worker.off("error", reject); resolve(value); }; worker.once("message", onMessage); worker.once("error", reject); });
const ready = await receive();
worker.postMessage(request);
const workerSuccess = await receive();
worker.postMessage(request);
const workerDuplicate = await receive();
const workerCancel = facade.createSketcherMakeRegularPolygonRequest("sketcher-regular-worker-cancel");
const workerCancelledPromise = new Promise((resolve, reject) => { const onMessage = (value) => { if (value.requestId === workerCancel.requestId) { worker.off("error", reject); resolve(value); } }; worker.on("message", onMessage); worker.once("error", reject); });
worker.postMessage(workerCancel);
worker.postMessage(envelope.createCancel("sketcher-regular-worker-cancel-control", workerCancel.requestId, "sketcher-python-method"));
const workerCancelled = await workerCancelledPromise;
worker.postMessage({ kind: "reset", requestId: "sketcher-regular-worker-reset" });
const reset = await receive();
await worker.terminate();
if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.result.geometryCount !== 6 || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request" || workerCancelled.kind !== "error" || workerCancelled.error.code !== "cancelled" || reset.requestId !== "sketcher-regular-worker-reset") throw new Error(`Sketcher regular polygon Worker sequencing failed: ${JSON.stringify({ ready, workerSuccess, workerDuplicate, workerCancelled, reset })}`);
const trace = { success, repeat, malformed, duplicate, duplicateResult, cancelled, direct, directRepeat, crossModule, unsupported };
const workerTrace = { ready, success: workerSuccess, duplicate: workerDuplicate, cancelled: workerCancelled, reset };
const report = {
schema: "freecad-web-p6-sketcher-regular-polygon-method-runtime/v1",
taskId: "FW-P6-FPA-Y",
module: "Sketcher",
tier: "tier-2-pure",
apiId: facade.SKETCHER_MAKE_REGULAR_POLYGON_API_ID,
status: "pass",
route: { command: facade.SKETCHER_PYTHON_METHOD_COMMAND, worker: "web/src/sketcher-python.worker.ts", facade: "web/src/sketcher-python-method-facade.ts", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/SketcherProbe.cpp:fc_web_dispatch_json" },
source: { entry: "src/Mod/Sketcher/ProfileLib/RegularPolygon.py", revision: success.result.sourceRevision, function: "makeRegularPolygon", guiImportBoundary: "top-level FreeCADGui import and command registration are excluded; the official function definition executes unchanged against native App/Sketcher/Part" },
request,
requestSha256: hash(request),
trace,
traceSha256: hash(trace),
worker: { trace: workerTrace, traceSha256: hash(workerTrace), sequencing: { duplicate: true, cancelAccepted: true, resetAccepted: true, maxActive: 1 } },
replay: { equal: true, resultSha256: hash(repeat.result) },
resources: { resourcesReleased: success.result.resourcesReleased === true, documentMutation: true, temporaryDocumentClosed: true },
artifacts: { wasm: { path: "web/public/kernel/FreeCADWebSketcherProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSketcherProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebSketcherProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSketcherProbe.js")) } },
commands: ["ninja -C freecad-source/build-web/configure FreeCADWebSketcherProbe -j8", "cp FreeCADWebSketcherProbe.js/.wasm web/public/kernel/", "node tools/run_p6_sketcher_regular_polygon_method_gate.mjs freecad-source/build-web/configure/bin"],
boundaries: ["The official function returns None after creating a native Sketcher::SketchObject; the result envelope reports the created object and recompute contract.", "GUI-only module import/command registration remains a declared headless boundary; no GUI result is substituted.", "All result fields and statuses come from compiled FreeCAD through fc_web_dispatch_json."]
};
const manifestPath = path.join(root, "docs/p6/python-api-manifest.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const row = manifest.records.find((record) => record.id === facade.SKETCHER_MAKE_REGULAR_POLYGON_API_ID);
if (!row) throw new Error("Sketcher makeRegularPolygon is missing from python-api-manifest.json");
row.disposition = "exposed";
row.dispositionEvidence = ["docs/p6/sketcher-regular-polygon-method-runtime.json"];
row.dispositionReason = "official Sketcher ProfileLib.RegularPolygon.makeRegularPolygon source replay through fc_web_dispatch_json";
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
report.resultSha256 = hash({ trace, worker: report.worker, source: report.source, resources: report.resources });
fs.writeFileSync(path.join(root, "docs/p6/sketcher-regular-polygon-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-sketcher-regular-polygon-method.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, sides: direct.result.sides, geometryCount: direct.result.geometryCount, constraintCount: direct.result.constraintCount, resourcesReleased: report.resources.resourcesReleased, traceSha256: report.traceSha256, workerTraceSha256: report.worker.traceSha256, resultSha256: report.resultSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, apiId: report.apiId, sides: direct.result.sides, geometryCount: direct.result.geometryCount, constraintCount: direct.result.constraintCount, workerCancel: workerCancelled.error.code, resultSha256: report.resultSha256 }));
// The Emscripten pthread pool may retain libuv handles after the worker and
// native assertions are complete. End after evidence is written so this gate
// reports a deterministic successful process exit to the scheduler.
process.exit(0);