@mica-js/editor 0.13.0 → 0.14.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.
@@ -1,4 +1,4 @@
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";
1
+ import { a as isImageBitmap, c as toWireFailure, d as transferOverlayFrame, f as transferPackageBytes, h as transferResourceBytes, m as transferProgramArtifact, n as FusedBridgeError, o as mapWireFailure, p as transferPresentationBytes, s as messageOf, u as transferDeviceState } from "./wire-Di4FVpnu.js";
2
2
  import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
3
  import { timePs, toTimePs } from "@mica-js/core";
4
4
  import { parseFusedDocument, parseGeometry2D, parseStrictJson } from "@mica-js/document/fused";
@@ -164,7 +164,7 @@ async function connectFusedWorkbench(options) {
164
164
  displayRpc = createRpc(displayChannel.port1);
165
165
  registerHostServices(simulationRpc, options);
166
166
  registerHostServices(displayRpc, options);
167
- const simulation = simulationRpc.getProxy(fusedSimulationService);
167
+ const simulation = simulationRpc.getProxy(fusedSimulationService, { transfer: transferDeviceState });
168
168
  const display = displayRpc.getProxy(fusedDisplayService, { transfer: (member, args) => member === "attachAudio" ? [args[0]] : [] });
169
169
  const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) => options.onDiagnostic?.(diagnostic));
170
170
  subscriptions.push(simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)), display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)));
@@ -552,6 +552,122 @@ function createHostModelRouter(proxy) {
552
552
  };
553
553
  }
554
554
  //#endregion
555
+ //#region src/fused/runtime/host/device-state.ts
556
+ var equal = (a, b) => a !== void 0 && a.length === b.length && a.every((value, index) => value === b[index]);
557
+ function createDeviceState(provider, document, report) {
558
+ const lifetime = new AbortController();
559
+ let active;
560
+ function failure(kind, instanceId, cause) {
561
+ const error = new FusedBridgeError(`device-state/${kind}-failed`, `Device state ${kind} for "${instanceId}": ${cause instanceof Error ? cause.message : String(cause)}`, { instanceId });
562
+ report({
563
+ code: error.code,
564
+ message: error.message,
565
+ instanceId
566
+ });
567
+ return error;
568
+ }
569
+ function startWrite(slot) {
570
+ if (slot.writing !== void 0) return slot.writing;
571
+ slot.writing = Promise.resolve().then(async () => {
572
+ while (slot.latest !== void 0 && !equal(slot.saved, slot.latest)) {
573
+ const snapshot = slot.latest;
574
+ try {
575
+ await provider.write(slot.key, snapshot.slice(), lifetime.signal);
576
+ } catch (cause) {
577
+ throw failure("write", slot.key.instanceId, cause);
578
+ }
579
+ slot.saved = snapshot;
580
+ }
581
+ }).finally(() => {
582
+ slot.writing = void 0;
583
+ });
584
+ return slot.writing;
585
+ }
586
+ function observe(slot, image, checkpoint = false) {
587
+ if (checkpoint && image instanceof Uint8Array && image.length === 0) return;
588
+ if (!(image instanceof Uint8Array) || image.length !== slot.request.byteLength) {
589
+ const error = failure("invalid", slot.key.instanceId, "Invalid image length or type");
590
+ if (checkpoint) throw error;
591
+ return;
592
+ }
593
+ if (equal(slot.latest ?? slot.saved, image)) return;
594
+ slot.latest = image.slice();
595
+ if (!checkpoint) startWrite(slot).catch(() => void 0);
596
+ }
597
+ return {
598
+ async read() {
599
+ const slots = /* @__PURE__ */ new Map();
600
+ for (const instance of document.instances) {
601
+ const version = document.dependencies[instance.device]?.version;
602
+ const binding = provider.bindings.find((entry) => entry.device === instance.device && entry.version === version);
603
+ if (binding === void 0) continue;
604
+ const { device, slot, formatVersion, byteLength, property, method, event } = binding;
605
+ const key = {
606
+ instanceId: instance.id,
607
+ device,
608
+ slot,
609
+ formatVersion
610
+ };
611
+ const bytes = await Promise.resolve().then(() => provider.read(key, lifetime.signal)).catch((cause) => {
612
+ throw failure("read", instance.id, cause);
613
+ });
614
+ if (bytes !== void 0 && (!(bytes instanceof Uint8Array) || bytes.length !== byteLength)) throw failure("invalid", instance.id, "Invalid image length or type");
615
+ const request = {
616
+ instanceId: instance.id,
617
+ property,
618
+ method,
619
+ event,
620
+ byteLength,
621
+ ...bytes === void 0 ? {} : { image: bytes.slice() }
622
+ };
623
+ slots.set(instance.id, {
624
+ key,
625
+ request,
626
+ saved: void 0,
627
+ latest: void 0,
628
+ writing: void 0
629
+ });
630
+ }
631
+ return {
632
+ slots,
633
+ requests: Array.from(slots.values(), (slot) => slot.request)
634
+ };
635
+ },
636
+ activate(generation, slots, baselines) {
637
+ for (const { instanceId, image } of baselines) {
638
+ const slot = slots.get(instanceId);
639
+ if (slot !== void 0) slot.saved = image.slice();
640
+ }
641
+ const previous = active;
642
+ active = {
643
+ generation,
644
+ slots
645
+ };
646
+ return () => {
647
+ active = previous;
648
+ };
649
+ },
650
+ event(event) {
651
+ if (active === void 0 || event.stateGeneration !== active.generation) return;
652
+ const slot = active.slots.get(event.instanceId);
653
+ if (slot?.request.event === event.event) observe(slot, event.payload.value);
654
+ },
655
+ async checkpoint(call) {
656
+ if (active === void 0) return;
657
+ const slots = [...active.slots.values()];
658
+ if (call !== void 0) for (const slot of slots) observe(slot, await call(slot.key.instanceId, slot.request.method), true);
659
+ const results = await Promise.allSettled(slots.map(startWrite));
660
+ for (const result of results) if (result.status === "rejected") throw result.reason;
661
+ },
662
+ clear() {
663
+ active = void 0;
664
+ },
665
+ dispose() {
666
+ lifetime.abort();
667
+ }
668
+ };
669
+ }
670
+ //#endregion
555
671
  //#region src/fused/runtime/host/runtime.ts
556
672
  /**
557
673
  * Fused editor runtime bridge of one workbench (RFC 0025).
@@ -568,7 +684,7 @@ var IDLE$1 = Object.freeze({
568
684
  });
569
685
  /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
570
686
  async function createFusedRuntime(options) {
571
- const workers = options.workers ?? (await import("./workers-Og_Z_xzw.js")).fusedWorkerFactories;
687
+ const workers = options.workers ?? (await import("./workers-c759BKce.js")).fusedWorkerFactories;
572
688
  const diagnostics = new Emitter();
573
689
  const overlays = new Emitter();
574
690
  const states = new Emitter();
@@ -602,6 +718,15 @@ async function createFusedRuntime(options) {
602
718
  let closed = false;
603
719
  let disposal;
604
720
  const clients = /* @__PURE__ */ new Map();
721
+ const deviceState = options.deviceStateProvider === void 0 ? void 0 : createDeviceState(options.deviceStateProvider, options.document, report);
722
+ const stopDeviceState = deviceState === void 0 ? void 0 : connection.simulation.onDidModelEvent(deviceState.event);
723
+ let controls = Promise.resolve();
724
+ function control(action) {
725
+ if (deviceState === void 0) return action();
726
+ const next = controls.then(action);
727
+ controls = next.catch(() => void 0);
728
+ return next;
729
+ }
605
730
  const stopState = connection.simulation.onDidChangeState((next) => setState(next));
606
731
  /**
607
732
  * 宿主能主动报告产物变化时按通知作废缓存;没有这条通道时退回「每次进入运行前重新解析」,
@@ -618,12 +743,12 @@ async function createFusedRuntime(options) {
618
743
  onDidRenderOverlay: overlays.event,
619
744
  getModel,
620
745
  display: displayHost.display,
621
- prepareDisplay,
746
+ prepareDisplay: (input) => control(() => prepareDisplay(input)),
622
747
  warmup,
623
- resume,
624
- pause,
625
- step,
626
- reset,
748
+ resume: () => control(resume),
749
+ pause: () => control(pause),
750
+ step: () => control(step),
751
+ reset: () => control(reset),
627
752
  dispose
628
753
  };
629
754
  try {
@@ -664,30 +789,47 @@ async function createFusedRuntime(options) {
664
789
  connection.audio.suspend();
665
790
  connection.audio.clear();
666
791
  const current = () => !closed && attempt === preparation;
792
+ if (mode === "run" && deviceState !== void 0) await pause();
793
+ if (!current()) return prepared;
667
794
  if (input.mode === "run" && stopProgramChanges === void 0) await mapWireFailure(() => connection.simulation.invalidatePrograms());
795
+ const boot = input.mode === "run" ? await deviceState?.read() : void 0;
796
+ if (!current()) return prepared;
668
797
  const described = await mapWireFailure(() => connection.simulation.prepare({
669
798
  document: options.document,
670
- mode: input.mode
799
+ mode: input.mode,
800
+ ...boot === void 0 ? {} : { deviceState: boot.requests.map(copyImage) }
671
801
  }));
672
802
  if (!current()) return prepared;
673
803
  if (input.mode === "edit") {
674
804
  await mapWireFailure(() => connection.simulation.dispose());
675
805
  if (!current()) return prepared;
806
+ deviceState?.clear();
676
807
  }
677
808
  await displayHost.prepare({ mode: input.mode }, described.instances);
678
809
  if (!current()) return prepared;
679
- if (input.mode === "run") try {
680
- const loaded = await mapWireFailure(() => connection.simulation.load({
681
- document: options.document,
682
- step: options.step,
683
- ...options.simulationPacing === void 0 ? {} : { simulationPacing: options.simulationPacing },
684
- ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
685
- }));
686
- if (!current()) return prepared;
687
- setState(loaded);
688
- } catch (cause) {
689
- await displayHost.prepare({ mode: input.mode }, []).catch(() => void 0);
690
- throw cause;
810
+ if (input.mode === "run") {
811
+ const rollback = boot === void 0 ? void 0 : deviceState?.activate(attempt, boot.slots, described.deviceState ?? []);
812
+ try {
813
+ const loaded = await mapWireFailure(() => connection.simulation.load({
814
+ document: options.document,
815
+ step: options.step,
816
+ ...boot === void 0 ? {} : {
817
+ deviceState: boot.requests.map(copyImage),
818
+ stateGeneration: attempt
819
+ },
820
+ ...options.simulationPacing === void 0 ? {} : { simulationPacing: options.simulationPacing },
821
+ ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
822
+ }));
823
+ if (!current()) return prepared;
824
+ setState(loaded);
825
+ } catch (cause) {
826
+ if (current()) rollback?.();
827
+ if (current()) {
828
+ await displayHost.prepare({ mode: mode ?? input.mode }, prepared).catch(() => void 0);
829
+ if (mode === "run") await displayHost.activate().catch(() => void 0);
830
+ }
831
+ throw cause;
832
+ }
691
833
  }
692
834
  prepared = described.instances;
693
835
  mode = input.mode;
@@ -720,6 +862,7 @@ async function createFusedRuntime(options) {
720
862
  async function pause() {
721
863
  if (closed || mode !== "run") return;
722
864
  await mapWireFailure(() => connection.simulation.pause());
865
+ await deviceState?.checkpoint(state.status === "faulted" ? void 0 : (id, method) => mapWireFailure(() => connection.simulation.call(id, method, null)));
723
866
  }
724
867
  async function step() {
725
868
  assertRun("step");
@@ -727,6 +870,10 @@ async function createFusedRuntime(options) {
727
870
  }
728
871
  async function reset() {
729
872
  assertRun("reset");
873
+ if (deviceState !== void 0) {
874
+ await prepareDisplay({ mode: "run" });
875
+ return;
876
+ }
730
877
  connection.audio.suspend();
731
878
  connection.audio.clear();
732
879
  const attempt = ++preparation;
@@ -744,9 +891,12 @@ async function createFusedRuntime(options) {
744
891
  }
745
892
  function dispose() {
746
893
  if (disposal !== void 0) return disposal;
747
- closed = true;
748
- connection.audio.dispose();
749
- disposal = (async () => {
894
+ disposal = control(async () => {
895
+ if (deviceState !== void 0) await pause();
896
+ closed = true;
897
+ connection.audio.dispose();
898
+ stopDeviceState?.();
899
+ deviceState?.dispose();
750
900
  const problems = [];
751
901
  try {
752
902
  await displayHost.dispose();
@@ -778,10 +928,19 @@ async function createFusedRuntime(options) {
778
928
  diagnostics.dispose();
779
929
  overlays.dispose();
780
930
  if (problems.length > 0) throw new AggregateError(problems, "The fused runtime failed to release every resource.");
781
- })();
931
+ }).catch((cause) => {
932
+ if (!closed) disposal = void 0;
933
+ throw cause;
934
+ });
782
935
  return disposal;
783
936
  }
784
937
  }
938
+ function copyImage(entry) {
939
+ return entry.image === void 0 ? entry : {
940
+ ...entry,
941
+ image: entry.image.slice()
942
+ };
943
+ }
785
944
  //#endregion
786
945
  //#region src/fused/runtime/values.ts
787
946
  /**
@@ -1107,8 +1266,10 @@ function startFusedSimulationGuest(port, options = {}) {
1107
1266
  const document = parseFusedDocument(request.document);
1108
1267
  const problems = [];
1109
1268
  const instances = [];
1269
+ const stateImages = new Map(request.deviceState?.map((image) => [image.instanceId, image]));
1270
+ const deviceState = [];
1110
1271
  for (const [index, instance] of document.instances.entries()) try {
1111
- const described = await describeInstance(index, document, instance);
1272
+ const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState);
1112
1273
  if (described !== void 0) instances.push(described);
1113
1274
  } catch (cause) {
1114
1275
  if (cause instanceof FusedBridgeError && cause.code === "runtime/presentation-failed") {
@@ -1127,9 +1288,12 @@ function startFusedSimulationGuest(port, options = {}) {
1127
1288
  }
1128
1289
  for (const problem of problems) report(problem);
1129
1290
  if (problems.length > 0) throw toWireFailure(new FusedBridgeError("runtime/prepare-failed", `${problems.length} instance(s) cannot join the 2D scene.`));
1130
- return { instances };
1291
+ return {
1292
+ instances,
1293
+ ...request.deviceState === void 0 ? {} : { deviceState }
1294
+ };
1131
1295
  }
1132
- async function describeInstance(index, document, instance) {
1296
+ async function describeInstance(index, document, instance, stateImage, deviceState) {
1133
1297
  const dependency = document.dependencies[instance.device];
1134
1298
  if (dependency === void 0) throw new FusedBridgeError("document/unlocked-device", `Instance "${instance.id}" uses the unlocked device "${instance.device}".`, { instanceId: instance.id });
1135
1299
  const lock = {
@@ -1138,6 +1302,26 @@ function startFusedSimulationGuest(port, options = {}) {
1138
1302
  integrity: dependency.integrity
1139
1303
  };
1140
1304
  const verified = await openVerifiedPackage(lock);
1305
+ const descriptors = verified.manifest.properties ?? {};
1306
+ let props;
1307
+ if (stateImage !== void 0) {
1308
+ const method = verified.manifest.model?.methods?.[stateImage.method];
1309
+ const event = verified.manifest.model?.events?.[stateImage.event];
1310
+ if (descriptors[stateImage.property]?.type !== "binary" || method === void 0 || !("type" in method.params) || method.params.type !== "null" || !("type" in method.returns) || method.returns.type !== "binary" || event === void 0 || !("type" in event) || event.type !== "binary") throw new Error(`Invalid device state binding for "${instance.id}".`);
1311
+ const override = stateImage.image;
1312
+ try {
1313
+ props = await resolvePresentationProps(verified, descriptors, instance, index, override === void 0 ? void 0 : /* @__PURE__ */ new Map([[stateImage.property, override]]));
1314
+ } catch (cause) {
1315
+ throw new Error(`Could not resolve the state seed for "${instance.id}": ${messageOf(cause)}`, { cause });
1316
+ }
1317
+ const value = props[stateImage.property];
1318
+ const image = value === null ? new Uint8Array(stateImage.byteLength) : value.slice();
1319
+ if (image.length !== stateImage.byteLength) throw new Error(`Invalid device state image length for "${instance.id}".`);
1320
+ deviceState.push({
1321
+ instanceId: instance.id,
1322
+ image
1323
+ });
1324
+ }
1141
1325
  const view = verified.manifest.view2d;
1142
1326
  if (view === void 0) {
1143
1327
  report({
@@ -1149,14 +1333,13 @@ function startFusedSimulationGuest(port, options = {}) {
1149
1333
  }
1150
1334
  const pins = Object.keys(verified.manifest.pins ?? {});
1151
1335
  const geometryValue = typeof view.geometry === "string" ? parseStrictJson(decodeSource(await verified.read(view.geometry))) : view.geometry;
1152
- const descriptors = verified.manifest.properties ?? {};
1153
1336
  return {
1154
1337
  instanceId: instance.id,
1155
1338
  device: instance.device,
1156
1339
  lock,
1157
1340
  geometry: parseGeometry2D(geometryValue, pins),
1158
1341
  view: view.entry,
1159
- props: presentationProps(await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1342
+ props: presentationProps(props ?? await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1160
1343
  methods: Object.keys(verified.manifest.model?.methods ?? {}),
1161
1344
  events: Object.keys(verified.manifest.model?.events ?? {})
1162
1345
  };
@@ -1168,13 +1351,14 @@ function startFusedSimulationGuest(port, options = {}) {
1168
1351
  *
1169
1352
  * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.
1170
1353
  */
1171
- async function resolvePresentationProps(verified, descriptors, instance, index) {
1354
+ async function resolvePresentationProps(verified, descriptors, instance, index, binaryOverrides) {
1172
1355
  try {
1173
1356
  return (await resolveInstanceProperties({
1174
1357
  instanceId: instance.id,
1175
1358
  package: verified,
1176
1359
  descriptors,
1177
1360
  overrides: instance.properties ?? {},
1361
+ ...binaryOverrides === void 0 ? {} : { binaryOverrides },
1178
1362
  irProperties: /* @__PURE__ */ new Map(),
1179
1363
  pointer: [
1180
1364
  "instances",
@@ -1253,6 +1437,8 @@ function startFusedSimulationGuest(port, options = {}) {
1253
1437
  const pending = [];
1254
1438
  let created;
1255
1439
  try {
1440
+ const binaryOverrides = /* @__PURE__ */ new Map();
1441
+ for (const entry of request.deviceState ?? []) if (entry.image !== void 0) binaryOverrides.set(entry.instanceId, /* @__PURE__ */ new Map([[entry.property, entry.image]]));
1256
1442
  created = await createHeadlessRuntime({
1257
1443
  document,
1258
1444
  registry: verifiedRegistry,
@@ -1260,9 +1446,10 @@ function startFusedSimulationGuest(port, options = {}) {
1260
1446
  step,
1261
1447
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
1262
1448
  resolveResource: resources.resolveResource,
1449
+ ...binaryOverrides.size === 0 ? {} : { binaryOverrides },
1263
1450
  programs: resources.programs,
1264
1451
  onModelEvent: (event) => {
1265
- if (sessionToken === token) publishModelEvent(event);
1452
+ if (sessionToken === token) publishModelEvent(event, request.stateGeneration);
1266
1453
  else if (!superseded()) pending.push(event);
1267
1454
  },
1268
1455
  onDiagnostic: (entry) => {
@@ -1297,7 +1484,7 @@ function startFusedSimulationGuest(port, options = {}) {
1297
1484
  })]
1298
1485
  };
1299
1486
  session = adopted;
1300
- for (const event of pending.splice(0)) publishModelEvent(event);
1487
+ for (const event of pending.splice(0)) publishModelEvent(event, request.stateGeneration);
1301
1488
  const initial = created.getState();
1302
1489
  setState({
1303
1490
  status: initial.status,
@@ -1471,11 +1658,12 @@ function startFusedSimulationGuest(port, options = {}) {
1471
1658
  if (strict) throw toWireFailure(cause);
1472
1659
  }
1473
1660
  }
1474
- function publishModelEvent(event) {
1661
+ function publishModelEvent(event, stateGeneration) {
1475
1662
  const wire = {
1476
1663
  instanceId: event.instanceId,
1477
1664
  event: event.event,
1478
- payload: event.payload
1665
+ payload: event.payload,
1666
+ ...stateGeneration === void 0 ? {} : { stateGeneration }
1479
1667
  };
1480
1668
  modelChannel?.deliver(wire);
1481
1669
  events.fire(wire);
@@ -2011,10 +2199,10 @@ function closeBitmap(bitmap) {
2011
2199
  * same factories to several runtimes.
2012
2200
  */
2013
2201
  async function loadFusedWorkerFactories() {
2014
- const { fusedWorkerFactories } = await import("./workers-Og_Z_xzw.js");
2202
+ const { fusedWorkerFactories } = await import("./workers-c759BKce.js");
2015
2203
  return fusedWorkerFactories;
2016
2204
  }
2017
2205
  //#endregion
2018
2206
  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 };
2019
2207
 
2020
- //# sourceMappingURL=runtime-hyeAcSP7.js.map
2208
+ //# sourceMappingURL=runtime-_9IqvWDa.js.map