Files
FreeCADWasmDev/tools/run_p6_sketcher_profile_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

105 lines
10 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";
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-method-"));
const hash = (value) => crypto.createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex");
const fileHash = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const tsc = path.join(root, "web/node_modules/.bin/tsc");
const { execFileSync } = await import("node:child_process");
execFileSync(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 invoke = (request) => JSON.parse(String(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify(request)])));
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 request = facade.createSketcherIsProfileActiveRequest("sketcher-profile-success");
const queue = new envelope.FacadeSerialQueue();
const success = await facade.dispatchSketcherPythonMethod(queue, request, kernel);
const repeated = await facade.dispatchSketcherPythonMethod(queue, facade.createSketcherIsProfileActiveRequest("sketcher-profile-repeat"), kernel);
const malformed = await facade.dispatchSketcherPythonMethod(queue, { ...request, requestId: "sketcher-profile-malformed", payload: { ...request.payload, tier: "tier-1-readonly" } }, kernel);
const cancelRequest = facade.createSketcherIsProfileActiveRequest("sketcher-profile-cancel");
const cancelledPromise = facade.dispatchSketcherPythonMethod(queue, cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
const cancelledAccepted = queue.cancel(envelope.createCancel("sketcher-profile-cancel-control", cancelRequest.requestId, "sketcher-python-method"));
const cancelled = await cancelledPromise;
const directRequest = { cmd: "sketcher.pythonMethod", args: request.payload };
const direct = invoke(directRequest);
const directRepeat = invoke(directRequest);
const crossModule = invoke({ cmd: directRequest.cmd, args: { ...directRequest.args, module: "Part", apiId: "py:Part:function:isProfileActive" } });
const unsupported = invoke({ cmd: "sketcher.unknown", args: {} });
if (success.kind !== "result" || success.result.result.value !== false || success.result.result.withoutDocument !== false || success.result.result.withDocument !== true || success.result.resourcesReleased !== true) throw new Error(`native Sketcher profile method failed: ${JSON.stringify(success)}`);
if (repeated.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeated.result)) throw new Error("Sketcher profile method replay changed");
if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error(`invalid Sketcher profile envelope was accepted: ${JSON.stringify(malformed)}`);
if (!cancelledAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error(`Sketcher profile cancellation failed: ${JSON.stringify(cancelled)}`);
if (direct.ok !== true || direct.result.value !== false || direct.result.withDocument !== true || directRepeat.ok !== true || JSON.stringify(direct) !== JSON.stringify(directRepeat)) throw new Error(`direct Sketcher profile 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 profile boundaries failed: ${JSON.stringify({ crossModule, unsupported })}`);
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_IS_PROFILE_ACTIVE_API_ID);
if (!row) throw new Error("Sketcher isProfileActive is missing from python-api-manifest.json");
row.disposition = "exposed";
row.dispositionEvidence = ["docs/p6/sketcher-profile-method-runtime.json"];
row.dispositionReason = "official Sketcher Profiles.isProfileActive source replay through fc_web_dispatch_json";
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const trace = { success, repeated, malformed, cancelled, direct, directRepeat, crossModule, unsupported };
const report = {
schema: "freecad-web-p6-sketcher-profile-method-runtime/v1",
taskId: "FW-P6-FPA-Y",
module: "Sketcher",
tier: "tier-2-pure",
apiId: facade.SKETCHER_IS_PROFILE_ACTIVE_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/Profiles.py", revision: success.result.sourceRevision, guiRegistrationBoundary: "Profiles.py GUI command registration is excluded from headless execution; isProfileActive function source is executed unchanged" },
request,
requestSha256: hash(request),
trace,
traceSha256: hash(trace),
replay: { equal: true, resultSha256: hash(repeated.result) },
resources: { resourcesReleased: success.result.resourcesReleased, documentMutation: false, 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_profile_method_gate.mjs freecad-source/build-web/configure/bin"],
boundaries: ["The official function returns false without an active document and true with a temporary native document.", "GUI-only Profiles command registration is a declared headless boundary; no GUI result is substituted.", "All result fields and statuses come from compiled FreeCAD through fc_web_dispatch_json."]
};
fs.writeFileSync(path.join(root, "docs/p6/sketcher-profile-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-sketcher-profile-method.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, withoutDocument: direct.result.value, withDocument: direct.result.withDocument, resourcesReleased: success.result.resourcesReleased, traceSha256: report.traceSha256 })}\n`);
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 messages = [];
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.createSketcherIsProfileActiveRequest("sketcher-profile-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-profile-worker-cancel-control", workerCancel.requestId, "sketcher-python-method"));
const workerCancelled = await workerCancelledPromise;
worker.postMessage({ kind: "reset", requestId: "sketcher-profile-worker-reset" });
const reset = await receive();
await worker.terminate();
if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.result.withDocument !== true || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request" || workerCancelled.kind !== "error" || workerCancelled.error.code !== "cancelled" || reset.requestId !== "sketcher-profile-worker-reset") throw new Error(`Sketcher profile Worker sequencing failed: ${JSON.stringify({ ready, workerSuccess, workerDuplicate, workerCancelled, reset })}`);
const workerTrace = { ready, success: workerSuccess, duplicate: workerDuplicate, cancelled: workerCancelled, reset };
report.worker = { trace: workerTrace, traceSha256: hash(workerTrace), sequencing: { duplicate: true, cancelAccepted: true, resetAccepted: true, maxActive: 1 } };
report.resultSha256 = hash({ trace: report.trace, worker: report.worker, source: report.source, resources: report.resources });
fs.writeFileSync(path.join(root, "docs/p6/sketcher-profile-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-sketcher-profile-method.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, withoutDocument: direct.result.value, withDocument: direct.result.withDocument, resourcesReleased: success.result.resourcesReleased, traceSha256: report.traceSha256, workerTraceSha256: report.worker.traceSha256, resultSha256: report.resultSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, apiId: report.apiId, withoutDocument: direct.result.value, withDocument: direct.result.withDocument, workerCancel: workerCancelled.error.code, resultSha256: report.resultSha256 }));
process.exit(0);