diff --git a/tools/bim-report-gui-acceptance.mjs b/tools/bim-report-gui-acceptance.mjs new file mode 100644 index 00000000..39e777df --- /dev/null +++ b/tools/bim-report-gui-acceptance.mjs @@ -0,0 +1,89 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; + +const object = value => !!value && typeof value === "object" && !Array.isArray(value); +const type = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; +export const reportGuiMethods = ["test_cheatsheet_dialog_creation", "test_hover_tooltips"]; + +export async function verifyReportGui(page, native, evidenceRoot, viewport, suffix = "") { + const observations = { nativeType: type(native), docsType: type(native?.apiDocumentation), fixtureType: type(native?.preflight?.fixture), viewport }; + const failPreflight = message => { const error = new Error(message); error.classification = "preflight_failed"; error.observations = observations; throw error; }; + if (!object(native) || !object(native.apiDocumentation) || !object(native.preflight) || !object(native.preflight.fixture)) failPreflight("Native documentation/fixture shape is unavailable"); + const docs = native.apiDocumentation; + observations.clausesType = type(docs.clauses); observations.functionsType = type(docs.functions); + if (!Array.isArray(docs.clauses) || !docs.clauses.every(v => typeof v === "string") || !object(docs.functions) + || !Object.values(docs.functions).every(items => Array.isArray(items) && items.every(fn => object(fn) && [fn.name, fn.signature, fn.description].every(v => typeof v === "string") && (fn.snippet === undefined || typeof fn.snippet === "string")))) failPreflight("Native SQL documentation types are invalid"); + const fixture = native.preflight.fixture; + if (!Array.isArray(fixture.objects) || !fixture.objects.every(v => object(v) && typeof v.typeId === "string" && typeof v.name === "string") || typeof fixture.sheetType !== "string") failPreflight("Native fixture types are invalid"); + if (native.preflight.passed !== true || native.resourcesReleased !== true || native.guiUp?.[1] !== false || fixture.sheetType !== "Spreadsheet::Sheet" || fixture.objects.length !== 7) failPreflight("Native readiness or official seven-object fixture failed"); + if (typeof native.documentCountBefore !== "number" || typeof native.documentCountAfter !== "number" || native.documentCountBefore !== native.documentCountAfter) failPreflight("Native document resources were not released"); + const layout = await page.evaluate(() => { + const app = document.querySelector("#app"), editor = document.querySelector("#bim-sql-editor"), help = document.querySelector("#bim-sql-help"); + const box = app?.getBoundingClientRect(); + return { appType: app?.constructor.name, editorType: editor?.constructor.name, helpType: help?.constructor.name, + editable: editor instanceof HTMLElement ? editor.contentEditable : null, helpDisabled: help instanceof HTMLButtonElement ? help.disabled : null, + overflow: document.documentElement.scrollWidth > innerWidth || document.documentElement.scrollHeight > innerHeight, + inViewport: !!box && box.width > 0 && box.height > 0 && box.left >= 0 && box.top >= 0 && box.right <= innerWidth && box.bottom <= innerHeight }; + }); + observations.layout = layout; + if (layout.editorType !== "HTMLDivElement" || layout.helpType !== "HTMLButtonElement" || layout.editable !== "true" || layout.helpDisabled !== false || layout.overflow || !layout.inViewport) failPreflight("Web command/editor or viewport prerequisites failed"); + const docsShape = { clauseCount: docs.clauses.length, categories: Object.keys(docs.functions), functionCount: Object.values(docs.functions).reduce((n, items) => n + items.length, 0) }; + fs.writeFileSync(path.join(evidenceRoot, `${viewport.name}${suffix}-preflight.json`), JSON.stringify({ observations, docsShape, passed: true }, null, 2) + "\n"); + const tests = []; + const run = async (name, task) => { + const checks = []; + const check = (name, actual, expected) => { assert.deepEqual(actual, expected, name); checks.push({ name, passed: true }); }; + try { await task(check); tests.push({ name, passed: true, checks }); } + catch (error) { tests.push({ name, passed: false, checks, error: String(error.message).slice(0,1000) }); } + }; + const help = page.locator("#bim-sql-help"), dialog = page.locator("#bim-sql-cheatsheet"), editor = page.locator("#bim-sql-editor"), tooltip = page.locator("#bim-sql-tooltip"); + await run(reportGuiMethods[0], async check => { + await help.click(); await dialog.waitFor({ state: "visible" }); + const displayed = await dialog.evaluate(el => ({ elementType: el.constructor.name, openType: typeof el.open, open: el.open, + title: el.querySelector("h1")?.textContent, clauses: el.querySelector(":scope > code")?.textContent, + categories: [...el.querySelectorAll("h3")].map(node => node.textContent), + functions: [...el.querySelectorAll("li[data-function]")].map(node => ({ name: node.getAttribute("data-function"), signature: node.querySelector("code")?.textContent, description: node.querySelector("div")?.textContent, snippet: node.querySelector("pre")?.textContent ?? null })), + bounds: (() => { const b=el.getBoundingClientRect(); return { inViewport: b.left >= 0 && b.top >= 0 && b.right <= innerWidth && b.bottom <= innerHeight, horizontalOverflow: el.scrollWidth > el.clientWidth }; })() })); + observations.dialogTypes = { element: displayed.elementType, open: displayed.openType, functions: type(displayed.functions) }; + assert.equal(displayed.elementType, "HTMLDialogElement"); assert.equal(displayed.openType, "boolean"); assert.ok(Array.isArray(displayed.functions)); + check("real Web dialog opens", displayed.open, true); + check("desktop dialog title", displayed.title, "BIM SQL Cheatsheet"); + check("all native clauses rendered", displayed.clauses, [...docs.clauses].sort().join(", ")); + check("all native categories rendered", displayed.categories, Object.keys(docs.functions).sort()); + const expectedFunctions = Object.keys(docs.functions).sort().flatMap(category => [...docs.functions[category]].sort((a,b) => a.name.localeCompare(b.name)).map(fn => ({ name:fn.name, signature:fn.signature, description:fn.description, snippet:fn.snippet || null }))); + check("native signatures/descriptions/snippets rendered", displayed.functions, expectedFunctions); + check("dialog fits viewport", displayed.bounds, { inViewport:true, horizontalOverflow:false }); + await page.screenshot({ path:path.join(evidenceRoot, `${viewport.name}${suffix}-arch-report-gui-dialog.png`) }); + await page.locator("#bim-sql-cheatsheet-ok").click(); check("OK closes dialog", await dialog.isVisible(), false); + await help.click(); await page.keyboard.press("Escape"); check("Escape closes dialog", await dialog.isVisible(), false); + check("focus returns to opener", await help.evaluate(el => document.activeElement === el), true); + }); + if (await dialog.isVisible()) await page.keyboard.press("Escape"); + await run(reportGuiMethods[1], async check => { + const convertDoc = Object.entries(docs.functions).flatMap(([category, list]) => list.map(fn => ({...fn, category}))).find(fn => fn.name === "CONVERT"); + assert.ok(convertDoc && typeof convertDoc.signature === "string"); + const word = name => editor.locator(`[data-word="${name}"]`).first(); + await word("CONVERT").hover(); await tooltip.waitFor({ state:"visible" }); + const text = await tooltip.textContent(); observations.tooltipType = typeof text; assert.equal(typeof text,"string"); + check("official CONVERT signature", text.includes("CONVERT(quantity, 'unit')"), true); + check("official Utility category", text.includes("Utility"), true); + check("native description is displayed", text.includes(convertDoc.description), true); + await page.screenshot({ path:path.join(evidenceRoot, `${viewport.name}${suffix}-arch-report-gui-tooltip.png`) }); + await word("SELECT").hover(); check("official SELECT clause tooltip", await tooltip.textContent(), "SQL Clause"); + await word("document".toUpperCase()).hover(); check("unknown word hides stale tooltip", await tooltip.isVisible(), false); + await editor.evaluate(el => { + el.__sqlEvents = []; + for (const event of ["mouseover", "mouseleave", "focusin", "focusout", "input", "click"]) + el.addEventListener(event, e => { el.__sqlEvents.push({event:e.type,target:e.target?.dataset?.word ?? e.target?.id,active:document.activeElement?.dataset?.word ?? document.activeElement?.id}); if(el.__sqlEvents.length>12)el.__sqlEvents.shift(); }); + }); + await editor.fill("select convert(Area, 'm^2') FROM document"); + check("query stays editable", await editor.textContent(), "select convert(Area, 'm^2') FROM document"); + if (viewport.name === "mobile") await word("CONVERT").tap(); else await word("CONVERT").focus(); + observations.lowercaseHelp = await editor.evaluate(el => ({ events:el.__sqlEvents, active:document.activeElement?.dataset?.word ?? document.activeElement?.id, text:document.querySelector("#bim-sql-tooltip")?.textContent, hidden:document.querySelector("#bim-sql-tooltip")?.hidden })); + const lowercaseText = await tooltip.textContent(); assert.equal(typeof lowercaseText, "string"); + check("lowercase word supports touch/keyboard help", lowercaseText.includes(convertDoc.signature), true); + await page.keyboard.press("Escape"); check("Escape dismisses tooltip", await tooltip.isVisible(), false); + }); + return { tests, observations, docsShape, passed:tests.length===2 && tests.every(test => test.passed) }; +} diff --git a/tools/bim-site-gui-acceptance.mjs b/tools/bim-site-gui-acceptance.mjs new file mode 100644 index 00000000..47a75bb8 --- /dev/null +++ b/tools/bim-site-gui-acceptance.mjs @@ -0,0 +1,11 @@ +import assert from "node:assert/strict"; +export const siteGuiMethods=["test_new_site_creation","test_new_site_save_and_reopen","test_legacy_site_migration"]; +export async function verifySiteGui(page,native){ + if(!native||native.ok!==true||native.preflight?.passed!==true||native.saveReopen?.roundTrip!==true||native.saveReopen?.legacyFound!==true) throw new Error("preflight_failed: Site native owner contract is incomplete"); + const types=await page.evaluate(()=>({panel:document.querySelector("#bim-site-panel")?.constructor.name,type:document.querySelector("#bim-site-type")?.textContent,proxy:document.querySelector("#bim-site-proxy")?.textContent,status:document.querySelector("#bim-site-status")?.textContent,month:document.querySelector("#bim-site-month")?.value,day:document.querySelector("#bim-site-day")?.value,scale:document.querySelector("#bim-site-scale")?.textContent,saveDisabled:document.querySelector("#bim-site-save")?.disabled,overflow:document.documentElement.scrollWidth>innerWidth||document.documentElement.scrollHeight>innerHeight,bounds:(()=>{const b=document.querySelector("#app")?.getBoundingClientRect();return !!b&&b.left>=0&&b.top>=0&&b.right<=innerWidth&&b.bottom<=innerHeight})()})); + assert.equal(types.panel,"HTMLDivElement");assert.equal(types.type,native.preflight.nativeSite.typeId);assert.equal(types.proxy,native.preflight.nativeSite.proxyType);assert.equal(types.month,"6");assert.equal(types.day,"21");assert.equal(types.scale,"20000");assert.equal(types.saveDisabled,false);assert.equal(types.overflow,false);assert.equal(types.bounds,true); + const checks=[];const check=(name,actual,expected)=>{assert.deepEqual(actual,expected,name);checks.push({name,passed:true});}; + check("Site object type is visible",types.type,native.preflight.nativeSite.typeId);check("Site proxy is visible",types.proxy,native.preflight.nativeSite.proxyType);check("default solar values are visible",[types.month,types.day,types.scale],["6","21","20000"]); + const month=page.locator("#bim-site-month");await month.fill("13");await month.dispatchEvent("change");check("SunDateMonth clamps at 12",await month.inputValue(),"12");await month.fill("0");await month.dispatchEvent("change");check("SunDateMonth clamps at 1",await month.inputValue(),"1");await month.fill("6");await page.screenshot({path:`${process.cwd()}/docs/current/business-evidence/desktop-test-bim-testarchsitegui-20261027/${types.bounds?'site':''}-${page.viewportSize()?.width===390?'mobile':'desktop'}-site-panel.png`}); + return {passed:checks.length===5,checks,types}; +} diff --git a/tools/bim-wall-gui-acceptance.mjs b/tools/bim-wall-gui-acceptance.mjs new file mode 100644 index 00000000..c8c1020f --- /dev/null +++ b/tools/bim-wall-gui-acceptance.mjs @@ -0,0 +1,7 @@ +import assert from "node:assert/strict"; +export const wallGuiMethods=Array.from({length:15},(_,i)=>`wall_method_${i+1}`); +export async function verifyWallGui(page,native){ + if(!native||native.ok!==true||native.preflight?.passed!==true||native.preflight.testsRun!==15||native.tests?.length!==15)throw new Error("preflight_failed: Wall native suite contract is incomplete"); + const obs=await page.evaluate(()=>({panel:document.querySelector("#bim-wall-panel")?.constructor.name,status:document.querySelector("#bim-wall-status")?.textContent,tests:document.querySelector("#bim-wall-tests")?.textContent,length:document.querySelector("#bim-wall-length")?.textContent,adapter:document.querySelector("#bim-wall-adapter")?.textContent,baselines:document.querySelector("#bim-wall-baselines")?.textContent,joins:document.querySelector("#bim-wall-joins")?.textContent,readyDisabled:document.querySelector("#bim-wall-ready")?.disabled,overflow:document.documentElement.scrollWidth>innerWidth||document.documentElement.scrollHeight>innerHeight,inViewport:(()=>{const b=document.querySelector("#app")?.getBoundingClientRect();return !!b&&b.left>=0&&b.top>=0&&b.right<=innerWidth&&b.bottom<=innerHeight})()})); + assert.equal(obs.panel,"HTMLDivElement");assert.equal(obs.tests,"15/15");assert.equal(obs.length,"2000");assert.equal(obs.baselines,"NONE, DRAFT_LINE, SKETCH");assert.equal(obs.joins,"AUTOJOIN, JOIN_WALL_SKETCHES, FALLBACK, OFF");assert.equal(obs.readyDisabled,false);assert.equal(obs.overflow,false);assert.equal(obs.inViewport,true);return{passed:true,checks:[{name:"15 official wall methods passed",passed:true},{name:"native geometry and modes rendered",passed:true},{name:"desktop/mobile panel bounds pass",passed:true}],observations:obs}; +} diff --git a/tools/bim-webgl-export-gui-acceptance.mjs b/tools/bim-webgl-export-gui-acceptance.mjs new file mode 100644 index 00000000..4b94be53 --- /dev/null +++ b/tools/bim-webgl-export-gui-acceptance.mjs @@ -0,0 +1,2 @@ +import assert from "node:assert/strict"; +export async function verifyWebGLGui(page,native){if(!native||native.ok!==true||native.preflight?.passed!==true||native.tests?.length!==4)throw new Error("preflight_failed: WebGL native contract incomplete");const obs=await page.evaluate(()=>({panel:document.querySelector("#bim-webgl-panel")?.constructor.name,status:document.querySelector("#bim-webgl-status")?.textContent,tests:document.querySelector("#bim-webgl-tests")?.textContent,template:document.querySelector("#bim-webgl-template")?.textContent,source:document.querySelector("#bim-webgl-source")?.textContent,numpy:document.querySelector("#bim-webgl-numpy")?.textContent,disabled:document.querySelector("#bim-webgl-export")?.disabled,overflow:document.documentElement.scrollWidth>innerWidth||document.documentElement.scrollHeight>innerHeight,inViewport:(()=>{const b=document.querySelector("#app")?.getBoundingClientRect();return !!b&&b.left>=0&&b.top>=0&&b.right<=innerWidth&&b.bottom<=innerHeight})()}));assert.equal(obs.panel,"HTMLDivElement");assert.equal(obs.tests,"4/4");assert.equal(obs.template,native.preflight.templatePath);assert.equal(obs.source,native.preflight.sourcePaths[0]);assert.equal(obs.disabled,false);assert.equal(obs.overflow,false);assert.equal(obs.inViewport,true);return{passed:true,observations:obs};} diff --git a/tools/official-fixture-resolver.mjs b/tools/official-fixture-resolver.mjs new file mode 100644 index 00000000..6f990e17 --- /dev/null +++ b/tools/official-fixture-resolver.mjs @@ -0,0 +1,81 @@ +import fs from "node:fs"; +import path from "node:path"; + +export const OFFICIAL_FIXTURE_AREAS = [ + "examples", "tests/ModelRefineTests", "tests/Step", "tests", +]; + +function inside(parent, candidate) { + const relative = path.relative(parent, candidate); + return relative === "" || (relative && !relative.startsWith("..") && !path.isAbsolute(relative)); +} + +function filesIn(directory) { + try { return fs.readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isFile()).map(entry => entry.name); } + catch { return []; } +} + +function resolveDirectoryInsensitive(dataRoot, area) { + let current = dataRoot; + for (const segment of area.split(/[\\/]/).filter(Boolean)) { + const exact = path.join(current, segment); + if (fs.existsSync(exact)) { current = exact; continue; } + let entries = []; + try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { return exact; } + const actual = entries.find(entry => entry.isDirectory() && entry.name.toLowerCase() === segment.toLowerCase()); + if (!actual) return exact; + current = path.join(current, actual.name); + } + return current; +} + +export function resolveOfficialFixture(root, input, extensions) { + if (typeof input !== "string" || !input.trim()) throw new Error("Fixture basename or data-relative path is required"); + const raw = input.trim().replaceAll("\\", "/"); + const dataRoot = path.resolve(root, "freecad-source/data"); + let requested = raw; + if (path.isAbsolute(raw)) { + const candidate = path.resolve(raw); + if (!inside(dataRoot, candidate)) throw new Error("Absolute fixture path must stay under freecad-source/data"); + requested = path.relative(dataRoot, candidate).split(path.sep).join("/"); + } + requested = requested.replace(/^(?:working\/FreeCAD\/)?freecad-source\/data\//i, "").replace(/^data\//i, ""); + if (requested.includes("..") || requested.startsWith("/")) throw new Error("Fixture path must stay under freecad-source/data"); + const allowed = new Set(extensions.map(extension => extension.toLowerCase())); + const requestedBase = path.basename(requested); + const requestedExt = path.extname(requestedBase).toLowerCase(); + const requestedStem = requestedExt ? requestedBase.slice(0, -requestedExt.length) : requestedBase; + if (requestedExt && !allowed.has(requestedExt)) throw new Error(`Unsupported fixture extension ${requestedExt}; expected ${[...allowed].join(", ")}`); + const areas = requested.includes("/") ? [path.dirname(requested)] : OFFICIAL_FIXTURE_AREAS; + const exact = [], folded = []; + for (const area of areas) { + const directory = path.resolve(resolveDirectoryInsensitive(dataRoot, area)); + if (!inside(dataRoot, directory)) continue; + const names = filesIn(directory); + for (const name of names) { + if (path.extname(name).toLowerCase() && !allowed.has(path.extname(name).toLowerCase())) continue; + const relative = path.posix.join(area.replaceAll(path.sep, "/"), name); + const requestedRelative = requested.includes("/") ? requested : name; + const stem = name.slice(0, -path.extname(name).length); + const basenameMatch = requestedExt ? name === requestedBase : stem === requestedStem; + const foldedBasenameMatch = requestedExt ? name.toLowerCase() === requestedBase.toLowerCase() : stem.toLowerCase() === requestedStem.toLowerCase(); + if (relative === requestedRelative || basenameMatch) exact.push(path.join(directory, name)); + if (relative.toLowerCase() === requested.toLowerCase() || foldedBasenameMatch) folded.push(path.join(directory, name)); + } + } + const matches = [...new Set(exact.length ? exact : folded)]; + if (matches.length === 1) return matches[0]; + if (matches.length > 1) throw new Error(`Fixture is ambiguous: ${input}; candidates: ${matches.map(file => path.relative(root, file)).join(", ")}`); + const searched = [...new Set(areas.map(area => path.relative(root, path.resolve(dataRoot, area))))]; + const suggestions = [...new Set(areas.flatMap(area => filesIn(path.resolve(dataRoot, area)).filter(name => name.toLowerCase().includes(requestedBase.toLowerCase())).map(name => path.posix.join(area, name))))].slice(0, 8); + throw new Error(`Fixture not found: ${input}; searched: ${searched.join(", ")}${suggestions.length ? `; candidates: ${suggestions.join(", ")}` : ""}`); +} + +export function officialFixtureCaseId(root, fixture) { + const relative = path.relative(root, fixture).split(path.sep).join("/"); + const stem = path.basename(fixture, path.extname(fixture)); + if (relative.includes("/data/examples/")) return `fixture.examples.${stem}`; + if (relative.includes("/data/tests/ModelRefineTests/")) return `fixture.tests.ModelRefineTests.${stem}`; + if (relative.includes("/data/tests/Step/")) return `fixture.tests.Step.${stem}`; + return `fixture.tests.${stem}${path.extname(fixture).toLowerCase()}`; +} diff --git a/tools/static-host.mjs b/tools/static-host.mjs new file mode 100644 index 00000000..e3e75d1f --- /dev/null +++ b/tools/static-host.mjs @@ -0,0 +1,39 @@ +/** Shared static host + Chrome discovery for browser runners and the MCP session. */ +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; + +export const CHROME_CANDIDATES = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/opt/google/chrome/google-chrome"]; + +export function findChrome() { + const override = process.env.FREECAD_CHROME; + if (override) return fs.existsSync(override) ? override : null; + return CHROME_CANDIDATES.find((candidate) => fs.existsSync(candidate)) ?? null; +} + +export const ISOLATION_HEADERS = { + "cross-origin-opener-policy": "same-origin", + "cross-origin-embedder-policy": "require-corp", +}; + +const CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css", ".json": "application/json", ".wasm": "application/wasm", ".png": "image/png" }; + +/** + * Serve a built dist directory on an ephemeral loopback port with COOP/COEP. + * Returns { server, origin, close }. + */ +export async function startStaticHost(distRoot, defaultDocument = "index.html") { + if (!fs.existsSync(path.join(distRoot, defaultDocument))) throw new Error(`web/dist/${defaultDocument} is missing; run npm run build first`); + const server = http.createServer((request, response) => { + const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname); + if (requestPath === "/favicon.ico") { response.writeHead(204, ISOLATION_HEADERS); response.end(); return; } + const relative = requestPath === "/" ? defaultDocument : requestPath.replace(/^\/+/, ""); + const filePath = path.resolve(distRoot, relative); + if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; } + if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { response.writeHead(404); response.end("not found"); return; } + response.writeHead(200, { "content-type": CONTENT_TYPES[path.extname(filePath)] ?? "application/octet-stream", "cache-control": "no-store", ...ISOLATION_HEADERS }); + fs.createReadStream(filePath).pipe(response); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + return { server, origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }; +} diff --git a/tools/wasm-probe-runtime.mjs b/tools/wasm-probe-runtime.mjs new file mode 100644 index 00000000..76acaef0 --- /dev/null +++ b/tools/wasm-probe-runtime.mjs @@ -0,0 +1,58 @@ +import fs from "node:fs"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; + +function hasArtifacts(directory, stem) { + return fs.existsSync(path.join(directory, `${stem}.js`)) + && fs.existsSync(path.join(directory, `${stem}.wasm`)); +} + +export function resolveProbeBuildDirectory(input, stem) { + const requested = path.resolve(input); + const candidates = [requested]; + if (path.basename(requested) === "bin") candidates.push(path.dirname(requested)); + else candidates.push(path.join(requested, "bin")); + for (const candidate of candidates) { + if (hasArtifacts(candidate, stem)) return candidate; + const bin = path.join(candidate, "bin"); + if (hasArtifacts(bin, stem)) return bin; + } + throw new Error(`missing ${stem}.{js,wasm} under ${requested}`); +} + +export function stagePthreadWorker(buildDirectory, stem) { + const workerJs = path.join(buildDirectory, `${stem}.worker.js`); + if (!fs.existsSync(workerJs)) return null; + const workerCjs = path.join(buildDirectory, `${stem}.worker.cjs`); + const source = fs.statSync(workerJs); + let current = null; + try { + current = fs.statSync(workerCjs); + } catch { + // The CommonJS staging artifact will be created below. + } + if (!current || current.size !== source.size || current.mtimeMs < source.mtimeMs) { + fs.copyFileSync(workerJs, workerCjs); + } + return workerCjs; +} + +export async function loadWasmProbe(input, stem, options = {}) { + const buildDirectory = resolveProbeBuildDirectory(input, stem); + const workerCjs = stagePthreadWorker(buildDirectory, stem); + globalThis.__dirname = `${buildDirectory}${path.sep}`; + globalThis.require = createRequire(import.meta.url); + const loader = await import(pathToFileURL(path.join(buildDirectory, `${stem}.js`))); + const locateFile = (file) => { + if (workerCjs && file.endsWith(".worker.js")) return workerCjs; + return path.join(buildDirectory, file); + }; + const kernel = await loader.default({ + wasmBinary: fs.readFileSync(path.join(buildDirectory, `${stem}.wasm`)), + locateFile, + print: options.print ?? (() => {}), + printErr: options.printErr ?? (() => {}), + }); + return { kernel, buildDirectory, workerCjs }; +} diff --git a/web/tools/artifact-assets.mjs b/web/tools/artifact-assets.mjs new file mode 100644 index 00000000..c89f43e9 --- /dev/null +++ b/web/tools/artifact-assets.mjs @@ -0,0 +1,60 @@ +import fs from "node:fs"; +import crypto from "node:crypto"; +import path from "node:path"; + +export function copyArtifactAtomically(source, destination, copy = fs.copyFileSync) { + let lastError; + for (let attempt = 0; attempt < 3; attempt += 1) { + const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`; + try { + const before = fs.statSync(source, { bigint: true }); + copy(source, temporary); + const after = fs.statSync(source, { bigint: true }); + if (before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ino !== after.ino) + throw new Error(`Artifact changed while copying; wait for its build to finish: ${source}`); + if (destination.endsWith(".wasm") && !WebAssembly.validate(fs.readFileSync(temporary))) + throw new Error(`Incomplete or invalid WASM; previous published file retained: ${source}`); + fs.renameSync(temporary, destination); + return; + } catch (error) { + lastError = error; + } finally { + fs.rmSync(temporary, { force: true }); + } + } + throw lastError; +} + +export function missingArtifactPair(source) { + const match = path.basename(source).match(/^(FreeCADWeb[A-Za-z0-9]+)\.(?:js|wasm|data|worker\.js)$/); + if (!match) return []; + const stem = path.join(path.dirname(source), match[1]); + return [stem + ".js", stem + ".wasm"].filter(file => !fs.existsSync(file)); +} + +export function pthreadSidecar(source, destination) { + if (!source.endsWith(".js") || source.endsWith(".worker.js")) return null; + const worker = source.slice(0, -3) + ".worker.js"; + return fs.existsSync(worker) ? [worker, destination.slice(0, -3) + ".worker.js"] : null; +} + +export function artifactRevision(hashes) { + return crypto.createHash("sha256").update(JSON.stringify(hashes)).digest("hex").slice(0, 16); +} + +export function writeManifestIfChanged(file, manifest) { + const stable = value => { + const copy = { ...value }; + delete copy.generatedAt; + return JSON.stringify(copy); + }; + try { + if (stable(JSON.parse(fs.readFileSync(file, "utf8"))) === stable(manifest)) return false; + } catch { + // Missing or incomplete manifests are replaced below. + } + const temporary = file + ".tmp"; + fs.writeFileSync(temporary, JSON.stringify(manifest, null, 2) + "\n"); + fs.renameSync(temporary, file); + return true; +}