@mica-js/editor 0.10.0 → 0.11.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.
@@ -564,7 +564,7 @@ var IDLE$1 = Object.freeze({
564
564
  });
565
565
  /** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */
566
566
  async function createFusedRuntime(options) {
567
- const workers = options.workers ?? (await import("./workers-DZvIeUV2.js")).fusedWorkerFactories;
567
+ const workers = options.workers ?? (await import("./workers-BCTUbUqo.js")).fusedWorkerFactories;
568
568
  const diagnostics = new Emitter();
569
569
  const overlays = new Emitter();
570
570
  const states = new Emitter();
@@ -608,6 +608,7 @@ async function createFusedRuntime(options) {
608
608
  getModel,
609
609
  display: displayHost.display,
610
610
  prepareDisplay,
611
+ warmup,
611
612
  resume,
612
613
  pause,
613
614
  step,
@@ -685,6 +686,21 @@ async function createFusedRuntime(options) {
685
686
  if (input.mode === "run") await mapWireFailure(() => connection.simulation.resume());
686
687
  return prepared;
687
688
  }
689
+ /**
690
+ * Translates the boot path in the background, for a run the user has not started yet.
691
+ *
692
+ * Only meaningful in edit mode: a mounted run session is already translated. The guest releases
693
+ * the throwaway session it builds, so nothing of it survives except the generated code.
694
+ */
695
+ async function warmup() {
696
+ assertOpen();
697
+ if (mode !== "edit") return;
698
+ await mapWireFailure(() => connection.simulation.warmup({
699
+ document: options.document,
700
+ step: options.step,
701
+ ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
702
+ }));
703
+ }
688
704
  async function resume() {
689
705
  assertRun("resume");
690
706
  await mapWireFailure(() => connection.simulation.resume());
@@ -968,11 +984,42 @@ var PS_PER_MS = toTimePs(1, "ms");
968
984
  var SLICE_MS = 4;
969
985
  var MAX_CATCH_UP_MS = 50;
970
986
  var MAX_STEPS_PER_SLICE = 2048;
987
+ /**
988
+ * 首个固定步要把整段启动路径翻译成 JS,可能要数秒。长步长的首步被切成这么多份,
989
+ * 每份之间回到事件循环:宿主可以在启动期间停止,界面也能报告进度。
990
+ */
991
+ var BOOT_SLICES = 16;
992
+ /** 低于这个步长时首步覆盖的代码太少,切片只增加开销。 */
993
+ var BOOT_SLICE_MIN_STEP = toTimePs(1, "ms");
994
+ /** 预热同样切片,好让真实的准备与装载插进来并立即取消它。 */
995
+ var WARMUP_SLICES = 8;
971
996
  /** Starts the simulation guest on the startup port of a sandbox worker. */
972
997
  function startFusedSimulationGuest(port, options = {}) {
973
998
  const endpoint = (options.createEndpoint ?? createRpc)(port);
974
999
  const importModule = options.importModule ?? importCode;
975
1000
  const packages = createHostPackageGateway(endpoint);
1001
+ /** 已校验的器件包与已求值的模块都按发布身份缓存:同一 realm 里的下一次 load 直接复用。 */
1002
+ const openedPackages = /* @__PURE__ */ new Map();
1003
+ const openedModules = /* @__PURE__ */ new Map();
1004
+ /**
1005
+ * 校验并缓存一个发布。
1006
+ *
1007
+ * 校验结论只取决于宿主交来的字节,而宿主按发布身份缓存字节,所以同一 lock 在
1008
+ * 一个 realm 里只需要校验一次。
1009
+ */
1010
+ function openVerifiedPackage(lock) {
1011
+ const key = packageLockKey(lock);
1012
+ const cached = openedPackages.get(key);
1013
+ if (cached !== void 0) return cached;
1014
+ const pending = openDevicePackage(packages, lock);
1015
+ openedPackages.set(key, pending);
1016
+ pending.catch(() => {
1017
+ if (openedPackages.get(key) === pending) openedPackages.delete(key);
1018
+ });
1019
+ return pending;
1020
+ }
1021
+ /** 校验接口原样交给运行时,避免它把同一份发布再校验一遍。 */
1022
+ const verifiedRegistry = { open: (lock) => openVerifiedPackage(lock).then((entry) => entry.source) };
976
1023
  const resources = createResourceGateway(endpoint);
977
1024
  const diagnostics = new Emitter();
978
1025
  const states = new Emitter();
@@ -985,11 +1032,15 @@ function startFusedSimulationGuest(port, options = {}) {
985
1032
  let sessionToken;
986
1033
  /** Incremented by every session transition, so late results of a replaced session are dropped. */
987
1034
  let sequence = 0;
1035
+ /** 递增即取消正在进行的预热;真实的准备与装载都会取消它。 */
1036
+ let warmupGeneration = 0;
1037
+ let warmupPending;
988
1038
  let closing = false;
989
1039
  let disposal;
990
1040
  endpoint.register(fusedSimulationService, {
991
1041
  prepare,
992
1042
  load,
1043
+ warmup,
993
1044
  step,
994
1045
  resume,
995
1046
  pause,
@@ -1032,6 +1083,7 @@ function startFusedSimulationGuest(port, options = {}) {
1032
1083
  }
1033
1084
  async function prepare(request) {
1034
1085
  assertOpen();
1086
+ cancelWarmup();
1035
1087
  const document = parseFusedDocument(request.document);
1036
1088
  const problems = [];
1037
1089
  const instances = [];
@@ -1065,7 +1117,7 @@ function startFusedSimulationGuest(port, options = {}) {
1065
1117
  version: dependency.version,
1066
1118
  integrity: dependency.integrity
1067
1119
  };
1068
- const verified = await openDevicePackage(packages, lock);
1120
+ const verified = await openVerifiedPackage(lock);
1069
1121
  const view = verified.manifest.view2d;
1070
1122
  if (view === void 0) {
1071
1123
  report({
@@ -1116,8 +1168,59 @@ function startFusedSimulationGuest(port, options = {}) {
1116
1168
  throw new FusedBridgeError("runtime/presentation-failed", `Presentation properties of "${instance.id}" cannot be resolved: ${describeProblems(cause, descriptors)}`, { instanceId: instance.id });
1117
1169
  }
1118
1170
  }
1171
+ /**
1172
+ * 在空闲时段先把启动路径翻译好。
1173
+ *
1174
+ * 首个固定步的翻译是廉价的生成代码 + 昂贵的 IR 处理,且生成的代码在同一 realm 内跨
1175
+ * JIT 注册复用;这里用一个临时会话把这段翻译做掉就释放,真实的运行随后只需重建模型。
1176
+ * 不发出状态与模型事件:预热不属于任何会话,用户看不到它。
1177
+ */
1178
+ async function warmup(request) {
1179
+ assertOpen();
1180
+ if (session !== void 0 || warmupPending !== void 0) return await warmupPending;
1181
+ const step = request.step;
1182
+ 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)}.`));
1183
+ const generation = ++warmupGeneration;
1184
+ const current = () => !closing && generation === warmupGeneration;
1185
+ const task = runWarmup(request, step, current).finally(() => {
1186
+ if (warmupPending === task) warmupPending = void 0;
1187
+ });
1188
+ warmupPending = task;
1189
+ return await task;
1190
+ }
1191
+ async function runWarmup(request, step, current) {
1192
+ let created;
1193
+ try {
1194
+ created = await createHeadlessRuntime({
1195
+ document: parseFusedDocument(request.document),
1196
+ registry: verifiedRegistry,
1197
+ loadModule,
1198
+ step,
1199
+ ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
1200
+ resolveResource: resources.resolveResource,
1201
+ programs: resources.programs,
1202
+ onModelEvent: () => {}
1203
+ });
1204
+ if (!current()) return;
1205
+ const slice = Math.floor(step / WARMUP_SLICES);
1206
+ for (let index = 1; index <= WARMUP_SLICES; index++) {
1207
+ if (!current()) return;
1208
+ const amount = index === WARMUP_SLICES ? step - slice * 7 : slice;
1209
+ await created.step(timePs(amount));
1210
+ if (index < WARMUP_SLICES) await yieldToHost();
1211
+ }
1212
+ } catch {} finally {
1213
+ if (created !== void 0) await created.dispose().catch(() => void 0);
1214
+ }
1215
+ }
1216
+ /** 取消在途的预热;切片之间会立即停下,已翻译的代码留在共享缓存里。 */
1217
+ function cancelWarmup() {
1218
+ warmupGeneration += 1;
1219
+ warmupPending = void 0;
1220
+ }
1119
1221
  async function load(request) {
1120
1222
  assertOpen();
1223
+ cancelWarmup();
1121
1224
  const step = request.step;
1122
1225
  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)}.`));
1123
1226
  const pacing = request.simulationPacing;
@@ -1132,7 +1235,7 @@ function startFusedSimulationGuest(port, options = {}) {
1132
1235
  try {
1133
1236
  created = await createHeadlessRuntime({
1134
1237
  document,
1135
- registry: packages,
1238
+ registry: verifiedRegistry,
1136
1239
  loadModule,
1137
1240
  step,
1138
1241
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
@@ -1196,18 +1299,34 @@ function startFusedSimulationGuest(port, options = {}) {
1196
1299
  const run = {
1197
1300
  wallStartMs: performance.now(),
1198
1301
  simStartPs: current.simTime,
1199
- timer: void 0
1302
+ timer: void 0,
1303
+ waiting: void 0
1200
1304
  };
1201
1305
  target.run = run;
1202
1306
  setState({
1203
- status: "running",
1307
+ status: "starting",
1204
1308
  simTime: current.simTime
1205
1309
  });
1206
- try {
1207
- await mapGuestCall(() => target.runtime.step());
1208
- } catch (cause) {
1209
- if (target.run === run) pause();
1210
- throw cause;
1310
+ run.timer = setTimeout(() => {
1311
+ run.timer = void 0;
1312
+ bootRun(target, run);
1313
+ }, 0);
1314
+ }
1315
+ /** 把首个固定步拆开执行,让启动期间的停止请求能在切片之间生效。 */
1316
+ async function bootRun(target, run) {
1317
+ const slices = target.step >= BOOT_SLICE_MIN_STEP ? BOOT_SLICES : 1;
1318
+ const slice = Math.floor(target.step / slices);
1319
+ for (let index = 1; index <= slices; index++) {
1320
+ if (target.run !== run) return;
1321
+ const amount = index === slices ? target.step - slice * (slices - 1) : slice;
1322
+ try {
1323
+ await target.runtime.step(timePs(amount));
1324
+ } catch {
1325
+ if (target.run === run) pause();
1326
+ return;
1327
+ }
1328
+ if (target.run !== run) return;
1329
+ if (index < slices) await yieldToSlice(run);
1211
1330
  }
1212
1331
  if (target.run !== run) return;
1213
1332
  run.wallStartMs = performance.now();
@@ -1218,6 +1337,17 @@ function startFusedSimulationGuest(port, options = {}) {
1218
1337
  });
1219
1338
  scheduleSlice(target, run, run.wallStartMs);
1220
1339
  }
1340
+ /** Returns to the event loop; `stopRun` resolves the same promise so a stop is immediate. */
1341
+ function yieldToSlice(run) {
1342
+ return new Promise((resolve) => {
1343
+ run.waiting = resolve;
1344
+ run.timer = setTimeout(() => {
1345
+ run.timer = void 0;
1346
+ run.waiting = void 0;
1347
+ resolve();
1348
+ }, 0);
1349
+ });
1350
+ }
1221
1351
  function scheduleSlice(target, run, lastStartedAt) {
1222
1352
  let delay = 0;
1223
1353
  if (target.pacing === "realtime") {
@@ -1265,8 +1395,14 @@ function startFusedSimulationGuest(port, options = {}) {
1265
1395
  scheduleSlice(target, run, startedAt);
1266
1396
  }
1267
1397
  function stopRun(target) {
1268
- clearTimeout(target.run?.timer);
1398
+ const run = target.run;
1269
1399
  target.run = void 0;
1400
+ if (run === void 0) return;
1401
+ clearTimeout(run.timer);
1402
+ run.timer = void 0;
1403
+ const waiting = run.waiting;
1404
+ run.waiting = void 0;
1405
+ waiting?.();
1270
1406
  }
1271
1407
  function pause() {
1272
1408
  if (session === void 0) return;
@@ -1324,8 +1460,22 @@ function startFusedSimulationGuest(port, options = {}) {
1324
1460
  modelChannel?.deliver(wire);
1325
1461
  events.fire(wire);
1326
1462
  }
1463
+ /**
1464
+ * 求值一个器件包模块,并按发布身份缓存结果。
1465
+ *
1466
+ * 每个模块都是一次 blob + `import()`,V8 要重新解析整份源码;同一 realm 里重复求值
1467
+ * 同一个发布没有意义,模块命名空间按 URL 缓存本来就是 ESM 的常规行为。
1468
+ */
1327
1469
  async function loadModule(files, path) {
1328
- return importModule(decodeSource(await files.read(path)));
1470
+ const key = `${packageLockKey(files.lock)}\u0000${path}`;
1471
+ const cached = openedModules.get(key);
1472
+ if (cached !== void 0) return await cached;
1473
+ const pending = files.read(path).then((bytes) => importModule(decodeSource(bytes)));
1474
+ openedModules.set(key, pending);
1475
+ pending.catch(() => {
1476
+ if (openedModules.get(key) === pending) openedModules.delete(key);
1477
+ });
1478
+ return await pending;
1329
1479
  }
1330
1480
  function dispose() {
1331
1481
  if (disposal !== void 0) return disposal;
@@ -1359,6 +1509,12 @@ async function mapGuestCall(run) {
1359
1509
  throw toWireFailure(cause);
1360
1510
  }
1361
1511
  }
1512
+ /** Returns to the event loop so a queued RPC request can run before the next slice. */
1513
+ function yieldToHost() {
1514
+ return new Promise((resolve) => {
1515
+ setTimeout(resolve, 0);
1516
+ });
1517
+ }
1362
1518
  /** Host resources the runtime pulls while it resolves instance properties. */
1363
1519
  function createResourceGateway(endpoint) {
1364
1520
  const host = endpoint.getProxy(fusedHostResourceService);
@@ -1825,10 +1981,10 @@ function closeBitmap(bitmap) {
1825
1981
  * same factories to several runtimes.
1826
1982
  */
1827
1983
  async function loadFusedWorkerFactories() {
1828
- const { fusedWorkerFactories } = await import("./workers-DZvIeUV2.js");
1984
+ const { fusedWorkerFactories } = await import("./workers-BCTUbUqo.js");
1829
1985
  return fusedWorkerFactories;
1830
1986
  }
1831
1987
  //#endregion
1832
1988
  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 };
1833
1989
 
1834
- //# sourceMappingURL=runtime-BrGlkcGO.js.map
1990
+ //# sourceMappingURL=runtime-DtM7aYdB.js.map