@mica-js/editor 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-DA-1aECx.js","names":["closeBitmap","IDLE"],"sources":["../src/fused/runtime/protocol.ts","../src/fused/runtime/packages.ts","../src/fused/runtime/host/audio.ts","../src/fused/runtime/host/connection.ts","../src/fused/runtime/host/display.ts","../src/fused/runtime/model-events.ts","../src/fused/runtime/host/model.ts","../src/fused/runtime/host/runtime.ts","../src/fused/runtime/values.ts","../src/fused/runtime/simulation/model-channel.ts","../src/fused/runtime/simulation/guest.ts","../src/fused/runtime/audio.ts","../src/fused/runtime/display/model.ts","../src/fused/runtime/display/view.ts","../src/fused/runtime/display/guest.ts","../src/fused/runtime/index.ts"],"sourcesContent":["/**\n * Wire contracts of the fused editor runtime bridge (RFC 0022 / RFC 0025).\n *\n * One simulation guest owns the document snapshot, the locked packages and every model; one display\n * guest owns the declared `view2d.entry` modules and draws overlays. Both are `SandboxWorker` guests\n * and speak only these typed RPC services over ports created with `createRpc`: the main thread never\n * imports a model or an author view module.\n *\n * Binary payloads, package bytes and overlay bitmaps travel through registration transfer hooks; the\n * model lane is a direct port between the two guests, so a display input handler reaches its model\n * without a hop through the editor.\n */\nimport { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { WidgetAudioMountInfo, WidgetAudioState } from '@mica-js/widget/audio-guest';\nimport type { IFusedAudio } from './audio';\nimport type {\n DeviceLock,\n FusedDocument,\n Geometry2D,\n PackageFile,\n Point2D,\n Value,\n} from '@mica-js/document/fused';\nimport type {\n ProgramArtifact,\n ProgramFile,\n ProgramTarget,\n MemoryProgram,\n ProgramFiles,\n ModelEvent,\n ResourceRequest,\n RuntimeDiagnostic,\n} from '@mica-js/sdk/fused';\n\n/** Session status the host mirrors; `idle` means no models are mounted (edit mode). */\nexport type FusedSessionStatus = 'idle' | 'paused' | 'running' | 'faulted' | 'disposed';\n\n/** Presentation mode of one workbench (RFC 0025). */\nexport type FusedDisplayMode = 'edit' | 'run';\n\n/** One loaded firmware segment of a presentation snapshot (RFC 0026). */\nexport interface IFusedFirmwareSegment {\n readonly addressSpace: string;\n readonly address: number;\n /** Segment bytes; an independent copy owned by the presentation snapshot. */\n readonly bytes: Uint8Array;\n}\n\n/** Read-only firmware snapshot a presentation may read (RFC 0026). */\nexport interface IFusedFirmwareSnapshot {\n readonly kind: 'firmware';\n readonly segments: readonly IFusedFirmwareSegment[];\n}\n\nexport interface IFusedProgramFilesSnapshot {\n readonly kind: 'filesystem';\n readonly files: readonly ProgramFile[];\n}\n\n/**\n * One resolved property value a presentation may read.\n *\n * Scalars stay plain; `image` and `binary` properties are their resolved bytes; `firmware`\n * properties are the loaded, segment-addressable snapshot. Resolution happens in the simulation\n * worker, so an unresolved property rejects the presentation instead of shrinking its props.\n */\nexport type FusedPresentationValue =\n | string\n | number\n | boolean\n | null\n | Uint8Array\n | IFusedFirmwareSnapshot\n | IFusedProgramFilesSnapshot;\n\nexport type FusedResolvedPresentationProps = Readonly<\n Record<string, string | number | boolean | null | Uint8Array | MemoryProgram | ProgramFiles>\n>;\n\n/** Read-only plain property snapshot handed to a 2D presentation. */\nexport type FusedPresentationProps = Readonly<Record<string, FusedPresentationValue>>;\n\n/** State of the simulation session as the host sees it. */\nexport interface IFusedSessionState {\n readonly status: FusedSessionStatus;\n readonly simTime: TimePs;\n}\n\n/**\n * Everything the display worker needs to prepare one instance.\n *\n * Geometry and the property projection are resolved inside the simulation worker, so the host never\n * parses a manifest or evaluates an author module.\n */\nexport interface IFusedInstancePresentation {\n readonly instanceId: string;\n /** Full `publisher:name` device id the instance locks. */\n readonly device: string;\n readonly lock: DeviceLock;\n readonly geometry: Geometry2D;\n /** Package-root relative `.js` overlay entry; `undefined` for a geometry-only device. */\n readonly view: string | undefined;\n /**\n * Resolved property snapshot, identical to the one the model receives: manifest default and\n * document override through the SDK, with resource bytes and the loaded firmware image. An\n * instance whose props cannot be projected has no presentation at all, so this is never partial.\n */\n readonly props: FusedPresentationProps;\n /** Declared model method names; empty for a device without a model. */\n readonly methods: readonly string[];\n /** Declared model event names; empty for a device without a model. */\n readonly events: readonly string[];\n}\n\n/** Preparation request of the simulation guest: verify packages and describe the scene. */\nexport interface IFusedPrepareRequest {\n readonly document: FusedDocument;\n readonly mode: FusedDisplayMode;\n}\n\nexport interface IFusedPrepareResult {\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Request that creates the models of one run session. */\nexport interface IFusedLoadRequest {\n readonly document: FusedDocument;\n /** Fixed positive step of every advance, in picoseconds. */\n readonly step: TimePs;\n /** Explicit simulator batch-execution switch; omitted uses the board default. */\n readonly batchExecution?: boolean;\n}\n\n/** One model event as it crosses the sandbox boundary. */\nexport interface IFusedModelEventWire {\n readonly instanceId: string;\n readonly event: string;\n readonly payload: ModelEvent<Value>;\n}\n\n/** Dynamic methods of one display-side model client; only declared names resolve. */\nexport type FusedModelMethods = Readonly<Record<string, (params: Value) => Promise<Value>>>;\n\n/** Declared event outlets of one model client. */\nexport type FusedModelEvents = Readonly<Record<string, Event<ModelEvent<Value>>>>;\n\n/**\n * Model client handed to a presentation or to the editor.\n *\n * Structurally the RFC 0021 `ModelClient` of a dynamically declared interface: methods are\n * asynchronous and every event is a core `Event` of a `ModelEvent` payload.\n */\nexport interface IFusedModelClient {\n readonly methods: FusedModelMethods;\n readonly events: FusedModelEvents;\n}\n\n/** Package resources one presentation may read (RFC 0022 `ViewAssets`). */\nexport interface IFusedViewAssets {\n /** Reads one declared package file; bytes are copied into the caller. */\n read(path: string): Promise<Uint8Array>;\n /** Decodes one image; the caller owns the bitmap and must `close()` it. */\n loadImage(path: string): Promise<ImageBitmap>;\n}\n\nexport type FusedViewInputType = 'pointerdown' | 'pointerup' | 'pointermove';\n\n/** Local pointer input delivered to one presentation (RFC 0022). */\nexport interface IFusedViewInput {\n readonly type: FusedViewInputType;\n /** Position in the device's local coordinates. */\n readonly position: Point2D;\n /** DOM button number of the event. */\n readonly button: number;\n /** DOM button bit mask of the buttons currently held. */\n readonly buttons: number;\n}\n\n/** Context a `view2d.entry` factory receives (RFC 0022). */\nexport interface IFusedView2DContext {\n readonly mode: FusedDisplayMode;\n readonly props: FusedResolvedPresentationProps;\n readonly geometry: Geometry2D;\n /** Proxy of the owning instance; `undefined` in edit mode and for devices without a model. */\n readonly model: IFusedModelClient | undefined;\n readonly assets: IFusedViewAssets;\n /** Instance audio, independent of overlay rendering and HTML panels. */\n readonly audio: IFusedAudio;\n /** Marks the overlay stale; the host decides when to repaint. */\n invalidate(): void;\n}\n\n/** Object a `view2d.entry` default factory returns (RFC 0022). */\nexport interface IFusedView2D {\n initialize?(): void | Promise<void>;\n renderOverlay?(context: OffscreenCanvasRenderingContext2D): void;\n input?(event: IFusedViewInput): void | Promise<void>;\n dispose?(): void;\n}\n\n/** Default export of a `view2d.entry` module. */\nexport type FusedView2DFactory = (context: IFusedView2DContext) => IFusedView2D;\n\n/** Simulation guest, reached through {@link fusedSimulationService}. */\nexport interface IFusedSimulationService {\n prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult>;\n load(request: IFusedLoadRequest): Promise<IFusedSessionState>;\n step(): Promise<IFusedSessionState>;\n resume(): Promise<void>;\n /** Stops advancement synchronously; the RPC result acknowledges the paused state. */\n pause(): void;\n reset(): Promise<void>;\n /** Releases the models and keeps the captured package bytes for the next load. */\n dispose(): Promise<void>;\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n getState(): IFusedSessionState;\n onDidChangeState(listener: (state: IFusedSessionState) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n /** Every model event of the session, in production order. */\n onDidModelEvent(listener: (event: IFusedModelEventWire) => void): () => void;\n}\n\n/** Paths of one locked package, resolved by the host (RFC 0020). */\nexport interface IFusedPackageFilesWire {\n readonly lock: DeviceLock;\n readonly files: Readonly<Record<string, PackageFile>>;\n}\n\n/** Host package access both guests share; the host owns the bytes and verifies nothing twice. */\nexport interface IFusedHostPackageService {\n open(lock: DeviceLock): Promise<IFusedPackageFilesWire>;\n /** Returns a copy the guest may keep; the reply transfers its buffer. */\n read(lock: DeviceLock, path: string): Promise<Uint8Array>;\n}\n\n/** Host resources the simulation guest reaches during preparation (RFC 0020 / RFC 0026). */\nexport interface IFusedHostResourceService {\n readResource(request: ResourceRequest): Promise<Uint8Array>;\n resolveProgramProject(projectId: string, target: ProgramTarget): Promise<ProgramArtifact>;\n}\n\n/** Model lane served by the simulation guest to the display guest over the direct port. */\nexport interface IFusedModelChannelService {\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n /** Replies on the model lane after every event already sent on that lane. */\n settle(): void;\n}\n\n/** Model event lane served by the display guest to the simulation guest. */\nexport interface IFusedModelSinkService {\n deliver(event: IFusedModelEventWire): void;\n}\n\n/** Preparation of the display guest: one mode and the instances of the current session. */\nexport interface IFusedDisplayPrepareRequest {\n readonly mode: FusedDisplayMode;\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Pixels per local unit and the overlay extent the host reserves for one instance. */\nexport interface IFusedDisplayLayout {\n /** Overlay width in device pixels. */\n readonly width: number;\n /** Overlay height in device pixels. */\n readonly height: number;\n /** Device pixels per local unit. */\n readonly scale: number;\n}\n\n/** One overlay render request. */\nexport interface IFusedRenderRequest extends IFusedDisplayLayout {\n readonly instanceId: string;\n /** Monotonic request number the frame echoes back, so stale results are dropped. */\n readonly generation: number;\n}\n\n/** Rendered overlay of one instance; the bitmap lives in the host after the transfer. */\nexport interface IFusedOverlayFrame extends IFusedDisplayLayout {\n readonly instanceId: string;\n readonly generation: number;\n readonly bitmap: ImageBitmap;\n}\n\n/** A presentation asked for a repaint. */\nexport interface IFusedInvalidateEvent {\n readonly instanceId: string;\n}\n\n/** Display guest, reached through {@link fusedDisplayService}. */\nexport interface IFusedDisplayService {\n /** Direct display guest to audio worklet lane, transferred by the host. */\n attachAudio(port: MessagePort): void;\n setAudioState(state: WidgetAudioState): void;\n /**\n * Creates the presentation factories of one mode; nothing is initialized yet.\n *\n * It runs before the models exist, so a factory can subscribe to model events and still observe\n * the events the model produces while it initializes.\n */\n prepare(request: IFusedDisplayPrepareRequest): Promise<void>;\n /**\n * Runs `initialize` of every prepared presentation, after the models are mounted and their initial\n * events were delivered (RFC 0025 startup barrier).\n */\n activate(): Promise<void>;\n /** Renders one overlay; `undefined` when the instance has no dynamic overlay. */\n render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined>;\n /** Delivers local pointer input; the guest reports a failing handler as `view2d/input-failed`. */\n input(instanceId: string, event: IFusedViewInput): void;\n release(instanceId: string): void;\n dispose(): Promise<void>;\n onDidInvalidate(listener: (change: IFusedInvalidateEvent) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n}\n\n/** Wire name of the simulation guest. */\nexport const fusedSimulationService = defineRpcService<IFusedSimulationService>('fused-simulation');\n\n/** Wire name of the 2D presentation guest. */\nexport const fusedDisplayService = defineRpcService<IFusedDisplayService>('fused-display');\n\n/** Wire name of the host package access both guests use. */\nexport const fusedHostPackageService =\n defineRpcService<IFusedHostPackageService>('fused-host-package');\n\n/** Wire name of the host resource access of the simulation guest. */\nexport const fusedHostResourceService =\n defineRpcService<IFusedHostResourceService>('fused-host-resource');\n\n/** Wire name of the model lane the simulation guest serves. */\nexport const fusedModelChannelService =\n defineRpcService<IFusedModelChannelService>('fused-model-channel');\n\n/** Wire name of the model sink the display guest serves. */\nexport const fusedModelSinkService = defineRpcService<IFusedModelSinkService>('fused-model-sink');\n\n/** Host opens and revokes instance generations; samples use the separate worklet port. */\nexport interface IFusedHostAudioService {\n open(instanceId: string): Promise<WidgetAudioMountInfo>;\n close(instanceId: string, session: string): void;\n}\n\nexport const fusedHostAudioService = defineRpcService<IFusedHostAudioService>('fused-host-audio');\n","/**\n * Package access of the sandbox guests (RFC 0020).\n *\n * The host owns the packages, so both guests reach the same typed service: `open` proves the lock\n * resolves and `read` hands over one declared file. The guest caches the bytes, because preparation\n * reads the same file for its digest and again for its content, and each reply transfers ownership.\n */\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry } from '@mica-js/document/fused';\nimport { fusedHostPackageService } from './protocol';\nimport type { IFusedPackageFilesWire } from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/** Wire key of one locked package. */\nexport function packageLockKey(lock: DeviceLock): string {\n return `${lock.id}@${lock.version}#${lock.integrity}`;\n}\n\n/** Registry implementation served by the host over `endpoint`. */\nexport function createHostPackageGateway(endpoint: RpcEndpoint): DeviceRegistry {\n const host = endpoint.getProxy(fusedHostPackageService);\n const opened = new Map<string, Promise<IFusedPackageFilesWire>>();\n const cache = new Map<string, Uint8Array>();\n const openLock = (lock: DeviceLock): Promise<IFusedPackageFilesWire> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = host.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n return {\n open(lock: DeviceLock) {\n return openLock(lock).then((files) => ({\n lock: files.lock,\n files: files.files,\n read: async (path: string) => {\n const key = `${packageLockKey(lock)}\\u0000${path}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.read(lock, path);\n if (!(bytes instanceof Uint8Array)) {\n throw new FusedBridgeError(\n 'package/not-found',\n `The host returned no bytes for ${lock.id}/${path}.`,\n );\n }\n // The reply transferred ownership, so the cache keeps the only copy of this realm.\n cache.set(key, bytes);\n return bytes.slice();\n },\n }));\n },\n };\n}\n","import { WidgetAudioEngine } from '@mica-js/widget/audio-host';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type { IFusedAudioControls, IFusedAudioOptions } from '../audio';\nimport { fusedHostAudioService, type IFusedDisplayService } from '../protocol';\n\n/** Browser-owned audio engine; the guest only receives session tokens and a worklet port. */\nexport function connectFusedAudio(\n rpc: RpcEndpoint,\n display: Pick<RpcProxy<IFusedDisplayService>, 'attachAudio' | 'setAudioState'>,\n options: IFusedAudioOptions | undefined,\n report: (diagnostic: RuntimeDiagnostic) => void,\n): IFusedAudioControls & { clear(): void; dispose(): void } {\n const instances = new Set<string>();\n const reported = new Set<string>();\n let disposed = false;\n function bridgeFailure(operation: string, cause: unknown): void {\n if (disposed || reported.has(operation)) return;\n reported.add(operation);\n report({ code: 'audio/failed', message: `Audio bridge ${operation} failed: ${String(cause)}` });\n }\n const engine =\n options === undefined\n ? undefined\n : new WidgetAudioEngine({\n context: options.context,\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n ...(options.limits === undefined ? {} : { limits: options.limits }),\n ...(options.getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => options.getAudioWorklet!(options.context),\n }),\n notify: {\n emitPort: (port) => {\n void display.attachAudio(port).catch((cause: unknown) => {\n port.close();\n bridgeFailure('attachAudio', cause);\n });\n },\n emitState: (state) => {\n void display.setAudioState(state).catch((cause: unknown) => {\n bridgeFailure('setAudioState', cause);\n });\n },\n },\n report: (code, instanceId, message) =>\n report({\n code: code.replace('widget/audio-', 'audio/'),\n message,\n ...(instanceId === '' ? {} : { instanceId }),\n }),\n });\n engine?.suspend();\n rpc.register(fusedHostAudioService, {\n async open(instanceId) {\n instances.add(instanceId);\n return (await engine?.open(instanceId)) ?? { state: 'unavailable' };\n },\n close(instanceId, session) {\n engine?.closeSession(instanceId, session);\n },\n });\n return {\n get state() {\n return engine?.state ?? 'unavailable';\n },\n suspend: () => engine?.suspend(),\n resume: () => engine?.resume(),\n setMuted: (muted) => engine?.setMuted(muted),\n setInstanceVolume: (id, volume) => engine?.setInstanceVolume(id, volume),\n clear() {\n for (const id of instances) engine?.close(id);\n instances.clear();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n engine?.dispose();\n },\n };\n}\n","/**\n * Worker wiring of one fused workbench (RFC 0025).\n *\n * Both guests start from the generated `?sandbox-worker` classes: the host waits for the sandbox to\n * boot, transfers one end of three `MessageChannel`s and creates the typed RPC endpoints. From then\n * on nothing but `createRpc` traffic crosses the boundary.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry, PackageFiles } from '@mica-js/document/fused';\nimport type { ProgramSources, ResourceResolver, RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedSimulationService,\n} from '../protocol';\nimport type { IFusedDisplayService, IFusedSimulationService } from '../protocol';\nimport { packageLockKey } from '../packages';\nimport { transferProgramArtifact, transferPackageBytes, transferResourceBytes } from '../wire';\nimport type { IFusedWorkerFactories } from './types';\nimport type { IFusedAudioOptions } from '../audio';\nimport { connectFusedAudio } from './audio';\n\nexport interface IFusedConnectionOptions {\n readonly audio?: IFusedAudioOptions;\n readonly workers: IFusedWorkerFactories;\n /** Host package access both guests share. */\n readonly registry: DeviceRegistry;\n /** Element that hosts the two hidden sandbox iframes. */\n readonly container?: HTMLElement;\n readonly resolveResource?: ResourceResolver;\n readonly programs?: ProgramSources;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n}\n\n/** Two guests of one workbench plus the endpoints that reach them. */\nexport interface IFusedConnection {\n readonly audio: ReturnType<typeof connectFusedAudio>;\n readonly simulation: RpcProxy<IFusedSimulationService>;\n readonly display: RpcProxy<IFusedDisplayService>;\n dispose(): Promise<void>;\n}\n\n/** Boots both guests of one workbench and wires their RPC surfaces. */\nexport async function connectFusedWorkbench(\n options: IFusedConnectionOptions,\n): Promise<IFusedConnection> {\n const workerOptions = options.container === undefined ? {} : { container: options.container };\n const simulationWorker = options.workers.createSimulationWorker(workerOptions);\n const displayWorker = options.workers.createDisplayWorker(workerOptions);\n const subscriptions: Array<() => void> = [];\n let simulationRpc: RpcEndpoint | undefined;\n let displayRpc: RpcEndpoint | undefined;\n try {\n await Promise.all([simulationWorker.ready, displayWorker.ready]);\n const simulationChannel = new MessageChannel();\n const displayChannel = new MessageChannel();\n const modelChannel = new MessageChannel();\n // Ports arrive in the guest as `event.ports`: the RPC port first, the model lane second.\n simulationWorker.postMessage(null, [simulationChannel.port2, modelChannel.port1]);\n displayWorker.postMessage(null, [displayChannel.port2, modelChannel.port2]);\n simulationRpc = createRpc(simulationChannel.port1);\n displayRpc = createRpc(displayChannel.port1);\n registerHostServices(simulationRpc, options);\n registerHostServices(displayRpc, options);\n const simulation = simulationRpc.getProxy(fusedSimulationService);\n const display = displayRpc.getProxy(fusedDisplayService, {\n transfer: (member, args) => (member === 'attachAudio' ? [args[0] as MessagePort] : []),\n });\n const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) =>\n options.onDiagnostic?.(diagnostic),\n );\n subscriptions.push(\n simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n );\n const ownedSimulationRpc = simulationRpc;\n const ownedDisplayRpc = displayRpc;\n let disposal: Promise<void> | undefined;\n return {\n audio,\n simulation,\n display,\n dispose() {\n return (disposal ??= (async () => {\n audio.dispose();\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n ownedSimulationRpc.dispose();\n ownedDisplayRpc.dispose();\n const results = await Promise.allSettled([\n simulationWorker.terminate('fused runtime disposed'),\n displayWorker.terminate('fused runtime disposed'),\n ]);\n const problems = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason as unknown);\n if (problems.length > 0) {\n throw new AggregateError(problems, 'Fused sandbox workers failed to terminate.');\n }\n })());\n },\n };\n } catch (cause) {\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n simulationRpc?.dispose();\n displayRpc?.dispose();\n await Promise.allSettled([\n simulationWorker.terminate('fused runtime failed to start'),\n displayWorker.terminate('fused runtime failed to start'),\n ]);\n throw cause;\n }\n}\n\n/** Package and resource services every guest of one workbench pulls from. */\nfunction registerHostServices(endpoint: RpcEndpoint, options: IFusedConnectionOptions): void {\n const opened = new Map<string, Promise<PackageFiles>>();\n const openLock = (lock: DeviceLock): Promise<PackageFiles> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = options.registry.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n endpoint.register(\n fusedHostPackageService,\n {\n async open(lock: DeviceLock) {\n const files = await openLock(lock);\n return { lock: files.lock, files: files.files };\n },\n async read(lock: DeviceLock, path: string) {\n const files = await openLock(lock);\n const bytes = await files.read(path);\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`The registry returned no bytes for ${lock.id}/${path}.`);\n }\n // The transfer hands the buffer to the guest, so the editor keeps its own copy.\n return bytes.slice();\n },\n },\n { transfer: transferPackageBytes },\n );\n endpoint.register(\n fusedHostResourceService,\n {\n async readResource(request) {\n if (options.resolveResource === undefined) {\n throw new Error(\n `No resource resolver is configured for ${request.instanceId}/${request.property}.`,\n );\n }\n return (await options.resolveResource(request)).slice();\n },\n async resolveProgramProject(id, target) {\n if (!options.programs?.projects) throw new Error('No program project provider configured.');\n const artifact = await options.programs.projects.resolve(id, target);\n return artifact.kind === 'memory'\n ? { kind: 'memory', format: artifact.format, data: artifact.data.slice() }\n : {\n kind: 'filesystem',\n files: artifact.files.map((file) => ({ path: file.path, data: file.data.slice() })),\n };\n },\n },\n {\n transfer: (member, value) =>\n member === 'resolveProgramProject'\n ? transferProgramArtifact(member, value)\n : transferResourceBytes(member, value),\n },\n );\n}\n","/**\n * Host-side 2D presentation surface (RFC 0022).\n *\n * The host reserves the overlay extent, numbers every request so a late frame can never overwrite a\n * newer one, and repaints instances whose presentation called `invalidate()`. Bitmaps of discarded\n * frames are closed instead of leaked.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n FusedDisplayMode,\n IFusedDisplayLayout,\n IFusedDisplayService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedViewInput,\n} from '../protocol';\nimport type { IFusedDisplay, IFusedDisplayPrepareInput } from './types';\nimport { isImageBitmap, mapWireFailure, messageOf } from '../wire';\n\nexport interface IFusedDisplayHostOptions {\n readonly proxy: RpcProxy<IFusedDisplayService>;\n readonly onOverlay?: (frame: IFusedOverlayFrame) => void;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n /** Overlay extent of one instance; defaults to its bounds at one device pixel per local unit. */\n readonly measure?: (instance: IFusedInstancePresentation) => IFusedDisplayLayout;\n /** Repaints when a presentation asks for it; defaults to `true`. */\n readonly autoRender?: boolean;\n}\n\n/** Display surface plus the preparation the runtime drives. */\nexport interface IFusedDisplayHost {\n readonly display: IFusedDisplay;\n /** Replaces the presentation of one mode; drops every pending frame of the previous one. */\n prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void>;\n /** Runs the author `initialize` hooks once the models of the mode exist. */\n activate(): Promise<void>;\n dispose(): Promise<void>;\n}\n\nexport function createFusedDisplay(options: IFusedDisplayHostOptions): IFusedDisplayHost {\n const { proxy } = options;\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const generations = new Map<string, number>();\n const dirty = new Set<string>();\n /** Reported framework failures of the current preparation, so a flood reports once. */\n const reported = new Set<string>();\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: FusedDisplayMode | undefined;\n /** Incremented by every preparation, so results of a replaced mode are dropped. */\n let epoch = 0;\n let pumping = false;\n let disposed = false;\n let disposal: Promise<void> | undefined;\n\n const stopInvalidate = proxy.onDidInvalidate((change) => {\n if (disposed) return;\n invalidations.fire(change);\n if (options.autoRender !== false) schedule(change.instanceId);\n });\n\n const display: IFusedDisplay = {\n get mode() {\n return mode;\n },\n get instances() {\n return prepared;\n },\n onDidInvalidate: invalidations.event,\n render,\n input,\n invalidate,\n dispose,\n };\n\n return { display, prepare, activate, dispose };\n\n async function prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void> {\n if (disposed) {\n throw new Error('The fused display is disposed.');\n }\n epoch += 1;\n generations.clear();\n dirty.clear();\n reported.clear();\n await mapWireFailure(() => proxy.prepare({ mode: input.mode, instances }));\n mode = input.mode;\n prepared = instances;\n }\n\n async function activate(): Promise<void> {\n if (disposed) return;\n await mapWireFailure(() => proxy.activate());\n }\n\n async function render(\n instanceId: string,\n layout?: IFusedDisplayLayout,\n ): Promise<IFusedOverlayFrame | undefined> {\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined || disposed) return undefined;\n const extent = layout ?? defaultLayout(instance);\n const generation = (generations.get(instanceId) ?? 0) + 1;\n generations.set(instanceId, generation);\n const attempt = epoch;\n const frame = await mapWireFailure(() => proxy.render({ instanceId, generation, ...extent }));\n if (frame === undefined) return undefined;\n if (disposed || attempt !== epoch || generation !== generations.get(instanceId)) {\n closeBitmap(frame.bitmap);\n return undefined;\n }\n options.onOverlay?.(frame);\n return frame;\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (disposed) return;\n void proxy.input(instanceId, event).catch((cause: unknown) => {\n // The guest reports author callback failures itself as `view2d/input-failed`; a rejection here\n // means the call never reached the presentation, so it is reported once per instance.\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n });\n }\n\n /**\n * Reports a framework failure of one instance once per distinct message.\n *\n * A dead guest fails every queued pointer event and every scheduled frame; without the dedupe the\n * same cause would flood the diagnostic sink.\n */\n function reportOnce(instanceId: string, code: string, message: string): void {\n const key = `${instanceId}\\u0000${code}\\u0000${message}`;\n if (reported.has(key)) return;\n reported.add(key);\n options.onDiagnostic?.({ code, message, instanceId });\n }\n\n function invalidate(instanceId?: string): void {\n if (disposed) return;\n if (instanceId !== undefined) {\n schedule(instanceId);\n return;\n }\n for (const instance of prepared) schedule(instance.instanceId);\n }\n\n function schedule(instanceId: string): void {\n if (!prepared.some((entry) => entry.instanceId === instanceId)) return;\n dirty.add(instanceId);\n if (pumping) return;\n pumping = true;\n void Promise.resolve().then(pump);\n }\n\n async function pump(): Promise<void> {\n while (!disposed) {\n const batch = [...dirty];\n if (batch.length === 0) {\n pumping = false;\n return;\n }\n dirty.clear();\n for (const instanceId of batch) {\n try {\n await render(instanceId);\n } catch (cause) {\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n }\n }\n }\n pumping = false;\n }\n\n function defaultLayout(instance: IFusedInstancePresentation): IFusedDisplayLayout {\n const measured = options.measure?.(instance);\n if (measured !== undefined) return measured;\n const bounds = instance.geometry.bounds;\n return {\n width: Math.max(1, Math.round(bounds.width)),\n height: Math.max(1, Math.round(bounds.height)),\n scale: 1,\n };\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n disposed = true;\n disposal = (async () => {\n const problems: unknown[] = [];\n try {\n stopInvalidate();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => proxy.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n invalidations.dispose();\n dirty.clear();\n prepared = [];\n mode = undefined;\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused presentation failed to release its guests.');\n }\n })();\n return disposal;\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap !== undefined && isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * Local fan-out of model events (RFC 0021).\n *\n * The host and the display guest both expose `Event<ModelEvent<T>>` outlets whose subscriptions are\n * lazy: the first listener of one instance and event subscribes on the wire, the last one\n * unsubscribes, and a released instance drops every local listener.\n */\nimport { Emitter, toDisposable } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\n\n/** Wire subscriptions the router needs from its owner. */\nexport interface IFusedModelEventChannel {\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n}\n\nexport interface IFusedModelEventRouter {\n /** Declared event outlet of one instance; only listeners create a wire subscription. */\n event(instanceId: string, event: string): Event<ModelEvent<Value>>;\n /** Delivers one event to the listeners active at this moment. */\n deliver(instanceId: string, event: string, payload: ModelEvent<Value>): void;\n /** Drops every listener of one instance. */\n release(instanceId: string): void;\n dispose(): void;\n /** Number of live wire subscriptions; used to keep the wire silent without listeners. */\n readonly activeSubscriptions: number;\n}\n\nexport function channelKey(instanceId: string, event: string): string {\n return `${instanceId}\\u0000${event}`;\n}\n\nexport function createModelEventRouter(channel: IFusedModelEventChannel): IFusedModelEventRouter {\n const entries = new Map<string, { emitter: Emitter<ModelEvent<Value>>; listeners: number }>();\n\n const event = (instanceId: string, name: string): Event<ModelEvent<Value>> => {\n const key = channelKey(instanceId, name);\n return (listener) => {\n let entry = entries.get(key);\n if (entry === undefined) {\n entry = { emitter: new Emitter<ModelEvent<Value>>(), listeners: 0 };\n entries.set(key, entry);\n }\n const current = entry;\n current.listeners += 1;\n if (current.listeners === 1) channel.subscribe(instanceId, name);\n const subscription = current.emitter.event(listener);\n return toDisposable(() => {\n subscription.dispose();\n current.listeners -= 1;\n if (current.listeners > 0) return;\n entries.delete(key);\n current.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n });\n };\n };\n\n const drop = (key: string, instanceId: string, name: string): void => {\n const entry = entries.get(key);\n if (entry === undefined) return;\n entries.delete(key);\n entry.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n };\n\n return {\n event,\n deliver(instanceId, name, payload) {\n entries.get(channelKey(instanceId, name))?.emitter.fire(payload);\n },\n release(instanceId) {\n const prefix = `${instanceId}\\u0000`;\n for (const key of [...entries.keys()]) {\n if (!key.startsWith(prefix)) continue;\n drop(key, instanceId, key.slice(prefix.length));\n }\n },\n dispose() {\n for (const key of [...entries.keys()]) {\n const separator = key.indexOf('\\u0000');\n drop(key, key.slice(0, separator), key.slice(separator + 1));\n }\n },\n get activeSubscriptions() {\n return entries.size;\n },\n };\n}\n","/**\n * Host-side model clients of the fused runtime (RFC 0021).\n *\n * The editor calls a model through the simulation worker, never in its own thread. Event outlets are\n * lazy: one wire listener serves every local subscription and is released with the last of them.\n */\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport type { IFusedModelEventRouter } from '../model-events';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedSimulationService,\n} from '../protocol';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\n/** Model clients of one runtime, keyed by the instance they belong to. */\nexport interface IFusedHostModelRouter {\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n release(instanceId: string): void;\n dispose(): void;\n}\n\nexport function createHostModelRouter(\n proxy: RpcProxy<IFusedSimulationService>,\n): IFusedHostModelRouter {\n let router: IFusedModelEventRouter | undefined;\n let subscriptions = 0;\n let stop: (() => void) | undefined;\n router = createModelEventRouter({\n subscribe() {\n subscriptions += 1;\n if (subscriptions > 1 || stop !== undefined) return;\n stop = proxy.onDidModelEvent((event) => {\n router?.deliver(event.instanceId, event.event, event.payload);\n });\n },\n unsubscribe() {\n subscriptions = Math.max(0, subscriptions - 1);\n if (subscriptions > 0) return;\n stop?.();\n stop = undefined;\n },\n });\n\n const active = (): IFusedModelEventRouter => {\n if (router === undefined) {\n throw new Error('The fused model router is disposed.');\n }\n return router;\n };\n\n const invoke = (instanceId: string, method: string, params: Value): Promise<Value> => {\n if (router === undefined) {\n return Promise.reject(\n new FusedBridgeError(\n 'model/disconnected',\n 'The model client is disconnected from any live model.',\n { instanceId },\n ),\n );\n }\n return mapWireFailure(() => proxy.call(instanceId, method, params));\n };\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) => invoke(instance.instanceId, name, params);\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = active().event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router?.release(instanceId);\n },\n dispose() {\n stop?.();\n stop = undefined;\n router?.dispose();\n router = undefined;\n },\n };\n}\n","/**\n * Fused editor runtime bridge of one workbench (RFC 0025).\n *\n * One simulation worker runs the document, the packages and the models; one presentation worker runs\n * the declared 2D view modules. The editor schedules both and never imports model or author code.\n *\n * Every asynchronous transition is numbered: a preparation, reset or disposal that was superseded\n * never applies its result, and a frame produced for a replaced presentation is closed, not shown.\n */\nimport { timePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedOverlayFrame,\n IFusedSessionState,\n} from '../protocol';\nimport { connectFusedWorkbench } from './connection';\nimport { createFusedDisplay } from './display';\nimport { createHostModelRouter } from './model';\nimport type { IFusedDisplayPrepareInput, IFusedRuntime, IFusedRuntimeOptions } from './types';\nimport type { IFusedWorkerFactories } from './types';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\n\n/** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */\nexport async function createFusedRuntime(options: IFusedRuntimeOptions): Promise<IFusedRuntime> {\n const workers: IFusedWorkerFactories =\n options.workers ?? (await import('../workers')).fusedWorkerFactories;\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const overlays = new Emitter<IFusedOverlayFrame>();\n const states = new Emitter<IFusedSessionState>();\n const report = (entry: RuntimeDiagnostic): void => {\n diagnostics.fire(entry);\n options.onDiagnostic?.(entry);\n };\n const connection = await connectFusedWorkbench({\n workers,\n registry: options.registry,\n ...(options.audio === undefined ? {} : { audio: options.audio }),\n ...(options.container === undefined ? {} : { container: options.container }),\n ...(options.resolveResource === undefined ? {} : { resolveResource: options.resolveResource }),\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n onDiagnostic: report,\n });\n const models = createHostModelRouter(connection.simulation);\n const displayHost = createFusedDisplay({\n proxy: connection.display,\n onDiagnostic: report,\n onOverlay: (frame) => {\n overlays.fire(frame);\n options.onOverlay?.(frame);\n },\n ...(options.measure === undefined ? {} : { measure: options.measure }),\n });\n\n let state: IFusedSessionState = IDLE;\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: 'edit' | 'run' | undefined;\n let preparation = 0;\n let closed = false;\n let disposal: Promise<void> | undefined;\n const clients = new Map<string, IFusedModelClient>();\n\n const stopState = connection.simulation.onDidChangeState((next) => setState(next));\n\n const runtime: IFusedRuntime = {\n audio: connection.audio,\n getState: () => state,\n onDidChangeState: states.event,\n onDidReportDiagnostic: diagnostics.event,\n onDidRenderOverlay: overlays.event,\n getModel,\n display: displayHost.display,\n prepareDisplay,\n resume,\n pause,\n step,\n reset,\n dispose,\n };\n try {\n await prepareDisplay({ mode: options.mode ?? 'edit' });\n } catch (cause) {\n await dispose().catch(() => undefined);\n throw cause;\n }\n return runtime;\n\n function setState(next: IFusedSessionState): void {\n if (next.status === 'running') connection.audio.resume();\n else connection.audio.suspend();\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closed) {\n throw new FusedBridgeError('runtime/unavailable-state', 'The fused runtime is disposed.');\n }\n }\n\n function assertRun(operation: string): void {\n assertOpen();\n if (mode !== 'run') {\n throw new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires a run session; prepare the run mode first.`,\n );\n }\n }\n\n function getModel(instanceId: string): IFusedModelClient {\n if (closed || mode !== 'run') {\n throw new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted: the fused runtime is not in run mode.',\n { instanceId },\n );\n }\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-instance',\n `No live model for instance \"${instanceId}\".`,\n { instanceId },\n );\n }\n let client = clients.get(instanceId);\n if (client === undefined) {\n client = models.client(instance);\n clients.set(instanceId, client);\n }\n return client;\n }\n\n async function prepareDisplay(\n input: IFusedDisplayPrepareInput,\n ): Promise<readonly IFusedInstancePresentation[]> {\n assertOpen();\n const attempt = ++preparation;\n connection.audio.suspend();\n connection.audio.clear();\n const current = (): boolean => !closed && attempt === preparation;\n const described = await mapWireFailure(() =>\n connection.simulation.prepare({ document: options.document, mode: input.mode }),\n );\n if (!current()) return prepared;\n if (input.mode === 'edit') {\n // Edit mode mounts presentation only: the models are released before any view is created.\n await mapWireFailure(() => connection.simulation.dispose());\n if (!current()) return prepared;\n }\n // Factories run before the models exist, so their subscriptions observe the initial events.\n await displayHost.prepare({ mode: input.mode }, described.instances);\n if (!current()) return prepared;\n if (input.mode === 'run') {\n try {\n const loaded = await mapWireFailure(() =>\n connection.simulation.load({\n document: options.document,\n step: options.step,\n ...(options.batchExecution === undefined\n ? {}\n : { batchExecution: options.batchExecution }),\n }),\n );\n if (!current()) return prepared;\n setState(loaded);\n } catch (cause) {\n // The factories of a session that never mounted must not keep drawing a dead model lane.\n await displayHost.prepare({ mode: input.mode }, []).catch(() => undefined);\n throw cause;\n }\n }\n prepared = described.instances;\n mode = input.mode;\n clients.clear();\n // `initialize` runs after the models mounted and delivered their initial events.\n await displayHost.activate();\n if (!current()) return prepared;\n // Static views need an initial frame even when they never invalidate themselves.\n displayHost.display.invalidate();\n if (input.mode === 'run') {\n // A run session starts advancing once every presentation subscribed to its model.\n await mapWireFailure(() => connection.simulation.resume());\n }\n return prepared;\n }\n\n async function resume(): Promise<void> {\n assertRun('resume');\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n async function pause(): Promise<void> {\n if (closed || mode !== 'run') return;\n await mapWireFailure(() => connection.simulation.pause());\n }\n\n async function step(): Promise<void> {\n assertRun('step');\n const next = await mapWireFailure(() => connection.simulation.step());\n setState(next);\n }\n\n async function reset(): Promise<void> {\n assertRun('reset');\n connection.audio.suspend();\n connection.audio.clear();\n const attempt = ++preparation;\n const current = (): boolean => !closed && attempt === preparation;\n const instances = prepared;\n // The rebuilt presentation subscribes first; the replacement models then deliver initial events.\n await displayHost.prepare({ mode: 'run' }, instances);\n if (!current()) return;\n clients.clear();\n await mapWireFailure(() => connection.simulation.reset());\n if (!current()) return;\n await displayHost.activate();\n if (!current()) return;\n displayHost.display.invalidate();\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closed = true;\n connection.audio.dispose();\n disposal = (async () => {\n const problems: unknown[] = [];\n // Presentation first: input stops and views release before the models go away.\n try {\n await displayHost.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => connection.simulation.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n try {\n stopState();\n } catch (cause) {\n problems.push(cause);\n }\n models.dispose();\n try {\n await connection.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n states.dispose();\n diagnostics.dispose();\n overlays.dispose();\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused runtime failed to release every resource.');\n }\n })();\n return disposal;\n }\n}\n","/** Small shared helpers of the fused sandbox bridge. */\nimport type { DevicePropertyDescriptor } from '@mica-js/document/fused';\nimport { createProgramFiles, readonlyBytes } from '@mica-js/sdk/fused';\nimport type {\n FusedPresentationProps,\n FusedPresentationValue,\n FusedResolvedPresentationProps,\n IFusedFirmwareSegment,\n IFusedFirmwareSnapshot,\n} from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/**\n * Resolved property snapshot handed to one presentation.\n *\n * Every declared property must appear in `resolved` (the simulation worker resolves the manifest\n * defaults and document overrides through the SDK, exactly like the model snapshot does). Byte and\n * firmware values are copied into independent arrays, because the snapshot crosses an RPC boundary\n * and is transferred to the presentation worker afterwards.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming the property and its declared\n * type whenever a value cannot be projected. A presentation never receives a partial snapshot.\n */\nexport function presentationProps(\n resolved: Readonly<Record<string, unknown>>,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): FusedPresentationProps {\n const props: Record<string, FusedPresentationValue> = {};\n for (const [name, descriptor] of Object.entries(descriptors)) {\n if (!Object.hasOwn(resolved, name)) {\n throw unpresentable(name, descriptor.type, 'has no resolved value');\n }\n const value = resolved[name];\n if (value === undefined) {\n throw unpresentable(name, descriptor.type, 'resolved to undefined');\n }\n switch (descriptor.type) {\n case 'string':\n case 'color':\n case 'enum':\n if (typeof value === 'string') {\n props[name] = value;\n continue;\n }\n break;\n case 'integer':\n case 'number':\n if (typeof value === 'number') {\n props[name] = value;\n continue;\n }\n break;\n case 'boolean':\n if (typeof value === 'boolean') {\n props[name] = value;\n continue;\n }\n break;\n case 'image':\n case 'binary':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = copyBytes(name, descriptor.type, value);\n continue;\n case 'firmware':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = firmwareSnapshot(name, value);\n continue;\n case 'program':\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n if (descriptor.loader === 'memory') props[name] = firmwareSnapshot(name, value);\n else {\n const files = value as { readonly paths?: unknown; readonly read?: unknown };\n if (!files || !Array.isArray(files.paths) || typeof files.read !== 'function')\n throw unpresentable(name, 'program', 'is not a file snapshot');\n props[name] = Object.freeze({\n kind: 'filesystem',\n files: Object.freeze(\n files.paths.map((path: string) =>\n Object.freeze({\n path,\n data: copyBytes(name, 'program', (files.read as (path: string) => unknown)(path)),\n }),\n ),\n ),\n });\n }\n continue;\n default:\n break;\n }\n\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n throw unpresentable(name, descriptor.type, `resolved to ${describeValue(value)}`);\n }\n return Object.freeze(props);\n}\n\nexport function reconstructPresentationProps(\n props: FusedPresentationProps,\n): FusedResolvedPresentationProps {\n return Object.freeze(\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => {\n if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array)) {\n if (value.kind === 'filesystem') return [name, createProgramFiles(value.files)];\n return [\n name,\n Object.freeze({\n segments: Object.freeze(\n value.segments.map((segment) =>\n Object.freeze({\n addressSpace: segment.addressSpace,\n address: segment.address,\n data: readonlyBytes(segment.bytes),\n }),\n ),\n ),\n }),\n ];\n }\n return [name, value];\n }),\n ),\n );\n}\n\n/** Copies one read-only byte snapshot; the SDK hands `ReadonlyBytes`, not raw arrays. */\nfunction copyBytes(name: string, type: string, value: unknown): Uint8Array {\n if (value instanceof Uint8Array) return value.slice();\n const candidate = value as { readonly slice?: unknown } | null;\n if (\n candidate !== null &&\n typeof candidate === 'object' &&\n typeof candidate.slice === 'function'\n ) {\n const copy = (candidate.slice as () => unknown).call(candidate);\n if (copy instanceof Uint8Array) return copy;\n }\n throw unpresentable(name, type, 'is not a byte snapshot');\n}\n\n/** Projects one loaded firmware image (RFC 0026) into a transferable snapshot. */\nfunction firmwareSnapshot(name: string, value: unknown): IFusedFirmwareSnapshot {\n const segments = (value as { readonly segments?: unknown } | null)?.segments;\n if (!Array.isArray(segments)) {\n throw unpresentable(name, 'firmware', 'is not a firmware image');\n }\n const projected: IFusedFirmwareSegment[] = [];\n for (const segment of segments) {\n const candidate = segment as {\n readonly addressSpace?: unknown;\n readonly address?: unknown;\n readonly data?: unknown;\n };\n if (typeof candidate.addressSpace !== 'string' || typeof candidate.address !== 'number') {\n throw unpresentable(name, 'firmware', 'has a segment without an address space or address');\n }\n projected.push({\n addressSpace: candidate.addressSpace,\n address: candidate.address,\n bytes: copyBytes(name, 'firmware', candidate.data),\n });\n }\n return Object.freeze({ kind: 'firmware', segments: Object.freeze(projected) });\n}\n\nfunction unpresentable(name: string, type: string, reason: string): FusedBridgeError {\n return new FusedBridgeError(\n 'runtime/presentation-failed',\n `Property \"${name}\" (${type}) ${reason}; the presentation cannot receive a partial snapshot.`,\n );\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n return `a value of type ${typeof value}`;\n}\n\n/** Whether a callback returned a promise instead of finishing synchronously. */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Evaluates one verified package module inside the guest.\n *\n * The bytes were verified against the package lock before this runs; a blob URL keeps the module\n * out of the host document and is revoked as soon as the namespace settles.\n */\nexport function importCode(code: string): Promise<unknown> {\n const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));\n return import(/* @vite-ignore */ url).finally(() => URL.revokeObjectURL(url));\n}\n\n/** Copies bytes into a plain `ArrayBuffer`, as `Blob` and transfer lists require. */\nexport function byteBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer;\n}\n\n/** Decodes package bytes as UTF-8 module source, tolerating a leading byte order mark. */\nexport function decodeSource(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes).replace(/^\\uFEFF/, '');\n}\n","/**\n * Model lane between the simulation guest and the display guest (RFC 0025).\n *\n * The host transfers one end of a `MessageChannel` to each guest, so a display input handler calls\n * its model directly instead of asking the editor to relay the call. The simulation guest serves\n * {@link fusedModelChannelService} and pushes events to the display sink only while the display is\n * subscribed to that instance and event.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport { channelKey } from '../model-events';\nimport type { IFusedModelEventWire } from '../protocol';\n\n/** Guest-side capabilities the display lane reaches through this port. */\nexport interface IFusedModelChannelHandlers {\n /** Invokes one declared model method; failures are already encoded for the wire. */\n readonly call: (instanceId: string, method: string, params: Value) => Promise<Value>;\n}\n\nexport interface IFusedSimulationModelChannel {\n /** Delivers one model event to the display guest when it subscribed to it. */\n deliver(event: IFusedModelEventWire): void;\n /** Drops every display subscription, e.g. when the session was replaced. */\n reset(): void;\n dispose(): void;\n}\n\n/** Starts the simulation end of the model lane over `port`. */\nexport function startSimulationModelChannel(\n port: MessagePort,\n handlers: IFusedModelChannelHandlers,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedSimulationModelChannel {\n const endpoint = createEndpoint(port);\n const sink = endpoint.getProxy(fusedModelSinkService);\n const subscriptions = new Set<string>();\n endpoint.register(fusedModelChannelService, {\n call: handlers.call,\n subscribe(instanceId, event) {\n subscriptions.add(channelKey(instanceId, event));\n },\n unsubscribe(instanceId, event) {\n subscriptions.delete(channelKey(instanceId, event));\n },\n settle: () => undefined,\n });\n return {\n deliver(event) {\n if (!subscriptions.has(channelKey(event.instanceId, event.event))) return;\n void sink.deliver(event).catch(() => undefined);\n },\n reset() {\n subscriptions.clear();\n },\n dispose() {\n subscriptions.clear();\n endpoint.dispose();\n },\n };\n}\n","/**\n * Simulation guest of the fused editor runtime (RFC 0025).\n *\n * The guest owns the production headless runtime: the document snapshot, the verified package bytes,\n * the models and the electrical solve. The editor keeps no model code on its own thread; it reaches\n * this guest through typed RPC and receives model events, state changes and diagnostics as events.\n *\n * Package bytes, host resources and firmware artifacts are pulled from host services registered on\n * the same RPC endpoint, so verification, preparation and model execution all happen here.\n */\nimport { timePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Disposable } from '@mica-js/core/lifecycle';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport { parseFusedDocument, parseGeometry2D, parseStrictJson } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n DevicePropertyDescriptor,\n FusedDocument,\n FusedInstance,\n PackageFiles,\n Value,\n} from '@mica-js/document/fused';\nimport {\n createHeadlessRuntime,\n FusedPreparationError,\n openDevicePackage,\n PreparationError,\n resolveInstanceProperties,\n} from '@mica-js/sdk/fused';\nimport type {\n ProgramSources,\n ProgramArtifact,\n ProgramFile,\n HeadlessRuntime,\n ResourceResolver,\n RuntimeDiagnostic,\n RuntimeModelEvent,\n VerifiedPackage,\n} from '@mica-js/sdk/fused';\nimport { fusedHostResourceService, fusedSimulationService } from '../protocol';\nimport type {\n IFusedInstancePresentation,\n IFusedLoadRequest,\n IFusedModelEventWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedSessionState,\n} from '../protocol';\nimport { decodeSource, importCode, presentationProps } from '../values';\nimport { FusedBridgeError, messageOf, toWireFailure, transferPresentationBytes } from '../wire';\nimport { createHostPackageGateway } from '../packages';\nimport { startSimulationModelChannel } from './model-channel';\nimport type { IFusedSimulationModelChannel } from './model-channel';\n\n/** Replaceable guest dependencies, so the runtime can be exercised outside a browser worker. */\nexport interface IFusedSimulationGuestOptions {\n /** Creates the endpoint over the startup port; tests inject a fake. */\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /**\n * Startup ports after the RPC port. The first one is the model lane (RFC 0025), the display guest\n * holds the other end of the same channel.\n */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified package module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n}\n\n/** Guest runtime plus the RPC endpoint that serves it. */\nexport interface IFusedSimulationGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\n\ninterface Session {\n readonly runtime: HeadlessRuntime;\n readonly subscriptions: Disposable[];\n}\n\n/** Starts the simulation guest on the startup port of a sandbox worker. */\nexport function startFusedSimulationGuest(\n port: MessagePort,\n options: IFusedSimulationGuestOptions = {},\n): IFusedSimulationGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const packages = createHostPackageGateway(endpoint);\n const resources = createResourceGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const states = new Emitter<IFusedSessionState>();\n const events = new Emitter<IFusedModelEventWire>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedSimulationModelChannel | undefined =\n modelPort === undefined\n ? undefined\n : startSimulationModelChannel(modelPort, {\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n });\n\n let state: IFusedSessionState = IDLE;\n let session: Session | undefined;\n /** Identity of the live session, so events of a discarded candidate never reach a listener. */\n let sessionToken: object | undefined;\n /** Incremented by every session transition, so late results of a replaced session are dropped. */\n let sequence = 0;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n endpoint.register(\n fusedSimulationService,\n {\n prepare,\n load,\n step,\n resume,\n pause,\n reset,\n dispose: releaseModels,\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n getState: () => state,\n onDidChangeState(listener) {\n const subscription = states.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidModelEvent(listener) {\n const subscription = events.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n // Presentation byte and firmware snapshots are handed over, never cloned.\n { transfer: transferPresentationBytes },\n );\n\n return {\n rpc: endpoint,\n dispose,\n };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function setState(next: IFusedSessionState): void {\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n 'The fused simulation guest is disposed.',\n ),\n );\n }\n }\n\n function requireSession(operation: string): Session {\n assertOpen();\n if (session === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires mounted models; prepare a run session first.`,\n ),\n );\n }\n return session;\n }\n\n async function prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult> {\n assertOpen();\n const document = parseFusedDocument(request.document);\n const problems: RuntimeDiagnostic[] = [];\n const instances: IFusedInstancePresentation[] = [];\n for (const [index, instance] of document.instances.entries()) {\n try {\n const described = await describeInstance(index, document, instance);\n if (described !== undefined) instances.push(described);\n } catch (cause) {\n // A presentation-only failure drops the view of that instance; the models of a run session\n // and every other presentation keep going (RFC 0025 `runtime/presentation-failed`).\n if (cause instanceof FusedBridgeError && cause.code === 'runtime/presentation-failed') {\n report({ code: cause.code, message: cause.message, instanceId: instance.id });\n continue;\n }\n problems.push({\n code: 'runtime/prepare-failed',\n message: `${instance.id}: ${messageOf(cause)}`,\n instanceId: instance.id,\n });\n }\n }\n for (const problem of problems) report(problem);\n if (problems.length > 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/prepare-failed',\n `${problems.length} instance(s) cannot join the 2D scene.`,\n ),\n );\n }\n return { instances };\n }\n\n async function describeInstance(\n index: number,\n document: FusedDocument,\n instance: FusedInstance,\n ): Promise<IFusedInstancePresentation | undefined> {\n const dependency = document.dependencies[instance.device];\n if (dependency === undefined) {\n throw new FusedBridgeError(\n 'document/unlocked-device',\n `Instance \"${instance.id}\" uses the unlocked device \"${instance.device}\".`,\n { instanceId: instance.id },\n );\n }\n const lock: DeviceLock = {\n id: instance.device,\n version: dependency.version,\n integrity: dependency.integrity,\n };\n const verified = await openDevicePackage(packages, lock);\n const view = verified.manifest.view2d;\n if (view === undefined) {\n report({\n code: 'view2d/unsupported',\n message: `${instance.device} declares no 2D geometry; \"${instance.id}\" stays out of the 2D scene.`,\n instanceId: instance.id,\n });\n return undefined;\n }\n const pins = Object.keys(verified.manifest.pins ?? {});\n const geometryValue =\n typeof view.geometry === 'string'\n ? parseStrictJson(decodeSource(await verified.read(view.geometry)))\n : view.geometry;\n const descriptors = verified.manifest.properties ?? {};\n return {\n instanceId: instance.id,\n device: instance.device,\n lock,\n geometry: parseGeometry2D(geometryValue, pins),\n view: view.entry,\n props: presentationProps(\n await resolvePresentationProps(verified, descriptors, instance, index),\n descriptors,\n ),\n methods: Object.keys(verified.manifest.model?.methods ?? {}),\n events: Object.keys(verified.manifest.model?.events ?? {}),\n };\n }\n\n /**\n * Resolves the declared properties a presentation reads through the SDK, so the projection is the\n * same snapshot the model receives: manifest defaults, document overrides, package and host\n * resources, and a loaded firmware image.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.\n */\n async function resolvePresentationProps(\n verified: VerifiedPackage,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n instance: FusedInstance,\n index: number,\n ): Promise<Readonly<Record<string, unknown>>> {\n try {\n const resolution = await resolveInstanceProperties({\n instanceId: instance.id,\n package: verified,\n descriptors,\n overrides: instance.properties ?? {},\n // The model IR adds nothing to `props`: an empty map keeps this resolution identical to the\n // one the runtime performs while it builds the board, so edit mode needs no model module.\n irProperties: new Map<string, never>(),\n pointer: ['instances', String(index), 'properties'],\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n });\n return resolution.props;\n } catch (cause) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `Presentation properties of \"${instance.id}\" cannot be resolved: ${describeProblems(\n cause,\n descriptors,\n )}`,\n { instanceId: instance.id },\n );\n }\n }\n\n async function load(request: IFusedLoadRequest): Promise<IFusedSessionState> {\n assertOpen();\n const step = request.step;\n if (!Number.isSafeInteger(step) || step <= 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/invalid-time',\n `\\`step\\` must be a positive integer number of picoseconds, received ${String(step)}.`,\n ),\n );\n }\n const document = parseFusedDocument(request.document);\n const attempt = ++sequence;\n const token = {};\n const superseded = (): boolean => closing || attempt !== sequence;\n /** Events of the factory phase are queued and delivered once the session is adopted. */\n const pending: RuntimeModelEvent[] = [];\n let created: HeadlessRuntime;\n try {\n created = await createHeadlessRuntime({\n document,\n registry: packages,\n loadModule,\n step,\n ...(request.batchExecution === undefined ? {} : { batchExecution: request.batchExecution }),\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n onModelEvent: (event) => {\n if (sessionToken === token) publishModelEvent(event);\n else if (!superseded()) pending.push(event);\n },\n onDiagnostic: (entry) => {\n if (!superseded()) report(entry);\n },\n });\n } catch (cause) {\n if (cause instanceof FusedPreparationError) {\n for (const entry of cause.diagnostics) report(entry);\n }\n throw toWireFailure(cause);\n }\n if (superseded()) {\n await created.dispose().catch(() => undefined);\n return state;\n }\n const previous = session;\n session = undefined;\n sessionToken = undefined;\n if (previous !== undefined) {\n // The candidate session exists before the running one is released, so a failed load keeps it.\n await releaseSession(previous, false);\n }\n // The model lane keeps the display subscriptions of the presentation prepared before this load.\n sessionToken = token;\n session = {\n runtime: created,\n subscriptions: [\n created.onDidChangeState((next) => {\n if (sessionToken === token) setState({ status: next.status, simTime: next.simTime });\n }),\n created.onDidReportDiagnostic((entry) => {\n if (sessionToken === token) report(entry);\n }),\n ],\n };\n for (const event of pending.splice(0)) publishModelEvent(event);\n const initial = created.getState();\n setState({ status: initial.status, simTime: initial.simTime });\n return state;\n }\n\n async function step(): Promise<IFusedSessionState> {\n const target = requireSession('step');\n await mapGuestCall(() => target.runtime.step());\n return state;\n }\n\n async function resume(): Promise<void> {\n const target = requireSession('resume');\n await mapGuestCall(() => target.runtime.resume());\n }\n\n function pause(): void {\n session?.runtime.pause();\n }\n\n async function reset(): Promise<void> {\n const target = requireSession('reset');\n await mapGuestCall(() => target.runtime.reset());\n }\n\n async function callModel(instanceId: string, method: string, params: Value): Promise<Value> {\n const target = session;\n if (closing || target === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted; prepare a run session first.',\n {\n instanceId,\n },\n ),\n );\n }\n try {\n const client = target.runtime.getModel(instanceId);\n const invoke = client.methods[method];\n if (invoke === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-method',\n `The model of \"${instanceId}\" declares no method \"${method}\".`,\n { instanceId },\n );\n }\n return await invoke(params);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n }\n\n async function releaseModels(): Promise<void> {\n assertOpen();\n await releaseCurrent(true);\n }\n\n async function releaseCurrent(strict: boolean): Promise<void> {\n const target = session;\n session = undefined;\n sessionToken = undefined;\n sequence += 1;\n modelChannel?.reset();\n setState(IDLE);\n if (target !== undefined) await releaseSession(target, strict);\n }\n\n async function releaseSession(target: Session, strict: boolean): Promise<void> {\n for (const subscription of target.subscriptions.splice(0)) subscription.dispose();\n try {\n await target.runtime.dispose();\n } catch (cause) {\n report({\n code: 'runtime/model-failed',\n message: `Releasing the models failed: ${messageOf(cause)}`,\n });\n if (strict) throw toWireFailure(cause);\n }\n }\n\n function publishModelEvent(event: RuntimeModelEvent): void {\n const wire: IFusedModelEventWire = {\n instanceId: event.instanceId,\n event: event.event,\n payload: event.payload,\n };\n modelChannel?.deliver(wire);\n events.fire(wire);\n }\n\n async function loadModule(files: PackageFiles, path: string) {\n return importModule(decodeSource(await files.read(path)));\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n modelChannel?.dispose();\n const target = session;\n session = undefined;\n sessionToken = undefined;\n const problems: unknown[] = [];\n if (target !== undefined) {\n try {\n await releaseSession(target, true);\n } catch (cause) {\n problems.push(cause);\n }\n }\n endpoint.dispose();\n diagnostics.dispose();\n states.dispose();\n events.dispose();\n if (problems.length > 0) throw problems[0];\n })();\n return disposal;\n }\n}\n\n/** One guest call whose rejection is rebuilt on the host. */\nasync function mapGuestCall<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (cause) {\n throw toWireFailure(cause);\n }\n}\n\n/** Host resources the runtime pulls while it resolves instance properties. */\nfunction createResourceGateway(endpoint: RpcEndpoint): {\n readonly resolveResource: ResourceResolver;\n readonly programs: ProgramSources;\n} {\n const host = endpoint.getProxy(fusedHostResourceService);\n // The presentation snapshot and the model snapshot resolve the same properties; the cache keeps\n // one host round trip per resource and one artifact fetch per project, and hands out copies.\n const resources = new Map<string, Uint8Array>();\n const programs = new Map<string, ProgramArtifact>();\n const copyFiles = (files: readonly ProgramFile[]) =>\n files.map((file) => ({ path: file.path, data: file.data.slice() }));\n const copyArtifact = (artifact: ProgramArtifact): ProgramArtifact =>\n artifact.kind === 'memory'\n ? { ...artifact, data: artifact.data.slice() }\n : { kind: 'filesystem', files: copyFiles(artifact.files) };\n return {\n programs: {\n projects: {\n resolve: async (id, target) => {\n const key = JSON.stringify([target.deviceId, target.property, target.loader, id]);\n let artifact = programs.get(key);\n if (!artifact) {\n artifact = await host.resolveProgramProject(id, target);\n programs.set(key, copyArtifact(artifact));\n }\n return copyArtifact(artifact);\n },\n },\n },\n resolveResource: async (request) => {\n const key = `${request.instanceId}\\u0000${request.property}`;\n const cached = resources.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.readResource(request);\n resources.set(key, bytes.slice());\n return bytes;\n },\n };\n}\n\n/** Flattens preparation problems, naming the property and its declared type. */\nfunction describeProblems(\n cause: unknown,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string {\n if (cause instanceof PreparationError) {\n return cause.problems\n .map((problem) => {\n const property = propertyOfPointer(problem.pointer, descriptors);\n const where = problem.pointer === '' ? '' : ` at ${problem.pointer}`;\n return `${problem.code}${where}${property === undefined ? '' : ` (${property})`}: ${problem.message}`;\n })\n .join('; ');\n }\n return messageOf(cause);\n}\n\n/** Names one property and its declared type from a JSON Pointer into the instance properties. */\nfunction propertyOfPointer(\n pointer: string,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string | undefined {\n const segments = pointer.split('/');\n const at = segments.indexOf('properties');\n const name = at < 0 ? undefined : segments[at + 1];\n if (name === undefined) return undefined;\n const type = descriptors[name]?.type;\n return type === undefined ? `property \"${name}\"` : `property \"${name}\", type ${type}`;\n}\n","import type { Event } from '@mica-js/core/lifecycle';\nimport type {\n WidgetAudioApi,\n WidgetAudioStream,\n WidgetAudioState,\n WidgetAudioStreamStatus,\n} from '@mica-js/widget/audio-guest';\n\nexport type {\n WidgetAudioOptions as IFusedAudioOptions,\n WidgetAudioControls as IFusedAudioControls,\n} from '@mica-js/widget/audio-host';\nexport type {\n WidgetAudioState as FusedAudioState,\n WidgetAudioTone as IFusedAudioTone,\n WidgetAudioToneOptions as IFusedAudioToneOptions,\n WidgetAudioStreamOptions as IFusedAudioStreamOptions,\n} from '@mica-js/widget/audio-guest';\n\nexport interface IFusedAudioStream extends Omit<WidgetAudioStream, 'onDrain' | 'onStatus'> {\n readonly onDidDrain: Event<void>;\n readonly onDidChangeStatus: Event<WidgetAudioStreamStatus>;\n}\n\n/** Audio handles belong to one instance generation, including while its body is hidden. */\nexport interface IFusedAudio extends Omit<WidgetAudioApi, 'onStateChange' | 'createStream'> {\n readonly onDidChangeState: Event<WidgetAudioState>;\n createStream(options: Parameters<WidgetAudioApi['createStream']>[0]): IFusedAudioStream;\n}\n\n/** Adapt the shared audio implementation's subscriptions to the editor lifecycle convention. */\nexport function fusedAudio(api: WidgetAudioApi): IFusedAudio {\n return {\n get state() {\n return api.state;\n },\n onDidChangeState: (listener) => ({ dispose: api.onStateChange(listener) }),\n tone: (options) => api.tone(options),\n createStream(options) {\n const stream = api.createStream(options);\n return Object.assign(stream, {\n onDidDrain: ((listener) => ({ dispose: stream.onDrain(() => listener()) })) as Event<void>,\n onDidChangeStatus: ((listener) => ({\n dispose: stream.onStatus(listener),\n })) as Event<WidgetAudioStreamStatus>,\n });\n },\n };\n}\n","/**\n * Display-side model client of one instance (RFC 0021 / RFC 0022).\n *\n * The client talks to the simulation guest over the direct model lane: a presentation input handler\n * calls its model without a hop through the editor, and `invalidate()` remains the only repaint\n * trigger. Only the methods and events the manifest declares resolve.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedModelEventWire,\n} from '../protocol';\nimport { mapWireFailure } from '../wire';\n\n/** Model lane as the display guest sees it. */\nexport interface IFusedDisplayModelChannel {\n /** Model client of one prepared instance. */\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n /** Drops every listener of a released instance. */\n release(instanceId: string): void;\n /**\n * Resolves once subscriptions reach the simulation guest and prior model events reach this guest.\n *\n * Preparation awaits this before the models are mounted, so an event produced while a model\n * initializes is never lost to a subscription that is still in flight.\n */\n settle(): Promise<void>;\n dispose(): void;\n}\n\n/** Starts the display end of the model lane over `port`. */\nexport function startDisplayModelChannel(\n port: MessagePort,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedDisplayModelChannel {\n const endpoint = createEndpoint(port);\n const lane = endpoint.getProxy(fusedModelChannelService);\n /** Wire subscriptions still in flight, so preparation can wait for the model lane to catch up. */\n const inFlight = new Set<Promise<void>>();\n const router = createModelEventRouter({\n subscribe(instanceId, event) {\n const call = lane.subscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n unsubscribe(instanceId, event) {\n const call = lane.unsubscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n });\n endpoint.register(fusedModelSinkService, {\n deliver(event: IFusedModelEventWire) {\n if (!isModelEvent(event)) return;\n router.deliver(event.instanceId, event.event, event.payload);\n },\n });\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) =>\n mapWireFailure(() => lane.call(instance.instanceId, name, params));\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = router.event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router.release(instanceId);\n },\n async settle() {\n while (inFlight.size > 0) {\n await Promise.allSettled([...inFlight]);\n }\n await lane.settle();\n },\n dispose() {\n router.dispose();\n endpoint.dispose();\n },\n };\n}\n\nfunction isModelEvent(value: unknown): value is IFusedModelEventWire {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly instanceId?: unknown; readonly event?: unknown };\n return typeof candidate.instanceId === 'string' && typeof candidate.event === 'string';\n}\n","/**\n * One 2D presentation of the display guest (RFC 0022).\n *\n * A session evaluates one verified `view2d.entry` module, builds the factory context and owns the\n * overlay canvas. Drawing is synchronous and never drives the model: `renderOverlay` only reads the\n * data the model already produced, and `invalidate()` is the only way a presentation asks for a\n * repaint.\n */\nimport type { Geometry2D } from '@mica-js/document/fused';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio, type IFusedAudio } from '../audio';\nimport type {\n FusedDisplayMode,\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedRenderRequest,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from '../protocol';\nimport { byteBuffer, decodeSource, isThenable, reconstructPresentationProps } from '../values';\nimport { FusedBridgeError, messageOf } from '../wire';\n\n/** Canvas one overlay is painted into; injectable so the guest runs off-browser in tests. */\nexport interface IFusedOverlaySurface {\n readonly width: number;\n readonly height: number;\n getContext(type: '2d'): OffscreenCanvasRenderingContext2D | null;\n transferToImageBitmap(): ImageBitmap;\n}\n\nexport type FusedSurfaceFactory = (width: number, height: number) => IFusedOverlaySurface;\n\n/** Requests the display guest performs on behalf of one session. */\nexport interface IFusedViewSessionOptions {\n readonly instance: IFusedInstancePresentation;\n readonly mode: FusedDisplayMode;\n readonly model: IFusedModelClient | undefined;\n readonly audio?: IFusedAudio;\n readonly readAsset: (path: string) => Promise<Uint8Array>;\n readonly importModule: (code: string) => Promise<unknown>;\n readonly createSurface: FusedSurfaceFactory;\n readonly invalidate: () => void;\n readonly report: (code: string, message: string) => void;\n}\n\nexport interface IFusedViewSession {\n readonly instanceId: string;\n readonly geometry: Geometry2D;\n /** Runs the author `initialize` hook once; safe to call again. */\n activate(): Promise<void>;\n /** Paints one overlay frame; the caller owns the returned bitmap. */\n render(request: IFusedRenderRequest): ImageBitmap | undefined;\n input(event: IFusedViewInput): void;\n dispose(): void;\n}\n\n/**\n * Evaluates the presentation entry of one instance and initializes it.\n *\n * @throws {FusedBridgeError} when the module has no factory or `initialize` fails.\n */\nexport async function createViewSession(\n options: IFusedViewSessionOptions,\n): Promise<IFusedViewSession> {\n const { instance } = options;\n const entry = instance.view;\n if (entry === undefined) {\n throw new FusedBridgeError(\n 'view2d/unsupported',\n `${instance.device} declares no \\`view2d.entry\\`.`,\n { instanceId: instance.instanceId },\n );\n }\n const namespace = (await options.importModule(decodeSource(await options.readAsset(entry)))) as {\n readonly default?: unknown;\n } | null;\n const factory =\n namespace !== null && typeof namespace === 'object' ? namespace.default : undefined;\n if (typeof factory !== 'function') {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} must default-export a presentation factory.`,\n { instanceId: instance.instanceId },\n );\n }\n\n let disposed = false;\n const localAudio = options.audio === undefined ? createWidgetAudioRuntime({}) : undefined;\n let surface: IFusedOverlaySurface | undefined;\n const assets: IFusedViewAssets = {\n read: (path: string) => options.readAsset(path),\n loadImage: async (path: string) =>\n createImageBitmap(new Blob([byteBuffer(await options.readAsset(path))])),\n };\n const context: IFusedView2DContext = {\n mode: options.mode,\n props: reconstructPresentationProps(instance.props),\n geometry: instance.geometry,\n model: options.model,\n assets,\n audio: options.audio ?? fusedAudio(localAudio!.api(instance.instanceId)),\n invalidate: () => {\n if (!disposed) options.invalidate();\n },\n };\n const view = (factory as FusedView2DFactory)(context);\n if (typeof view !== 'object' || view === null) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} returned no presentation object.`,\n { instanceId: instance.instanceId },\n );\n }\n let activated = false;\n\n return {\n instanceId: instance.instanceId,\n geometry: instance.geometry,\n /**\n * Runs `initialize` once, after the models exist (RFC 0025 startup barrier). The factory itself\n * only registers listeners, so a presentation sees the initial model events before this runs.\n */\n async activate() {\n if (disposed || activated) return;\n activated = true;\n const initialized = view.initialize?.();\n if (isThenable(initialized)) await initialized;\n },\n render(request) {\n const draw = view.renderOverlay;\n if (disposed || draw === undefined) return undefined;\n const target = surfaceFor(request.width, request.height);\n const context2d = target.getContext('2d');\n if (context2d === null) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'The overlay canvas has no 2D context.',\n {\n instanceId: instance.instanceId,\n },\n );\n }\n context2d.save();\n try {\n context2d.setTransform(1, 0, 0, 1, 0, 0);\n context2d.clearRect(0, 0, request.width, request.height);\n const bounds = instance.geometry.bounds;\n context2d.setTransform(\n request.scale,\n 0,\n 0,\n request.scale,\n -bounds.x * request.scale,\n -bounds.y * request.scale,\n );\n const result = draw.call(view, context2d);\n if (isThenable(result)) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'renderOverlay must draw synchronously.',\n { instanceId: instance.instanceId },\n );\n }\n } finally {\n context2d.restore();\n }\n return target.transferToImageBitmap();\n },\n input(event) {\n const handle = view.input;\n if (disposed || handle === undefined) return;\n try {\n const result = handle.call(view, event);\n if (isThenable(result)) {\n void Promise.resolve(result).catch((cause: unknown) => {\n options.report('view2d/input-failed', messageOf(cause));\n });\n }\n } catch (cause) {\n options.report('view2d/input-failed', messageOf(cause));\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n localAudio?.dispose();\n try {\n view.dispose?.();\n } catch (cause) {\n options.report(\n 'runtime/presentation-failed',\n `Releasing the presentation failed: ${messageOf(cause)}`,\n );\n }\n },\n };\n\n function surfaceFor(width: number, height: number): IFusedOverlaySurface {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n `The overlay extent ${String(width)}x${String(height)} must be positive.`,\n { instanceId: instance.instanceId },\n );\n }\n if (surface === undefined || surface.width !== width || surface.height !== height) {\n surface = options.createSurface(width, height);\n }\n return surface;\n }\n}\n","/**\n * 2D presentation guest of the fused editor runtime (RFC 0022 / RFC 0025).\n *\n * One guest serves every instance of the workbench: it evaluates the declared `view2d.entry` modules\n * of the current mode, draws overlays into its own canvases and reports the bitmaps to the host. It\n * holds no document and no model: geometry, properties and the model lane all come from the\n * simulation guest through the host.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio } from '../audio';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock } from '@mica-js/document/fused';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport { fusedDisplayService, fusedHostAudioService } from '../protocol';\nimport type {\n IFusedDisplayPrepareRequest,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedRenderRequest,\n IFusedViewInput,\n} from '../protocol';\nimport { createHostPackageGateway } from '../packages';\nimport { importCode } from '../values';\nimport {\n FusedBridgeError,\n isImageBitmap,\n messageOf,\n toWireFailure,\n transferOverlayFrame,\n} from '../wire';\nimport { startDisplayModelChannel } from './model';\nimport type { IFusedDisplayModelChannel } from './model';\nimport { createViewSession } from './view';\nimport type { FusedSurfaceFactory, IFusedViewSession } from './view';\n\n/** Replaceable guest dependencies, so the presentation runs off-browser in tests. */\nexport interface IFusedDisplayGuestOptions {\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /** Startup ports after the RPC port; the first one is the model lane (RFC 0025). */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified view module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n /** Creates the overlay canvas; defaults to `OffscreenCanvas`. */\n readonly createSurface?: FusedSurfaceFactory;\n}\n\nexport interface IFusedDisplayGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\n/** Starts the 2D presentation guest on the startup port of a sandbox worker. */\nexport function startFusedDisplayGuest(\n port: MessagePort,\n options: IFusedDisplayGuestOptions = {},\n): IFusedDisplayGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const createSurface: FusedSurfaceFactory =\n options.createSurface ?? ((width, height) => new OffscreenCanvas(width, height));\n const packages = createHostPackageGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const audio = createWidgetAudioRuntime({\n onListenerError: (instanceId, cause) =>\n diagnostics.fire({\n code: 'audio/listener-failed',\n message: messageOf(cause),\n instanceId,\n }),\n });\n const hostAudio = endpoint.getProxy(fusedHostAudioService);\n const audioSessions = new Map<string, string>();\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedDisplayModelChannel | undefined =\n modelPort === undefined ? undefined : startDisplayModelChannel(modelPort);\n\n let sessions = new Map<string, IFusedViewSession>();\n /** Incremented by every preparation, so late initializations of a replaced mode are dropped. */\n let sequence = 0;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n // The overlay bitmap is transferable-only: cloning one is invalid, so the hook hands it over.\n endpoint.register(\n fusedDisplayService,\n {\n attachAudio: (port) => audio.attachPort(port),\n setAudioState: (state) => audio.setState(state),\n prepare,\n activate,\n render,\n input,\n release,\n dispose: releaseAll,\n onDidInvalidate(listener) {\n const subscription = invalidations.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n { transfer: transferOverlayFrame },\n );\n\n return { rpc: endpoint, dispose };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function readAsset(lock: DeviceLock, path: string): Promise<Uint8Array> {\n return packages.open(lock).then((files) => files.read(path));\n }\n\n async function prepare(request: IFusedDisplayPrepareRequest): Promise<void> {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError('runtime/unavailable-state', 'The fused display guest is disposed.'),\n );\n }\n const attempt = ++sequence;\n dropSessions();\n for (const instance of request.instances) {\n if (instance.view === undefined) continue;\n const instanceId = instance.instanceId;\n try {\n if (request.mode === 'run') {\n const info = await hostAudio.open(instanceId);\n if (closing || attempt !== sequence) {\n if (info.session !== undefined)\n void hostAudio.close(instanceId, info.session).catch(() => undefined);\n return;\n }\n audio.open(instanceId, info);\n if (info.session !== undefined) audioSessions.set(instanceId, info.session);\n } else audio.open(instanceId, undefined);\n const session = await createViewSession({\n instance,\n mode: request.mode,\n model: request.mode === 'run' ? modelChannel?.client(instance) : undefined,\n audio: fusedAudio(audio.api(instanceId)),\n readAsset: (path) => readAsset(instance.lock, path),\n importModule,\n createSurface,\n invalidate: () => {\n if (attempt === sequence && !closing) invalidations.fire({ instanceId });\n },\n report: (code, message) => report({ code, message, instanceId }),\n });\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n sessions.set(instanceId, session);\n } catch (cause) {\n releaseAudio(instanceId);\n // One broken presentation must not take the other instances down (RFC 0025).\n report({\n code: 'runtime/presentation-failed',\n message: messageOf(cause),\n instanceId,\n });\n }\n }\n // The runtime loads the models only after this resolves, so factory subscriptions are live.\n await modelChannel?.settle();\n }\n\n /**\n * Runs the author `initialize` hook of every prepared presentation.\n *\n * The runtime calls it after the models exist and their initial events were delivered, so a query\n * started here observes the state the model already has. A failing hook faults its own\n * presentation only (RFC 0025 `runtime/presentation-failed`).\n */\n async function activate(): Promise<void> {\n if (closing) return;\n const attempt = sequence;\n // Host activation and model events use different ports; synchronize on the model lane first.\n await modelChannel?.settle();\n if (closing || attempt !== sequence) return;\n for (const [instanceId, session] of [...sessions]) {\n try {\n await session.activate();\n } catch (cause) {\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n report({\n code: 'runtime/presentation-failed',\n message: `Initializing the presentation failed: ${messageOf(cause)}`,\n instanceId,\n });\n release(instanceId);\n }\n }\n }\n\n async function render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined> {\n if (closing) return undefined;\n const session = sessions.get(request.instanceId);\n if (session === undefined) return undefined;\n const attempt = sequence;\n let bitmap: ImageBitmap | undefined;\n try {\n bitmap = session.render(request);\n } catch (cause) {\n report({\n code: 'view2d/render-failed',\n message: messageOf(cause),\n instanceId: request.instanceId,\n });\n return undefined;\n }\n if (bitmap === undefined) return undefined;\n if (closing || attempt !== sequence) {\n closeBitmap(bitmap);\n return undefined;\n }\n return {\n instanceId: request.instanceId,\n generation: request.generation,\n width: request.width,\n height: request.height,\n scale: request.scale,\n bitmap,\n };\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (closing) return;\n sessions.get(instanceId)?.input(event);\n }\n\n function release(instanceId: string): void {\n releaseAudio(instanceId);\n const session = sessions.get(instanceId);\n if (session === undefined) return;\n sessions.delete(instanceId);\n session.dispose();\n modelChannel?.release(instanceId);\n }\n\n async function releaseAll(): Promise<void> {\n if (closing) return;\n sequence += 1;\n dropSessions();\n }\n\n function dropSessions(): void {\n for (const instanceId of [...audioSessions.keys()]) releaseAudio(instanceId);\n const current = sessions;\n sessions = new Map<string, IFusedViewSession>();\n for (const session of current.values()) {\n releaseAudio(session.instanceId);\n session.dispose();\n modelChannel?.release(session.instanceId);\n }\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n dropSessions();\n modelChannel?.dispose();\n audio.dispose();\n endpoint.dispose();\n diagnostics.dispose();\n invalidations.dispose();\n })();\n return disposal;\n }\n\n function releaseAudio(instanceId: string): void {\n audio.release(instanceId);\n const token = audioSessions.get(instanceId);\n audioSessions.delete(instanceId);\n if (token !== undefined) void hostAudio.close(instanceId, token).catch(() => undefined);\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap): void {\n if (isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * `@mica-js/editor/fused/runtime`: the browser bridge of the fused editor runtime (RFC 0022 / 0025).\n *\n * Two sandbox workers serve one workbench. The simulation worker owns the document, the locked\n * packages and every model; the presentation worker runs the declared `view2d.entry` modules and\n * returns overlay bitmaps. They talk over typed RPC services and one direct model lane, and the\n * editor thread never imports model or author view code.\n *\n * ```ts\n * const runtime = await createFusedRuntime({\n * document,\n * registry,\n * step: toTimePs(1, 'ms'),\n * mode: 'run', // mounts the models; advancing starts as soon as the presentations are ready\n * onOverlay: (frame) => paint(frame.instanceId, frame.bitmap),\n * onDiagnostic: (entry) => report(entry),\n * });\n * runtime.display.input(instanceId, { type: 'pointerdown', position, button: 0, buttons: 1 });\n * const frame = await runtime.display.render(instanceId);\n * await runtime.pause(); // step() requires the paused state\n * await runtime.dispose();\n * ```\n */\nimport type { IFusedWorkerFactories } from './host/types';\nexport type * from './audio';\n\nexport { createFusedRuntime } from './host/runtime';\n\n/**\n * Loads the generated worker factories on demand.\n *\n * `createFusedRuntime` does this itself; call it to preload both guest bundles, or to pass the\n * same factories to several runtimes.\n */\nexport async function loadFusedWorkerFactories(): Promise<IFusedWorkerFactories> {\n const { fusedWorkerFactories } = await import('./workers');\n return fusedWorkerFactories;\n}\nexport { connectFusedWorkbench } from './host/connection';\nexport type { IFusedConnection, IFusedConnectionOptions } from './host/connection';\nexport { createFusedDisplay } from './host/display';\nexport type { IFusedDisplayHost, IFusedDisplayHostOptions } from './host/display';\nexport { createHostModelRouter } from './host/model';\nexport type { IFusedHostModelRouter } from './host/model';\nexport type {\n IFusedDisplay,\n IFusedDisplayPrepareInput,\n IFusedRuntime,\n IFusedRuntimeOptions,\n IFusedWorker,\n IFusedWorkerFactories,\n IFusedWorkerOptions,\n} from './host/types';\n\nexport { startFusedSimulationGuest } from './simulation/guest';\nexport type { IFusedSimulationGuest, IFusedSimulationGuestOptions } from './simulation/guest';\nexport { startFusedDisplayGuest } from './display/guest';\nexport type { IFusedDisplayGuest, IFusedDisplayGuestOptions } from './display/guest';\nexport { createViewSession } from './display/view';\nexport type {\n IFusedOverlaySurface,\n FusedSurfaceFactory,\n IFusedViewSession,\n IFusedViewSessionOptions,\n} from './display/view';\nexport { createModelEventRouter, channelKey } from './model-events';\nexport type { IFusedModelEventChannel, IFusedModelEventRouter } from './model-events';\nexport { createHostPackageGateway, packageLockKey } from './packages';\n\nexport {\n FUSED_WIRE_FAILURE,\n FusedBridgeError,\n fromWireFailure,\n isFusedBridgeError,\n mapWireFailure,\n toWireFailure,\n} from './wire';\nexport type { IFusedBridgeErrorOptions, IFusedFailurePayload } from './wire';\n\nexport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedModelChannelService,\n fusedModelSinkService,\n fusedSimulationService,\n} from './protocol';\nexport type {\n FusedDisplayMode,\n FusedPresentationProps,\n FusedPresentationValue,\n FusedSessionStatus,\n FusedViewInputType,\n IFusedDisplayLayout,\n IFusedDisplayPrepareRequest,\n IFusedDisplayService,\n IFusedHostPackageService,\n IFusedHostResourceService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedLoadRequest,\n IFusedModelChannelService,\n IFusedModelClient,\n IFusedModelEventWire,\n FusedModelEvents,\n FusedModelMethods,\n IFusedModelSinkService,\n IFusedOverlayFrame,\n IFusedPackageFilesWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedRenderRequest,\n IFusedSessionState,\n IFusedSimulationService,\n IFusedView2D,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from './protocol';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgUA,IAAa,yBAAyB,iBAA0C,kBAAk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QAAQ,UAAU;EAC1C;CACF;CAEA,SAAS,UAAyB;EAChC,IAAI,aAAa,KAAA,GAAW,OAAO;EACnC,UAAU;EACV,YAAY,YAAY;GACtB,YAAY;GACZ,aAAa;GACb,cAAc,QAAQ;GACtB,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,YAAY,QAAQ;GACpB,cAAc,QAAQ;EACxB,EAAA,CAAG;EACH,OAAO;CACT;CAEA,SAAS,aAAa,YAA0B;EAC9C,MAAM,QAAQ,UAAU;EACxB,MAAM,QAAQ,cAAc,IAAI,UAAU;EAC1C,cAAc,OAAO,UAAU;EAC/B,IAAI,UAAU,KAAA,GAAW,UAAe,MAAM,YAAY,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS;CACxF;AACF;AAEA,SAAS,YAAY,QAA2B;CAC9C,IAAI,cAAc,MAAM,GAAG,OAAO,MAAM;AAC1C;;;;;;;;;ACjQA,eAAsB,2BAA2D;CAC/E,MAAM,EAAE,yBAAyB,MAAM,OAAO;CAC9C,OAAO;AACT"}
1
+ {"version":3,"file":"runtime-CQVaxxMm.js","names":["closeBitmap","IDLE"],"sources":["../src/fused/runtime/protocol.ts","../src/fused/runtime/packages.ts","../src/fused/runtime/host/audio.ts","../src/fused/runtime/host/connection.ts","../src/fused/runtime/host/display.ts","../src/fused/runtime/model-events.ts","../src/fused/runtime/host/model.ts","../src/fused/runtime/host/runtime.ts","../src/fused/runtime/values.ts","../src/fused/runtime/simulation/model-channel.ts","../src/fused/runtime/simulation/guest.ts","../src/fused/runtime/audio.ts","../src/fused/runtime/display/model.ts","../src/fused/runtime/display/view.ts","../src/fused/runtime/display/guest.ts","../src/fused/runtime/index.ts"],"sourcesContent":["/**\n * Wire contracts of the fused editor runtime bridge (RFC 0022 / RFC 0025).\n *\n * One simulation guest owns the document snapshot, the locked packages and every model; one display\n * guest owns the declared `view2d.entry` modules and draws overlays. Both are `SandboxWorker` guests\n * and speak only these typed RPC services over ports created with `createRpc`: the main thread never\n * imports a model or an author view module.\n *\n * Binary payloads, package bytes and overlay bitmaps travel through registration transfer hooks; the\n * model lane is a direct port between the two guests, so a display input handler reaches its model\n * without a hop through the editor.\n */\nimport { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { WidgetAudioMountInfo, WidgetAudioState } from '@mica-js/widget/audio-guest';\nimport type { IFusedAudio } from './audio';\nimport type {\n DeviceLock,\n FusedDocument,\n Geometry2D,\n PackageFile,\n Point2D,\n Value,\n} from '@mica-js/document/fused';\nimport type {\n ProgramArtifact,\n ProgramFile,\n ProgramTarget,\n MemoryProgram,\n ProgramFiles,\n ModelEvent,\n ResourceRequest,\n RuntimeDiagnostic,\n} from '@mica-js/sdk/fused';\n\n/** Session status the host mirrors; `idle` means no models are mounted (edit mode). */\nexport type FusedSessionStatus = 'idle' | 'paused' | 'running' | 'faulted' | 'disposed';\n\n/** Presentation mode of one workbench (RFC 0025). */\nexport type FusedDisplayMode = 'edit' | 'run';\n\n/** One loaded firmware segment of a presentation snapshot (RFC 0026). */\nexport interface IFusedFirmwareSegment {\n readonly addressSpace: string;\n readonly address: number;\n /** Segment bytes; an independent copy owned by the presentation snapshot. */\n readonly bytes: Uint8Array;\n}\n\n/** Read-only firmware snapshot a presentation may read (RFC 0026). */\nexport interface IFusedFirmwareSnapshot {\n readonly kind: 'firmware';\n readonly segments: readonly IFusedFirmwareSegment[];\n}\n\nexport interface IFusedProgramFilesSnapshot {\n readonly kind: 'filesystem';\n readonly files: readonly ProgramFile[];\n}\n\n/**\n * One resolved property value a presentation may read.\n *\n * Scalars stay plain; `image` and `binary` properties are their resolved bytes; `firmware`\n * properties are the loaded, segment-addressable snapshot. Resolution happens in the simulation\n * worker, so an unresolved property rejects the presentation instead of shrinking its props.\n */\nexport type FusedPresentationValue =\n | string\n | number\n | boolean\n | null\n | Uint8Array\n | IFusedFirmwareSnapshot\n | IFusedProgramFilesSnapshot;\n\nexport type FusedResolvedPresentationProps = Readonly<\n Record<string, string | number | boolean | null | Uint8Array | MemoryProgram | ProgramFiles>\n>;\n\n/** Read-only plain property snapshot handed to a 2D presentation. */\nexport type FusedPresentationProps = Readonly<Record<string, FusedPresentationValue>>;\n\n/** State of the simulation session as the host sees it. */\nexport interface IFusedSessionState {\n readonly status: FusedSessionStatus;\n readonly simTime: TimePs;\n}\n\n/**\n * Everything the display worker needs to prepare one instance.\n *\n * Geometry and the property projection are resolved inside the simulation worker, so the host never\n * parses a manifest or evaluates an author module.\n */\nexport interface IFusedInstancePresentation {\n readonly instanceId: string;\n /** Full `publisher:name` device id the instance locks. */\n readonly device: string;\n readonly lock: DeviceLock;\n readonly geometry: Geometry2D;\n /** Package-root relative `.js` overlay entry; `undefined` for a geometry-only device. */\n readonly view: string | undefined;\n /**\n * Resolved property snapshot, identical to the one the model receives: manifest default and\n * document override through the SDK, with resource bytes and the loaded firmware image. An\n * instance whose props cannot be projected has no presentation at all, so this is never partial.\n */\n readonly props: FusedPresentationProps;\n /** Declared model method names; empty for a device without a model. */\n readonly methods: readonly string[];\n /** Declared model event names; empty for a device without a model. */\n readonly events: readonly string[];\n}\n\n/** Preparation request of the simulation guest: verify packages and describe the scene. */\nexport interface IFusedPrepareRequest {\n readonly document: FusedDocument;\n readonly mode: FusedDisplayMode;\n}\n\nexport interface IFusedPrepareResult {\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Request that creates the models of one run session. */\nexport interface IFusedLoadRequest {\n readonly document: FusedDocument;\n /** Fixed positive step of every advance, in picoseconds. */\n readonly step: TimePs;\n /** Explicit simulator batch-execution switch; omitted uses the board default. */\n readonly batchExecution?: boolean;\n}\n\n/** One model event as it crosses the sandbox boundary. */\nexport interface IFusedModelEventWire {\n readonly instanceId: string;\n readonly event: string;\n readonly payload: ModelEvent<Value>;\n}\n\n/** Dynamic methods of one display-side model client; only declared names resolve. */\nexport type FusedModelMethods = Readonly<Record<string, (params: Value) => Promise<Value>>>;\n\n/** Declared event outlets of one model client. */\nexport type FusedModelEvents = Readonly<Record<string, Event<ModelEvent<Value>>>>;\n\n/**\n * Model client handed to a presentation or to the editor.\n *\n * Structurally the RFC 0021 `ModelClient` of a dynamically declared interface: methods are\n * asynchronous and every event is a core `Event` of a `ModelEvent` payload.\n */\nexport interface IFusedModelClient {\n readonly methods: FusedModelMethods;\n readonly events: FusedModelEvents;\n}\n\n/** Package resources one presentation may read (RFC 0022 `ViewAssets`). */\nexport interface IFusedViewAssets {\n /** Reads one declared package file; bytes are copied into the caller. */\n read(path: string): Promise<Uint8Array>;\n /** Decodes one image; the caller owns the bitmap and must `close()` it. */\n loadImage(path: string): Promise<ImageBitmap>;\n}\n\nexport type FusedViewInputType = 'pointerdown' | 'pointerup' | 'pointermove';\n\n/** Local pointer input delivered to one presentation (RFC 0022). */\nexport interface IFusedViewInput {\n readonly type: FusedViewInputType;\n /** Position in the device's local coordinates. */\n readonly position: Point2D;\n /** DOM button number of the event. */\n readonly button: number;\n /** DOM button bit mask of the buttons currently held. */\n readonly buttons: number;\n}\n\n/** Context a `view2d.entry` factory receives (RFC 0022). */\nexport interface IFusedView2DContext {\n readonly mode: FusedDisplayMode;\n readonly props: FusedResolvedPresentationProps;\n readonly geometry: Geometry2D;\n /** Proxy of the owning instance; `undefined` in edit mode and for devices without a model. */\n readonly model: IFusedModelClient | undefined;\n readonly assets: IFusedViewAssets;\n /** Instance audio, independent of overlay rendering and HTML panels. */\n readonly audio: IFusedAudio;\n /** Marks the overlay stale; the host decides when to repaint. */\n invalidate(): void;\n}\n\n/** Object a `view2d.entry` default factory returns (RFC 0022). */\nexport interface IFusedView2D {\n initialize?(): void | Promise<void>;\n renderOverlay?(context: OffscreenCanvasRenderingContext2D): void;\n input?(event: IFusedViewInput): void | Promise<void>;\n dispose?(): void;\n}\n\n/** Default export of a `view2d.entry` module. */\nexport type FusedView2DFactory = (context: IFusedView2DContext) => IFusedView2D;\n\n/** Simulation guest, reached through {@link fusedSimulationService}. */\nexport interface IFusedSimulationService {\n prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult>;\n load(request: IFusedLoadRequest): Promise<IFusedSessionState>;\n step(): Promise<IFusedSessionState>;\n resume(): Promise<void>;\n /** Stops advancement synchronously; the RPC result acknowledges the paused state. */\n pause(): void;\n reset(): Promise<void>;\n /** Releases the models and keeps the captured package bytes for the next load. */\n dispose(): Promise<void>;\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n getState(): IFusedSessionState;\n onDidChangeState(listener: (state: IFusedSessionState) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n /** Every model event of the session, in production order. */\n onDidModelEvent(listener: (event: IFusedModelEventWire) => void): () => void;\n}\n\n/** Paths of one locked package, resolved by the host (RFC 0020). */\nexport interface IFusedPackageFilesWire {\n readonly lock: DeviceLock;\n readonly files: Readonly<Record<string, PackageFile>>;\n}\n\n/** Host package access both guests share; the host owns the bytes and verifies nothing twice. */\nexport interface IFusedHostPackageService {\n open(lock: DeviceLock): Promise<IFusedPackageFilesWire>;\n /** Returns a copy the guest may keep; the reply transfers its buffer. */\n read(lock: DeviceLock, path: string): Promise<Uint8Array>;\n}\n\n/** Host resources the simulation guest reaches during preparation (RFC 0020 / RFC 0026). */\nexport interface IFusedHostResourceService {\n readResource(request: ResourceRequest): Promise<Uint8Array>;\n resolveProgramProject(projectId: string, target: ProgramTarget): Promise<ProgramArtifact>;\n}\n\n/** Model lane served by the simulation guest to the display guest over the direct port. */\nexport interface IFusedModelChannelService {\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n /** Replies on the model lane after every event already sent on that lane. */\n settle(): void;\n}\n\n/** Model event lane served by the display guest to the simulation guest. */\nexport interface IFusedModelSinkService {\n deliver(event: IFusedModelEventWire): void;\n}\n\n/** Preparation of the display guest: one mode and the instances of the current session. */\nexport interface IFusedDisplayPrepareRequest {\n readonly mode: FusedDisplayMode;\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Pixels per local unit and the overlay extent the host reserves for one instance. */\nexport interface IFusedDisplayLayout {\n /** Overlay width in device pixels. */\n readonly width: number;\n /** Overlay height in device pixels. */\n readonly height: number;\n /** Device pixels per local unit. */\n readonly scale: number;\n}\n\n/** One overlay render request. */\nexport interface IFusedRenderRequest extends IFusedDisplayLayout {\n readonly instanceId: string;\n /** Monotonic request number the frame echoes back, so stale results are dropped. */\n readonly generation: number;\n}\n\n/** Rendered overlay of one instance; the bitmap lives in the host after the transfer. */\nexport interface IFusedOverlayFrame extends IFusedDisplayLayout {\n readonly instanceId: string;\n readonly generation: number;\n readonly bitmap: ImageBitmap;\n}\n\n/** A presentation asked for a repaint. */\nexport interface IFusedInvalidateEvent {\n readonly instanceId: string;\n}\n\n/** Display guest, reached through {@link fusedDisplayService}. */\nexport interface IFusedDisplayService {\n /** Direct display guest to audio worklet lane, transferred by the host. */\n attachAudio(port: MessagePort): void;\n setAudioState(state: WidgetAudioState): void;\n /**\n * Creates the presentation factories of one mode; nothing is initialized yet.\n *\n * It runs before the models exist, so a factory can subscribe to model events and still observe\n * the events the model produces while it initializes.\n */\n prepare(request: IFusedDisplayPrepareRequest): Promise<void>;\n /**\n * Runs `initialize` of every prepared presentation, after the models are mounted and their initial\n * events were delivered (RFC 0025 startup barrier).\n */\n activate(): Promise<void>;\n /** Renders one overlay; `undefined` when the instance has no dynamic overlay. */\n render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined>;\n /** Delivers local pointer input; the guest reports a failing handler as `view2d/input-failed`. */\n input(instanceId: string, event: IFusedViewInput): void;\n release(instanceId: string): void;\n dispose(): Promise<void>;\n onDidInvalidate(listener: (change: IFusedInvalidateEvent) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n}\n\n/** Wire name of the simulation guest. */\nexport const fusedSimulationService = defineRpcService<IFusedSimulationService>('fused-simulation');\n\n/** Wire name of the 2D presentation guest. */\nexport const fusedDisplayService = defineRpcService<IFusedDisplayService>('fused-display');\n\n/** Wire name of the host package access both guests use. */\nexport const fusedHostPackageService =\n defineRpcService<IFusedHostPackageService>('fused-host-package');\n\n/** Wire name of the host resource access of the simulation guest. */\nexport const fusedHostResourceService =\n defineRpcService<IFusedHostResourceService>('fused-host-resource');\n\n/** Wire name of the model lane the simulation guest serves. */\nexport const fusedModelChannelService =\n defineRpcService<IFusedModelChannelService>('fused-model-channel');\n\n/** Wire name of the model sink the display guest serves. */\nexport const fusedModelSinkService = defineRpcService<IFusedModelSinkService>('fused-model-sink');\n\n/** Host opens and revokes instance generations; samples use the separate worklet port. */\nexport interface IFusedHostAudioService {\n open(instanceId: string): Promise<WidgetAudioMountInfo>;\n close(instanceId: string, session: string): void;\n}\n\nexport const fusedHostAudioService = defineRpcService<IFusedHostAudioService>('fused-host-audio');\n","/**\n * Package access of the sandbox guests (RFC 0020).\n *\n * The host owns the packages, so both guests reach the same typed service: `open` proves the lock\n * resolves and `read` hands over one declared file. The guest caches the bytes, because preparation\n * reads the same file for its digest and again for its content, and each reply transfers ownership.\n */\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry } from '@mica-js/document/fused';\nimport { fusedHostPackageService } from './protocol';\nimport type { IFusedPackageFilesWire } from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/** Wire key of one locked package. */\nexport function packageLockKey(lock: DeviceLock): string {\n return `${lock.id}@${lock.version}#${lock.integrity}`;\n}\n\n/** Registry implementation served by the host over `endpoint`. */\nexport function createHostPackageGateway(endpoint: RpcEndpoint): DeviceRegistry {\n const host = endpoint.getProxy(fusedHostPackageService);\n const opened = new Map<string, Promise<IFusedPackageFilesWire>>();\n const cache = new Map<string, Uint8Array>();\n const openLock = (lock: DeviceLock): Promise<IFusedPackageFilesWire> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = host.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n return {\n open(lock: DeviceLock) {\n return openLock(lock).then((files) => ({\n lock: files.lock,\n files: files.files,\n read: async (path: string) => {\n const key = `${packageLockKey(lock)}\\u0000${path}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.read(lock, path);\n if (!(bytes instanceof Uint8Array)) {\n throw new FusedBridgeError(\n 'package/not-found',\n `The host returned no bytes for ${lock.id}/${path}.`,\n );\n }\n // The reply transferred ownership, so the cache keeps the only copy of this realm.\n cache.set(key, bytes);\n return bytes.slice();\n },\n }));\n },\n };\n}\n","import { WidgetAudioEngine } from '@mica-js/widget/audio-host';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type { IFusedAudioControls, IFusedAudioOptions } from '../audio';\nimport { fusedHostAudioService, type IFusedDisplayService } from '../protocol';\n\n/** Browser-owned audio engine; the guest only receives session tokens and a worklet port. */\nexport function connectFusedAudio(\n rpc: RpcEndpoint,\n display: Pick<RpcProxy<IFusedDisplayService>, 'attachAudio' | 'setAudioState'>,\n options: IFusedAudioOptions | undefined,\n report: (diagnostic: RuntimeDiagnostic) => void,\n): IFusedAudioControls & { clear(): void; dispose(): void } {\n const instances = new Set<string>();\n const reported = new Set<string>();\n let disposed = false;\n function bridgeFailure(operation: string, cause: unknown): void {\n if (disposed || reported.has(operation)) return;\n reported.add(operation);\n report({ code: 'audio/failed', message: `Audio bridge ${operation} failed: ${String(cause)}` });\n }\n const engine =\n options === undefined\n ? undefined\n : new WidgetAudioEngine({\n context: options.context,\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n ...(options.limits === undefined ? {} : { limits: options.limits }),\n ...(options.getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => options.getAudioWorklet!(options.context),\n }),\n notify: {\n emitPort: (port) => {\n void display.attachAudio(port).catch((cause: unknown) => {\n port.close();\n bridgeFailure('attachAudio', cause);\n });\n },\n emitState: (state) => {\n void display.setAudioState(state).catch((cause: unknown) => {\n bridgeFailure('setAudioState', cause);\n });\n },\n },\n report: (code, instanceId, message) =>\n report({\n code: code.replace('widget/audio-', 'audio/'),\n message,\n ...(instanceId === '' ? {} : { instanceId }),\n }),\n });\n engine?.suspend();\n rpc.register(fusedHostAudioService, {\n async open(instanceId) {\n instances.add(instanceId);\n return (await engine?.open(instanceId)) ?? { state: 'unavailable' };\n },\n close(instanceId, session) {\n engine?.closeSession(instanceId, session);\n },\n });\n return {\n get state() {\n return engine?.state ?? 'unavailable';\n },\n suspend: () => engine?.suspend(),\n resume: () => engine?.resume(),\n setMuted: (muted) => engine?.setMuted(muted),\n setInstanceVolume: (id, volume) => engine?.setInstanceVolume(id, volume),\n clear() {\n for (const id of instances) engine?.close(id);\n instances.clear();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n engine?.dispose();\n },\n };\n}\n","/**\n * Worker wiring of one fused workbench (RFC 0025).\n *\n * Both guests start from the generated `?sandbox-worker` classes: the host waits for the sandbox to\n * boot, transfers one end of three `MessageChannel`s and creates the typed RPC endpoints. From then\n * on nothing but `createRpc` traffic crosses the boundary.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry, PackageFiles } from '@mica-js/document/fused';\nimport type { ProgramSources, ResourceResolver, RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedSimulationService,\n} from '../protocol';\nimport type { IFusedDisplayService, IFusedSimulationService } from '../protocol';\nimport { packageLockKey } from '../packages';\nimport { transferProgramArtifact, transferPackageBytes, transferResourceBytes } from '../wire';\nimport type { IFusedWorkerFactories } from './types';\nimport type { IFusedAudioOptions } from '../audio';\nimport { connectFusedAudio } from './audio';\n\nexport interface IFusedConnectionOptions {\n readonly audio?: IFusedAudioOptions;\n readonly workers: IFusedWorkerFactories;\n /** Host package access both guests share. */\n readonly registry: DeviceRegistry;\n /** Element that hosts the two hidden sandbox iframes. */\n readonly container?: HTMLElement;\n readonly resolveResource?: ResourceResolver;\n readonly programs?: ProgramSources;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n}\n\n/** Two guests of one workbench plus the endpoints that reach them. */\nexport interface IFusedConnection {\n readonly audio: ReturnType<typeof connectFusedAudio>;\n readonly simulation: RpcProxy<IFusedSimulationService>;\n readonly display: RpcProxy<IFusedDisplayService>;\n dispose(): Promise<void>;\n}\n\n/** Boots both guests of one workbench and wires their RPC surfaces. */\nexport async function connectFusedWorkbench(\n options: IFusedConnectionOptions,\n): Promise<IFusedConnection> {\n const workerOptions = options.container === undefined ? {} : { container: options.container };\n const simulationWorker = options.workers.createSimulationWorker(workerOptions);\n const displayWorker = options.workers.createDisplayWorker(workerOptions);\n const subscriptions: Array<() => void> = [];\n let simulationRpc: RpcEndpoint | undefined;\n let displayRpc: RpcEndpoint | undefined;\n try {\n await Promise.all([simulationWorker.ready, displayWorker.ready]);\n const simulationChannel = new MessageChannel();\n const displayChannel = new MessageChannel();\n const modelChannel = new MessageChannel();\n // Ports arrive in the guest as `event.ports`: the RPC port first, the model lane second.\n simulationWorker.postMessage(null, [simulationChannel.port2, modelChannel.port1]);\n displayWorker.postMessage(null, [displayChannel.port2, modelChannel.port2]);\n simulationRpc = createRpc(simulationChannel.port1);\n displayRpc = createRpc(displayChannel.port1);\n registerHostServices(simulationRpc, options);\n registerHostServices(displayRpc, options);\n const simulation = simulationRpc.getProxy(fusedSimulationService);\n const display = displayRpc.getProxy(fusedDisplayService, {\n transfer: (member, args) => (member === 'attachAudio' ? [args[0] as MessagePort] : []),\n });\n const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) =>\n options.onDiagnostic?.(diagnostic),\n );\n subscriptions.push(\n simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n );\n const ownedSimulationRpc = simulationRpc;\n const ownedDisplayRpc = displayRpc;\n let disposal: Promise<void> | undefined;\n return {\n audio,\n simulation,\n display,\n dispose() {\n return (disposal ??= (async () => {\n audio.dispose();\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n ownedSimulationRpc.dispose();\n ownedDisplayRpc.dispose();\n const results = await Promise.allSettled([\n simulationWorker.terminate('fused runtime disposed'),\n displayWorker.terminate('fused runtime disposed'),\n ]);\n const problems = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason as unknown);\n if (problems.length > 0) {\n throw new AggregateError(problems, 'Fused sandbox workers failed to terminate.');\n }\n })());\n },\n };\n } catch (cause) {\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n simulationRpc?.dispose();\n displayRpc?.dispose();\n await Promise.allSettled([\n simulationWorker.terminate('fused runtime failed to start'),\n displayWorker.terminate('fused runtime failed to start'),\n ]);\n throw cause;\n }\n}\n\n/** Package and resource services every guest of one workbench pulls from. */\nfunction registerHostServices(endpoint: RpcEndpoint, options: IFusedConnectionOptions): void {\n const opened = new Map<string, Promise<PackageFiles>>();\n const openLock = (lock: DeviceLock): Promise<PackageFiles> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = options.registry.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n endpoint.register(\n fusedHostPackageService,\n {\n async open(lock: DeviceLock) {\n const files = await openLock(lock);\n return { lock: files.lock, files: files.files };\n },\n async read(lock: DeviceLock, path: string) {\n const files = await openLock(lock);\n const bytes = await files.read(path);\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`The registry returned no bytes for ${lock.id}/${path}.`);\n }\n // The transfer hands the buffer to the guest, so the editor keeps its own copy.\n return bytes.slice();\n },\n },\n { transfer: transferPackageBytes },\n );\n endpoint.register(\n fusedHostResourceService,\n {\n async readResource(request) {\n if (options.resolveResource === undefined) {\n throw new Error(\n `No resource resolver is configured for ${request.instanceId}/${request.property}.`,\n );\n }\n return (await options.resolveResource(request)).slice();\n },\n async resolveProgramProject(id, target) {\n if (!options.programs?.projects) throw new Error('No program project provider configured.');\n const artifact = await options.programs.projects.resolve(id, target);\n return artifact.kind === 'memory'\n ? { kind: 'memory', format: artifact.format, data: artifact.data.slice() }\n : {\n kind: 'filesystem',\n files: artifact.files.map((file) => ({ path: file.path, data: file.data.slice() })),\n };\n },\n },\n {\n transfer: (member, value) =>\n member === 'resolveProgramProject'\n ? transferProgramArtifact(member, value)\n : transferResourceBytes(member, value),\n },\n );\n}\n","/**\n * Host-side 2D presentation surface (RFC 0022).\n *\n * The host reserves the overlay extent, numbers every request so a late frame can never overwrite a\n * newer one, and repaints instances whose presentation called `invalidate()`. Bitmaps of discarded\n * frames are closed instead of leaked.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n FusedDisplayMode,\n IFusedDisplayLayout,\n IFusedDisplayService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedViewInput,\n} from '../protocol';\nimport type { IFusedDisplay, IFusedDisplayPrepareInput } from './types';\nimport { isImageBitmap, mapWireFailure, messageOf } from '../wire';\n\nexport interface IFusedDisplayHostOptions {\n readonly proxy: RpcProxy<IFusedDisplayService>;\n readonly onOverlay?: (frame: IFusedOverlayFrame) => void;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n /** Overlay extent of one instance; defaults to its bounds at one device pixel per local unit. */\n readonly measure?: (instance: IFusedInstancePresentation) => IFusedDisplayLayout;\n /** Repaints when a presentation asks for it; defaults to `true`. */\n readonly autoRender?: boolean;\n}\n\n/** Display surface plus the preparation the runtime drives. */\nexport interface IFusedDisplayHost {\n readonly display: IFusedDisplay;\n /** Replaces the presentation of one mode; drops every pending frame of the previous one. */\n prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void>;\n /** Runs the author `initialize` hooks once the models of the mode exist. */\n activate(): Promise<void>;\n dispose(): Promise<void>;\n}\n\nexport function createFusedDisplay(options: IFusedDisplayHostOptions): IFusedDisplayHost {\n const { proxy } = options;\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const generations = new Map<string, number>();\n const dirty = new Set<string>();\n /** Reported framework failures of the current preparation, so a flood reports once. */\n const reported = new Set<string>();\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: FusedDisplayMode | undefined;\n /** Incremented by every preparation, so results of a replaced mode are dropped. */\n let epoch = 0;\n let pumping = false;\n let disposed = false;\n let disposal: Promise<void> | undefined;\n\n const stopInvalidate = proxy.onDidInvalidate((change) => {\n if (disposed) return;\n invalidations.fire(change);\n if (options.autoRender !== false) schedule(change.instanceId);\n });\n\n const display: IFusedDisplay = {\n get mode() {\n return mode;\n },\n get instances() {\n return prepared;\n },\n onDidInvalidate: invalidations.event,\n render,\n input,\n invalidate,\n dispose,\n };\n\n return { display, prepare, activate, dispose };\n\n async function prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void> {\n if (disposed) {\n throw new Error('The fused display is disposed.');\n }\n epoch += 1;\n generations.clear();\n dirty.clear();\n reported.clear();\n await mapWireFailure(() => proxy.prepare({ mode: input.mode, instances }));\n mode = input.mode;\n prepared = instances;\n }\n\n async function activate(): Promise<void> {\n if (disposed) return;\n await mapWireFailure(() => proxy.activate());\n }\n\n async function render(\n instanceId: string,\n layout?: IFusedDisplayLayout,\n ): Promise<IFusedOverlayFrame | undefined> {\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined || disposed) return undefined;\n const extent = layout ?? defaultLayout(instance);\n const generation = (generations.get(instanceId) ?? 0) + 1;\n generations.set(instanceId, generation);\n const attempt = epoch;\n const frame = await mapWireFailure(() => proxy.render({ instanceId, generation, ...extent }));\n if (frame === undefined) return undefined;\n if (disposed || attempt !== epoch || generation !== generations.get(instanceId)) {\n closeBitmap(frame.bitmap);\n return undefined;\n }\n options.onOverlay?.(frame);\n return frame;\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (disposed) return;\n void proxy.input(instanceId, event).catch((cause: unknown) => {\n // The guest reports author callback failures itself as `view2d/input-failed`; a rejection here\n // means the call never reached the presentation, so it is reported once per instance.\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n });\n }\n\n /**\n * Reports a framework failure of one instance once per distinct message.\n *\n * A dead guest fails every queued pointer event and every scheduled frame; without the dedupe the\n * same cause would flood the diagnostic sink.\n */\n function reportOnce(instanceId: string, code: string, message: string): void {\n const key = `${instanceId}\\u0000${code}\\u0000${message}`;\n if (reported.has(key)) return;\n reported.add(key);\n options.onDiagnostic?.({ code, message, instanceId });\n }\n\n function invalidate(instanceId?: string): void {\n if (disposed) return;\n if (instanceId !== undefined) {\n schedule(instanceId);\n return;\n }\n for (const instance of prepared) schedule(instance.instanceId);\n }\n\n function schedule(instanceId: string): void {\n if (!prepared.some((entry) => entry.instanceId === instanceId)) return;\n dirty.add(instanceId);\n if (pumping) return;\n pumping = true;\n void Promise.resolve().then(pump);\n }\n\n async function pump(): Promise<void> {\n while (!disposed) {\n const batch = [...dirty];\n if (batch.length === 0) {\n pumping = false;\n return;\n }\n dirty.clear();\n for (const instanceId of batch) {\n try {\n await render(instanceId);\n } catch (cause) {\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n }\n }\n }\n pumping = false;\n }\n\n function defaultLayout(instance: IFusedInstancePresentation): IFusedDisplayLayout {\n const measured = options.measure?.(instance);\n if (measured !== undefined) return measured;\n const bounds = instance.geometry.bounds;\n return {\n width: Math.max(1, Math.round(bounds.width)),\n height: Math.max(1, Math.round(bounds.height)),\n scale: 1,\n };\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n disposed = true;\n disposal = (async () => {\n const problems: unknown[] = [];\n try {\n stopInvalidate();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => proxy.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n invalidations.dispose();\n dirty.clear();\n prepared = [];\n mode = undefined;\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused presentation failed to release its guests.');\n }\n })();\n return disposal;\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap !== undefined && isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * Local fan-out of model events (RFC 0021).\n *\n * The host and the display guest both expose `Event<ModelEvent<T>>` outlets whose subscriptions are\n * lazy: the first listener of one instance and event subscribes on the wire, the last one\n * unsubscribes, and a released instance drops every local listener.\n */\nimport { Emitter, toDisposable } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\n\n/** Wire subscriptions the router needs from its owner. */\nexport interface IFusedModelEventChannel {\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n}\n\nexport interface IFusedModelEventRouter {\n /** Declared event outlet of one instance; only listeners create a wire subscription. */\n event(instanceId: string, event: string): Event<ModelEvent<Value>>;\n /** Delivers one event to the listeners active at this moment. */\n deliver(instanceId: string, event: string, payload: ModelEvent<Value>): void;\n /** Drops every listener of one instance. */\n release(instanceId: string): void;\n dispose(): void;\n /** Number of live wire subscriptions; used to keep the wire silent without listeners. */\n readonly activeSubscriptions: number;\n}\n\nexport function channelKey(instanceId: string, event: string): string {\n return `${instanceId}\\u0000${event}`;\n}\n\nexport function createModelEventRouter(channel: IFusedModelEventChannel): IFusedModelEventRouter {\n const entries = new Map<string, { emitter: Emitter<ModelEvent<Value>>; listeners: number }>();\n\n const event = (instanceId: string, name: string): Event<ModelEvent<Value>> => {\n const key = channelKey(instanceId, name);\n return (listener) => {\n let entry = entries.get(key);\n if (entry === undefined) {\n entry = { emitter: new Emitter<ModelEvent<Value>>(), listeners: 0 };\n entries.set(key, entry);\n }\n const current = entry;\n current.listeners += 1;\n if (current.listeners === 1) channel.subscribe(instanceId, name);\n const subscription = current.emitter.event(listener);\n return toDisposable(() => {\n subscription.dispose();\n current.listeners -= 1;\n if (current.listeners > 0) return;\n entries.delete(key);\n current.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n });\n };\n };\n\n const drop = (key: string, instanceId: string, name: string): void => {\n const entry = entries.get(key);\n if (entry === undefined) return;\n entries.delete(key);\n entry.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n };\n\n return {\n event,\n deliver(instanceId, name, payload) {\n entries.get(channelKey(instanceId, name))?.emitter.fire(payload);\n },\n release(instanceId) {\n const prefix = `${instanceId}\\u0000`;\n for (const key of [...entries.keys()]) {\n if (!key.startsWith(prefix)) continue;\n drop(key, instanceId, key.slice(prefix.length));\n }\n },\n dispose() {\n for (const key of [...entries.keys()]) {\n const separator = key.indexOf('\\u0000');\n drop(key, key.slice(0, separator), key.slice(separator + 1));\n }\n },\n get activeSubscriptions() {\n return entries.size;\n },\n };\n}\n","/**\n * Host-side model clients of the fused runtime (RFC 0021).\n *\n * The editor calls a model through the simulation worker, never in its own thread. Event outlets are\n * lazy: one wire listener serves every local subscription and is released with the last of them.\n */\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport type { IFusedModelEventRouter } from '../model-events';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedSimulationService,\n} from '../protocol';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\n/** Model clients of one runtime, keyed by the instance they belong to. */\nexport interface IFusedHostModelRouter {\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n release(instanceId: string): void;\n dispose(): void;\n}\n\nexport function createHostModelRouter(\n proxy: RpcProxy<IFusedSimulationService>,\n): IFusedHostModelRouter {\n let router: IFusedModelEventRouter | undefined;\n let subscriptions = 0;\n let stop: (() => void) | undefined;\n router = createModelEventRouter({\n subscribe() {\n subscriptions += 1;\n if (subscriptions > 1 || stop !== undefined) return;\n stop = proxy.onDidModelEvent((event) => {\n router?.deliver(event.instanceId, event.event, event.payload);\n });\n },\n unsubscribe() {\n subscriptions = Math.max(0, subscriptions - 1);\n if (subscriptions > 0) return;\n stop?.();\n stop = undefined;\n },\n });\n\n const active = (): IFusedModelEventRouter => {\n if (router === undefined) {\n throw new Error('The fused model router is disposed.');\n }\n return router;\n };\n\n const invoke = (instanceId: string, method: string, params: Value): Promise<Value> => {\n if (router === undefined) {\n return Promise.reject(\n new FusedBridgeError(\n 'model/disconnected',\n 'The model client is disconnected from any live model.',\n { instanceId },\n ),\n );\n }\n return mapWireFailure(() => proxy.call(instanceId, method, params));\n };\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) => invoke(instance.instanceId, name, params);\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = active().event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router?.release(instanceId);\n },\n dispose() {\n stop?.();\n stop = undefined;\n router?.dispose();\n router = undefined;\n },\n };\n}\n","/**\n * Fused editor runtime bridge of one workbench (RFC 0025).\n *\n * One simulation worker runs the document, the packages and the models; one presentation worker runs\n * the declared 2D view modules. The editor schedules both and never imports model or author code.\n *\n * Every asynchronous transition is numbered: a preparation, reset or disposal that was superseded\n * never applies its result, and a frame produced for a replaced presentation is closed, not shown.\n */\nimport { timePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedOverlayFrame,\n IFusedSessionState,\n} from '../protocol';\nimport { connectFusedWorkbench } from './connection';\nimport { createFusedDisplay } from './display';\nimport { createHostModelRouter } from './model';\nimport type { IFusedDisplayPrepareInput, IFusedRuntime, IFusedRuntimeOptions } from './types';\nimport type { IFusedWorkerFactories } from './types';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\n\n/** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */\nexport async function createFusedRuntime(options: IFusedRuntimeOptions): Promise<IFusedRuntime> {\n const workers: IFusedWorkerFactories =\n options.workers ?? (await import('../workers')).fusedWorkerFactories;\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const overlays = new Emitter<IFusedOverlayFrame>();\n const states = new Emitter<IFusedSessionState>();\n const report = (entry: RuntimeDiagnostic): void => {\n diagnostics.fire(entry);\n options.onDiagnostic?.(entry);\n };\n const connection = await connectFusedWorkbench({\n workers,\n registry: options.registry,\n ...(options.audio === undefined ? {} : { audio: options.audio }),\n ...(options.container === undefined ? {} : { container: options.container }),\n ...(options.resolveResource === undefined ? {} : { resolveResource: options.resolveResource }),\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n onDiagnostic: report,\n });\n const models = createHostModelRouter(connection.simulation);\n const displayHost = createFusedDisplay({\n proxy: connection.display,\n onDiagnostic: report,\n onOverlay: (frame) => {\n overlays.fire(frame);\n options.onOverlay?.(frame);\n },\n ...(options.measure === undefined ? {} : { measure: options.measure }),\n });\n\n let state: IFusedSessionState = IDLE;\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: 'edit' | 'run' | undefined;\n let preparation = 0;\n let closed = false;\n let disposal: Promise<void> | undefined;\n const clients = new Map<string, IFusedModelClient>();\n\n const stopState = connection.simulation.onDidChangeState((next) => setState(next));\n\n const runtime: IFusedRuntime = {\n audio: connection.audio,\n getState: () => state,\n onDidChangeState: states.event,\n onDidReportDiagnostic: diagnostics.event,\n onDidRenderOverlay: overlays.event,\n getModel,\n display: displayHost.display,\n prepareDisplay,\n resume,\n pause,\n step,\n reset,\n dispose,\n };\n try {\n await prepareDisplay({ mode: options.mode ?? 'edit' });\n } catch (cause) {\n await dispose().catch(() => undefined);\n throw cause;\n }\n return runtime;\n\n function setState(next: IFusedSessionState): void {\n if (next.status === 'running') connection.audio.resume();\n else connection.audio.suspend();\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closed) {\n throw new FusedBridgeError('runtime/unavailable-state', 'The fused runtime is disposed.');\n }\n }\n\n function assertRun(operation: string): void {\n assertOpen();\n if (mode !== 'run') {\n throw new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires a run session; prepare the run mode first.`,\n );\n }\n }\n\n function getModel(instanceId: string): IFusedModelClient {\n if (closed || mode !== 'run') {\n throw new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted: the fused runtime is not in run mode.',\n { instanceId },\n );\n }\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-instance',\n `No live model for instance \"${instanceId}\".`,\n { instanceId },\n );\n }\n let client = clients.get(instanceId);\n if (client === undefined) {\n client = models.client(instance);\n clients.set(instanceId, client);\n }\n return client;\n }\n\n async function prepareDisplay(\n input: IFusedDisplayPrepareInput,\n ): Promise<readonly IFusedInstancePresentation[]> {\n assertOpen();\n const attempt = ++preparation;\n connection.audio.suspend();\n connection.audio.clear();\n const current = (): boolean => !closed && attempt === preparation;\n const described = await mapWireFailure(() =>\n connection.simulation.prepare({ document: options.document, mode: input.mode }),\n );\n if (!current()) return prepared;\n if (input.mode === 'edit') {\n // Edit mode mounts presentation only: the models are released before any view is created.\n await mapWireFailure(() => connection.simulation.dispose());\n if (!current()) return prepared;\n }\n // Factories run before the models exist, so their subscriptions observe the initial events.\n await displayHost.prepare({ mode: input.mode }, described.instances);\n if (!current()) return prepared;\n if (input.mode === 'run') {\n try {\n const loaded = await mapWireFailure(() =>\n connection.simulation.load({\n document: options.document,\n step: options.step,\n ...(options.batchExecution === undefined\n ? {}\n : { batchExecution: options.batchExecution }),\n }),\n );\n if (!current()) return prepared;\n setState(loaded);\n } catch (cause) {\n // The factories of a session that never mounted must not keep drawing a dead model lane.\n await displayHost.prepare({ mode: input.mode }, []).catch(() => undefined);\n throw cause;\n }\n }\n prepared = described.instances;\n mode = input.mode;\n clients.clear();\n // `initialize` runs after the models mounted and delivered their initial events.\n await displayHost.activate();\n if (!current()) return prepared;\n // Static views need an initial frame even when they never invalidate themselves.\n displayHost.display.invalidate();\n if (input.mode === 'run') {\n // A run session starts advancing once every presentation subscribed to its model.\n await mapWireFailure(() => connection.simulation.resume());\n }\n return prepared;\n }\n\n async function resume(): Promise<void> {\n assertRun('resume');\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n async function pause(): Promise<void> {\n if (closed || mode !== 'run') return;\n await mapWireFailure(() => connection.simulation.pause());\n }\n\n async function step(): Promise<void> {\n assertRun('step');\n const next = await mapWireFailure(() => connection.simulation.step());\n setState(next);\n }\n\n async function reset(): Promise<void> {\n assertRun('reset');\n connection.audio.suspend();\n connection.audio.clear();\n const attempt = ++preparation;\n const current = (): boolean => !closed && attempt === preparation;\n const instances = prepared;\n // The rebuilt presentation subscribes first; the replacement models then deliver initial events.\n await displayHost.prepare({ mode: 'run' }, instances);\n if (!current()) return;\n clients.clear();\n await mapWireFailure(() => connection.simulation.reset());\n if (!current()) return;\n await displayHost.activate();\n if (!current()) return;\n displayHost.display.invalidate();\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closed = true;\n connection.audio.dispose();\n disposal = (async () => {\n const problems: unknown[] = [];\n // Presentation first: input stops and views release before the models go away.\n try {\n await displayHost.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => connection.simulation.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n try {\n stopState();\n } catch (cause) {\n problems.push(cause);\n }\n models.dispose();\n try {\n await connection.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n states.dispose();\n diagnostics.dispose();\n overlays.dispose();\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused runtime failed to release every resource.');\n }\n })();\n return disposal;\n }\n}\n","/** Small shared helpers of the fused sandbox bridge. */\nimport type { DevicePropertyDescriptor } from '@mica-js/document/fused';\nimport { createProgramFiles, readonlyBytes } from '@mica-js/sdk/fused';\nimport type {\n FusedPresentationProps,\n FusedPresentationValue,\n FusedResolvedPresentationProps,\n IFusedFirmwareSegment,\n IFusedFirmwareSnapshot,\n} from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/**\n * Resolved property snapshot handed to one presentation.\n *\n * Every declared property must appear in `resolved` (the simulation worker resolves the manifest\n * defaults and document overrides through the SDK, exactly like the model snapshot does). Byte and\n * firmware values are copied into independent arrays, because the snapshot crosses an RPC boundary\n * and is transferred to the presentation worker afterwards.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming the property and its declared\n * type whenever a value cannot be projected. A presentation never receives a partial snapshot.\n */\nexport function presentationProps(\n resolved: Readonly<Record<string, unknown>>,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): FusedPresentationProps {\n const props: Record<string, FusedPresentationValue> = {};\n for (const [name, descriptor] of Object.entries(descriptors)) {\n if (!Object.hasOwn(resolved, name)) {\n throw unpresentable(name, descriptor.type, 'has no resolved value');\n }\n const value = resolved[name];\n if (value === undefined) {\n throw unpresentable(name, descriptor.type, 'resolved to undefined');\n }\n switch (descriptor.type) {\n case 'string':\n case 'color':\n case 'enum':\n if (typeof value === 'string') {\n props[name] = value;\n continue;\n }\n break;\n case 'integer':\n case 'number':\n if (typeof value === 'number') {\n props[name] = value;\n continue;\n }\n break;\n case 'boolean':\n if (typeof value === 'boolean') {\n props[name] = value;\n continue;\n }\n break;\n case 'image':\n case 'binary':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = copyBytes(name, descriptor.type, value);\n continue;\n case 'firmware':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = firmwareSnapshot(name, value);\n continue;\n case 'program':\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n if (descriptor.loader === 'memory') props[name] = firmwareSnapshot(name, value);\n else {\n const files = value as { readonly paths?: unknown; readonly read?: unknown };\n if (!files || !Array.isArray(files.paths) || typeof files.read !== 'function')\n throw unpresentable(name, 'program', 'is not a file snapshot');\n props[name] = Object.freeze({\n kind: 'filesystem',\n files: Object.freeze(\n files.paths.map((path: string) =>\n Object.freeze({\n path,\n data: copyBytes(name, 'program', (files.read as (path: string) => unknown)(path)),\n }),\n ),\n ),\n });\n }\n continue;\n default:\n break;\n }\n\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n throw unpresentable(name, descriptor.type, `resolved to ${describeValue(value)}`);\n }\n return Object.freeze(props);\n}\n\nexport function reconstructPresentationProps(\n props: FusedPresentationProps,\n): FusedResolvedPresentationProps {\n return Object.freeze(\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => {\n if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array)) {\n if (value.kind === 'filesystem') return [name, createProgramFiles(value.files)];\n return [\n name,\n Object.freeze({\n segments: Object.freeze(\n value.segments.map((segment) =>\n Object.freeze({\n addressSpace: segment.addressSpace,\n address: segment.address,\n data: readonlyBytes(segment.bytes),\n }),\n ),\n ),\n }),\n ];\n }\n return [name, value];\n }),\n ),\n );\n}\n\n/** Copies one read-only byte snapshot; the SDK hands `ReadonlyBytes`, not raw arrays. */\nfunction copyBytes(name: string, type: string, value: unknown): Uint8Array {\n if (value instanceof Uint8Array) return value.slice();\n const candidate = value as { readonly slice?: unknown } | null;\n if (\n candidate !== null &&\n typeof candidate === 'object' &&\n typeof candidate.slice === 'function'\n ) {\n const copy = (candidate.slice as () => unknown).call(candidate);\n if (copy instanceof Uint8Array) return copy;\n }\n throw unpresentable(name, type, 'is not a byte snapshot');\n}\n\n/** Projects one loaded firmware image (RFC 0026) into a transferable snapshot. */\nfunction firmwareSnapshot(name: string, value: unknown): IFusedFirmwareSnapshot {\n const segments = (value as { readonly segments?: unknown } | null)?.segments;\n if (!Array.isArray(segments)) {\n throw unpresentable(name, 'firmware', 'is not a firmware image');\n }\n const projected: IFusedFirmwareSegment[] = [];\n for (const segment of segments) {\n const candidate = segment as {\n readonly addressSpace?: unknown;\n readonly address?: unknown;\n readonly data?: unknown;\n };\n if (typeof candidate.addressSpace !== 'string' || typeof candidate.address !== 'number') {\n throw unpresentable(name, 'firmware', 'has a segment without an address space or address');\n }\n projected.push({\n addressSpace: candidate.addressSpace,\n address: candidate.address,\n bytes: copyBytes(name, 'firmware', candidate.data),\n });\n }\n return Object.freeze({ kind: 'firmware', segments: Object.freeze(projected) });\n}\n\nfunction unpresentable(name: string, type: string, reason: string): FusedBridgeError {\n return new FusedBridgeError(\n 'runtime/presentation-failed',\n `Property \"${name}\" (${type}) ${reason}; the presentation cannot receive a partial snapshot.`,\n );\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n return `a value of type ${typeof value}`;\n}\n\n/** Whether a callback returned a promise instead of finishing synchronously. */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Evaluates one verified package module inside the guest.\n *\n * The bytes were verified against the package lock before this runs; a blob URL keeps the module\n * out of the host document and is revoked as soon as the namespace settles.\n */\nexport function importCode(code: string): Promise<unknown> {\n const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));\n return import(/* @vite-ignore */ url).finally(() => URL.revokeObjectURL(url));\n}\n\n/** Copies bytes into a plain `ArrayBuffer`, as `Blob` and transfer lists require. */\nexport function byteBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer;\n}\n\n/** Decodes package bytes as UTF-8 module source, tolerating a leading byte order mark. */\nexport function decodeSource(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes).replace(/^\\uFEFF/, '');\n}\n","/**\n * Model lane between the simulation guest and the display guest (RFC 0025).\n *\n * The host transfers one end of a `MessageChannel` to each guest, so a display input handler calls\n * its model directly instead of asking the editor to relay the call. The simulation guest serves\n * {@link fusedModelChannelService} and pushes events to the display sink only while the display is\n * subscribed to that instance and event.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport { channelKey } from '../model-events';\nimport type { IFusedModelEventWire } from '../protocol';\n\n/** Guest-side capabilities the display lane reaches through this port. */\nexport interface IFusedModelChannelHandlers {\n /** Invokes one declared model method; failures are already encoded for the wire. */\n readonly call: (instanceId: string, method: string, params: Value) => Promise<Value>;\n}\n\nexport interface IFusedSimulationModelChannel {\n /** Delivers one model event to the display guest when it subscribed to it. */\n deliver(event: IFusedModelEventWire): void;\n /** Drops every display subscription, e.g. when the session was replaced. */\n reset(): void;\n dispose(): void;\n}\n\n/** Starts the simulation end of the model lane over `port`. */\nexport function startSimulationModelChannel(\n port: MessagePort,\n handlers: IFusedModelChannelHandlers,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedSimulationModelChannel {\n const endpoint = createEndpoint(port);\n const sink = endpoint.getProxy(fusedModelSinkService);\n const subscriptions = new Set<string>();\n endpoint.register(fusedModelChannelService, {\n call: handlers.call,\n subscribe(instanceId, event) {\n subscriptions.add(channelKey(instanceId, event));\n },\n unsubscribe(instanceId, event) {\n subscriptions.delete(channelKey(instanceId, event));\n },\n settle: () => undefined,\n });\n return {\n deliver(event) {\n if (!subscriptions.has(channelKey(event.instanceId, event.event))) return;\n void sink.deliver(event).catch(() => undefined);\n },\n reset() {\n subscriptions.clear();\n },\n dispose() {\n subscriptions.clear();\n endpoint.dispose();\n },\n };\n}\n","/**\n * Simulation guest of the fused editor runtime (RFC 0025).\n *\n * The guest owns the production headless runtime: the document snapshot, the verified package bytes,\n * the models and the electrical solve. The editor keeps no model code on its own thread; it reaches\n * this guest through typed RPC and receives model events, state changes and diagnostics as events.\n *\n * Package bytes, host resources and firmware artifacts are pulled from host services registered on\n * the same RPC endpoint, so verification, preparation and model execution all happen here.\n */\nimport { timePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Disposable } from '@mica-js/core/lifecycle';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport { parseFusedDocument, parseGeometry2D, parseStrictJson } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n DevicePropertyDescriptor,\n FusedDocument,\n FusedInstance,\n PackageFiles,\n Value,\n} from '@mica-js/document/fused';\nimport {\n createHeadlessRuntime,\n FusedPreparationError,\n openDevicePackage,\n PreparationError,\n resolveInstanceProperties,\n} from '@mica-js/sdk/fused';\nimport type {\n ProgramSources,\n ProgramArtifact,\n ProgramFile,\n HeadlessRuntime,\n ResourceResolver,\n RuntimeDiagnostic,\n RuntimeModelEvent,\n VerifiedPackage,\n} from '@mica-js/sdk/fused';\nimport { fusedHostResourceService, fusedSimulationService } from '../protocol';\nimport type {\n IFusedInstancePresentation,\n IFusedLoadRequest,\n IFusedModelEventWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedSessionState,\n} from '../protocol';\nimport { decodeSource, importCode, presentationProps } from '../values';\nimport { FusedBridgeError, messageOf, toWireFailure, transferPresentationBytes } from '../wire';\nimport { createHostPackageGateway } from '../packages';\nimport { startSimulationModelChannel } from './model-channel';\nimport type { IFusedSimulationModelChannel } from './model-channel';\n\n/** Replaceable guest dependencies, so the runtime can be exercised outside a browser worker. */\nexport interface IFusedSimulationGuestOptions {\n /** Creates the endpoint over the startup port; tests inject a fake. */\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /**\n * Startup ports after the RPC port. The first one is the model lane (RFC 0025), the display guest\n * holds the other end of the same channel.\n */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified package module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n}\n\n/** Guest runtime plus the RPC endpoint that serves it. */\nexport interface IFusedSimulationGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\n\ninterface Session {\n readonly runtime: HeadlessRuntime;\n readonly subscriptions: Disposable[];\n}\n\n/** Starts the simulation guest on the startup port of a sandbox worker. */\nexport function startFusedSimulationGuest(\n port: MessagePort,\n options: IFusedSimulationGuestOptions = {},\n): IFusedSimulationGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const packages = createHostPackageGateway(endpoint);\n const resources = createResourceGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const states = new Emitter<IFusedSessionState>();\n const events = new Emitter<IFusedModelEventWire>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedSimulationModelChannel | undefined =\n modelPort === undefined\n ? undefined\n : startSimulationModelChannel(modelPort, {\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n });\n\n let state: IFusedSessionState = IDLE;\n let session: Session | undefined;\n /** Identity of the live session, so events of a discarded candidate never reach a listener. */\n let sessionToken: object | undefined;\n /** Incremented by every session transition, so late results of a replaced session are dropped. */\n let sequence = 0;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n endpoint.register(\n fusedSimulationService,\n {\n prepare,\n load,\n step,\n resume,\n pause,\n reset,\n dispose: releaseModels,\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n getState: () => state,\n onDidChangeState(listener) {\n const subscription = states.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidModelEvent(listener) {\n const subscription = events.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n // Presentation byte and firmware snapshots are handed over, never cloned.\n { transfer: transferPresentationBytes },\n );\n\n return {\n rpc: endpoint,\n dispose,\n };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function setState(next: IFusedSessionState): void {\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n 'The fused simulation guest is disposed.',\n ),\n );\n }\n }\n\n function requireSession(operation: string): Session {\n assertOpen();\n if (session === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires mounted models; prepare a run session first.`,\n ),\n );\n }\n return session;\n }\n\n async function prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult> {\n assertOpen();\n const document = parseFusedDocument(request.document);\n const problems: RuntimeDiagnostic[] = [];\n const instances: IFusedInstancePresentation[] = [];\n for (const [index, instance] of document.instances.entries()) {\n try {\n const described = await describeInstance(index, document, instance);\n if (described !== undefined) instances.push(described);\n } catch (cause) {\n // A presentation-only failure drops the view of that instance; the models of a run session\n // and every other presentation keep going (RFC 0025 `runtime/presentation-failed`).\n if (cause instanceof FusedBridgeError && cause.code === 'runtime/presentation-failed') {\n report({ code: cause.code, message: cause.message, instanceId: instance.id });\n continue;\n }\n problems.push({\n code: 'runtime/prepare-failed',\n message: `${instance.id}: ${messageOf(cause)}`,\n instanceId: instance.id,\n });\n }\n }\n for (const problem of problems) report(problem);\n if (problems.length > 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/prepare-failed',\n `${problems.length} instance(s) cannot join the 2D scene.`,\n ),\n );\n }\n return { instances };\n }\n\n async function describeInstance(\n index: number,\n document: FusedDocument,\n instance: FusedInstance,\n ): Promise<IFusedInstancePresentation | undefined> {\n const dependency = document.dependencies[instance.device];\n if (dependency === undefined) {\n throw new FusedBridgeError(\n 'document/unlocked-device',\n `Instance \"${instance.id}\" uses the unlocked device \"${instance.device}\".`,\n { instanceId: instance.id },\n );\n }\n const lock: DeviceLock = {\n id: instance.device,\n version: dependency.version,\n integrity: dependency.integrity,\n };\n const verified = await openDevicePackage(packages, lock);\n const view = verified.manifest.view2d;\n if (view === undefined) {\n report({\n code: 'view2d/unsupported',\n message: `${instance.device} declares no 2D geometry; \"${instance.id}\" stays out of the 2D scene.`,\n instanceId: instance.id,\n });\n return undefined;\n }\n const pins = Object.keys(verified.manifest.pins ?? {});\n const geometryValue =\n typeof view.geometry === 'string'\n ? parseStrictJson(decodeSource(await verified.read(view.geometry)))\n : view.geometry;\n const descriptors = verified.manifest.properties ?? {};\n return {\n instanceId: instance.id,\n device: instance.device,\n lock,\n geometry: parseGeometry2D(geometryValue, pins),\n view: view.entry,\n props: presentationProps(\n await resolvePresentationProps(verified, descriptors, instance, index),\n descriptors,\n ),\n methods: Object.keys(verified.manifest.model?.methods ?? {}),\n events: Object.keys(verified.manifest.model?.events ?? {}),\n };\n }\n\n /**\n * Resolves the declared properties a presentation reads through the SDK, so the projection is the\n * same snapshot the model receives: manifest defaults, document overrides, package and host\n * resources, and a loaded firmware image.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.\n */\n async function resolvePresentationProps(\n verified: VerifiedPackage,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n instance: FusedInstance,\n index: number,\n ): Promise<Readonly<Record<string, unknown>>> {\n try {\n const resolution = await resolveInstanceProperties({\n instanceId: instance.id,\n package: verified,\n descriptors,\n overrides: instance.properties ?? {},\n // The model IR adds nothing to `props`: an empty map keeps this resolution identical to the\n // one the runtime performs while it builds the board, so edit mode needs no model module.\n irProperties: new Map<string, never>(),\n pointer: ['instances', String(index), 'properties'],\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n });\n return resolution.props;\n } catch (cause) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `Presentation properties of \"${instance.id}\" cannot be resolved: ${describeProblems(\n cause,\n descriptors,\n )}`,\n { instanceId: instance.id },\n );\n }\n }\n\n async function load(request: IFusedLoadRequest): Promise<IFusedSessionState> {\n assertOpen();\n const step = request.step;\n if (!Number.isSafeInteger(step) || step <= 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/invalid-time',\n `\\`step\\` must be a positive integer number of picoseconds, received ${String(step)}.`,\n ),\n );\n }\n const document = parseFusedDocument(request.document);\n const attempt = ++sequence;\n const token = {};\n const superseded = (): boolean => closing || attempt !== sequence;\n /** Events of the factory phase are queued and delivered once the session is adopted. */\n const pending: RuntimeModelEvent[] = [];\n let created: HeadlessRuntime;\n try {\n created = await createHeadlessRuntime({\n document,\n registry: packages,\n loadModule,\n step,\n ...(request.batchExecution === undefined ? {} : { batchExecution: request.batchExecution }),\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n onModelEvent: (event) => {\n if (sessionToken === token) publishModelEvent(event);\n else if (!superseded()) pending.push(event);\n },\n onDiagnostic: (entry) => {\n if (!superseded()) report(entry);\n },\n });\n } catch (cause) {\n if (cause instanceof FusedPreparationError) {\n for (const entry of cause.diagnostics) report(entry);\n }\n throw toWireFailure(cause);\n }\n if (superseded()) {\n await created.dispose().catch(() => undefined);\n return state;\n }\n const previous = session;\n session = undefined;\n sessionToken = undefined;\n if (previous !== undefined) {\n // The candidate session exists before the running one is released, so a failed load keeps it.\n await releaseSession(previous, false);\n }\n // The model lane keeps the display subscriptions of the presentation prepared before this load.\n sessionToken = token;\n session = {\n runtime: created,\n subscriptions: [\n created.onDidChangeState((next) => {\n if (sessionToken === token) setState({ status: next.status, simTime: next.simTime });\n }),\n created.onDidReportDiagnostic((entry) => {\n if (sessionToken === token) report(entry);\n }),\n ],\n };\n for (const event of pending.splice(0)) publishModelEvent(event);\n const initial = created.getState();\n setState({ status: initial.status, simTime: initial.simTime });\n return state;\n }\n\n async function step(): Promise<IFusedSessionState> {\n const target = requireSession('step');\n await mapGuestCall(() => target.runtime.step());\n return state;\n }\n\n async function resume(): Promise<void> {\n const target = requireSession('resume');\n await mapGuestCall(() => target.runtime.resume());\n }\n\n function pause(): void {\n session?.runtime.pause();\n }\n\n async function reset(): Promise<void> {\n const target = requireSession('reset');\n await mapGuestCall(() => target.runtime.reset());\n }\n\n async function callModel(instanceId: string, method: string, params: Value): Promise<Value> {\n const target = session;\n if (closing || target === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted; prepare a run session first.',\n {\n instanceId,\n },\n ),\n );\n }\n try {\n const client = target.runtime.getModel(instanceId);\n const invoke = client.methods[method];\n if (invoke === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-method',\n `The model of \"${instanceId}\" declares no method \"${method}\".`,\n { instanceId },\n );\n }\n return await invoke(params);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n }\n\n async function releaseModels(): Promise<void> {\n assertOpen();\n await releaseCurrent(true);\n }\n\n async function releaseCurrent(strict: boolean): Promise<void> {\n const target = session;\n session = undefined;\n sessionToken = undefined;\n sequence += 1;\n modelChannel?.reset();\n setState(IDLE);\n if (target !== undefined) await releaseSession(target, strict);\n }\n\n async function releaseSession(target: Session, strict: boolean): Promise<void> {\n for (const subscription of target.subscriptions.splice(0)) subscription.dispose();\n try {\n await target.runtime.dispose();\n } catch (cause) {\n report({\n code: 'runtime/model-failed',\n message: `Releasing the models failed: ${messageOf(cause)}`,\n });\n if (strict) throw toWireFailure(cause);\n }\n }\n\n function publishModelEvent(event: RuntimeModelEvent): void {\n const wire: IFusedModelEventWire = {\n instanceId: event.instanceId,\n event: event.event,\n payload: event.payload,\n };\n modelChannel?.deliver(wire);\n events.fire(wire);\n }\n\n async function loadModule(files: PackageFiles, path: string) {\n return importModule(decodeSource(await files.read(path)));\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n modelChannel?.dispose();\n const target = session;\n session = undefined;\n sessionToken = undefined;\n const problems: unknown[] = [];\n if (target !== undefined) {\n try {\n await releaseSession(target, true);\n } catch (cause) {\n problems.push(cause);\n }\n }\n endpoint.dispose();\n diagnostics.dispose();\n states.dispose();\n events.dispose();\n if (problems.length > 0) throw problems[0];\n })();\n return disposal;\n }\n}\n\n/** One guest call whose rejection is rebuilt on the host. */\nasync function mapGuestCall<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (cause) {\n throw toWireFailure(cause);\n }\n}\n\n/** Host resources the runtime pulls while it resolves instance properties. */\nfunction createResourceGateway(endpoint: RpcEndpoint): {\n readonly resolveResource: ResourceResolver;\n readonly programs: ProgramSources;\n} {\n const host = endpoint.getProxy(fusedHostResourceService);\n // The presentation snapshot and the model snapshot resolve the same properties; the cache keeps\n // one host round trip per resource and one artifact fetch per project, and hands out copies.\n const resources = new Map<string, Uint8Array>();\n const programs = new Map<string, ProgramArtifact>();\n const copyFiles = (files: readonly ProgramFile[]) =>\n files.map((file) => ({ path: file.path, data: file.data.slice() }));\n const copyArtifact = (artifact: ProgramArtifact): ProgramArtifact =>\n artifact.kind === 'memory'\n ? { ...artifact, data: artifact.data.slice() }\n : { kind: 'filesystem', files: copyFiles(artifact.files) };\n return {\n programs: {\n projects: {\n resolve: async (id, target) => {\n const key = JSON.stringify([target.deviceId, target.property, target.loader, id]);\n let artifact = programs.get(key);\n if (!artifact) {\n artifact = await host.resolveProgramProject(id, target);\n programs.set(key, copyArtifact(artifact));\n }\n return copyArtifact(artifact);\n },\n },\n },\n resolveResource: async (request) => {\n const key = `${request.instanceId}\\u0000${request.property}`;\n const cached = resources.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.readResource(request);\n resources.set(key, bytes.slice());\n return bytes;\n },\n };\n}\n\n/** Flattens preparation problems, naming the property and its declared type. */\nfunction describeProblems(\n cause: unknown,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string {\n if (cause instanceof PreparationError) {\n return cause.problems\n .map((problem) => {\n const property = propertyOfPointer(problem.pointer, descriptors);\n const where = problem.pointer === '' ? '' : ` at ${problem.pointer}`;\n return `${problem.code}${where}${property === undefined ? '' : ` (${property})`}: ${problem.message}`;\n })\n .join('; ');\n }\n return messageOf(cause);\n}\n\n/** Names one property and its declared type from a JSON Pointer into the instance properties. */\nfunction propertyOfPointer(\n pointer: string,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string | undefined {\n const segments = pointer.split('/');\n const at = segments.indexOf('properties');\n const name = at < 0 ? undefined : segments[at + 1];\n if (name === undefined) return undefined;\n const type = descriptors[name]?.type;\n return type === undefined ? `property \"${name}\"` : `property \"${name}\", type ${type}`;\n}\n","import type { Event } from '@mica-js/core/lifecycle';\nimport type {\n WidgetAudioApi,\n WidgetAudioStream,\n WidgetAudioState,\n WidgetAudioStreamStatus,\n} from '@mica-js/widget/audio-guest';\n\nexport type {\n WidgetAudioOptions as IFusedAudioOptions,\n WidgetAudioControls as IFusedAudioControls,\n} from '@mica-js/widget/audio-host';\nexport type {\n WidgetAudioState as FusedAudioState,\n WidgetAudioTone as IFusedAudioTone,\n WidgetAudioToneOptions as IFusedAudioToneOptions,\n WidgetAudioStreamOptions as IFusedAudioStreamOptions,\n} from '@mica-js/widget/audio-guest';\n\nexport interface IFusedAudioStream extends Omit<WidgetAudioStream, 'onDrain' | 'onStatus'> {\n readonly onDidDrain: Event<void>;\n readonly onDidChangeStatus: Event<WidgetAudioStreamStatus>;\n}\n\n/** Audio handles belong to one instance generation, including while its body is hidden. */\nexport interface IFusedAudio extends Omit<WidgetAudioApi, 'onStateChange' | 'createStream'> {\n readonly onDidChangeState: Event<WidgetAudioState>;\n createStream(options: Parameters<WidgetAudioApi['createStream']>[0]): IFusedAudioStream;\n}\n\n/** Adapt the shared audio implementation's subscriptions to the editor lifecycle convention. */\nexport function fusedAudio(api: WidgetAudioApi): IFusedAudio {\n return {\n get state() {\n return api.state;\n },\n onDidChangeState: (listener) => ({ dispose: api.onStateChange(listener) }),\n tone: (options) => api.tone(options),\n createStream(options) {\n const stream = api.createStream(options);\n return Object.assign(stream, {\n onDidDrain: ((listener) => ({ dispose: stream.onDrain(() => listener()) })) as Event<void>,\n onDidChangeStatus: ((listener) => ({\n dispose: stream.onStatus(listener),\n })) as Event<WidgetAudioStreamStatus>,\n });\n },\n };\n}\n","/**\n * Display-side model client of one instance (RFC 0021 / RFC 0022).\n *\n * The client talks to the simulation guest over the direct model lane: a presentation input handler\n * calls its model without a hop through the editor, and `invalidate()` remains the only repaint\n * trigger. Only the methods and events the manifest declares resolve.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedModelEventWire,\n} from '../protocol';\nimport { mapWireFailure } from '../wire';\n\n/** Model lane as the display guest sees it. */\nexport interface IFusedDisplayModelChannel {\n /** Model client of one prepared instance. */\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n /** Drops every listener of a released instance. */\n release(instanceId: string): void;\n /**\n * Resolves once subscriptions reach the simulation guest and prior model events reach this guest.\n *\n * Preparation awaits this before the models are mounted, so an event produced while a model\n * initializes is never lost to a subscription that is still in flight.\n */\n settle(): Promise<void>;\n dispose(): void;\n}\n\n/** Starts the display end of the model lane over `port`. */\nexport function startDisplayModelChannel(\n port: MessagePort,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedDisplayModelChannel {\n const endpoint = createEndpoint(port);\n const lane = endpoint.getProxy(fusedModelChannelService);\n /** Wire subscriptions still in flight, so preparation can wait for the model lane to catch up. */\n const inFlight = new Set<Promise<void>>();\n const router = createModelEventRouter({\n subscribe(instanceId, event) {\n const call = lane.subscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n unsubscribe(instanceId, event) {\n const call = lane.unsubscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n });\n endpoint.register(fusedModelSinkService, {\n deliver(event: IFusedModelEventWire) {\n if (!isModelEvent(event)) return;\n router.deliver(event.instanceId, event.event, event.payload);\n },\n });\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) =>\n mapWireFailure(() => lane.call(instance.instanceId, name, params));\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = router.event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router.release(instanceId);\n },\n async settle() {\n while (inFlight.size > 0) {\n await Promise.allSettled([...inFlight]);\n }\n await lane.settle();\n },\n dispose() {\n router.dispose();\n endpoint.dispose();\n },\n };\n}\n\nfunction isModelEvent(value: unknown): value is IFusedModelEventWire {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly instanceId?: unknown; readonly event?: unknown };\n return typeof candidate.instanceId === 'string' && typeof candidate.event === 'string';\n}\n","/**\n * One 2D presentation of the display guest (RFC 0022).\n *\n * A session evaluates one verified `view2d.entry` module, builds the factory context and owns the\n * overlay canvas. Drawing is synchronous and never drives the model: `renderOverlay` only reads the\n * data the model already produced, and `invalidate()` is the only way a presentation asks for a\n * repaint.\n */\nimport type { Geometry2D } from '@mica-js/document/fused';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio, type IFusedAudio } from '../audio';\nimport type {\n FusedDisplayMode,\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedRenderRequest,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from '../protocol';\nimport { byteBuffer, decodeSource, isThenable, reconstructPresentationProps } from '../values';\nimport { FusedBridgeError, messageOf } from '../wire';\n\n/** Canvas one overlay is painted into; injectable so the guest runs off-browser in tests. */\nexport interface IFusedOverlaySurface {\n readonly width: number;\n readonly height: number;\n getContext(type: '2d'): OffscreenCanvasRenderingContext2D | null;\n transferToImageBitmap(): ImageBitmap;\n}\n\nexport type FusedSurfaceFactory = (width: number, height: number) => IFusedOverlaySurface;\n\n/** Requests the display guest performs on behalf of one session. */\nexport interface IFusedViewSessionOptions {\n readonly instance: IFusedInstancePresentation;\n readonly mode: FusedDisplayMode;\n readonly model: IFusedModelClient | undefined;\n readonly audio?: IFusedAudio;\n readonly readAsset: (path: string) => Promise<Uint8Array>;\n readonly importModule: (code: string) => Promise<unknown>;\n readonly createSurface: FusedSurfaceFactory;\n readonly invalidate: () => void;\n readonly report: (code: string, message: string) => void;\n}\n\nexport interface IFusedViewSession {\n readonly instanceId: string;\n readonly geometry: Geometry2D;\n /** Runs the author `initialize` hook once; safe to call again. */\n activate(): Promise<void>;\n /** Paints one overlay frame; the caller owns the returned bitmap. */\n render(request: IFusedRenderRequest): ImageBitmap | undefined;\n input(event: IFusedViewInput): void;\n dispose(): void;\n}\n\n/**\n * Evaluates the presentation entry of one instance and initializes it.\n *\n * @throws {FusedBridgeError} when the module has no factory or `initialize` fails.\n */\nexport async function createViewSession(\n options: IFusedViewSessionOptions,\n): Promise<IFusedViewSession> {\n const { instance } = options;\n const entry = instance.view;\n if (entry === undefined) {\n throw new FusedBridgeError(\n 'view2d/unsupported',\n `${instance.device} declares no \\`view2d.entry\\`.`,\n { instanceId: instance.instanceId },\n );\n }\n const namespace = (await options.importModule(decodeSource(await options.readAsset(entry)))) as {\n readonly default?: unknown;\n } | null;\n const factory =\n namespace !== null && typeof namespace === 'object' ? namespace.default : undefined;\n if (typeof factory !== 'function') {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} must default-export a presentation factory.`,\n { instanceId: instance.instanceId },\n );\n }\n\n let disposed = false;\n const localAudio = options.audio === undefined ? createWidgetAudioRuntime({}) : undefined;\n let surface: IFusedOverlaySurface | undefined;\n const assets: IFusedViewAssets = {\n read: (path: string) => options.readAsset(path),\n loadImage: async (path: string) =>\n createImageBitmap(new Blob([byteBuffer(await options.readAsset(path))])),\n };\n const context: IFusedView2DContext = {\n mode: options.mode,\n props: reconstructPresentationProps(instance.props),\n geometry: instance.geometry,\n model: options.model,\n assets,\n audio: options.audio ?? fusedAudio(localAudio!.api(instance.instanceId)),\n invalidate: () => {\n if (!disposed) options.invalidate();\n },\n };\n const view = (factory as FusedView2DFactory)(context);\n if (typeof view !== 'object' || view === null) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} returned no presentation object.`,\n { instanceId: instance.instanceId },\n );\n }\n let activated = false;\n\n return {\n instanceId: instance.instanceId,\n geometry: instance.geometry,\n /**\n * Runs `initialize` once, after the models exist (RFC 0025 startup barrier). The factory itself\n * only registers listeners, so a presentation sees the initial model events before this runs.\n */\n async activate() {\n if (disposed || activated) return;\n activated = true;\n const initialized = view.initialize?.();\n if (isThenable(initialized)) await initialized;\n },\n render(request) {\n const draw = view.renderOverlay;\n if (disposed || draw === undefined) return undefined;\n const target = surfaceFor(request.width, request.height);\n const context2d = target.getContext('2d');\n if (context2d === null) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'The overlay canvas has no 2D context.',\n {\n instanceId: instance.instanceId,\n },\n );\n }\n context2d.save();\n try {\n context2d.setTransform(1, 0, 0, 1, 0, 0);\n context2d.clearRect(0, 0, request.width, request.height);\n const bounds = instance.geometry.bounds;\n context2d.setTransform(\n request.scale,\n 0,\n 0,\n request.scale,\n -bounds.x * request.scale,\n -bounds.y * request.scale,\n );\n const result = draw.call(view, context2d);\n if (isThenable(result)) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'renderOverlay must draw synchronously.',\n { instanceId: instance.instanceId },\n );\n }\n } finally {\n context2d.restore();\n }\n return target.transferToImageBitmap();\n },\n input(event) {\n const handle = view.input;\n if (disposed || handle === undefined) return;\n try {\n const result = handle.call(view, event);\n if (isThenable(result)) {\n void Promise.resolve(result).catch((cause: unknown) => {\n options.report('view2d/input-failed', messageOf(cause));\n });\n }\n } catch (cause) {\n options.report('view2d/input-failed', messageOf(cause));\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n localAudio?.dispose();\n try {\n view.dispose?.();\n } catch (cause) {\n options.report(\n 'runtime/presentation-failed',\n `Releasing the presentation failed: ${messageOf(cause)}`,\n );\n }\n },\n };\n\n function surfaceFor(width: number, height: number): IFusedOverlaySurface {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n `The overlay extent ${String(width)}x${String(height)} must be positive.`,\n { instanceId: instance.instanceId },\n );\n }\n if (surface === undefined || surface.width !== width || surface.height !== height) {\n surface = options.createSurface(width, height);\n }\n return surface;\n }\n}\n","/**\n * 2D presentation guest of the fused editor runtime (RFC 0022 / RFC 0025).\n *\n * One guest serves every instance of the workbench: it evaluates the declared `view2d.entry` modules\n * of the current mode, draws overlays into its own canvases and reports the bitmaps to the host. It\n * holds no document and no model: geometry, properties and the model lane all come from the\n * simulation guest through the host.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio } from '../audio';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock } from '@mica-js/document/fused';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport { fusedDisplayService, fusedHostAudioService } from '../protocol';\nimport type {\n IFusedDisplayPrepareRequest,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedRenderRequest,\n IFusedViewInput,\n} from '../protocol';\nimport { createHostPackageGateway } from '../packages';\nimport { importCode } from '../values';\nimport {\n FusedBridgeError,\n isImageBitmap,\n messageOf,\n toWireFailure,\n transferOverlayFrame,\n} from '../wire';\nimport { startDisplayModelChannel } from './model';\nimport type { IFusedDisplayModelChannel } from './model';\nimport { createViewSession } from './view';\nimport type { FusedSurfaceFactory, IFusedViewSession } from './view';\n\n/** Replaceable guest dependencies, so the presentation runs off-browser in tests. */\nexport interface IFusedDisplayGuestOptions {\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /** Startup ports after the RPC port; the first one is the model lane (RFC 0025). */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified view module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n /** Creates the overlay canvas; defaults to `OffscreenCanvas`. */\n readonly createSurface?: FusedSurfaceFactory;\n}\n\nexport interface IFusedDisplayGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\n/** Starts the 2D presentation guest on the startup port of a sandbox worker. */\nexport function startFusedDisplayGuest(\n port: MessagePort,\n options: IFusedDisplayGuestOptions = {},\n): IFusedDisplayGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const createSurface: FusedSurfaceFactory =\n options.createSurface ?? ((width, height) => new OffscreenCanvas(width, height));\n const packages = createHostPackageGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const audio = createWidgetAudioRuntime({\n onListenerError: (instanceId, cause) =>\n diagnostics.fire({\n code: 'audio/listener-failed',\n message: messageOf(cause),\n instanceId,\n }),\n });\n const hostAudio = endpoint.getProxy(fusedHostAudioService);\n const audioSessions = new Map<string, string>();\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedDisplayModelChannel | undefined =\n modelPort === undefined ? undefined : startDisplayModelChannel(modelPort);\n\n let sessions = new Map<string, IFusedViewSession>();\n /** Incremented by every preparation, so late initializations of a replaced mode are dropped. */\n let sequence = 0;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n // The overlay bitmap is transferable-only: cloning one is invalid, so the hook hands it over.\n endpoint.register(\n fusedDisplayService,\n {\n attachAudio: (port) => audio.attachPort(port),\n setAudioState: (state) => audio.setState(state),\n prepare,\n activate,\n render,\n input,\n release,\n dispose: releaseAll,\n onDidInvalidate(listener) {\n const subscription = invalidations.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n { transfer: transferOverlayFrame },\n );\n\n return { rpc: endpoint, dispose };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function readAsset(lock: DeviceLock, path: string): Promise<Uint8Array> {\n return packages.open(lock).then((files) => files.read(path));\n }\n\n async function prepare(request: IFusedDisplayPrepareRequest): Promise<void> {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError('runtime/unavailable-state', 'The fused display guest is disposed.'),\n );\n }\n const attempt = ++sequence;\n dropSessions();\n for (const instance of request.instances) {\n if (instance.view === undefined) continue;\n const instanceId = instance.instanceId;\n try {\n if (request.mode === 'run') {\n const info = await hostAudio.open(instanceId);\n if (closing || attempt !== sequence) {\n if (info.session !== undefined)\n void hostAudio.close(instanceId, info.session).catch(() => undefined);\n return;\n }\n audio.open(instanceId, info);\n if (info.session !== undefined) audioSessions.set(instanceId, info.session);\n } else audio.open(instanceId, undefined);\n const session = await createViewSession({\n instance,\n mode: request.mode,\n model: request.mode === 'run' ? modelChannel?.client(instance) : undefined,\n audio: fusedAudio(audio.api(instanceId)),\n readAsset: (path) => readAsset(instance.lock, path),\n importModule,\n createSurface,\n invalidate: () => {\n if (attempt === sequence && !closing) invalidations.fire({ instanceId });\n },\n report: (code, message) => report({ code, message, instanceId }),\n });\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n sessions.set(instanceId, session);\n } catch (cause) {\n releaseAudio(instanceId);\n // One broken presentation must not take the other instances down (RFC 0025).\n report({\n code: 'runtime/presentation-failed',\n message: messageOf(cause),\n instanceId,\n });\n }\n }\n // The runtime loads the models only after this resolves, so factory subscriptions are live.\n await modelChannel?.settle();\n }\n\n /**\n * Runs the author `initialize` hook of every prepared presentation.\n *\n * The runtime calls it after the models exist and their initial events were delivered, so a query\n * started here observes the state the model already has. A failing hook faults its own\n * presentation only (RFC 0025 `runtime/presentation-failed`).\n */\n async function activate(): Promise<void> {\n if (closing) return;\n const attempt = sequence;\n // Host activation and model events use different ports; synchronize on the model lane first.\n await modelChannel?.settle();\n if (closing || attempt !== sequence) return;\n for (const [instanceId, session] of [...sessions]) {\n try {\n await session.activate();\n } catch (cause) {\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n report({\n code: 'runtime/presentation-failed',\n message: `Initializing the presentation failed: ${messageOf(cause)}`,\n instanceId,\n });\n release(instanceId);\n }\n }\n }\n\n async function render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined> {\n if (closing) return undefined;\n const session = sessions.get(request.instanceId);\n if (session === undefined) return undefined;\n const attempt = sequence;\n let bitmap: ImageBitmap | undefined;\n try {\n bitmap = session.render(request);\n } catch (cause) {\n report({\n code: 'view2d/render-failed',\n message: messageOf(cause),\n instanceId: request.instanceId,\n });\n return undefined;\n }\n if (bitmap === undefined) return undefined;\n if (closing || attempt !== sequence) {\n closeBitmap(bitmap);\n return undefined;\n }\n return {\n instanceId: request.instanceId,\n generation: request.generation,\n width: request.width,\n height: request.height,\n scale: request.scale,\n bitmap,\n };\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (closing) return;\n sessions.get(instanceId)?.input(event);\n }\n\n function release(instanceId: string): void {\n releaseAudio(instanceId);\n const session = sessions.get(instanceId);\n if (session === undefined) return;\n sessions.delete(instanceId);\n session.dispose();\n modelChannel?.release(instanceId);\n }\n\n async function releaseAll(): Promise<void> {\n if (closing) return;\n sequence += 1;\n dropSessions();\n }\n\n function dropSessions(): void {\n for (const instanceId of [...audioSessions.keys()]) releaseAudio(instanceId);\n const current = sessions;\n sessions = new Map<string, IFusedViewSession>();\n for (const session of current.values()) {\n releaseAudio(session.instanceId);\n session.dispose();\n modelChannel?.release(session.instanceId);\n }\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n dropSessions();\n modelChannel?.dispose();\n audio.dispose();\n endpoint.dispose();\n diagnostics.dispose();\n invalidations.dispose();\n })();\n return disposal;\n }\n\n function releaseAudio(instanceId: string): void {\n audio.release(instanceId);\n const token = audioSessions.get(instanceId);\n audioSessions.delete(instanceId);\n if (token !== undefined) void hostAudio.close(instanceId, token).catch(() => undefined);\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap): void {\n if (isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * `@mica-js/editor/fused/runtime`: the browser bridge of the fused editor runtime (RFC 0022 / 0025).\n *\n * Two sandbox workers serve one workbench. The simulation worker owns the document, the locked\n * packages and every model; the presentation worker runs the declared `view2d.entry` modules and\n * returns overlay bitmaps. They talk over typed RPC services and one direct model lane, and the\n * editor thread never imports model or author view code.\n *\n * ```ts\n * const runtime = await createFusedRuntime({\n * document,\n * registry,\n * step: toTimePs(1, 'ms'),\n * mode: 'run', // mounts the models; advancing starts as soon as the presentations are ready\n * onOverlay: (frame) => paint(frame.instanceId, frame.bitmap),\n * onDiagnostic: (entry) => report(entry),\n * });\n * runtime.display.input(instanceId, { type: 'pointerdown', position, button: 0, buttons: 1 });\n * const frame = await runtime.display.render(instanceId);\n * await runtime.pause(); // step() requires the paused state\n * await runtime.dispose();\n * ```\n */\nimport type { IFusedWorkerFactories } from './host/types';\nexport type * from './audio';\n\nexport { createFusedRuntime } from './host/runtime';\n\n/**\n * Loads the generated worker factories on demand.\n *\n * `createFusedRuntime` does this itself; call it to preload both guest bundles, or to pass the\n * same factories to several runtimes.\n */\nexport async function loadFusedWorkerFactories(): Promise<IFusedWorkerFactories> {\n const { fusedWorkerFactories } = await import('./workers');\n return fusedWorkerFactories;\n}\nexport { connectFusedWorkbench } from './host/connection';\nexport type { IFusedConnection, IFusedConnectionOptions } from './host/connection';\nexport { createFusedDisplay } from './host/display';\nexport type { IFusedDisplayHost, IFusedDisplayHostOptions } from './host/display';\nexport { createHostModelRouter } from './host/model';\nexport type { IFusedHostModelRouter } from './host/model';\nexport type {\n IFusedDisplay,\n IFusedDisplayPrepareInput,\n IFusedRuntime,\n IFusedRuntimeOptions,\n IFusedWorker,\n IFusedWorkerFactories,\n IFusedWorkerOptions,\n} from './host/types';\n\nexport { startFusedSimulationGuest } from './simulation/guest';\nexport type { IFusedSimulationGuest, IFusedSimulationGuestOptions } from './simulation/guest';\nexport { startFusedDisplayGuest } from './display/guest';\nexport type { IFusedDisplayGuest, IFusedDisplayGuestOptions } from './display/guest';\nexport { createViewSession } from './display/view';\nexport type {\n IFusedOverlaySurface,\n FusedSurfaceFactory,\n IFusedViewSession,\n IFusedViewSessionOptions,\n} from './display/view';\nexport { createModelEventRouter, channelKey } from './model-events';\nexport type { IFusedModelEventChannel, IFusedModelEventRouter } from './model-events';\nexport { createHostPackageGateway, packageLockKey } from './packages';\n\nexport {\n FUSED_WIRE_FAILURE,\n FusedBridgeError,\n fromWireFailure,\n isFusedBridgeError,\n mapWireFailure,\n toWireFailure,\n} from './wire';\nexport type { IFusedBridgeErrorOptions, IFusedFailurePayload } from './wire';\n\nexport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedModelChannelService,\n fusedModelSinkService,\n fusedSimulationService,\n} from './protocol';\nexport type {\n FusedDisplayMode,\n FusedPresentationProps,\n FusedPresentationValue,\n FusedSessionStatus,\n FusedViewInputType,\n IFusedDisplayLayout,\n IFusedDisplayPrepareRequest,\n IFusedDisplayService,\n IFusedHostPackageService,\n IFusedHostResourceService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedLoadRequest,\n IFusedModelChannelService,\n IFusedModelClient,\n IFusedModelEventWire,\n FusedModelEvents,\n FusedModelMethods,\n IFusedModelSinkService,\n IFusedOverlayFrame,\n IFusedPackageFilesWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedRenderRequest,\n IFusedSessionState,\n IFusedSimulationService,\n IFusedView2D,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from './protocol';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgUA,IAAa,yBAAyB,iBAA0C,kBAAkB;;AAGlG,IAAa,sBAAsB,iBAAuC,eAAe;;AAGzF,IAAa,0BACX,iBAA2C,oBAAoB;;AAGjE,IAAa,2BACX,iBAA4C,qBAAqB;;AAGnE,IAAa,2BACX,iBAA4C,qBAAqB;;AAGnE,IAAa,wBAAwB,iBAAyC,kBAAkB;AAQhG,IAAa,wBAAwB,iBAAyC,kBAAkB;;;;AC5UhG,SAAgB,eAAe,MAA0B;CACvD,OAAO,GAAG,KAAK,GAAG,GAAG,KAAK,QAAQ,GAAG,KAAK;AAC5C;;AAGA,SAAgB,yBAAyB,UAAuC;CAC9E,MAAM,OAAO,SAAS,SAAS,uBAAuB;CACtD,MAAM,yBAAS,IAAI,IAA6C;CAChE,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,MAAM,YAAY,SAAsD;EACtE,MAAM,MAAM,eAAe,IAAI;EAC/B,IAAI,UAAU,OAAO,IAAI,GAAG;EAC5B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,KAAK,KAAK,IAAI;GACxB,OAAO,IAAI,KAAK,OAAO;EACzB;EACA,OAAO;CACT;CACA,OAAO,EACL,KAAK,MAAkB;EACrB,OAAO,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