@mica-js/editor 0.9.4 → 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.
@@ -1,6 +1,6 @@
1
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
2
  import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
3
- import { timePs } from "@mica-js/core";
3
+ import { timePs, toTimePs } from "@mica-js/core";
4
4
  import { parseFusedDocument, parseGeometry2D, parseStrictJson } from "@mica-js/document/fused";
5
5
  import { FusedPreparationError, PreparationError, createHeadlessRuntime, createProgramFiles, openDevicePackage, readonlyBytes, resolveInstanceProperties } from "@mica-js/sdk/fused";
6
6
  import { createRpc, defineRpcService } from "@mica-js/core/rpc";
@@ -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-BMFz2OCK.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,
@@ -667,6 +668,7 @@ async function createFusedRuntime(options) {
667
668
  const loaded = await mapWireFailure(() => connection.simulation.load({
668
669
  document: options.document,
669
670
  step: options.step,
671
+ ...options.simulationPacing === void 0 ? {} : { simulationPacing: options.simulationPacing },
670
672
  ...options.batchExecution === void 0 ? {} : { batchExecution: options.batchExecution }
671
673
  }));
672
674
  if (!current()) return prepared;
@@ -684,6 +686,21 @@ async function createFusedRuntime(options) {
684
686
  if (input.mode === "run") await mapWireFailure(() => connection.simulation.resume());
685
687
  return prepared;
686
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
+ }
687
704
  async function resume() {
688
705
  assertRun("resume");
689
706
  await mapWireFailure(() => connection.simulation.resume());
@@ -963,11 +980,46 @@ var IDLE = Object.freeze({
963
980
  status: "idle",
964
981
  simTime: timePs(0)
965
982
  });
983
+ var PS_PER_MS = toTimePs(1, "ms");
984
+ var SLICE_MS = 4;
985
+ var MAX_CATCH_UP_MS = 50;
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;
966
996
  /** Starts the simulation guest on the startup port of a sandbox worker. */
967
997
  function startFusedSimulationGuest(port, options = {}) {
968
998
  const endpoint = (options.createEndpoint ?? createRpc)(port);
969
999
  const importModule = options.importModule ?? importCode;
970
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) };
971
1023
  const resources = createResourceGateway(endpoint);
972
1024
  const diagnostics = new Emitter();
973
1025
  const states = new Emitter();
@@ -980,11 +1032,15 @@ function startFusedSimulationGuest(port, options = {}) {
980
1032
  let sessionToken;
981
1033
  /** Incremented by every session transition, so late results of a replaced session are dropped. */
982
1034
  let sequence = 0;
1035
+ /** 递增即取消正在进行的预热;真实的准备与装载都会取消它。 */
1036
+ let warmupGeneration = 0;
1037
+ let warmupPending;
983
1038
  let closing = false;
984
1039
  let disposal;
985
1040
  endpoint.register(fusedSimulationService, {
986
1041
  prepare,
987
1042
  load,
1043
+ warmup,
988
1044
  step,
989
1045
  resume,
990
1046
  pause,
@@ -1027,6 +1083,7 @@ function startFusedSimulationGuest(port, options = {}) {
1027
1083
  }
1028
1084
  async function prepare(request) {
1029
1085
  assertOpen();
1086
+ cancelWarmup();
1030
1087
  const document = parseFusedDocument(request.document);
1031
1088
  const problems = [];
1032
1089
  const instances = [];
@@ -1060,7 +1117,7 @@ function startFusedSimulationGuest(port, options = {}) {
1060
1117
  version: dependency.version,
1061
1118
  integrity: dependency.integrity
1062
1119
  };
1063
- const verified = await openDevicePackage(packages, lock);
1120
+ const verified = await openVerifiedPackage(lock);
1064
1121
  const view = verified.manifest.view2d;
1065
1122
  if (view === void 0) {
1066
1123
  report({
@@ -1111,10 +1168,63 @@ function startFusedSimulationGuest(port, options = {}) {
1111
1168
  throw new FusedBridgeError("runtime/presentation-failed", `Presentation properties of "${instance.id}" cannot be resolved: ${describeProblems(cause, descriptors)}`, { instanceId: instance.id });
1112
1169
  }
1113
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
+ }
1114
1221
  async function load(request) {
1115
1222
  assertOpen();
1223
+ cancelWarmup();
1116
1224
  const step = request.step;
1117
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)}.`));
1226
+ const pacing = request.simulationPacing;
1227
+ if (pacing !== void 0 && pacing !== "realtime" && pacing !== "unlimited") throw toWireFailure(new FusedBridgeError("runtime/invalid-pacing", "Expected realtime or unlimited pacing."));
1118
1228
  const document = parseFusedDocument(request.document);
1119
1229
  const attempt = ++sequence;
1120
1230
  const token = {};
@@ -1125,7 +1235,7 @@ function startFusedSimulationGuest(port, options = {}) {
1125
1235
  try {
1126
1236
  created = await createHeadlessRuntime({
1127
1237
  document,
1128
- registry: packages,
1238
+ registry: verifiedRegistry,
1129
1239
  loadModule,
1130
1240
  step,
1131
1241
  ...request.batchExecution === void 0 ? {} : { batchExecution: request.batchExecution },
@@ -1152,17 +1262,21 @@ function startFusedSimulationGuest(port, options = {}) {
1152
1262
  sessionToken = void 0;
1153
1263
  if (previous !== void 0) await releaseSession(previous, false);
1154
1264
  sessionToken = token;
1155
- session = {
1265
+ const adopted = {
1156
1266
  runtime: created,
1267
+ step,
1268
+ pacing: pacing ?? "unlimited",
1269
+ run: void 0,
1157
1270
  subscriptions: [created.onDidChangeState((next) => {
1158
- if (sessionToken === token) setState({
1159
- status: next.status,
1160
- simTime: next.simTime
1161
- });
1271
+ if (sessionToken !== token) return;
1272
+ if (next.status === "paused" && adopted.run !== void 0) return;
1273
+ stopRun(adopted);
1274
+ setState(next);
1162
1275
  }), created.onDidReportDiagnostic((entry) => {
1163
1276
  if (sessionToken === token) report(entry);
1164
1277
  })]
1165
1278
  };
1279
+ session = adopted;
1166
1280
  for (const event of pending.splice(0)) publishModelEvent(event);
1167
1281
  const initial = created.getState();
1168
1282
  setState({
@@ -1173,18 +1287,131 @@ function startFusedSimulationGuest(port, options = {}) {
1173
1287
  }
1174
1288
  async function step() {
1175
1289
  const target = requireSession("step");
1290
+ if (target.run !== void 0) throw toWireFailure(new FusedBridgeError("runtime/unavailable-state", "step requires the paused state; pause the runtime first."));
1176
1291
  await mapGuestCall(() => target.runtime.step());
1177
1292
  return state;
1178
1293
  }
1179
1294
  async function resume() {
1180
1295
  const target = requireSession("resume");
1181
- await mapGuestCall(() => target.runtime.resume());
1296
+ if (target.run !== void 0) return;
1297
+ const current = target.runtime.getState();
1298
+ if (current.status === "faulted") throw toWireFailure(new FusedBridgeError("runtime/model-failed", "resume is not allowed while the runtime is faulted; call reset first."));
1299
+ const run = {
1300
+ wallStartMs: performance.now(),
1301
+ simStartPs: current.simTime,
1302
+ timer: void 0,
1303
+ waiting: void 0
1304
+ };
1305
+ target.run = run;
1306
+ setState({
1307
+ status: "starting",
1308
+ simTime: current.simTime
1309
+ });
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);
1330
+ }
1331
+ if (target.run !== run) return;
1332
+ run.wallStartMs = performance.now();
1333
+ run.simStartPs = target.runtime.getState().simTime;
1334
+ setState({
1335
+ status: "running",
1336
+ simTime: run.simStartPs
1337
+ });
1338
+ scheduleSlice(target, run, run.wallStartMs);
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
+ }
1351
+ function scheduleSlice(target, run, lastStartedAt) {
1352
+ let delay = 0;
1353
+ if (target.pacing === "realtime") {
1354
+ const nextPs = target.runtime.getState().simTime + target.step;
1355
+ const due = run.wallStartMs + (nextPs - run.simStartPs) / PS_PER_MS;
1356
+ delay = Math.max(0, Math.ceil(Math.max(due, lastStartedAt + SLICE_MS) - performance.now()));
1357
+ }
1358
+ run.timer = setTimeout(() => {
1359
+ run.timer = void 0;
1360
+ advanceSlice(target, run);
1361
+ }, delay);
1362
+ }
1363
+ async function advanceSlice(target, run) {
1364
+ if (target.run !== run) return;
1365
+ const startedAt = performance.now();
1366
+ const from = target.runtime.getState().simTime;
1367
+ let limit = from + target.step;
1368
+ if (target.pacing === "realtime") {
1369
+ let elapsedMs = startedAt - run.wallStartMs;
1370
+ const maxLagMs = Math.max(MAX_CATCH_UP_MS, target.step / PS_PER_MS);
1371
+ if (elapsedMs - (from - run.simStartPs) / PS_PER_MS > maxLagMs) {
1372
+ run.wallStartMs = startedAt - maxLagMs;
1373
+ run.simStartPs = from;
1374
+ elapsedMs = maxLagMs;
1375
+ }
1376
+ limit = run.simStartPs + Math.floor(elapsedMs * PS_PER_MS);
1377
+ }
1378
+ let simTime = from;
1379
+ try {
1380
+ for (let step = 0; step < MAX_STEPS_PER_SLICE && simTime + target.step <= limit; step++) {
1381
+ if (target.run !== run) return;
1382
+ await target.runtime.step();
1383
+ simTime += target.step;
1384
+ if (performance.now() - startedAt >= SLICE_MS) break;
1385
+ }
1386
+ } catch {
1387
+ if (target.run === run) pause();
1388
+ return;
1389
+ }
1390
+ if (target.run !== run) return;
1391
+ setState({
1392
+ status: "running",
1393
+ simTime: target.runtime.getState().simTime
1394
+ });
1395
+ scheduleSlice(target, run, startedAt);
1396
+ }
1397
+ function stopRun(target) {
1398
+ const run = target.run;
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?.();
1182
1406
  }
1183
1407
  function pause() {
1184
- session?.runtime.pause();
1408
+ if (session === void 0) return;
1409
+ stopRun(session);
1410
+ setState(session.runtime.getState());
1185
1411
  }
1186
1412
  async function reset() {
1187
1413
  const target = requireSession("reset");
1414
+ pause();
1188
1415
  await mapGuestCall(() => target.runtime.reset());
1189
1416
  }
1190
1417
  async function callModel(instanceId, method, params) {
@@ -1212,6 +1439,7 @@ function startFusedSimulationGuest(port, options = {}) {
1212
1439
  if (target !== void 0) await releaseSession(target, strict);
1213
1440
  }
1214
1441
  async function releaseSession(target, strict) {
1442
+ stopRun(target);
1215
1443
  for (const subscription of target.subscriptions.splice(0)) subscription.dispose();
1216
1444
  try {
1217
1445
  await target.runtime.dispose();
@@ -1232,8 +1460,22 @@ function startFusedSimulationGuest(port, options = {}) {
1232
1460
  modelChannel?.deliver(wire);
1233
1461
  events.fire(wire);
1234
1462
  }
1463
+ /**
1464
+ * 求值一个器件包模块,并按发布身份缓存结果。
1465
+ *
1466
+ * 每个模块都是一次 blob + `import()`,V8 要重新解析整份源码;同一 realm 里重复求值
1467
+ * 同一个发布没有意义,模块命名空间按 URL 缓存本来就是 ESM 的常规行为。
1468
+ */
1235
1469
  async function loadModule(files, path) {
1236
- 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;
1237
1479
  }
1238
1480
  function dispose() {
1239
1481
  if (disposal !== void 0) return disposal;
@@ -1267,6 +1509,12 @@ async function mapGuestCall(run) {
1267
1509
  throw toWireFailure(cause);
1268
1510
  }
1269
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
+ }
1270
1518
  /** Host resources the runtime pulls while it resolves instance properties. */
1271
1519
  function createResourceGateway(endpoint) {
1272
1520
  const host = endpoint.getProxy(fusedHostResourceService);
@@ -1733,10 +1981,10 @@ function closeBitmap(bitmap) {
1733
1981
  * same factories to several runtimes.
1734
1982
  */
1735
1983
  async function loadFusedWorkerFactories() {
1736
- const { fusedWorkerFactories } = await import("./workers-BMFz2OCK.js");
1984
+ const { fusedWorkerFactories } = await import("./workers-BCTUbUqo.js");
1737
1985
  return fusedWorkerFactories;
1738
1986
  }
1739
1987
  //#endregion
1740
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 };
1741
1989
 
1742
- //# sourceMappingURL=runtime-CXsJcvxe.js.map
1990
+ //# sourceMappingURL=runtime-DtM7aYdB.js.map