@mica-js/editor 0.3.3 → 0.4.0

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.
@@ -0,0 +1,1739 @@
1
+ import { a as isImageBitmap, c as toWireFailure, d as transferPackageBytes, f as transferPresentationBytes, m as transferResourceBytes, n as FusedBridgeError, o as mapWireFailure, p as transferProgramArtifact, s as messageOf, u as transferOverlayFrame } from "./wire-BDHL5Aj9.js";
2
+ import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
+ import { timePs } from "@mica-js/core";
4
+ import { parseFusedDocument, parseGeometry2D, parseStrictJson } from "@mica-js/document/fused";
5
+ import { FusedPreparationError, PreparationError, createHeadlessRuntime, createProgramFiles, openDevicePackage, readonlyBytes, resolveInstanceProperties } from "@mica-js/sdk/fused";
6
+ import { createRpc, defineRpcService } from "@mica-js/core/rpc";
7
+ import { WidgetAudioEngine } from "@mica-js/widget/audio-host";
8
+ import { createWidgetAudioRuntime } from "@mica-js/widget/audio-guest";
9
+ //#region src/fused/runtime/protocol.ts
10
+ /**
11
+ * Wire contracts of the fused editor runtime bridge (RFC 0022 / RFC 0025).
12
+ *
13
+ * One simulation guest owns the document snapshot, the locked packages and every model; one display
14
+ * guest owns the declared `view2d.entry` modules and draws overlays. Both are `SandboxWorker` guests
15
+ * and speak only these typed RPC services over ports created with `createRpc`: the main thread never
16
+ * imports a model or an author view module.
17
+ *
18
+ * Binary payloads, package bytes and overlay bitmaps travel through registration transfer hooks; the
19
+ * model lane is a direct port between the two guests, so a display input handler reaches its model
20
+ * without a hop through the editor.
21
+ */
22
+ /** Wire name of the simulation guest. */
23
+ var fusedSimulationService = defineRpcService("fused-simulation");
24
+ /** Wire name of the 2D presentation guest. */
25
+ var fusedDisplayService = defineRpcService("fused-display");
26
+ /** Wire name of the host package access both guests use. */
27
+ var fusedHostPackageService = defineRpcService("fused-host-package");
28
+ /** Wire name of the host resource access of the simulation guest. */
29
+ var fusedHostResourceService = defineRpcService("fused-host-resource");
30
+ /** Wire name of the model lane the simulation guest serves. */
31
+ var fusedModelChannelService = defineRpcService("fused-model-channel");
32
+ /** Wire name of the model sink the display guest serves. */
33
+ var fusedModelSinkService = defineRpcService("fused-model-sink");
34
+ var fusedHostAudioService = defineRpcService("fused-host-audio");
35
+ //#endregion
36
+ //#region src/fused/runtime/packages.ts
37
+ /** Wire key of one locked package. */
38
+ function packageLockKey(lock) {
39
+ return `${lock.id}@${lock.version}#${lock.integrity}`;
40
+ }
41
+ /** Registry implementation served by the host over `endpoint`. */
42
+ function createHostPackageGateway(endpoint) {
43
+ const host = endpoint.getProxy(fusedHostPackageService);
44
+ const opened = /* @__PURE__ */ new Map();
45
+ const cache = /* @__PURE__ */ new Map();
46
+ const openLock = (lock) => {
47
+ const key = packageLockKey(lock);
48
+ let pending = opened.get(key);
49
+ if (pending === void 0) {
50
+ pending = host.open(lock);
51
+ opened.set(key, pending);
52
+ }
53
+ return pending;
54
+ };
55
+ return { open(lock) {
56
+ return openLock(lock).then((files) => ({
57
+ lock: files.lock,
58
+ files: files.files,
59
+ read: async (path) => {
60
+ const key = `${packageLockKey(lock)}\u0000${path}`;
61
+ const cached = cache.get(key);
62
+ if (cached !== void 0) return cached.slice();
63
+ const bytes = await host.read(lock, path);
64
+ if (!(bytes instanceof Uint8Array)) throw new FusedBridgeError("package/not-found", `The host returned no bytes for ${lock.id}/${path}.`);
65
+ cache.set(key, bytes);
66
+ return bytes.slice();
67
+ }
68
+ }));
69
+ } };
70
+ }
71
+ //#endregion
72
+ //#region src/fused/runtime/host/audio.ts
73
+ /** Browser-owned audio engine; the guest only receives session tokens and a worklet port. */
74
+ function connectFusedAudio(rpc, display, options, report) {
75
+ const instances = /* @__PURE__ */ new Set();
76
+ const reported = /* @__PURE__ */ new Set();
77
+ let disposed = false;
78
+ function bridgeFailure(operation, cause) {
79
+ if (disposed || reported.has(operation)) return;
80
+ reported.add(operation);
81
+ report({
82
+ code: "audio/failed",
83
+ message: `Audio bridge ${operation} failed: ${String(cause)}`
84
+ });
85
+ }
86
+ const engine = options === void 0 ? void 0 : new WidgetAudioEngine({
87
+ context: options.context,
88
+ ...options.destination === void 0 ? {} : { destination: options.destination },
89
+ ...options.limits === void 0 ? {} : { limits: options.limits },
90
+ ...options.getAudioWorklet === void 0 ? {} : { loadWorklet: () => options.getAudioWorklet(options.context) },
91
+ notify: {
92
+ emitPort: (port) => {
93
+ display.attachAudio(port).catch((cause) => {
94
+ port.close();
95
+ bridgeFailure("attachAudio", cause);
96
+ });
97
+ },
98
+ emitState: (state) => {
99
+ display.setAudioState(state).catch((cause) => {
100
+ bridgeFailure("setAudioState", cause);
101
+ });
102
+ }
103
+ },
104
+ report: (code, instanceId, message) => report({
105
+ code: code.replace("widget/audio-", "audio/"),
106
+ message,
107
+ ...instanceId === "" ? {} : { instanceId }
108
+ })
109
+ });
110
+ engine?.suspend();
111
+ rpc.register(fusedHostAudioService, {
112
+ async open(instanceId) {
113
+ instances.add(instanceId);
114
+ return await engine?.open(instanceId) ?? { state: "unavailable" };
115
+ },
116
+ close(instanceId, session) {
117
+ engine?.closeSession(instanceId, session);
118
+ }
119
+ });
120
+ return {
121
+ get state() {
122
+ return engine?.state ?? "unavailable";
123
+ },
124
+ suspend: () => engine?.suspend(),
125
+ resume: () => engine?.resume(),
126
+ setMuted: (muted) => engine?.setMuted(muted),
127
+ setInstanceVolume: (id, volume) => engine?.setInstanceVolume(id, volume),
128
+ clear() {
129
+ for (const id of instances) engine?.close(id);
130
+ instances.clear();
131
+ },
132
+ dispose() {
133
+ if (disposed) return;
134
+ disposed = true;
135
+ engine?.dispose();
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ //#region src/fused/runtime/host/connection.ts
141
+ /**
142
+ * Worker wiring of one fused workbench (RFC 0025).
143
+ *
144
+ * Both guests start from the generated `?sandbox-worker` classes: the host waits for the sandbox to
145
+ * boot, transfers one end of three `MessageChannel`s and creates the typed RPC endpoints. From then
146
+ * on nothing but `createRpc` traffic crosses the boundary.
147
+ */
148
+ /** Boots both guests of one workbench and wires their RPC surfaces. */
149
+ async function connectFusedWorkbench(options) {
150
+ const workerOptions = options.container === void 0 ? {} : { container: options.container };
151
+ const simulationWorker = options.workers.createSimulationWorker(workerOptions);
152
+ const displayWorker = options.workers.createDisplayWorker(workerOptions);
153
+ const subscriptions = [];
154
+ let simulationRpc;
155
+ let displayRpc;
156
+ try {
157
+ await Promise.all([simulationWorker.ready, displayWorker.ready]);
158
+ const simulationChannel = new MessageChannel();
159
+ const displayChannel = new MessageChannel();
160
+ const modelChannel = new MessageChannel();
161
+ simulationWorker.postMessage(null, [simulationChannel.port2, modelChannel.port1]);
162
+ displayWorker.postMessage(null, [displayChannel.port2, modelChannel.port2]);
163
+ simulationRpc = createRpc(simulationChannel.port1);
164
+ displayRpc = createRpc(displayChannel.port1);
165
+ registerHostServices(simulationRpc, options);
166
+ registerHostServices(displayRpc, options);
167
+ const simulation = simulationRpc.getProxy(fusedSimulationService);
168
+ const display = displayRpc.getProxy(fusedDisplayService, { transfer: (member, args) => member === "attachAudio" ? [args[0]] : [] });
169
+ const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) => options.onDiagnostic?.(diagnostic));
170
+ subscriptions.push(simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)), display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)));
171
+ const ownedSimulationRpc = simulationRpc;
172
+ const ownedDisplayRpc = displayRpc;
173
+ let disposal;
174
+ return {
175
+ audio,
176
+ simulation,
177
+ display,
178
+ dispose() {
179
+ return disposal ??= (async () => {
180
+ audio.dispose();
181
+ for (const stop of subscriptions.splice(0)) try {
182
+ stop();
183
+ } catch {}
184
+ ownedSimulationRpc.dispose();
185
+ ownedDisplayRpc.dispose();
186
+ const problems = (await Promise.allSettled([simulationWorker.terminate("fused runtime disposed"), displayWorker.terminate("fused runtime disposed")])).filter((result) => result.status === "rejected").map((result) => result.reason);
187
+ if (problems.length > 0) throw new AggregateError(problems, "Fused sandbox workers failed to terminate.");
188
+ })();
189
+ }
190
+ };
191
+ } catch (cause) {
192
+ for (const stop of subscriptions.splice(0)) try {
193
+ stop();
194
+ } catch {}
195
+ simulationRpc?.dispose();
196
+ displayRpc?.dispose();
197
+ await Promise.allSettled([simulationWorker.terminate("fused runtime failed to start"), displayWorker.terminate("fused runtime failed to start")]);
198
+ throw cause;
199
+ }
200
+ }
201
+ /** Package and resource services every guest of one workbench pulls from. */
202
+ function registerHostServices(endpoint, options) {
203
+ const opened = /* @__PURE__ */ new Map();
204
+ const openLock = (lock) => {
205
+ const key = packageLockKey(lock);
206
+ let pending = opened.get(key);
207
+ if (pending === void 0) {
208
+ pending = options.registry.open(lock);
209
+ opened.set(key, pending);
210
+ }
211
+ return pending;
212
+ };
213
+ endpoint.register(fusedHostPackageService, {
214
+ async open(lock) {
215
+ const files = await openLock(lock);
216
+ return {
217
+ lock: files.lock,
218
+ files: files.files
219
+ };
220
+ },
221
+ async read(lock, path) {
222
+ const bytes = await (await openLock(lock)).read(path);
223
+ if (!(bytes instanceof Uint8Array)) throw new Error(`The registry returned no bytes for ${lock.id}/${path}.`);
224
+ return bytes.slice();
225
+ }
226
+ }, { transfer: transferPackageBytes });
227
+ endpoint.register(fusedHostResourceService, {
228
+ async readResource(request) {
229
+ if (options.resolveResource === void 0) throw new Error(`No resource resolver is configured for ${request.instanceId}/${request.property}.`);
230
+ return (await options.resolveResource(request)).slice();
231
+ },
232
+ async resolveProgramProject(id, target) {
233
+ if (!options.programs?.projects) throw new Error("No program project provider configured.");
234
+ const artifact = await options.programs.projects.resolve(id, target);
235
+ return artifact.kind === "memory" ? {
236
+ kind: "memory",
237
+ format: artifact.format,
238
+ data: artifact.data.slice()
239
+ } : {
240
+ kind: "filesystem",
241
+ files: artifact.files.map((file) => ({
242
+ path: file.path,
243
+ data: file.data.slice()
244
+ }))
245
+ };
246
+ }
247
+ }, { transfer: (member, value) => member === "resolveProgramProject" ? transferProgramArtifact(member, value) : transferResourceBytes(member, value) });
248
+ }
249
+ //#endregion
250
+ //#region src/fused/runtime/host/display.ts
251
+ /**
252
+ * Host-side 2D presentation surface (RFC 0022).
253
+ *
254
+ * The host reserves the overlay extent, numbers every request so a late frame can never overwrite a
255
+ * newer one, and repaints instances whose presentation called `invalidate()`. Bitmaps of discarded
256
+ * frames are closed instead of leaked.
257
+ */
258
+ function createFusedDisplay(options) {
259
+ const { proxy } = options;
260
+ const invalidations = new Emitter();
261
+ const generations = /* @__PURE__ */ new Map();
262
+ const dirty = /* @__PURE__ */ new Set();
263
+ /** Reported framework failures of the current preparation, so a flood reports once. */
264
+ const reported = /* @__PURE__ */ new Set();
265
+ let prepared = [];
266
+ let mode;
267
+ /** Incremented by every preparation, so results of a replaced mode are dropped. */
268
+ let epoch = 0;
269
+ let pumping = false;
270
+ let disposed = false;
271
+ let disposal;
272
+ const stopInvalidate = proxy.onDidInvalidate((change) => {
273
+ if (disposed) return;
274
+ invalidations.fire(change);
275
+ if (options.autoRender !== false) schedule(change.instanceId);
276
+ });
277
+ return {
278
+ display: {
279
+ get mode() {
280
+ return mode;
281
+ },
282
+ get instances() {
283
+ return prepared;
284
+ },
285
+ onDidInvalidate: invalidations.event,
286
+ render,
287
+ input,
288
+ invalidate,
289
+ dispose
290
+ },
291
+ prepare,
292
+ activate,
293
+ dispose
294
+ };
295
+ async function prepare(input, instances) {
296
+ if (disposed) throw new Error("The fused display is disposed.");
297
+ epoch += 1;
298
+ generations.clear();
299
+ dirty.clear();
300
+ reported.clear();
301
+ await mapWireFailure(() => proxy.prepare({
302
+ mode: input.mode,
303
+ instances
304
+ }));
305
+ mode = input.mode;
306
+ prepared = instances;
307
+ }
308
+ async function activate() {
309
+ if (disposed) return;
310
+ await mapWireFailure(() => proxy.activate());
311
+ }
312
+ async function render(instanceId, layout) {
313
+ const instance = prepared.find((entry) => entry.instanceId === instanceId);
314
+ if (instance === void 0 || disposed) return void 0;
315
+ const extent = layout ?? defaultLayout(instance);
316
+ const generation = (generations.get(instanceId) ?? 0) + 1;
317
+ generations.set(instanceId, generation);
318
+ const attempt = epoch;
319
+ const frame = await mapWireFailure(() => proxy.render({
320
+ instanceId,
321
+ generation,
322
+ ...extent
323
+ }));
324
+ if (frame === void 0) return void 0;
325
+ if (disposed || attempt !== epoch || generation !== generations.get(instanceId)) {
326
+ closeBitmap$1(frame.bitmap);
327
+ return;
328
+ }
329
+ options.onOverlay?.(frame);
330
+ return frame;
331
+ }
332
+ function input(instanceId, event) {
333
+ if (disposed) return;
334
+ proxy.input(instanceId, event).catch((cause) => {
335
+ reportOnce(instanceId, "runtime/presentation-failed", messageOf(cause));
336
+ });
337
+ }
338
+ /**
339
+ * Reports a framework failure of one instance once per distinct message.
340
+ *
341
+ * A dead guest fails every queued pointer event and every scheduled frame; without the dedupe the
342
+ * same cause would flood the diagnostic sink.
343
+ */
344
+ function reportOnce(instanceId, code, message) {
345
+ const key = `${instanceId}\u0000${code}\u0000${message}`;
346
+ if (reported.has(key)) return;
347
+ reported.add(key);
348
+ options.onDiagnostic?.({
349
+ code,
350
+ message,
351
+ instanceId
352
+ });
353
+ }
354
+ function invalidate(instanceId) {
355
+ if (disposed) return;
356
+ if (instanceId !== void 0) {
357
+ schedule(instanceId);
358
+ return;
359
+ }
360
+ for (const instance of prepared) schedule(instance.instanceId);
361
+ }
362
+ function schedule(instanceId) {
363
+ if (!prepared.some((entry) => entry.instanceId === instanceId)) return;
364
+ dirty.add(instanceId);
365
+ if (pumping) return;
366
+ pumping = true;
367
+ Promise.resolve().then(pump);
368
+ }
369
+ async function pump() {
370
+ while (!disposed) {
371
+ const batch = [...dirty];
372
+ if (batch.length === 0) {
373
+ pumping = false;
374
+ return;
375
+ }
376
+ dirty.clear();
377
+ for (const instanceId of batch) try {
378
+ await render(instanceId);
379
+ } catch (cause) {
380
+ reportOnce(instanceId, "runtime/presentation-failed", messageOf(cause));
381
+ }
382
+ }
383
+ pumping = false;
384
+ }
385
+ function defaultLayout(instance) {
386
+ const measured = options.measure?.(instance);
387
+ if (measured !== void 0) return measured;
388
+ const bounds = instance.geometry.bounds;
389
+ return {
390
+ width: Math.max(1, Math.round(bounds.width)),
391
+ height: Math.max(1, Math.round(bounds.height)),
392
+ scale: 1
393
+ };
394
+ }
395
+ function dispose() {
396
+ if (disposal !== void 0) return disposal;
397
+ disposed = true;
398
+ disposal = (async () => {
399
+ const problems = [];
400
+ try {
401
+ stopInvalidate();
402
+ } catch (cause) {
403
+ problems.push(cause);
404
+ }
405
+ try {
406
+ await mapWireFailure(() => proxy.dispose());
407
+ } catch (cause) {
408
+ problems.push(cause);
409
+ }
410
+ invalidations.dispose();
411
+ dirty.clear();
412
+ prepared = [];
413
+ mode = void 0;
414
+ if (problems.length > 0) throw new AggregateError(problems, "The fused presentation failed to release its guests.");
415
+ })();
416
+ return disposal;
417
+ }
418
+ }
419
+ function closeBitmap$1(bitmap) {
420
+ if (bitmap !== void 0 && isImageBitmap(bitmap)) bitmap.close();
421
+ }
422
+ //#endregion
423
+ //#region src/fused/runtime/model-events.ts
424
+ /**
425
+ * Local fan-out of model events (RFC 0021).
426
+ *
427
+ * The host and the display guest both expose `Event<ModelEvent<T>>` outlets whose subscriptions are
428
+ * lazy: the first listener of one instance and event subscribes on the wire, the last one
429
+ * unsubscribes, and a released instance drops every local listener.
430
+ */
431
+ function channelKey(instanceId, event) {
432
+ return `${instanceId}\u0000${event}`;
433
+ }
434
+ function createModelEventRouter(channel) {
435
+ const entries = /* @__PURE__ */ new Map();
436
+ const event = (instanceId, name) => {
437
+ const key = channelKey(instanceId, name);
438
+ return (listener) => {
439
+ let entry = entries.get(key);
440
+ if (entry === void 0) {
441
+ entry = {
442
+ emitter: new Emitter(),
443
+ listeners: 0
444
+ };
445
+ entries.set(key, entry);
446
+ }
447
+ const current = entry;
448
+ current.listeners += 1;
449
+ if (current.listeners === 1) channel.subscribe(instanceId, name);
450
+ const subscription = current.emitter.event(listener);
451
+ return toDisposable(() => {
452
+ subscription.dispose();
453
+ current.listeners -= 1;
454
+ if (current.listeners > 0) return;
455
+ entries.delete(key);
456
+ current.emitter.dispose();
457
+ channel.unsubscribe(instanceId, name);
458
+ });
459
+ };
460
+ };
461
+ const drop = (key, instanceId, name) => {
462
+ const entry = entries.get(key);
463
+ if (entry === void 0) return;
464
+ entries.delete(key);
465
+ entry.emitter.dispose();
466
+ channel.unsubscribe(instanceId, name);
467
+ };
468
+ return {
469
+ event,
470
+ deliver(instanceId, name, payload) {
471
+ entries.get(channelKey(instanceId, name))?.emitter.fire(payload);
472
+ },
473
+ release(instanceId) {
474
+ const prefix = `${instanceId}\u0000`;
475
+ for (const key of [...entries.keys()]) {
476
+ if (!key.startsWith(prefix)) continue;
477
+ drop(key, instanceId, key.slice(prefix.length));
478
+ }
479
+ },
480
+ dispose() {
481
+ for (const key of [...entries.keys()]) {
482
+ const separator = key.indexOf("\0");
483
+ drop(key, key.slice(0, separator), key.slice(separator + 1));
484
+ }
485
+ },
486
+ get activeSubscriptions() {
487
+ return entries.size;
488
+ }
489
+ };
490
+ }
491
+ //#endregion
492
+ //#region src/fused/runtime/host/model.ts
493
+ function createHostModelRouter(proxy) {
494
+ let router;
495
+ let subscriptions = 0;
496
+ let stop;
497
+ router = createModelEventRouter({
498
+ subscribe() {
499
+ subscriptions += 1;
500
+ if (subscriptions > 1 || stop !== void 0) return;
501
+ stop = proxy.onDidModelEvent((event) => {
502
+ router?.deliver(event.instanceId, event.event, event.payload);
503
+ });
504
+ },
505
+ unsubscribe() {
506
+ subscriptions = Math.max(0, subscriptions - 1);
507
+ if (subscriptions > 0) return;
508
+ stop?.();
509
+ stop = void 0;
510
+ }
511
+ });
512
+ const active = () => {
513
+ if (router === void 0) throw new Error("The fused model router is disposed.");
514
+ return router;
515
+ };
516
+ const invoke = (instanceId, method, params) => {
517
+ if (router === void 0) return Promise.reject(new FusedBridgeError("model/disconnected", "The model client is disconnected from any live model.", { instanceId }));
518
+ return mapWireFailure(() => proxy.call(instanceId, method, params));
519
+ };
520
+ return {
521
+ client(instance) {
522
+ const declared = new Set(instance.methods);
523
+ const methods = new Proxy(Object.create(null), {
524
+ get(_target, name) {
525
+ if (typeof name !== "string" || !declared.has(name)) return void 0;
526
+ return (params) => invoke(instance.instanceId, name, params);
527
+ },
528
+ has(_target, name) {
529
+ return typeof name === "string" && declared.has(name);
530
+ }
531
+ });
532
+ const events = {};
533
+ for (const name of instance.events) events[name] = active().event(instance.instanceId, name);
534
+ return {
535
+ methods,
536
+ events
537
+ };
538
+ },
539
+ release(instanceId) {
540
+ router?.release(instanceId);
541
+ },
542
+ dispose() {
543
+ stop?.();
544
+ stop = void 0;
545
+ router?.dispose();
546
+ router = void 0;
547
+ }
548
+ };
549
+ }
550
+ //#endregion
551
+ //#region src/fused/runtime/host/runtime.ts
552
+ /**
553
+ * Fused editor runtime bridge of one workbench (RFC 0025).
554
+ *
555
+ * One simulation worker runs the document, the packages and the models; one presentation worker runs
556
+ * the declared 2D view modules. The editor schedules both and never imports model or author code.
557
+ *
558
+ * Every asynchronous transition is numbered: a preparation, reset or disposal that was superseded
559
+ * never applies its result, and a frame produced for a replaced presentation is closed, not shown.
560
+ */
561
+ var IDLE$1 = Object.freeze({
562
+ status: "idle",
563
+ simTime: timePs(0)
564
+ });
565
+ /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
566
+ async function createFusedRuntime(options) {
567
+ const workers = options.workers ?? (await import("./workers-BsocIPUc.js")).fusedWorkerFactories;
568
+ const diagnostics = new Emitter();
569
+ const overlays = new Emitter();
570
+ const states = new Emitter();
571
+ const report = (entry) => {
572
+ diagnostics.fire(entry);
573
+ options.onDiagnostic?.(entry);
574
+ };
575
+ const connection = await connectFusedWorkbench({
576
+ workers,
577
+ registry: options.registry,
578
+ ...options.audio === void 0 ? {} : { audio: options.audio },
579
+ ...options.container === void 0 ? {} : { container: options.container },
580
+ ...options.resolveResource === void 0 ? {} : { resolveResource: options.resolveResource },
581
+ ...options.programs === void 0 ? {} : { programs: options.programs },
582
+ onDiagnostic: report
583
+ });
584
+ const models = createHostModelRouter(connection.simulation);
585
+ const displayHost = createFusedDisplay({
586
+ proxy: connection.display,
587
+ onDiagnostic: report,
588
+ onOverlay: (frame) => {
589
+ overlays.fire(frame);
590
+ options.onOverlay?.(frame);
591
+ },
592
+ ...options.measure === void 0 ? {} : { measure: options.measure }
593
+ });
594
+ let state = IDLE$1;
595
+ let prepared = [];
596
+ let mode;
597
+ let preparation = 0;
598
+ let closed = false;
599
+ let disposal;
600
+ const clients = /* @__PURE__ */ new Map();
601
+ const stopState = connection.simulation.onDidChangeState((next) => setState(next));
602
+ const runtime = {
603
+ audio: connection.audio,
604
+ getState: () => state,
605
+ onDidChangeState: states.event,
606
+ onDidReportDiagnostic: diagnostics.event,
607
+ onDidRenderOverlay: overlays.event,
608
+ getModel,
609
+ display: displayHost.display,
610
+ prepareDisplay,
611
+ resume,
612
+ pause,
613
+ step,
614
+ reset,
615
+ dispose
616
+ };
617
+ try {
618
+ await prepareDisplay({ mode: options.mode ?? "edit" });
619
+ } catch (cause) {
620
+ await dispose().catch(() => void 0);
621
+ throw cause;
622
+ }
623
+ return runtime;
624
+ function setState(next) {
625
+ if (next.status === "running") connection.audio.resume();
626
+ else connection.audio.suspend();
627
+ if (next.status === state.status && next.simTime === state.simTime) return;
628
+ state = next;
629
+ states.fire(next);
630
+ }
631
+ function assertOpen() {
632
+ if (closed) throw new FusedBridgeError("runtime/unavailable-state", "The fused runtime is disposed.");
633
+ }
634
+ function assertRun(operation) {
635
+ assertOpen();
636
+ if (mode !== "run") throw new FusedBridgeError("runtime/unavailable-state", `${operation} requires a run session; prepare the run mode first.`);
637
+ }
638
+ function getModel(instanceId) {
639
+ if (closed || mode !== "run") throw new FusedBridgeError("model/disconnected", "No model is mounted: the fused runtime is not in run mode.", { instanceId });
640
+ const instance = prepared.find((entry) => entry.instanceId === instanceId);
641
+ if (instance === void 0) throw new FusedBridgeError("model/unknown-instance", `No live model for instance "${instanceId}".`, { instanceId });
642
+ let client = clients.get(instanceId);
643
+ if (client === void 0) {
644
+ client = models.client(instance);
645
+ clients.set(instanceId, client);
646
+ }
647
+ return client;
648
+ }
649
+ async function prepareDisplay(input) {
650
+ assertOpen();
651
+ const attempt = ++preparation;
652
+ connection.audio.suspend();
653
+ connection.audio.clear();
654
+ const current = () => !closed && attempt === preparation;
655
+ const described = await mapWireFailure(() => connection.simulation.prepare({
656
+ document: options.document,
657
+ mode: input.mode
658
+ }));
659
+ if (!current()) return prepared;
660
+ if (input.mode === "edit") {
661
+ await mapWireFailure(() => connection.simulation.dispose());
662
+ if (!current()) return prepared;
663
+ }
664
+ await displayHost.prepare({ mode: input.mode }, described.instances);
665
+ if (!current()) return prepared;
666
+ if (input.mode === "run") try {
667
+ const loaded = await mapWireFailure(() => connection.simulation.load({
668
+ document: options.document,
669
+ step: options.step
670
+ }));
671
+ if (!current()) return prepared;
672
+ setState(loaded);
673
+ } catch (cause) {
674
+ await displayHost.prepare({ mode: input.mode }, []).catch(() => void 0);
675
+ throw cause;
676
+ }
677
+ prepared = described.instances;
678
+ mode = input.mode;
679
+ clients.clear();
680
+ await displayHost.activate();
681
+ if (!current()) return prepared;
682
+ if (input.mode === "run") await mapWireFailure(() => connection.simulation.resume());
683
+ return prepared;
684
+ }
685
+ async function resume() {
686
+ assertRun("resume");
687
+ await mapWireFailure(() => connection.simulation.resume());
688
+ }
689
+ function pause() {
690
+ if (closed || mode !== "run") return;
691
+ connection.audio.suspend();
692
+ connection.simulation.pause().catch(() => void 0);
693
+ }
694
+ async function step() {
695
+ assertRun("step");
696
+ setState(await mapWireFailure(() => connection.simulation.step()));
697
+ }
698
+ async function reset() {
699
+ assertRun("reset");
700
+ connection.audio.suspend();
701
+ connection.audio.clear();
702
+ const attempt = ++preparation;
703
+ const current = () => !closed && attempt === preparation;
704
+ const instances = prepared;
705
+ await displayHost.prepare({ mode: "run" }, instances);
706
+ if (!current()) return;
707
+ clients.clear();
708
+ await mapWireFailure(() => connection.simulation.reset());
709
+ if (!current()) return;
710
+ await displayHost.activate();
711
+ if (!current()) return;
712
+ await mapWireFailure(() => connection.simulation.resume());
713
+ }
714
+ function dispose() {
715
+ if (disposal !== void 0) return disposal;
716
+ closed = true;
717
+ connection.audio.dispose();
718
+ disposal = (async () => {
719
+ const problems = [];
720
+ try {
721
+ await displayHost.dispose();
722
+ } catch (cause) {
723
+ problems.push(cause);
724
+ }
725
+ try {
726
+ await mapWireFailure(() => connection.simulation.dispose());
727
+ } catch (cause) {
728
+ problems.push(cause);
729
+ }
730
+ try {
731
+ stopState();
732
+ } catch (cause) {
733
+ problems.push(cause);
734
+ }
735
+ models.dispose();
736
+ try {
737
+ await connection.dispose();
738
+ } catch (cause) {
739
+ problems.push(cause);
740
+ }
741
+ states.dispose();
742
+ diagnostics.dispose();
743
+ overlays.dispose();
744
+ if (problems.length > 0) throw new AggregateError(problems, "The fused runtime failed to release every resource.");
745
+ })();
746
+ return disposal;
747
+ }
748
+ }
749
+ //#endregion
750
+ //#region src/fused/runtime/values.ts
751
+ /**
752
+ * Resolved property snapshot handed to one presentation.
753
+ *
754
+ * Every declared property must appear in `resolved` (the simulation worker resolves the manifest
755
+ * defaults and document overrides through the SDK, exactly like the model snapshot does). Byte and
756
+ * firmware values are copied into independent arrays, because the snapshot crosses an RPC boundary
757
+ * and is transferred to the presentation worker afterwards.
758
+ *
759
+ * @throws {FusedBridgeError} `runtime/presentation-failed` naming the property and its declared
760
+ * type whenever a value cannot be projected. A presentation never receives a partial snapshot.
761
+ */
762
+ function presentationProps(resolved, descriptors) {
763
+ const props = {};
764
+ for (const [name, descriptor] of Object.entries(descriptors)) {
765
+ if (!Object.hasOwn(resolved, name)) throw unpresentable(name, descriptor.type, "has no resolved value");
766
+ const value = resolved[name];
767
+ if (value === void 0) throw unpresentable(name, descriptor.type, "resolved to undefined");
768
+ switch (descriptor.type) {
769
+ case "string":
770
+ case "color":
771
+ case "enum":
772
+ if (typeof value === "string") {
773
+ props[name] = value;
774
+ continue;
775
+ }
776
+ break;
777
+ case "integer":
778
+ case "number":
779
+ if (typeof value === "number") {
780
+ props[name] = value;
781
+ continue;
782
+ }
783
+ break;
784
+ case "boolean":
785
+ if (typeof value === "boolean") {
786
+ props[name] = value;
787
+ continue;
788
+ }
789
+ break;
790
+ case "image":
791
+ case "binary":
792
+ if (value === null) {
793
+ props[name] = null;
794
+ continue;
795
+ }
796
+ props[name] = copyBytes(name, descriptor.type, value);
797
+ continue;
798
+ case "firmware":
799
+ if (value === null) {
800
+ props[name] = null;
801
+ continue;
802
+ }
803
+ props[name] = firmwareSnapshot(name, value);
804
+ continue;
805
+ case "program":
806
+ if (value === null && descriptor.nullable === true) {
807
+ props[name] = null;
808
+ continue;
809
+ }
810
+ if (descriptor.loader === "memory") props[name] = firmwareSnapshot(name, value);
811
+ else {
812
+ const files = value;
813
+ if (!files || !Array.isArray(files.paths) || typeof files.read !== "function") throw unpresentable(name, "program", "is not a file snapshot");
814
+ props[name] = Object.freeze({
815
+ kind: "filesystem",
816
+ files: Object.freeze(files.paths.map((path) => Object.freeze({
817
+ path,
818
+ data: copyBytes(name, "program", files.read(path))
819
+ })))
820
+ });
821
+ }
822
+ continue;
823
+ }
824
+ if (value === null && descriptor.nullable === true) {
825
+ props[name] = null;
826
+ continue;
827
+ }
828
+ throw unpresentable(name, descriptor.type, `resolved to ${describeValue(value)}`);
829
+ }
830
+ return Object.freeze(props);
831
+ }
832
+ function reconstructPresentationProps(props) {
833
+ return Object.freeze(Object.fromEntries(Object.entries(props).map(([name, value]) => {
834
+ if (value !== null && typeof value === "object" && !(value instanceof Uint8Array)) {
835
+ if (value.kind === "filesystem") return [name, createProgramFiles(value.files)];
836
+ return [name, Object.freeze({ segments: Object.freeze(value.segments.map((segment) => Object.freeze({
837
+ addressSpace: segment.addressSpace,
838
+ address: segment.address,
839
+ data: readonlyBytes(segment.bytes)
840
+ }))) })];
841
+ }
842
+ return [name, value];
843
+ })));
844
+ }
845
+ /** Copies one read-only byte snapshot; the SDK hands `ReadonlyBytes`, not raw arrays. */
846
+ function copyBytes(name, type, value) {
847
+ if (value instanceof Uint8Array) return value.slice();
848
+ const candidate = value;
849
+ if (candidate !== null && typeof candidate === "object" && typeof candidate.slice === "function") {
850
+ const copy = candidate.slice.call(candidate);
851
+ if (copy instanceof Uint8Array) return copy;
852
+ }
853
+ throw unpresentable(name, type, "is not a byte snapshot");
854
+ }
855
+ /** Projects one loaded firmware image (RFC 0026) into a transferable snapshot. */
856
+ function firmwareSnapshot(name, value) {
857
+ const segments = value?.segments;
858
+ if (!Array.isArray(segments)) throw unpresentable(name, "firmware", "is not a firmware image");
859
+ const projected = [];
860
+ for (const segment of segments) {
861
+ const candidate = segment;
862
+ if (typeof candidate.addressSpace !== "string" || typeof candidate.address !== "number") throw unpresentable(name, "firmware", "has a segment without an address space or address");
863
+ projected.push({
864
+ addressSpace: candidate.addressSpace,
865
+ address: candidate.address,
866
+ bytes: copyBytes(name, "firmware", candidate.data)
867
+ });
868
+ }
869
+ return Object.freeze({
870
+ kind: "firmware",
871
+ segments: Object.freeze(projected)
872
+ });
873
+ }
874
+ function unpresentable(name, type, reason) {
875
+ return new FusedBridgeError("runtime/presentation-failed", `Property "${name}" (${type}) ${reason}; the presentation cannot receive a partial snapshot.`);
876
+ }
877
+ function describeValue(value) {
878
+ if (value === null) return "null";
879
+ if (Array.isArray(value)) return "an array";
880
+ return `a value of type ${typeof value}`;
881
+ }
882
+ /** Whether a callback returned a promise instead of finishing synchronously. */
883
+ function isThenable(value) {
884
+ return typeof value === "object" && value !== null && typeof value.then === "function";
885
+ }
886
+ /**
887
+ * Evaluates one verified package module inside the guest.
888
+ *
889
+ * The bytes were verified against the package lock before this runs; a blob URL keeps the module
890
+ * out of the host document and is revoked as soon as the namespace settles.
891
+ */
892
+ function importCode(code) {
893
+ const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
894
+ return import(
895
+ /* @vite-ignore */
896
+ url
897
+ ).finally(() => URL.revokeObjectURL(url));
898
+ }
899
+ /** Copies bytes into a plain `ArrayBuffer`, as `Blob` and transfer lists require. */
900
+ function byteBuffer(bytes) {
901
+ const copy = new Uint8Array(bytes.byteLength);
902
+ copy.set(bytes);
903
+ return copy.buffer;
904
+ }
905
+ /** Decodes package bytes as UTF-8 module source, tolerating a leading byte order mark. */
906
+ function decodeSource(bytes) {
907
+ return new TextDecoder().decode(bytes).replace(/^\uFEFF/, "");
908
+ }
909
+ //#endregion
910
+ //#region src/fused/runtime/simulation/model-channel.ts
911
+ /**
912
+ * Model lane between the simulation guest and the display guest (RFC 0025).
913
+ *
914
+ * The host transfers one end of a `MessageChannel` to each guest, so a display input handler calls
915
+ * its model directly instead of asking the editor to relay the call. The simulation guest serves
916
+ * {@link fusedModelChannelService} and pushes events to the display sink only while the display is
917
+ * subscribed to that instance and event.
918
+ */
919
+ /** Starts the simulation end of the model lane over `port`. */
920
+ function startSimulationModelChannel(port, handlers, createEndpoint = createRpc) {
921
+ const endpoint = createEndpoint(port);
922
+ const sink = endpoint.getProxy(fusedModelSinkService);
923
+ const subscriptions = /* @__PURE__ */ new Set();
924
+ endpoint.register(fusedModelChannelService, {
925
+ call: handlers.call,
926
+ subscribe(instanceId, event) {
927
+ subscriptions.add(channelKey(instanceId, event));
928
+ },
929
+ unsubscribe(instanceId, event) {
930
+ subscriptions.delete(channelKey(instanceId, event));
931
+ },
932
+ settle: () => void 0
933
+ });
934
+ return {
935
+ deliver(event) {
936
+ if (!subscriptions.has(channelKey(event.instanceId, event.event))) return;
937
+ sink.deliver(event).catch(() => void 0);
938
+ },
939
+ reset() {
940
+ subscriptions.clear();
941
+ },
942
+ dispose() {
943
+ subscriptions.clear();
944
+ endpoint.dispose();
945
+ }
946
+ };
947
+ }
948
+ //#endregion
949
+ //#region src/fused/runtime/simulation/guest.ts
950
+ /**
951
+ * Simulation guest of the fused editor runtime (RFC 0025).
952
+ *
953
+ * The guest owns the production headless runtime: the document snapshot, the verified package bytes,
954
+ * the models and the electrical solve. The editor keeps no model code on its own thread; it reaches
955
+ * this guest through typed RPC and receives model events, state changes and diagnostics as events.
956
+ *
957
+ * Package bytes, host resources and firmware artifacts are pulled from host services registered on
958
+ * the same RPC endpoint, so verification, preparation and model execution all happen here.
959
+ */
960
+ var IDLE = Object.freeze({
961
+ status: "idle",
962
+ simTime: timePs(0)
963
+ });
964
+ /** Starts the simulation guest on the startup port of a sandbox worker. */
965
+ function startFusedSimulationGuest(port, options = {}) {
966
+ const endpoint = (options.createEndpoint ?? createRpc)(port);
967
+ const importModule = options.importModule ?? importCode;
968
+ const packages = createHostPackageGateway(endpoint);
969
+ const resources = createResourceGateway(endpoint);
970
+ const diagnostics = new Emitter();
971
+ const states = new Emitter();
972
+ const events = new Emitter();
973
+ const modelPort = options.ports?.[0];
974
+ const modelChannel = modelPort === void 0 ? void 0 : startSimulationModelChannel(modelPort, { call: (instanceId, method, params) => callModel(instanceId, method, params) });
975
+ let state = IDLE;
976
+ let session;
977
+ /** Identity of the live session, so events of a discarded candidate never reach a listener. */
978
+ let sessionToken;
979
+ /** Incremented by every session transition, so late results of a replaced session are dropped. */
980
+ let sequence = 0;
981
+ let closing = false;
982
+ let disposal;
983
+ endpoint.register(fusedSimulationService, {
984
+ prepare,
985
+ load,
986
+ step,
987
+ resume,
988
+ pause,
989
+ reset,
990
+ dispose: releaseModels,
991
+ call: (instanceId, method, params) => callModel(instanceId, method, params),
992
+ getState: () => state,
993
+ onDidChangeState(listener) {
994
+ const subscription = states.event((value) => listener(value));
995
+ return () => subscription.dispose();
996
+ },
997
+ onDidReportDiagnostic(listener) {
998
+ const subscription = diagnostics.event((value) => listener(value));
999
+ return () => subscription.dispose();
1000
+ },
1001
+ onDidModelEvent(listener) {
1002
+ const subscription = events.event((value) => listener(value));
1003
+ return () => subscription.dispose();
1004
+ }
1005
+ }, { transfer: transferPresentationBytes });
1006
+ return {
1007
+ rpc: endpoint,
1008
+ dispose
1009
+ };
1010
+ function report(entry) {
1011
+ diagnostics.fire(entry);
1012
+ }
1013
+ function setState(next) {
1014
+ if (next.status === state.status && next.simTime === state.simTime) return;
1015
+ state = next;
1016
+ states.fire(next);
1017
+ }
1018
+ function assertOpen() {
1019
+ if (closing) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", "The fused simulation guest is disposed."));
1020
+ }
1021
+ function requireSession(operation) {
1022
+ assertOpen();
1023
+ if (session === void 0) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", `${operation} requires mounted models; prepare a run session first.`));
1024
+ return session;
1025
+ }
1026
+ async function prepare(request) {
1027
+ assertOpen();
1028
+ const document = parseFusedDocument(request.document);
1029
+ const problems = [];
1030
+ const instances = [];
1031
+ for (const [index, instance] of document.instances.entries()) try {
1032
+ const described = await describeInstance(index, document, instance);
1033
+ if (described !== void 0) instances.push(described);
1034
+ } catch (cause) {
1035
+ if (cause instanceof FusedBridgeError && cause.code === "runtime/presentation-failed") {
1036
+ report({
1037
+ code: cause.code,
1038
+ message: cause.message,
1039
+ instanceId: instance.id
1040
+ });
1041
+ continue;
1042
+ }
1043
+ problems.push({
1044
+ code: "runtime/prepare-failed",
1045
+ message: `${instance.id}: ${messageOf(cause)}`,
1046
+ instanceId: instance.id
1047
+ });
1048
+ }
1049
+ for (const problem of problems) report(problem);
1050
+ if (problems.length > 0) throw toWireFailure(new FusedBridgeError("runtime/prepare-failed", `${problems.length} instance(s) cannot join the 2D scene.`));
1051
+ return { instances };
1052
+ }
1053
+ async function describeInstance(index, document, instance) {
1054
+ const dependency = document.dependencies[instance.device];
1055
+ if (dependency === void 0) throw new FusedBridgeError("document/unlocked-device", `Instance "${instance.id}" uses the unlocked device "${instance.device}".`, { instanceId: instance.id });
1056
+ const lock = {
1057
+ id: instance.device,
1058
+ version: dependency.version,
1059
+ integrity: dependency.integrity
1060
+ };
1061
+ const verified = await openDevicePackage(packages, lock);
1062
+ const view = verified.manifest.view2d;
1063
+ if (view === void 0) {
1064
+ report({
1065
+ code: "view2d/unsupported",
1066
+ message: `${instance.device} declares no 2D geometry; "${instance.id}" stays out of the 2D scene.`,
1067
+ instanceId: instance.id
1068
+ });
1069
+ return;
1070
+ }
1071
+ const pins = Object.keys(verified.manifest.pins ?? {});
1072
+ const geometryValue = typeof view.geometry === "string" ? parseStrictJson(decodeSource(await verified.read(view.geometry))) : view.geometry;
1073
+ const descriptors = verified.manifest.properties ?? {};
1074
+ return {
1075
+ instanceId: instance.id,
1076
+ device: instance.device,
1077
+ lock,
1078
+ geometry: parseGeometry2D(geometryValue, pins),
1079
+ view: view.entry,
1080
+ props: presentationProps(await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1081
+ methods: Object.keys(verified.manifest.model?.methods ?? {}),
1082
+ events: Object.keys(verified.manifest.model?.events ?? {})
1083
+ };
1084
+ }
1085
+ /**
1086
+ * Resolves the declared properties a presentation reads through the SDK, so the projection is the
1087
+ * same snapshot the model receives: manifest defaults, document overrides, package and host
1088
+ * resources, and a loaded firmware image.
1089
+ *
1090
+ * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.
1091
+ */
1092
+ async function resolvePresentationProps(verified, descriptors, instance, index) {
1093
+ try {
1094
+ return (await resolveInstanceProperties({
1095
+ instanceId: instance.id,
1096
+ package: verified,
1097
+ descriptors,
1098
+ overrides: instance.properties ?? {},
1099
+ irProperties: /* @__PURE__ */ new Map(),
1100
+ pointer: [
1101
+ "instances",
1102
+ String(index),
1103
+ "properties"
1104
+ ],
1105
+ resolveResource: resources.resolveResource,
1106
+ programs: resources.programs
1107
+ })).props;
1108
+ } catch (cause) {
1109
+ throw new FusedBridgeError("runtime/presentation-failed", `Presentation properties of "${instance.id}" cannot be resolved: ${describeProblems(cause, descriptors)}`, { instanceId: instance.id });
1110
+ }
1111
+ }
1112
+ async function load(request) {
1113
+ assertOpen();
1114
+ const step = request.step;
1115
+ if (!Number.isSafeInteger(step) || step <= 0) throw toWireFailure(new FusedBridgeError("runtime/invalid-time", `\`step\` must be a positive integer number of picoseconds, received ${String(step)}.`));
1116
+ const document = parseFusedDocument(request.document);
1117
+ const attempt = ++sequence;
1118
+ const token = {};
1119
+ const superseded = () => closing || attempt !== sequence;
1120
+ /** Events of the factory phase are queued and delivered once the session is adopted. */
1121
+ const pending = [];
1122
+ let created;
1123
+ try {
1124
+ created = await createHeadlessRuntime({
1125
+ document,
1126
+ registry: packages,
1127
+ loadModule,
1128
+ step,
1129
+ resolveResource: resources.resolveResource,
1130
+ programs: resources.programs,
1131
+ onModelEvent: (event) => {
1132
+ if (sessionToken === token) publishModelEvent(event);
1133
+ else if (!superseded()) pending.push(event);
1134
+ },
1135
+ onDiagnostic: (entry) => {
1136
+ if (!superseded()) report(entry);
1137
+ }
1138
+ });
1139
+ } catch (cause) {
1140
+ if (cause instanceof FusedPreparationError) for (const entry of cause.diagnostics) report(entry);
1141
+ throw toWireFailure(cause);
1142
+ }
1143
+ if (superseded()) {
1144
+ await created.dispose().catch(() => void 0);
1145
+ return state;
1146
+ }
1147
+ const previous = session;
1148
+ session = void 0;
1149
+ sessionToken = void 0;
1150
+ if (previous !== void 0) await releaseSession(previous, false);
1151
+ sessionToken = token;
1152
+ session = {
1153
+ runtime: created,
1154
+ subscriptions: [created.onDidChangeState((next) => {
1155
+ if (sessionToken === token) setState({
1156
+ status: next.status,
1157
+ simTime: next.simTime
1158
+ });
1159
+ }), created.onDidReportDiagnostic((entry) => {
1160
+ if (sessionToken === token) report(entry);
1161
+ })]
1162
+ };
1163
+ for (const event of pending.splice(0)) publishModelEvent(event);
1164
+ const initial = created.getState();
1165
+ setState({
1166
+ status: initial.status,
1167
+ simTime: initial.simTime
1168
+ });
1169
+ return state;
1170
+ }
1171
+ async function step() {
1172
+ const target = requireSession("step");
1173
+ await mapGuestCall(() => target.runtime.step());
1174
+ return state;
1175
+ }
1176
+ async function resume() {
1177
+ const target = requireSession("resume");
1178
+ await mapGuestCall(() => target.runtime.resume());
1179
+ }
1180
+ function pause() {
1181
+ session?.runtime.pause();
1182
+ }
1183
+ async function reset() {
1184
+ const target = requireSession("reset");
1185
+ await mapGuestCall(() => target.runtime.reset());
1186
+ }
1187
+ async function callModel(instanceId, method, params) {
1188
+ const target = session;
1189
+ if (closing || target === void 0) throw toWireFailure(new FusedBridgeError("model/disconnected", "No model is mounted; prepare a run session first.", { instanceId }));
1190
+ try {
1191
+ const invoke = target.runtime.getModel(instanceId).methods[method];
1192
+ if (invoke === void 0) throw new FusedBridgeError("model/unknown-method", `The model of "${instanceId}" declares no method "${method}".`, { instanceId });
1193
+ return await invoke(params);
1194
+ } catch (cause) {
1195
+ throw toWireFailure(cause);
1196
+ }
1197
+ }
1198
+ async function releaseModels() {
1199
+ assertOpen();
1200
+ await releaseCurrent(true);
1201
+ }
1202
+ async function releaseCurrent(strict) {
1203
+ const target = session;
1204
+ session = void 0;
1205
+ sessionToken = void 0;
1206
+ sequence += 1;
1207
+ modelChannel?.reset();
1208
+ setState(IDLE);
1209
+ if (target !== void 0) await releaseSession(target, strict);
1210
+ }
1211
+ async function releaseSession(target, strict) {
1212
+ for (const subscription of target.subscriptions.splice(0)) subscription.dispose();
1213
+ try {
1214
+ await target.runtime.dispose();
1215
+ } catch (cause) {
1216
+ report({
1217
+ code: "runtime/model-failed",
1218
+ message: `Releasing the models failed: ${messageOf(cause)}`
1219
+ });
1220
+ if (strict) throw toWireFailure(cause);
1221
+ }
1222
+ }
1223
+ function publishModelEvent(event) {
1224
+ const wire = {
1225
+ instanceId: event.instanceId,
1226
+ event: event.event,
1227
+ payload: event.payload
1228
+ };
1229
+ modelChannel?.deliver(wire);
1230
+ events.fire(wire);
1231
+ }
1232
+ async function loadModule(files, path) {
1233
+ return importModule(decodeSource(await files.read(path)));
1234
+ }
1235
+ function dispose() {
1236
+ if (disposal !== void 0) return disposal;
1237
+ closing = true;
1238
+ disposal = (async () => {
1239
+ sequence += 1;
1240
+ modelChannel?.dispose();
1241
+ const target = session;
1242
+ session = void 0;
1243
+ sessionToken = void 0;
1244
+ const problems = [];
1245
+ if (target !== void 0) try {
1246
+ await releaseSession(target, true);
1247
+ } catch (cause) {
1248
+ problems.push(cause);
1249
+ }
1250
+ endpoint.dispose();
1251
+ diagnostics.dispose();
1252
+ states.dispose();
1253
+ events.dispose();
1254
+ if (problems.length > 0) throw problems[0];
1255
+ })();
1256
+ return disposal;
1257
+ }
1258
+ }
1259
+ /** One guest call whose rejection is rebuilt on the host. */
1260
+ async function mapGuestCall(run) {
1261
+ try {
1262
+ return await run();
1263
+ } catch (cause) {
1264
+ throw toWireFailure(cause);
1265
+ }
1266
+ }
1267
+ /** Host resources the runtime pulls while it resolves instance properties. */
1268
+ function createResourceGateway(endpoint) {
1269
+ const host = endpoint.getProxy(fusedHostResourceService);
1270
+ const resources = /* @__PURE__ */ new Map();
1271
+ const programs = /* @__PURE__ */ new Map();
1272
+ const copyFiles = (files) => files.map((file) => ({
1273
+ path: file.path,
1274
+ data: file.data.slice()
1275
+ }));
1276
+ const copyArtifact = (artifact) => artifact.kind === "memory" ? {
1277
+ ...artifact,
1278
+ data: artifact.data.slice()
1279
+ } : {
1280
+ kind: "filesystem",
1281
+ files: copyFiles(artifact.files)
1282
+ };
1283
+ return {
1284
+ programs: { projects: { resolve: async (id, target) => {
1285
+ const key = JSON.stringify([
1286
+ target.deviceId,
1287
+ target.property,
1288
+ target.loader,
1289
+ id
1290
+ ]);
1291
+ let artifact = programs.get(key);
1292
+ if (!artifact) {
1293
+ artifact = await host.resolveProgramProject(id, target);
1294
+ programs.set(key, copyArtifact(artifact));
1295
+ }
1296
+ return copyArtifact(artifact);
1297
+ } } },
1298
+ resolveResource: async (request) => {
1299
+ const key = `${request.instanceId}\u0000${request.property}`;
1300
+ const cached = resources.get(key);
1301
+ if (cached !== void 0) return cached.slice();
1302
+ const bytes = await host.readResource(request);
1303
+ resources.set(key, bytes.slice());
1304
+ return bytes;
1305
+ }
1306
+ };
1307
+ }
1308
+ /** Flattens preparation problems, naming the property and its declared type. */
1309
+ function describeProblems(cause, descriptors) {
1310
+ if (cause instanceof PreparationError) return cause.problems.map((problem) => {
1311
+ const property = propertyOfPointer(problem.pointer, descriptors);
1312
+ const where = problem.pointer === "" ? "" : ` at ${problem.pointer}`;
1313
+ return `${problem.code}${where}${property === void 0 ? "" : ` (${property})`}: ${problem.message}`;
1314
+ }).join("; ");
1315
+ return messageOf(cause);
1316
+ }
1317
+ /** Names one property and its declared type from a JSON Pointer into the instance properties. */
1318
+ function propertyOfPointer(pointer, descriptors) {
1319
+ const segments = pointer.split("/");
1320
+ const at = segments.indexOf("properties");
1321
+ const name = at < 0 ? void 0 : segments[at + 1];
1322
+ if (name === void 0) return void 0;
1323
+ const type = descriptors[name]?.type;
1324
+ return type === void 0 ? `property "${name}"` : `property "${name}", type ${type}`;
1325
+ }
1326
+ //#endregion
1327
+ //#region src/fused/runtime/audio.ts
1328
+ /** Adapt the shared audio implementation's subscriptions to the editor lifecycle convention. */
1329
+ function fusedAudio(api) {
1330
+ return {
1331
+ get state() {
1332
+ return api.state;
1333
+ },
1334
+ onDidChangeState: (listener) => ({ dispose: api.onStateChange(listener) }),
1335
+ tone: (options) => api.tone(options),
1336
+ createStream(options) {
1337
+ const stream = api.createStream(options);
1338
+ return Object.assign(stream, {
1339
+ onDidDrain: ((listener) => ({ dispose: stream.onDrain(() => listener()) })),
1340
+ onDidChangeStatus: ((listener) => ({ dispose: stream.onStatus(listener) }))
1341
+ });
1342
+ }
1343
+ };
1344
+ }
1345
+ //#endregion
1346
+ //#region src/fused/runtime/display/model.ts
1347
+ /**
1348
+ * Display-side model client of one instance (RFC 0021 / RFC 0022).
1349
+ *
1350
+ * The client talks to the simulation guest over the direct model lane: a presentation input handler
1351
+ * calls its model without a hop through the editor, and `invalidate()` remains the only repaint
1352
+ * trigger. Only the methods and events the manifest declares resolve.
1353
+ */
1354
+ /** Starts the display end of the model lane over `port`. */
1355
+ function startDisplayModelChannel(port, createEndpoint = createRpc) {
1356
+ const endpoint = createEndpoint(port);
1357
+ const lane = endpoint.getProxy(fusedModelChannelService);
1358
+ /** Wire subscriptions still in flight, so preparation can wait for the model lane to catch up. */
1359
+ const inFlight = /* @__PURE__ */ new Set();
1360
+ const router = createModelEventRouter({
1361
+ subscribe(instanceId, event) {
1362
+ const call = lane.subscribe(instanceId, event).catch(() => void 0);
1363
+ inFlight.add(call);
1364
+ call.finally(() => inFlight.delete(call));
1365
+ },
1366
+ unsubscribe(instanceId, event) {
1367
+ const call = lane.unsubscribe(instanceId, event).catch(() => void 0);
1368
+ inFlight.add(call);
1369
+ call.finally(() => inFlight.delete(call));
1370
+ }
1371
+ });
1372
+ endpoint.register(fusedModelSinkService, { deliver(event) {
1373
+ if (!isModelEvent(event)) return;
1374
+ router.deliver(event.instanceId, event.event, event.payload);
1375
+ } });
1376
+ return {
1377
+ client(instance) {
1378
+ const declared = new Set(instance.methods);
1379
+ const methods = new Proxy(Object.create(null), {
1380
+ get(_target, name) {
1381
+ if (typeof name !== "string" || !declared.has(name)) return void 0;
1382
+ return (params) => mapWireFailure(() => lane.call(instance.instanceId, name, params));
1383
+ },
1384
+ has(_target, name) {
1385
+ return typeof name === "string" && declared.has(name);
1386
+ }
1387
+ });
1388
+ const events = {};
1389
+ for (const name of instance.events) events[name] = router.event(instance.instanceId, name);
1390
+ return {
1391
+ methods,
1392
+ events
1393
+ };
1394
+ },
1395
+ release(instanceId) {
1396
+ router.release(instanceId);
1397
+ },
1398
+ async settle() {
1399
+ while (inFlight.size > 0) await Promise.allSettled([...inFlight]);
1400
+ await lane.settle();
1401
+ },
1402
+ dispose() {
1403
+ router.dispose();
1404
+ endpoint.dispose();
1405
+ }
1406
+ };
1407
+ }
1408
+ function isModelEvent(value) {
1409
+ if (typeof value !== "object" || value === null) return false;
1410
+ const candidate = value;
1411
+ return typeof candidate.instanceId === "string" && typeof candidate.event === "string";
1412
+ }
1413
+ //#endregion
1414
+ //#region src/fused/runtime/display/view.ts
1415
+ /**
1416
+ * Evaluates the presentation entry of one instance and initializes it.
1417
+ *
1418
+ * @throws {FusedBridgeError} when the module has no factory or `initialize` fails.
1419
+ */
1420
+ async function createViewSession(options) {
1421
+ const { instance } = options;
1422
+ const entry = instance.view;
1423
+ if (entry === void 0) throw new FusedBridgeError("view2d/unsupported", `${instance.device} declares no \`view2d.entry\`.`, { instanceId: instance.instanceId });
1424
+ const namespace = await options.importModule(decodeSource(await options.readAsset(entry)));
1425
+ const factory = namespace !== null && typeof namespace === "object" ? namespace.default : void 0;
1426
+ if (typeof factory !== "function") throw new FusedBridgeError("runtime/presentation-failed", `${instance.device}/${entry} must default-export a presentation factory.`, { instanceId: instance.instanceId });
1427
+ let disposed = false;
1428
+ const localAudio = options.audio === void 0 ? createWidgetAudioRuntime({}) : void 0;
1429
+ let surface;
1430
+ const view = factory({
1431
+ mode: options.mode,
1432
+ props: reconstructPresentationProps(instance.props),
1433
+ geometry: instance.geometry,
1434
+ model: options.model,
1435
+ assets: {
1436
+ read: (path) => options.readAsset(path),
1437
+ loadImage: async (path) => createImageBitmap(new Blob([byteBuffer(await options.readAsset(path))]))
1438
+ },
1439
+ audio: options.audio ?? fusedAudio(localAudio.api(instance.instanceId)),
1440
+ invalidate: () => {
1441
+ if (!disposed) options.invalidate();
1442
+ }
1443
+ });
1444
+ if (typeof view !== "object" || view === null) throw new FusedBridgeError("runtime/presentation-failed", `${instance.device}/${entry} returned no presentation object.`, { instanceId: instance.instanceId });
1445
+ let activated = false;
1446
+ return {
1447
+ instanceId: instance.instanceId,
1448
+ geometry: instance.geometry,
1449
+ /**
1450
+ * Runs `initialize` once, after the models exist (RFC 0025 startup barrier). The factory itself
1451
+ * only registers listeners, so a presentation sees the initial model events before this runs.
1452
+ */
1453
+ async activate() {
1454
+ if (disposed || activated) return;
1455
+ activated = true;
1456
+ const initialized = view.initialize?.();
1457
+ if (isThenable(initialized)) await initialized;
1458
+ },
1459
+ render(request) {
1460
+ const draw = view.renderOverlay;
1461
+ if (disposed || draw === void 0) return void 0;
1462
+ const target = surfaceFor(request.width, request.height);
1463
+ const context2d = target.getContext("2d");
1464
+ if (context2d === null) throw new FusedBridgeError("view2d/render-failed", "The overlay canvas has no 2D context.", { instanceId: instance.instanceId });
1465
+ context2d.save();
1466
+ try {
1467
+ context2d.setTransform(1, 0, 0, 1, 0, 0);
1468
+ context2d.clearRect(0, 0, request.width, request.height);
1469
+ const bounds = instance.geometry.bounds;
1470
+ context2d.setTransform(request.scale, 0, 0, request.scale, -bounds.x * request.scale, -bounds.y * request.scale);
1471
+ if (isThenable(draw.call(view, context2d))) throw new FusedBridgeError("view2d/render-failed", "renderOverlay must draw synchronously.", { instanceId: instance.instanceId });
1472
+ } finally {
1473
+ context2d.restore();
1474
+ }
1475
+ return target.transferToImageBitmap();
1476
+ },
1477
+ input(event) {
1478
+ const handle = view.input;
1479
+ if (disposed || handle === void 0) return;
1480
+ try {
1481
+ const result = handle.call(view, event);
1482
+ if (isThenable(result)) Promise.resolve(result).catch((cause) => {
1483
+ options.report("view2d/input-failed", messageOf(cause));
1484
+ });
1485
+ } catch (cause) {
1486
+ options.report("view2d/input-failed", messageOf(cause));
1487
+ }
1488
+ },
1489
+ dispose() {
1490
+ if (disposed) return;
1491
+ disposed = true;
1492
+ localAudio?.dispose();
1493
+ try {
1494
+ view.dispose?.();
1495
+ } catch (cause) {
1496
+ options.report("runtime/presentation-failed", `Releasing the presentation failed: ${messageOf(cause)}`);
1497
+ }
1498
+ }
1499
+ };
1500
+ function surfaceFor(width, height) {
1501
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) throw new FusedBridgeError("view2d/render-failed", `The overlay extent ${String(width)}x${String(height)} must be positive.`, { instanceId: instance.instanceId });
1502
+ if (surface === void 0 || surface.width !== width || surface.height !== height) surface = options.createSurface(width, height);
1503
+ return surface;
1504
+ }
1505
+ }
1506
+ //#endregion
1507
+ //#region src/fused/runtime/display/guest.ts
1508
+ /**
1509
+ * 2D presentation guest of the fused editor runtime (RFC 0022 / RFC 0025).
1510
+ *
1511
+ * One guest serves every instance of the workbench: it evaluates the declared `view2d.entry` modules
1512
+ * of the current mode, draws overlays into its own canvases and reports the bitmaps to the host. It
1513
+ * holds no document and no model: geometry, properties and the model lane all come from the
1514
+ * simulation guest through the host.
1515
+ */
1516
+ /** Starts the 2D presentation guest on the startup port of a sandbox worker. */
1517
+ function startFusedDisplayGuest(port, options = {}) {
1518
+ const endpoint = (options.createEndpoint ?? createRpc)(port);
1519
+ const importModule = options.importModule ?? importCode;
1520
+ const createSurface = options.createSurface ?? ((width, height) => new OffscreenCanvas(width, height));
1521
+ const packages = createHostPackageGateway(endpoint);
1522
+ const diagnostics = new Emitter();
1523
+ const audio = createWidgetAudioRuntime({ onListenerError: (instanceId, cause) => diagnostics.fire({
1524
+ code: "audio/listener-failed",
1525
+ message: messageOf(cause),
1526
+ instanceId
1527
+ }) });
1528
+ const hostAudio = endpoint.getProxy(fusedHostAudioService);
1529
+ const audioSessions = /* @__PURE__ */ new Map();
1530
+ const invalidations = new Emitter();
1531
+ const modelPort = options.ports?.[0];
1532
+ const modelChannel = modelPort === void 0 ? void 0 : startDisplayModelChannel(modelPort);
1533
+ let sessions = /* @__PURE__ */ new Map();
1534
+ /** Incremented by every preparation, so late initializations of a replaced mode are dropped. */
1535
+ let sequence = 0;
1536
+ let closing = false;
1537
+ let disposal;
1538
+ endpoint.register(fusedDisplayService, {
1539
+ attachAudio: (port) => audio.attachPort(port),
1540
+ setAudioState: (state) => audio.setState(state),
1541
+ prepare,
1542
+ activate,
1543
+ render,
1544
+ input,
1545
+ release,
1546
+ dispose: releaseAll,
1547
+ onDidInvalidate(listener) {
1548
+ const subscription = invalidations.event((value) => listener(value));
1549
+ return () => subscription.dispose();
1550
+ },
1551
+ onDidReportDiagnostic(listener) {
1552
+ const subscription = diagnostics.event((value) => listener(value));
1553
+ return () => subscription.dispose();
1554
+ }
1555
+ }, { transfer: transferOverlayFrame });
1556
+ return {
1557
+ rpc: endpoint,
1558
+ dispose
1559
+ };
1560
+ function report(entry) {
1561
+ diagnostics.fire(entry);
1562
+ }
1563
+ function readAsset(lock, path) {
1564
+ return packages.open(lock).then((files) => files.read(path));
1565
+ }
1566
+ async function prepare(request) {
1567
+ if (closing) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", "The fused display guest is disposed."));
1568
+ const attempt = ++sequence;
1569
+ dropSessions();
1570
+ for (const instance of request.instances) {
1571
+ if (instance.view === void 0) continue;
1572
+ const instanceId = instance.instanceId;
1573
+ try {
1574
+ if (request.mode === "run") {
1575
+ const info = await hostAudio.open(instanceId);
1576
+ if (closing || attempt !== sequence) {
1577
+ if (info.session !== void 0) hostAudio.close(instanceId, info.session).catch(() => void 0);
1578
+ return;
1579
+ }
1580
+ audio.open(instanceId, info);
1581
+ if (info.session !== void 0) audioSessions.set(instanceId, info.session);
1582
+ } else audio.open(instanceId, void 0);
1583
+ const session = await createViewSession({
1584
+ instance,
1585
+ mode: request.mode,
1586
+ model: request.mode === "run" ? modelChannel?.client(instance) : void 0,
1587
+ audio: fusedAudio(audio.api(instanceId)),
1588
+ readAsset: (path) => readAsset(instance.lock, path),
1589
+ importModule,
1590
+ createSurface,
1591
+ invalidate: () => {
1592
+ if (attempt === sequence && !closing) invalidations.fire({ instanceId });
1593
+ },
1594
+ report: (code, message) => report({
1595
+ code,
1596
+ message,
1597
+ instanceId
1598
+ })
1599
+ });
1600
+ if (closing || attempt !== sequence) {
1601
+ session.dispose();
1602
+ return;
1603
+ }
1604
+ sessions.set(instanceId, session);
1605
+ } catch (cause) {
1606
+ releaseAudio(instanceId);
1607
+ report({
1608
+ code: "runtime/presentation-failed",
1609
+ message: messageOf(cause),
1610
+ instanceId
1611
+ });
1612
+ }
1613
+ }
1614
+ await modelChannel?.settle();
1615
+ }
1616
+ /**
1617
+ * Runs the author `initialize` hook of every prepared presentation.
1618
+ *
1619
+ * The runtime calls it after the models exist and their initial events were delivered, so a query
1620
+ * started here observes the state the model already has. A failing hook faults its own
1621
+ * presentation only (RFC 0025 `runtime/presentation-failed`).
1622
+ */
1623
+ async function activate() {
1624
+ if (closing) return;
1625
+ const attempt = sequence;
1626
+ await modelChannel?.settle();
1627
+ if (closing || attempt !== sequence) return;
1628
+ for (const [instanceId, session] of [...sessions]) try {
1629
+ await session.activate();
1630
+ } catch (cause) {
1631
+ if (closing || attempt !== sequence) {
1632
+ session.dispose();
1633
+ return;
1634
+ }
1635
+ report({
1636
+ code: "runtime/presentation-failed",
1637
+ message: `Initializing the presentation failed: ${messageOf(cause)}`,
1638
+ instanceId
1639
+ });
1640
+ release(instanceId);
1641
+ }
1642
+ }
1643
+ async function render(request) {
1644
+ if (closing) return void 0;
1645
+ const session = sessions.get(request.instanceId);
1646
+ if (session === void 0) return void 0;
1647
+ const attempt = sequence;
1648
+ let bitmap;
1649
+ try {
1650
+ bitmap = session.render(request);
1651
+ } catch (cause) {
1652
+ report({
1653
+ code: "view2d/render-failed",
1654
+ message: messageOf(cause),
1655
+ instanceId: request.instanceId
1656
+ });
1657
+ return;
1658
+ }
1659
+ if (bitmap === void 0) return void 0;
1660
+ if (closing || attempt !== sequence) {
1661
+ closeBitmap(bitmap);
1662
+ return;
1663
+ }
1664
+ return {
1665
+ instanceId: request.instanceId,
1666
+ generation: request.generation,
1667
+ width: request.width,
1668
+ height: request.height,
1669
+ scale: request.scale,
1670
+ bitmap
1671
+ };
1672
+ }
1673
+ function input(instanceId, event) {
1674
+ if (closing) return;
1675
+ sessions.get(instanceId)?.input(event);
1676
+ }
1677
+ function release(instanceId) {
1678
+ releaseAudio(instanceId);
1679
+ const session = sessions.get(instanceId);
1680
+ if (session === void 0) return;
1681
+ sessions.delete(instanceId);
1682
+ session.dispose();
1683
+ modelChannel?.release(instanceId);
1684
+ }
1685
+ async function releaseAll() {
1686
+ if (closing) return;
1687
+ sequence += 1;
1688
+ dropSessions();
1689
+ }
1690
+ function dropSessions() {
1691
+ for (const instanceId of [...audioSessions.keys()]) releaseAudio(instanceId);
1692
+ const current = sessions;
1693
+ sessions = /* @__PURE__ */ new Map();
1694
+ for (const session of current.values()) {
1695
+ releaseAudio(session.instanceId);
1696
+ session.dispose();
1697
+ modelChannel?.release(session.instanceId);
1698
+ }
1699
+ }
1700
+ function dispose() {
1701
+ if (disposal !== void 0) return disposal;
1702
+ closing = true;
1703
+ disposal = (async () => {
1704
+ sequence += 1;
1705
+ dropSessions();
1706
+ modelChannel?.dispose();
1707
+ audio.dispose();
1708
+ endpoint.dispose();
1709
+ diagnostics.dispose();
1710
+ invalidations.dispose();
1711
+ })();
1712
+ return disposal;
1713
+ }
1714
+ function releaseAudio(instanceId) {
1715
+ audio.release(instanceId);
1716
+ const token = audioSessions.get(instanceId);
1717
+ audioSessions.delete(instanceId);
1718
+ if (token !== void 0) hostAudio.close(instanceId, token).catch(() => void 0);
1719
+ }
1720
+ }
1721
+ function closeBitmap(bitmap) {
1722
+ if (isImageBitmap(bitmap)) bitmap.close();
1723
+ }
1724
+ //#endregion
1725
+ //#region src/fused/runtime/index.ts
1726
+ /**
1727
+ * Loads the generated worker factories on demand.
1728
+ *
1729
+ * `createFusedRuntime` does this itself; call it to preload both guest bundles, or to pass the
1730
+ * same factories to several runtimes.
1731
+ */
1732
+ async function loadFusedWorkerFactories() {
1733
+ const { fusedWorkerFactories } = await import("./workers-BsocIPUc.js");
1734
+ return fusedWorkerFactories;
1735
+ }
1736
+ //#endregion
1737
+ export { fusedModelSinkService as _, createFusedRuntime as a, createModelEventRouter as c, createHostPackageGateway as d, packageLockKey as f, fusedModelChannelService as g, fusedHostResourceService as h, startFusedSimulationGuest as i, createFusedDisplay as l, fusedHostPackageService as m, startFusedDisplayGuest as n, createHostModelRouter as o, fusedDisplayService as p, createViewSession as r, channelKey as s, loadFusedWorkerFactories as t, connectFusedWorkbench as u, fusedSimulationService as v };
1738
+
1739
+ //# sourceMappingURL=runtime-CXYJzbbj.js.map