import { createMockFacade } from './facade/mockFacade'
import { createFemAnalysis } from './facade/fem'
type FemReport = { schemaVersion: 1; status: 'pass' | 'failed'; browserId: 'chrome'; crossOriginIsolated: boolean; geometry?: { sourceShape: string; valid: boolean; vertices: number; volume: number }; solve?: { status: string; strategy: string; nodes: number; nodeSets: number; resultFields: string[]; maxDisplacement: number; maxStress: number; csvBytes: number }; persistence?: { mode: string; byteLength: number; hash: string; roundTrip: boolean; released: boolean }; opfs?: { markerSuite: string; nodes: number; markerRemoved: boolean }; afterRelease?: { shapeCount: number; kernelReferenceCount: number }; error?: string }
const sha256 = async (bytes: Uint8Array) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes).buffer))].map((value) => value.toString(16).padStart(2, '0')).join('')
const run = async (): Promise<FemReport> => { const facade = createMockFacade(); const report: FemReport = { schemaVersion: 1, status: 'failed', browserId: 'chrome', crossOriginIsolated: globalThis.crossOriginIsolated === true }; try { if (!report.crossOriginIsolated || !navigator.storage?.getDirectory) throw new Error('Chrome FEM evidence requires isolated OPFS.'); await facade.project.list(); const shape = await facade.geometry.createBox({ documentId: 'fem', documentVersion: 1, width: 10, length: 2, height: 2 }); const quality = await facade.geometry.qualityReport(shape); const mass = await facade.geometry.massProperties(shape); const fem = createFemAnalysis('analysis', 'Reference bar'); fem.setMaterial({ id: 'steel', youngsModulus: 200000, poissonRatio: 0.3 }); fem.setMesh([{ id: 1, position: [0, 0, 0] }, { id: 2, position: [10, 0, 0] }]); fem.addNodeSet({ id: 'bar-ends', nodeIds: [1, 2], role: 'result' }); fem.fixNode(1); fem.addLoad({ nodeId: 2, force: 100 }); const solved = fem.solve({ length: 10, area: 4 }); const csv = new TextEncoder().encode(fem.exportResultsCsv()); const snapshot = fem.snapshot(); const payload = new TextEncoder().encode(JSON.stringify(snapshot)); const stored = await facade.project.resource.put(payload, 'text/csv'); const loaded = await facade.project.resource.get(stored.hash); const roundTrip = loaded !== null && await sha256(loaded) === await sha256(payload); await facade.project.resource.release(stored.hash); const released = await facade.project.resource.get(stored.hash) === null; const directory = await navigator.storage.getDirectory(); const markerName = 'fem-chrome-marker.json'; const marker = await directory.getFileHandle(markerName, { create: true }); const writable = await marker.createWritable(); await writable.write(JSON.stringify({ suite: 'FEM-ALL', nodes: snapshot.nodes.length })); await writable.close(); const markerPayload = JSON.parse(await (await marker.getFile()).text()) as { suite: string; nodes: number }; await directory.removeEntry(markerName); let markerRemoved = false; try { await directory.getFileHandle(markerName) } catch (error) { markerRemoved = error instanceof DOMException && error.name === 'NotFoundError' }; report.geometry = { sourceShape: shape.id, valid: quality.structuralValid, vertices: quality.vertices, volume: mass.volume }; report.solve = { status: solved.status, strategy: solved.solverStrategy, nodes: solved.results.length, nodeSets: solved.nodeSets.length, resultFields: solved.resultFields.map((field) => field.name), maxDisplacement: Math.max(...solved.results.map((entry) => entry.displacement)), maxStress: Math.max(...solved.results.map((entry) => entry.stress)), csvBytes: csv.byteLength }; report.persistence = { mode: facade.project.capabilities().mode, byteLength: stored.byteLength, hash: stored.hash, roundTrip, released }; report.opfs = { markerSuite: markerPayload.suite, nodes: markerPayload.nodes, markerRemoved }; report.status = report.geometry.valid && report.solve.status === 'solved' && report.solve.strategy === 'local-reference' && report.solve.nodes === 2 && report.solve.nodeSets === 1 && JSON.stringify(report.solve.resultFields) === JSON.stringify(['displacement', 'stress']) && report.solve.maxDisplacement === 0.00125 && report.solve.maxStress === 25 && report.solve.csvBytes > 0 && report.persistence.mode === 'sqlite-opfs' && report.persistence.roundTrip && report.persistence.released && report.opfs.markerSuite === 'FEM-ALL' && report.opfs.nodes === 2 && report.opfs.markerRemoved ? 'pass' : 'failed' } catch (error) { report.error = error instanceof Error ? error.stack || error.message : String(error) } finally { facade.geometry.dispose(); await new Promise((resolve) => setTimeout(resolve, 0)); const capabilities = facade.geometry.capabilities(); report.afterRelease = { shapeCount: capabilities.shapeCount, kernelReferenceCount: capabilities.kernelReferenceCount }; if (capabilities.shapeCount !== 0 || capabilities.kernelReferenceCount !== 0) { report.status = 'failed'; report.error = `${report.error ? `${report.error} ` : ''}Shape ownership gate failed.` } } return report }
run().then((report) => { ;(window as Window & { __bitbybitFemReport?: FemReport }).__bitbybitFemReport = report; document.documentElement.dataset.status = report.status; document.querySelector('#result')!.textContent = JSON.stringify(report, null, 2) }).catch((error) => { document.documentElement.dataset.status = 'failed'; document.querySelector('#result')!.textContent = error instanceof Error ? error.stack || error.message : String(error) })
export {}
