#!/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 { execFileSync } from "node:child_process"; import { Worker } from "node:worker_threads"; import { pathToFileURL } from "node:url"; const root = "/home/mes123456/FreeCADWasmDev/working/FreeCAD"; 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-material-translate-")); 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", path.join(root, "web/src/facade-envelope.ts"), path.join(root, "web/src/material-python-family-facade.ts"), path.join(root, "web/src/api-method-bridge.ts"), ], { cwd: root, stdio: "inherit" }); globalThis.__dirname = `${build}${path.sep}`; globalThis.require = createRequire(import.meta.url); const loader = await import(pathToFileURL(path.join(build, "FreeCADWebMaterialKernelProbe.js"))); const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebMaterialKernelProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {}, }); const facade = await import(pathToFileURL(path.join(out, "material-python-family-facade.js"))); const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js"))); const request = facade.createMaterialTranslateRequest("material-translate-success", { context: "Material", text: "FreeCAD Web" }); const queue = new envelope.FacadeSerialQueue(); const success = await facade.dispatchMaterialPythonFamily(queue, request, kernel); const repeat = await facade.dispatchMaterialPythonFamily(queue, facade.createMaterialTranslateRequest("material-translate-repeat", { context: "Material", text: "FreeCAD Web" }), kernel); const malformed = await facade.dispatchMaterialPythonFamily(queue, { ...request, requestId: "material-translate-malformed", payload: { ...request.payload, tier: "tier-unsupported" } }, kernel); const invalidRequest = facade.createMaterialTranslateRequest("material-translate-invalid", { context: "Material" }); const invalid = await facade.dispatchMaterialPythonFamily(queue, invalidRequest, kernel); const duplicateRequest = facade.createMaterialTranslateRequest("material-translate-duplicate", { context: "Material", text: "duplicate" }); const delayed = facade.dispatchMaterialPythonFamily(queue, duplicateRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25))); const duplicate = await facade.dispatchMaterialPythonFamily(queue, duplicateRequest, kernel); const duplicateResult = await delayed; const cancelRequest = facade.createMaterialTranslateRequest("material-translate-cancel", { context: "Material", text: "cancel" }); const cancelledPromise = facade.dispatchMaterialPythonFamily(queue, cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25))); const cancelAccepted = queue.cancel(envelope.createCancel("material-translate-cancel-control", cancelRequest.requestId)); const cancelled = await cancelledPromise; const invoke = (value) => JSON.parse(String(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify(value)]))); const direct = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [request.payload.records[0]] } }); const directRepeat = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [request.payload.records[0]] } }); const crossModule = invoke({ cmd: "material.pythonFamilyBatch", args: { tier: "tier-2-pure", records: [{ ...request.payload.records[0], apiId: "py:Part:function:translate" }] } }); const unsupported = invoke({ cmd: "material.unknown", args: {} }); const apiBridge = await import(pathToFileURL(path.join(out, "api-method-bridge.js"))); const runtimeIndex = JSON.parse(fs.readFileSync(path.join(root, "web/public/api/python-api-index.json"), "utf8")); const bridgeRouter = { request: async (_module, _command, payload) => envelope.createSuccess("router-translate", await facade.handleMaterialPythonFamily(payload, new AbortController().signal, kernel)), }; const bridge = new apiBridge.ApiMethodBridge(bridgeRouter, runtimeIndex); const bridgeSuccess = await bridge.call({ apiId: facade.MATERIAL_TRANSLATE_API_ID, args: ["Material", "FreeCAD Web"] }); const bridgeInvalid = await bridge.call({ apiId: facade.MATERIAL_TRANSLATE_API_ID, args: ["Material"] }); if (success.kind !== "result" || success.result.records[0]?.status !== "exposed" || success.result.records[0]?.result !== "FreeCAD Web" || success.result.resourcesReleased !== true) throw new Error(`native Material translate method failed: ${JSON.stringify(success)}`); if (repeat.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeat.result)) throw new Error("Material translate replay changed"); if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error(`invalid Material translate envelope was accepted: ${JSON.stringify(malformed)}`); if (invalid.kind !== "result" || invalid.result.records[0]?.status !== "not_implemented" || invalid.result.records[0]?.code !== "source_error") throw new Error(`invalid Material translate fixture was not rejected: ${JSON.stringify(invalid)}`); if (duplicate.kind !== "error" || duplicate.error.code !== "duplicate_request" || duplicateResult.kind !== "result") throw new Error(`Material translate duplicate sequencing failed: ${JSON.stringify({ duplicate, duplicateResult })}`); if (!cancelAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error(`Material translate cancellation failed: ${JSON.stringify(cancelled)}`); if (direct.ok !== true || direct.records[0]?.status !== "exposed" || direct.records[0]?.result !== "FreeCAD Web" || JSON.stringify(direct) !== JSON.stringify(directRepeat)) throw new Error(`direct Material translate dispatch failed: ${JSON.stringify({ direct, directRepeat })}`); if (crossModule.ok !== true || crossModule.records?.[0]?.status !== "not_implemented" || crossModule.records?.[0]?.code !== "unmatched_source_record" || unsupported.ok !== false || unsupported.code !== "unsupported_command") throw new Error(`Material translate boundaries failed: ${JSON.stringify({ crossModule, unsupported })}`); if (bridgeSuccess.kind !== "result" || bridgeSuccess.result.records?.[0]?.result !== "FreeCAD Web" || bridgeInvalid.kind !== "error" || bridgeInvalid.error.code !== "invalid_arguments") throw new Error(`Material translate API bridge failed: ${JSON.stringify({ bridgeSuccess, bridgeInvalid })}`); const worker = new Worker(path.join(root, "tools/material-python-family-facade-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(out, "material-python-family-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 workerCancelRequest = facade.createMaterialTranslateRequest("material-translate-worker-cancel", { context: "Material", text: "cancel" }); const workerCancelledPromise = new Promise((resolve, reject) => { const onMessage = (value) => { if (value.requestId === workerCancelRequest.requestId) { worker.off("error", reject); resolve(value); } }; worker.on("message", onMessage); worker.once("error", reject); }); worker.postMessage(workerCancelRequest); worker.postMessage(envelope.createCancel("material-translate-worker-cancel-control", workerCancelRequest.requestId)); const workerCancelled = await workerCancelledPromise; worker.postMessage({ kind: "reset", requestId: "material-translate-worker-reset" }); const reset = await receive(); await worker.terminate(); if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.records[0]?.result !== "FreeCAD Web" || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request" || workerCancelled.kind !== "error" || workerCancelled.error.code !== "cancelled" || reset.requestId !== "material-translate-worker-reset") throw new Error(`Material translate Worker sequencing failed: ${JSON.stringify({ ready, workerSuccess, workerDuplicate, workerCancelled, reset })}`); const trace = { success, repeat, malformed, invalid, duplicate, duplicateResult, cancelled, direct, directRepeat, crossModule, unsupported, bridgeSuccess, bridgeInvalid }; const workerTrace = { ready, success: workerSuccess, duplicate: workerDuplicate, cancelled: workerCancelled, reset }; const manifestPath = path.join(root, "docs/p6/python-api-manifest.json"); const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); const row = manifest.records.find((entry) => entry.id === facade.MATERIAL_TRANSLATE_API_ID); if (!row) throw new Error("Material translate is missing from python-api-manifest.json"); row.disposition = "exposed"; row.dispositionEvidence = ["docs/p6/material-translate-method-runtime.json"]; row.dispositionReason = "official MaterialEditor.translate source replay through fc_web_dispatch_json"; fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); execFileSync("python3", [path.join(root, "tools/generate_python_api_runtime_index.py")], { cwd: root, stdio: "inherit" }); const report = { schema: "freecad-web-p6-material-translate-method-runtime/v1", taskId: "FW-P6-FPA-Y", module: "Material", tier: "tier-2-pure", apiId: facade.MATERIAL_TRANSLATE_API_ID, status: "pass", route: { command: facade.MATERIAL_PYTHON_FAMILY_COMMAND, worker: "web/src/material.worker.ts", facade: "web/src/material-python-family-facade.ts", apiBridge: "web/src/api-method-bridge.ts", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/MaterialKernelProbe.cpp:fc_web_dispatch_json" }, source: { entry: "src/Mod/Material/MaterialEditor.py", line: 957, revision: success.result.records[0].sourceRevision, function: "translate", guiImportBoundary: "official pure function definition is extracted without executing MaterialEditor GUI imports" }, 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: true, documentMutation: false }, artifacts: { wasm: { path: "web/public/kernel/FreeCADWebMaterialKernelProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebMaterialKernelProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebMaterialKernelProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebMaterialKernelProbe.js")) }, }, commands: ["ninja -C freecad-source/build-web/configure FreeCADWebMaterialKernelProbe -j8", "cp FreeCADWebMaterialKernelProbe.js/.wasm web/public/kernel/", "node tools/run_p6_material_translate_method_gate.mjs freecad-source/build-web/configure/bin"], boundaries: ["MaterialEditor top-level Qt/FreeCADGui imports and editor UI remain headless boundaries; only the official pure translate definition is executed.", "All result fields and statuses derive from compiled FreeCAD through fc_web_dispatch_json; no JavaScript API result is substituted."], }; report.resultSha256 = hash({ trace, worker: report.worker, source: report.source, resources: report.resources }); fs.writeFileSync(path.join(root, "docs/p6/material-translate-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`); fs.writeFileSync(path.join(root, "docs/freecad-p6-material-translate-method-gate.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, result: direct.records[0].result, 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, result: direct.records[0].result, workerCancel: workerCancelled.error.code, resultSha256: report.resultSha256 })); process.exit(0);