import type { TestViewExampleResult } from "./test-facade.js"; import { executeMeasureDocument } from "./measure-document-adapter.js"; import { executeMeshPartCurve } from "./meshpart-desktop-adapter.js"; import { executeSurfaceDocument } from "./surface-document-adapter.js"; import { createFailure, createSuccess, createCancel, createRequest, type FacadeFailure, type FacadeRequest, type FacadeResponse, } from "./facade-envelope.js"; import { createWebModuleWorker, getWebModuleRoute, getWebModuleWorkerForCommand, type WebModuleRoute } from "./module-registry.generated.js"; import { loadWebModuleManifest, type WebModuleArtifact } from "./module-loader.js"; import { ResourceLifecycle } from "./resource-lifecycle.js"; import { nativeSourceDecision } from "./native-source-policy.js"; type WorkerReady = { kind: "ready"; action: string }; type WorkerReset = { kind: "reset"; requestId: string }; type WorkerBootstrapError = { kind: "bootstrap-error"; message: string }; type WorkerMessage = FacadeResponse | WorkerReady | WorkerReset | WorkerBootstrapError; interface PendingRequest { resolve: (response: FacadeResponse) => void; reject: (error: Error) => void; cleanup?: () => void; } interface ModuleSession { readonly route: WebModuleRoute; readonly worker: Worker; readonly ready: Promise; readonly failReady: (error: Error) => void; readonly pending: Map; readonly artifactRevision?: string; } /** Routes typed facade envelopes to the existing native module workers. */ export class WebModuleRouter { private readonly sessions = new Map(); private readonly artifacts = new Map(); private readonly lifecycle = new ResourceLifecycle(); private sequence = 0; readonly testSceneDocuments = new Map(); // These documents remain in the Assembly Worker while using the shared body editor. readonly assemblyModelingDocuments = new Set(); private readonly inspectionDocumentOwners = new Map(); readonly meshPartCurveDocuments = new Set(); readonly meshPartMesherDocuments = new Map(); readonly modelingDocumentOwners = new Map(); /** Capture the retained worker identity, without an unrelated-worker fallback. */ graphicsDocumentReader(documentId: string): (() => Promise) | undefined { const document = this.modelingDocumentOwners.get(documentId)?.document ?? documentId; const owner = this.inspectionDocumentOwners.get(document); if (!owner) return; return () => { const current = this.inspectionDocumentOwners.get(document); if (current?.module !== owner.module || current?.workerFile !== owner.workerFile) return Promise.resolve(createFailure("graphics-scene", "document_closed", "The originating document owner is no longer available")); return this.request("Inspection", "inspection.pythonFamilyBatch", { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [{ apiId: "Inspection:desktop:Inspection_VisualInspection", name: "Inspection_VisualInspection", family: "desktop-command", args: { document, action: "read", graphicsSceneRead: true } }], }, document); }; } private readonly completionListeners = new Set<(module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void>(); onRequestCompleted(listener: (module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void): () => void { this.completionListeners.add(listener); return () => { this.completionListeners.delete(listener); }; } route(module: string): WebModuleRoute | undefined { return getWebModuleRoute(module); } private open(module: string, workerFile?: string): ModuleSession | undefined { const route = getWebModuleRoute(module); const selectedWorker = workerFile ?? route?.primaryWorker ?? undefined; const sessionKey = `${module}:${selectedWorker ?? ""}`; const existing = this.sessions.get(sessionKey); if (existing) return existing; const artifact = this.artifacts.get(module); const worker = createWebModuleWorker(module, selectedWorker, artifact); if (!route || !worker) return undefined; const pending = new Map(); let resolveReady!: () => void; let rejectReady!: (error: Error) => void; const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); const session: ModuleSession = { route, worker, ready, failReady: rejectReady, pending, artifactRevision: artifact?.revision }; const failSession = (error: Error) => { rejectReady(error); for (const request of pending.values()) { request.cleanup?.(); request.reject(error); } pending.clear(); if (this.sessions.get(sessionKey) === session) { this.sessions.delete(sessionKey); this.lifecycle.release(`worker:${sessionKey}`); } }; worker.onmessage = (event: MessageEvent) => { const message = event.data; if (message.kind === "ready") { resolveReady(); return; } if (message.kind === "reset") return; if (message.kind === "bootstrap-error") { failSession(new Error(`${module} worker bootstrap failed: ${message.message}`)); return; } const request = pending.get(message.requestId); if (!request) { // Older workers use these sentinel IDs for startup/protocol errors. // They cannot be correlated to one command, so fail the broken session. if (message.kind === "error" && ["initialization", "invalid"].includes(message.requestId)) { failSession(new Error(`${module} ${selectedWorker} failed: ${message.error.code}: ${message.error.message}`)); } return; } pending.delete(message.requestId); request.cleanup?.(); request.resolve(message); }; worker.onerror = (event) => { const error = new Error(`${module} worker failed: ${event.message}`); failSession(error); }; this.sessions.set(sessionKey, session); this.lifecycle.track({ label: `worker:${sessionKey}`, dispose: () => worker.terminate() }); return session; } /** Register or replace the independently built artifact for one module. */ setArtifact(module: string, artifact: WebModuleArtifact): void { if (!getWebModuleRoute(module)) throw new Error(`module ${module} is not registered`); const previous = this.artifacts.get(module); this.artifacts.set(module, artifact); if (previous?.revision === artifact.revision) return; if (module === "Test") this.testSceneDocuments.clear(); this.closeSessions(module, new Error(`module ${module} artifact changed to ${artifact.revision}`)); } clearArtifact(module: string): void { this.artifacts.delete(module); if (module === "Test") this.testSceneDocuments.clear(); this.closeSessions(module, new Error(`module ${module} artifact cleared`)); } getArtifact(module: string): WebModuleArtifact | undefined { return this.artifacts.get(module); } async loadManifest(url: string, init?: RequestInit): Promise { const manifest = await loadWebModuleManifest(url, init); const loaded: string[] = []; for (const [module, artifact] of Object.entries(manifest.modules)) { if (!getWebModuleRoute(module)) continue; this.setArtifact(module, artifact); loaded.push(module); } return loaded.sort(); } listLoaded(): Array<{ module: string; worker: string; revision?: string }> { return [...this.sessions.entries()].map(([key, session]) => { const separator = key.indexOf(":"); return { module: separator < 0 ? key : key.slice(0, separator), worker: separator < 0 ? key : key.slice(separator + 1), revision: session.artifactRevision, }; }); } /** Preload one command worker without issuing a native command. */ async preload(module: string, workerFile?: string): Promise { const selectedWorker = workerFile ?? getWebModuleRoute(module)?.primaryWorker ?? undefined; const session = this.open(module, selectedWorker); if (!session) throw new Error(`${module} has no runnable Web Worker route`); await session.ready; } private closeSessions(module?: string, error?: Error): void { if (!module || module === "MeshPart") { this.meshPartCurveDocuments.clear(); this.meshPartMesherDocuments.clear(); } for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name); for (const [key, session] of this.sessions) { if (module && !key.startsWith(`${module}:`)) continue; this.sessions.delete(key); session.failReady(error ?? new Error(`module ${key} closed`)); if (error) for (const request of session.pending.values()) { request.cleanup?.(); request.reject(error); } session.pending.clear(); session.worker.terminate(); this.lifecycle.release(`worker:${key}`); } } async request(module: string, command: string, payload: Payload, documentId = `${module.toLowerCase()}-document`, signal?: AbortSignal): Promise { if (module === "ReverseEngineering" && command === "reverseengineering.pythonFamilyBatch") { const records = (payload as any)?.records; if (records?.some((row: any) => ["Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(row.name))) { if (records.length !== 1) return createFailure("native-fit", "invalid_request", "Run one approximation command at a time"); if (signal?.aborted) return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch"); if (!this.inspectionDocumentOwners.has(documentId)) return createFailure("native-fit", "missing_document", "Select geometry in an open native document"); const response = await this.request("Inspection", "inspection.pythonFamilyBatch", { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command", args: { ...records[0].args, document: documentId, approximationCommand: records[0].name } }], }, documentId, signal); if (response.kind !== "result") return response; const batch = response.result as any; if (batch.ok === false || !Array.isArray(batch.records)) return createFailure("native-fit", batch.code || "native_error", batch.error || "Native fitting failed"); return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering", schema: "freecad-web-reverseengineering/python-family-batch/v1", records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) }); } if (records?.some((row: any) => ["Reen_Segmentation", "Reen_SegmentationManual", "Reen_SegmentationFromComponents"].includes(row.name))) { if (records.length !== 1) return createFailure("manual-segmentation", "active_task", "Open one manual segmentation task at a time"); if (!this.inspectionDocumentOwners.has(documentId)) return createFailure("manual-segmentation", "missing_document", "Choose an active native document before opening manual segmentation"); const response = await this.request("Inspection", "inspection.pythonFamilyBatch", { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command", args: { ...records[0].args, document: documentId, manualSegmentation: records[0].name === "Reen_SegmentationManual", automaticSegmentation: records[0].name === "Reen_Segmentation", componentsSegmentation: records[0].name === "Reen_SegmentationFromComponents" } }], }, documentId, signal); if (response.kind !== "result") return response; const batch = response.result as any; return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering", schema: "freecad-web-reverseengineering/python-family-batch/v1", records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) }); } } if (module === "Measure" && command === "measure.pythonFamilyBatch") { const records = (payload as { records?: Array<{ apiId: string; args?: Record }> }).records; if (records?.some(r => ["Measure:desktop:Std_Measure", "Measure:desktop:Std_MassProperties"].includes(r.apiId))) { if (records.length !== 1) return createFailure("measure-document", "invalid_request", "Measure one selection at a time"); return executeMeasureDocument(this, { ...records[0].args, ...(records[0].apiId.endsWith(":Std_MassProperties") ? { action: "massProperties" } : {}) }, documentId); } } if (module === "Surface" && command === "Surface_CurveOnMesh") { const args = payload as Record; return executeMeshPartCurve(this, { id: "MeshPart:desktop:MeshPart_CurveOnMesh", module: "MeshPart", command: "MeshPart_CurveOnMesh", kind: "desktop-gui", sourcePath: "src/Mod/Surface/Gui/Command.cpp" }, args, typeof args.documentId === "string" ? args.documentId : documentId); } if (module === "Surface" && ["Surface_BlendCurve", "Surface_ExtendFace"].includes(command)) return (await executeSurfaceDocument(this, command, payload as Record, documentId))!; if (module === "Surface" && ["surface.desktopCommand", "surface.pythonFamilyBatch"].includes(command)) { const commands = (payload as { commands?: Array<{ apiId: string; args?: Record }>; records?: Array<{ apiId: string; args?: Record }> })?.[command === "surface.desktopCommand" ? "commands" : "records"]; if (commands?.some(item => item.apiId === "Surface:desktop:Surface_CurveOnMesh")) { if (commands.length !== 1) return createFailure("surface-curve", "active_task", "Open one curve task at a time"); return this.request("Surface", "Surface_CurveOnMesh", commands[0].args ?? {}, documentId, signal); } if (commands?.some(item => ["Surface:desktop:Surface_BlendCurve", "Surface:desktop:Surface_Filling", "Surface:desktop:Surface_Sections", "Surface:desktop:Surface_ExtendFace"].includes(item.apiId))) { if (commands.length !== 1) return createFailure("surface-document", "invalid_request", "Edit one Surface feature at a time"); const response = await executeSurfaceDocument(this, commands[0].apiId.split(":").pop()!, commands[0].args ?? {}, documentId); if (!response || response.kind === "error") return response!; return createSuccess(response.requestId, { ok: true, cmd: command, module: "Surface", source: "freecad-source", count: 1, results: [{ apiId: commands[0].apiId, status: "exposed", native: true, runtimeOwner: "DocumentProbe", ...response.result as object }] }); } } if (module === "Points" && ["points.saveReopen", "points.createRecompute"].includes(command)) { const args = payload as Record; payload = { ...args, document: args.document ?? documentId } as Payload; } const inspectionTask = module === "Inspection" && command === "inspection.pythonFamilyBatch" && (payload as any)?.records?.every((record: any) => ["Inspection_VisualInspection", "Inspection_InspectElement"].includes(record.name)); const inspectionOwner = inspectionTask ? this.inspectionDocumentOwners.get(documentId) : undefined; if (module === "Test") { const scenePayload = payload as { command?: string; args?: Record }; if (["Std_ViewExample1", "Std_ViewExample2", "Std_ViewExample3"].includes(scenePayload.command ?? "")) { const id = String(scenePayload.args?.documentId ?? documentId); scenePayload.args = { ...scenePayload.args, documentId: id.startsWith("test-scene-") ? id : `test-scene-${id}` }; } } const sourceDecision = nativeSourceDecision(module, command); if (sourceDecision) return createFailure(`module-${module.toLowerCase()}-native-source`, sourceDecision.code, sourceDecision.message, sourceDecision.diagnostic); const route = getWebModuleRoute(module); if (!route) return createFailure("invalid", "unknown_module", `module ${module} is not registered`, { module }); const pointsCurveTask = module === "Points" && command === "reverseengineering.pythonFamilyBatch"; if (!pointsCurveTask && !route.commands.includes(command)) return createFailure("invalid", "not_implemented", `command ${command} is not registered for ${module}`, { module, command }); const assemblyModeling = command === "partdesign.document" && this.assemblyModelingDocuments.has(documentId); const workerFile = assemblyModeling ? "assembly.worker.ts" : inspectionOwner?.workerFile ?? (pointsCurveTask ? "points.worker.ts" : getWebModuleWorkerForCommand(module, command)); const ownerModule = assemblyModeling ? "Assembly" : inspectionOwner?.module ?? module; const session = this.open(ownerModule, workerFile); if (!session) return createFailure("invalid", "not_implemented", `${module} has no runnable Web Worker route`, { module }); await session.ready; if (inspectionTask && (payload as any)?.records?.some((row: any) => row.args?.approximationCommand) && signal?.aborted) return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch"); const requestId = `module-${module.toLowerCase()}-${++this.sequence}`; const request = createRequest(requestId, command, payload, documentId) as FacadeRequest; return new Promise((resolve, reject) => { const onAbort = () => session.worker.postMessage(createCancel(`module-cancel-${++this.sequence}`, requestId, documentId)); signal?.addEventListener("abort", onAbort, { once: true }); session.pending.set(requestId, { resolve: (response) => { if ((command === "part.document" || command === "partdesign.document") && response.kind === "result") { const result = response.result as { document?: string; closed?: boolean }; if (result.document) { if (result.closed) { for (const [key, owner] of this.modelingDocumentOwners) if (owner.document === result.document) this.modelingDocumentOwners.delete(key); } else { const owner = { document: result.document, module: command === "part.document" ? "Part" as const : "PartDesign" as const }; this.modelingDocumentOwners.set(documentId, owner); this.modelingDocumentOwners.set(result.document, owner); } } } if (response.kind === "result" && workerFile && ["part-save.worker.ts", "part.worker.ts", "partdesign.worker.ts", "partdesign-python.worker.ts", "sketcher.worker.ts", "sketcher-python.worker.ts", "draft.worker.ts", "bim.worker.ts", "points.worker.ts", "mesh.worker.ts", "inspection.worker.ts"].includes(workerFile)) { const value = response.result as any; const candidates = [value, ...(value.records ?? []).flatMap((row: any) => row.status === "exposed" ? [row, row.result, row.value] : [])]; for (const candidate of candidates) { const name = candidate?.documentId ?? candidate?.document ?? candidate?.documentHandle; if (typeof name === "string" && (Array.isArray(candidate?.objects) || Array.isArray(candidate?.shapes) || typeof candidate?.geometryCount === "number" || candidate?.closed)) { if (candidate.closed) this.inspectionDocumentOwners.delete(name); else this.inspectionDocumentOwners.set(name, { module: ownerModule, workerFile }); } } } if (module === "Test" && response.kind === "result") { const result = response.result as TestViewExampleResult; if (result.operation === "view-example") { if (result.closed) this.testSceneDocuments.delete(result.documentId); else if (result.documentName) this.testSceneDocuments.set(result.documentId, result); } } resolve(response); for (const listener of this.completionListeners) listener(module, command, payload, documentId, response); }, reject, cleanup: signal ? () => signal.removeEventListener("abort", onAbort) : undefined }); session.worker.postMessage(request); }); } reset(module?: string): void { if (!module || module === "Test") this.testSceneDocuments.clear(); for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name); const sessions = module ? [...this.sessions.entries()].filter(([key]) => key.startsWith(`${module}:`)).map(([, session]) => session) : [...this.sessions.values()]; for (const session of sessions) { const requestId = `module-reset-${++this.sequence}`; session.worker.postMessage({ kind: "reset", requestId }); } } dispose(): void { this.closeSessions(undefined, new Error("module router disposed")); this.lifecycle.disposeAll(); this.testSceneDocuments.clear(); this.sessions.clear(); this.artifacts.clear(); } } export type WebModuleFailure = FacadeFailure;