@mica-js/editor 0.15.0 → 0.16.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.
@@ -332,6 +332,10 @@ function registerHostServices(endpoint, options) {
332
332
  if (options.resolveResource === void 0) throw new Error(`No resource resolver is configured for ${request.instanceId}/${request.property}.`);
333
333
  return (await options.resolveResource(request)).slice();
334
334
  },
335
+ async writeDisk(assetId, bytes) {
336
+ if (options.writeDisk === void 0) throw new Error("No disk writer is configured.");
337
+ await options.writeDisk(assetId, bytes);
338
+ },
335
339
  async resolveProgramProject(id, target) {
336
340
  if (!options.programs?.projects) throw new Error("No program project provider configured.");
337
341
  const artifact = await options.programs.projects.resolve(id, target);
@@ -789,7 +793,7 @@ var nextRun = 0;
789
793
  var nextSession = 0;
790
794
  /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
791
795
  async function createFusedRuntime(options) {
792
- const workers = options.workers ?? (await import("./workers-BpHcfNEu.js")).fusedWorkerFactories;
796
+ const workers = options.workers ?? (await import("./workers-CazFr0iO.js")).fusedWorkerFactories;
793
797
  const diagnostics = new Emitter();
794
798
  const overlays = new Emitter();
795
799
  const states = new Emitter();
@@ -818,6 +822,7 @@ async function createFusedRuntime(options) {
818
822
  ...options.audio === void 0 ? {} : { audio: options.audio },
819
823
  ...options.container === void 0 ? {} : { container: options.container },
820
824
  ...options.resolveResource === void 0 ? {} : { resolveResource: options.resolveResource },
825
+ ...options.writeDisk === void 0 ? {} : { writeDisk: options.writeDisk },
821
826
  ...options.programs === void 0 ? {} : { programs: options.programs },
822
827
  onDiagnostic: report,
823
828
  ...observer === void 0 ? {} : { observability: {
@@ -1030,6 +1035,11 @@ async function createFusedRuntime(options) {
1030
1035
  const current = () => !closed && attempt === preparation;
1031
1036
  if (mode === "run" && deviceState !== void 0) await pause();
1032
1037
  if (!current()) return prepared;
1038
+ const releaseBeforePreparing = mode === "run" && options.writeDisk !== void 0;
1039
+ if (releaseBeforePreparing) {
1040
+ await mapWireFailure(() => connection.simulation.dispose());
1041
+ if (!current()) return prepared;
1042
+ }
1033
1043
  if (input.mode === "run" && stopProgramChanges === void 0) await mapWireFailure(() => connection.simulation.invalidatePrograms());
1034
1044
  const boot = input.mode === "run" ? await deviceState?.read() : void 0;
1035
1045
  if (!current()) return prepared;
@@ -1037,13 +1047,16 @@ async function createFusedRuntime(options) {
1037
1047
  const described = await mapWireFailure(() => connection.simulation.prepare({
1038
1048
  document: options.document,
1039
1049
  mode: input.mode,
1050
+ preparationId: attempt,
1040
1051
  ...context === void 0 ? {} : { observation: context },
1041
1052
  ...boot === void 0 ? {} : { deviceState: boot.requests.map(copyImage) }
1042
1053
  }));
1043
1054
  if (!current()) return prepared;
1044
1055
  if (input.mode === "edit") {
1045
- await mapWireFailure(() => connection.simulation.dispose());
1046
- if (!current()) return prepared;
1056
+ if (!releaseBeforePreparing) {
1057
+ await mapWireFailure(() => connection.simulation.dispose());
1058
+ if (!current()) return prepared;
1059
+ }
1047
1060
  deviceState?.clear();
1048
1061
  sessionId = void 0;
1049
1062
  runId = void 0;
@@ -1056,6 +1069,8 @@ async function createFusedRuntime(options) {
1056
1069
  const loaded = await mapWireFailure(() => connection.simulation.load({
1057
1070
  document: options.document,
1058
1071
  step: options.step,
1072
+ preparationId: attempt,
1073
+ writableDisks: options.writeDisk !== void 0,
1059
1074
  ...context === void 0 ? {} : { observation: context },
1060
1075
  ...boot === void 0 ? {} : {
1061
1076
  deviceState: boot.requests.map(copyImage),
@@ -1248,6 +1263,7 @@ function presentationProps(resolved, descriptors) {
1248
1263
  break;
1249
1264
  case "image":
1250
1265
  case "binary":
1266
+ case "disk":
1251
1267
  if (value === null) {
1252
1268
  props[name] = null;
1253
1269
  continue;
@@ -1525,6 +1541,7 @@ function startFusedSimulationGuest(port, options = {}) {
1525
1541
  return { open: (lock) => openVerifiedPackage(lock, context).then((entry) => entry.source) };
1526
1542
  }
1527
1543
  const resources = createResourceGateway(endpoint);
1544
+ let diskPreparation;
1528
1545
  const diagnostics = new Emitter();
1529
1546
  const states = new Emitter();
1530
1547
  const events = new Emitter();
@@ -1542,6 +1559,7 @@ function startFusedSimulationGuest(port, options = {}) {
1542
1559
  let warmupProgress = "not-started";
1543
1560
  let closing = false;
1544
1561
  let disposal;
1562
+ let releasing;
1545
1563
  endpoint.register(fusedSimulationService, {
1546
1564
  prepare,
1547
1565
  load: observedLoad,
@@ -1596,12 +1614,17 @@ function startFusedSimulationGuest(port, options = {}) {
1596
1614
  assertOpen();
1597
1615
  cancelWarmup();
1598
1616
  const document = parseFusedDocument(request.document);
1617
+ const resolveResource = resources.createScopedResolver();
1618
+ diskPreparation = request.mode === "run" && request.preparationId !== void 0 ? {
1619
+ id: request.preparationId,
1620
+ resolve: resolveResource
1621
+ } : void 0;
1599
1622
  const problems = [];
1600
1623
  const instances = [];
1601
1624
  const stateImages = new Map(request.deviceState?.map((image) => [image.instanceId, image]));
1602
1625
  const deviceState = [];
1603
1626
  for (const [index, instance] of document.instances.entries()) try {
1604
- const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState, request.observation);
1627
+ const described = await describeInstance(index, document, instance, stateImages.get(instance.id), deviceState, request.observation, resolveResource);
1605
1628
  if (described !== void 0) instances.push(described);
1606
1629
  } catch (cause) {
1607
1630
  if (cause instanceof FusedBridgeError && cause.code === "runtime/presentation-failed") {
@@ -1625,7 +1648,7 @@ function startFusedSimulationGuest(port, options = {}) {
1625
1648
  ...request.deviceState === void 0 ? {} : { deviceState }
1626
1649
  };
1627
1650
  }
1628
- async function describeInstance(index, document, instance, stateImage, deviceState, observation) {
1651
+ async function describeInstance(index, document, instance, stateImage, deviceState, observation, resolveResource) {
1629
1652
  const dependency = document.dependencies[instance.device];
1630
1653
  if (dependency === void 0) throw new FusedBridgeError("document/unlocked-device", `Instance "${instance.id}" uses the unlocked device "${instance.device}".`, { instanceId: instance.id });
1631
1654
  const lock = {
@@ -1642,7 +1665,7 @@ function startFusedSimulationGuest(port, options = {}) {
1642
1665
  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}".`);
1643
1666
  const override = stateImage.image;
1644
1667
  try {
1645
- props = await resolvePresentationProps(verified, descriptors, instance, index, override === void 0 ? void 0 : /* @__PURE__ */ new Map([[stateImage.property, override]]));
1668
+ props = await resolvePresentationProps(verified, descriptors, instance, index, resolveResource, override === void 0 ? void 0 : /* @__PURE__ */ new Map([[stateImage.property, override]]));
1646
1669
  } catch (cause) {
1647
1670
  throw new Error(`Could not resolve the state seed for "${instance.id}": ${messageOf(cause)}`, { cause });
1648
1671
  }
@@ -1671,7 +1694,7 @@ function startFusedSimulationGuest(port, options = {}) {
1671
1694
  lock,
1672
1695
  geometry: parseGeometry2D(geometryValue, pins),
1673
1696
  view: view.entry,
1674
- props: presentationProps(props ?? await resolvePresentationProps(verified, descriptors, instance, index), descriptors),
1697
+ props: presentationProps(props ?? await resolvePresentationProps(verified, descriptors, instance, index, resolveResource), descriptors),
1675
1698
  methods: Object.keys(verified.manifest.model?.methods ?? {}),
1676
1699
  events: Object.keys(verified.manifest.model?.events ?? {})
1677
1700
  };
@@ -1683,7 +1706,7 @@ function startFusedSimulationGuest(port, options = {}) {
1683
1706
  *
1684
1707
  * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.
1685
1708
  */
1686
- async function resolvePresentationProps(verified, descriptors, instance, index, binaryOverrides) {
1709
+ async function resolvePresentationProps(verified, descriptors, instance, index, resolveResource, binaryOverrides) {
1687
1710
  try {
1688
1711
  return (await resolveInstanceProperties({
1689
1712
  instanceId: instance.id,
@@ -1697,7 +1720,7 @@ function startFusedSimulationGuest(port, options = {}) {
1697
1720
  String(index),
1698
1721
  "properties"
1699
1722
  ],
1700
- resolveResource: resources.resolveResource,
1723
+ resolveResource,
1701
1724
  programs: resources.programs
1702
1725
  })).props;
1703
1726
  } catch (cause) {
@@ -1741,7 +1764,8 @@ function startFusedSimulationGuest(port, options = {}) {
1741
1764
  loadModule,
1742
1765
  step,
1743
1766
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
1744
- resolveResource: resources.resolveResource,
1767
+ resolveResource: resources.createScopedResolver(),
1768
+ writeDisk: async () => {},
1745
1769
  programs: resources.programs,
1746
1770
  onModelEvent: () => {}
1747
1771
  });
@@ -1759,7 +1783,7 @@ function startFusedSimulationGuest(port, options = {}) {
1759
1783
  } catch {
1760
1784
  return current() ? "failed" : "cancelled";
1761
1785
  } finally {
1762
- if (created !== void 0) await created.dispose().catch(() => void 0);
1786
+ if (created !== void 0) await created.dispose({ saveDisks: false }).catch(() => void 0);
1763
1787
  }
1764
1788
  }
1765
1789
  /** 取消在途的预热;切片之间会立即停下,已翻译的代码留在共享缓存里。 */
@@ -1810,6 +1834,8 @@ function startFusedSimulationGuest(port, options = {}) {
1810
1834
  const pacing = request.simulationPacing;
1811
1835
  if (pacing !== void 0 && pacing !== "realtime" && pacing !== "unlimited") throw toWireFailure(new FusedBridgeError("runtime/invalid-pacing", "Expected realtime or unlimited pacing."));
1812
1836
  const document = parseFusedDocument(request.document);
1837
+ const resolveResource = diskPreparation !== void 0 && diskPreparation.id === request.preparationId ? diskPreparation.resolve : resources.createScopedResolver();
1838
+ if (diskPreparation?.id === request.preparationId) diskPreparation = void 0;
1813
1839
  const attempt = ++sequence;
1814
1840
  const token = {};
1815
1841
  const superseded = () => closing || attempt !== sequence;
@@ -1825,8 +1851,9 @@ function startFusedSimulationGuest(port, options = {}) {
1825
1851
  loadModule,
1826
1852
  step,
1827
1853
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
1828
- resolveResource: resources.resolveResource,
1854
+ resolveResource,
1829
1855
  ...binaryOverrides.size === 0 ? {} : { binaryOverrides },
1856
+ ...request.writableDisks === true ? { writeDisk: resources.writeDisk } : {},
1830
1857
  programs: resources.programs,
1831
1858
  onModelEvent: (event) => {
1832
1859
  if (sessionToken === token) publishModelEvent(event, request.stateGeneration);
@@ -1841,7 +1868,7 @@ function startFusedSimulationGuest(port, options = {}) {
1841
1868
  throw toWireFailure(cause);
1842
1869
  }
1843
1870
  if (superseded()) {
1844
- await created.dispose().catch(() => void 0);
1871
+ await created.dispose({ saveDisks: false }).catch(() => void 0);
1845
1872
  return state;
1846
1873
  }
1847
1874
  const previous = session;
@@ -2070,9 +2097,17 @@ function startFusedSimulationGuest(port, options = {}) {
2070
2097
  session = void 0;
2071
2098
  sessionToken = void 0;
2072
2099
  sequence += 1;
2100
+ diskPreparation = void 0;
2073
2101
  modelChannel?.reset();
2074
2102
  setState(IDLE);
2075
- if (target !== void 0) await releaseSession(target, strict);
2103
+ if (target === void 0) return await releasing;
2104
+ const release = releaseSession(target, strict);
2105
+ releasing = release;
2106
+ try {
2107
+ await release;
2108
+ } finally {
2109
+ if (releasing === release) releasing = void 0;
2110
+ }
2076
2111
  }
2077
2112
  async function releaseSession(target, strict) {
2078
2113
  stopRun(target);
@@ -2124,6 +2159,11 @@ function startFusedSimulationGuest(port, options = {}) {
2124
2159
  session = void 0;
2125
2160
  sessionToken = void 0;
2126
2161
  const problems = [];
2162
+ try {
2163
+ await releasing;
2164
+ } catch (cause) {
2165
+ problems.push(cause);
2166
+ }
2127
2167
  if (target !== void 0) try {
2128
2168
  await releaseSession(target, true);
2129
2169
  } catch (cause) {
@@ -2154,7 +2194,7 @@ function yieldToHost() {
2154
2194
  }
2155
2195
  /** Host resources the runtime pulls while it resolves instance properties. */
2156
2196
  function createResourceGateway(endpoint) {
2157
- const host = endpoint.getProxy(fusedHostResourceService);
2197
+ const host = endpoint.getProxy(fusedHostResourceService, { transfer: (member, args) => member === "writeDisk" && args[1] instanceof Uint8Array ? [args[1].buffer] : [] });
2158
2198
  const resources = /* @__PURE__ */ new Map();
2159
2199
  const programs = /* @__PURE__ */ new Map();
2160
2200
  const copyFiles = (files) => files.map((file) => ({
@@ -2186,14 +2226,27 @@ function createResourceGateway(endpoint) {
2186
2226
  });
2187
2227
  return copyArtifact(artifact);
2188
2228
  } } },
2189
- resolveResource: async (request) => {
2190
- const key = `${request.instanceId}\u0000${request.property}`;
2191
- const cached = resources.get(key);
2192
- if (cached !== void 0) return cached.slice();
2193
- const bytes = await host.readResource(request);
2194
- resources.set(key, bytes.slice());
2195
- return bytes;
2229
+ createScopedResolver() {
2230
+ const diskAssets = /* @__PURE__ */ new Map();
2231
+ return async (request) => {
2232
+ if (request.kind === "disk" && request.reference.mode === "asset") {
2233
+ const key = request.reference.assetId;
2234
+ let pending = diskAssets.get(key);
2235
+ if (pending === void 0) {
2236
+ pending = host.readResource(request);
2237
+ diskAssets.set(key, pending);
2238
+ }
2239
+ return (await pending).slice();
2240
+ }
2241
+ const key = `${request.instanceId}\u0000${request.property}`;
2242
+ const cached = resources.get(key);
2243
+ if (cached !== void 0) return cached.slice();
2244
+ const bytes = await host.readResource(request);
2245
+ resources.set(key, bytes.slice());
2246
+ return bytes;
2247
+ };
2196
2248
  },
2249
+ writeDisk: (assetId, bytes) => host.writeDisk(assetId, bytes),
2197
2250
  invalidatePrograms(projectId, fingerprint) {
2198
2251
  for (const [key, cached] of programs) {
2199
2252
  if (projectId !== void 0 && cached.projectId !== projectId) continue;
@@ -2628,10 +2681,10 @@ function closeBitmap(bitmap) {
2628
2681
  * same factories to several runtimes.
2629
2682
  */
2630
2683
  async function loadFusedWorkerFactories() {
2631
- const { fusedWorkerFactories } = await import("./workers-BpHcfNEu.js");
2684
+ const { fusedWorkerFactories } = await import("./workers-CazFr0iO.js");
2632
2685
  return fusedWorkerFactories;
2633
2686
  }
2634
2687
  //#endregion
2635
2688
  export { fusedSimulationService as S, fusedDisplayService as _, createFusedRuntime as a, fusedModelChannelService as b, createModelEventRouter as c, loggedStartupFailures as d, summarizeStartup as f, packageLockKey as g, createHostPackageGateway as h, startFusedSimulationGuest as i, createFusedDisplay as l, writeWorkbenchConsole as m, startFusedDisplayGuest as n, createHostModelRouter as o, writeFusedLog as p, createViewSession as r, channelKey as s, loadFusedWorkerFactories as t, connectFusedWorkbench as u, fusedHostPackageService as v, fusedModelSinkService as x, fusedHostResourceService as y };
2636
2689
 
2637
- //# sourceMappingURL=runtime-DuxZ_yVl.js.map
2690
+ //# sourceMappingURL=runtime-DuYOb1Tc.js.map