@isoloop/runtime 0.0.0-next.f57e259 → 0.0.0-next.g3322248

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.
package/dist/bootstrap.js CHANGED
@@ -8,14 +8,14 @@ var __esmMin = (fn, res, err) => () => {
8
8
  throw err = [e], e;
9
9
  }
10
10
  };
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
11
+ var __exportAll = (all, flags) => {
12
+ let target = Object.setPrototypeOf({}, null);
13
13
  for (var name in all) __defProp(target, name, {
14
14
  get: all[name],
15
15
  enumerable: true
16
16
  });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
17
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return flags & 2 ? target : Object.preventExtensions(target);
19
19
  };
20
20
  // ../protocol/dist/index.js
21
21
  /**
@@ -38,6 +38,69 @@ function envelopeGuard(types) {
38
38
  function isSystemTopic(topic) {
39
39
  return topic.startsWith(SYSTEM_TOPIC_PREFIX);
40
40
  }
41
+ function createCommitter(o) {
42
+ const intervalMs = o.intervalMs ?? 100;
43
+ const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
44
+ /** Highest settled offset per topic, not yet sent. */
45
+ const offsets = /* @__PURE__ */ new Map();
46
+ /** Records settled per topic since its last send: the early send at half the credit. */
47
+ const counts = /* @__PURE__ */ new Map();
48
+ let timer;
49
+ let queued = false;
50
+ const take = () => {
51
+ if (timer !== void 0) {
52
+ clearTimeout(timer);
53
+ timer = void 0;
54
+ }
55
+ queued = false;
56
+ if (offsets.size === 0) return void 0;
57
+ const out = [];
58
+ for (const [topic, offset] of offsets) out.push({
59
+ topic,
60
+ offset
61
+ });
62
+ offsets.clear();
63
+ counts.clear();
64
+ return out;
65
+ };
66
+ const flush = () => {
67
+ const out = take();
68
+ if (out) o.send(out);
69
+ };
70
+ const schedule = () => {
71
+ if (intervalMs === 0) {
72
+ if (queued) return;
73
+ queued = true;
74
+ queueMicrotask(() => {
75
+ if (queued) flush();
76
+ });
77
+ return;
78
+ }
79
+ timer ??= setTimeout(flush, intervalMs);
80
+ };
81
+ return {
82
+ settle(topic, offset, records = 1) {
83
+ const prev = offsets.get(topic);
84
+ if (prev === void 0 || offset > prev) offsets.set(topic, offset);
85
+ const n = (counts.get(topic) ?? 0) + records;
86
+ counts.set(topic, n);
87
+ if (n >= half) flush();
88
+ else schedule();
89
+ },
90
+ flush,
91
+ take,
92
+ drop(topic) {
93
+ offsets.delete(topic);
94
+ counts.delete(topic);
95
+ },
96
+ pending: () => offsets,
97
+ dispose() {
98
+ if (timer !== void 0) clearTimeout(timer);
99
+ timer = void 0;
100
+ queued = false;
101
+ }
102
+ };
103
+ }
41
104
  /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
42
105
  function systemSchema(check) {
43
106
  return { "~standard": {
@@ -152,8 +215,266 @@ var init_dist = __esmMin((() => {
152
215
  retention: { kind: "compacted" }
153
216
  });
154
217
  }));
218
+ // src/busy.ts
219
+ function createBusy(now = () => performance.now()) {
220
+ let frame = null;
221
+ const spent = /* @__PURE__ */ new Map();
222
+ const containers = /* @__PURE__ */ new WeakMap();
223
+ const bill = (key, ms) => {
224
+ spent.set(key, (spent.get(key) ?? 0) + ms);
225
+ };
226
+ const settle = (f) => {
227
+ const fallback = f.owner.key === PENDING ? null : f.owner.key;
228
+ if (f.pending) for (const o of f.pending) o.key = fallback;
229
+ if (f.roots && f.roots.length > 0) {
230
+ const unique = [...new Set(f.roots)];
231
+ const share = f.spent / unique.length;
232
+ for (const key of unique) bill(key, share);
233
+ } else if (fallback !== null) bill(fallback, f.spent);
234
+ };
235
+ const busy = {
236
+ run(owner, fn, self, args) {
237
+ const t = now();
238
+ const outer = frame;
239
+ if (outer) outer.spent += t - outer.start;
240
+ const f = {
241
+ owner,
242
+ start: t,
243
+ spent: 0,
244
+ parent: outer,
245
+ roots: null,
246
+ pending: null
247
+ };
248
+ frame = f;
249
+ try {
250
+ return fn.apply(self, args);
251
+ } finally {
252
+ const end = now();
253
+ f.spent += end - f.start;
254
+ frame = outer;
255
+ if (outer) outer.start = end;
256
+ settle(f);
257
+ }
258
+ },
259
+ capture() {
260
+ const f = frame;
261
+ if (!f) return { key: null };
262
+ const o = { key: PENDING };
263
+ (f.pending ??= []).push(o);
264
+ return o;
265
+ },
266
+ of: (key) => ({ key }),
267
+ bind(fn) {
268
+ const owner = busy.capture();
269
+ return (...args) => busy.run(owner, fn, void 0, args);
270
+ },
271
+ report(key) {
272
+ const f = frame;
273
+ if (!f) return;
274
+ (f.roots ??= []).push(key);
275
+ if (f.pending) {
276
+ for (const o of f.pending) o.key = key;
277
+ f.pending = null;
278
+ }
279
+ },
280
+ take(key) {
281
+ const ms = spent.get(key) ?? 0;
282
+ spent.delete(key);
283
+ return ms;
284
+ },
285
+ claim(container, key) {
286
+ containers.set(container, key);
287
+ },
288
+ keyOf(container) {
289
+ if (typeof container !== "object" || container === null) return null;
290
+ return containers.has(container) ? containers.get(container) ?? void 0 : null;
291
+ }
292
+ };
293
+ return busy;
294
+ }
295
+ /** Keeps a wrapper's `name` and `length` the native function's. */
296
+ function like(wrapper, native) {
297
+ Object.defineProperty(wrapper, "name", {
298
+ value: native.name,
299
+ configurable: true
300
+ });
301
+ Object.defineProperty(wrapper, "length", {
302
+ value: native.length,
303
+ configurable: true
304
+ });
305
+ return wrapper;
306
+ }
307
+ /** `f` as a callback, when it is a function: schedulers call any function. */
308
+ function callable(f) {
309
+ return typeof f === "function" ? f : null;
310
+ }
311
+ /**
312
+ * `cb` run as `owner` when the scheduler calls it, with the scheduler's `this`
313
+ * and arguments. Always in a frame, even for nobody: a shared framework's
314
+ * task (React's scheduler port, set up while its module loaded) still splits
315
+ * among the roots it reports.
316
+ */
317
+ function billed(busy, owner, cb) {
318
+ return function(...args) {
319
+ return busy.run(owner, cb, this, args);
320
+ };
321
+ }
322
+ /**
323
+ * Wraps a scheduling function on `scope` so the callback in argument 0 is
324
+ * billed to the owner current at registration. Everything else (the return
325
+ * value, ids, `clear*`, other arguments) is the native's.
326
+ */
327
+ function wrapScheduler(scope, name, busy) {
328
+ const native = Reflect.get(scope, name);
329
+ if (typeof native !== "function") return;
330
+ const wrapper = like(function(...args) {
331
+ const cb = callable(args[0]);
332
+ if (cb) args[0] = billed(busy, busy.capture(), cb);
333
+ return Reflect.apply(native, this ?? scope, args);
334
+ }, native);
335
+ Reflect.set(scope, name, wrapper);
336
+ }
337
+ /**
338
+ * Wraps `MessagePort`'s `onmessage` and its `message` listeners, so a port
339
+ * a member creates (a scheduler's `MessageChannel`, say) bills its messages
340
+ * to that member. `onmessage` still reads back the function that was set,
341
+ * and `removeEventListener` still removes what `addEventListener` added.
342
+ */
343
+ function wrapPorts(scope, busy) {
344
+ const Port = Reflect.get(scope, "MessagePort");
345
+ if (typeof Port !== "function") return;
346
+ const proto = Reflect.get(Port, "prototype");
347
+ if (typeof proto !== "object" || proto === null) return;
348
+ const on = Object.getOwnPropertyDescriptor(proto, "onmessage");
349
+ const get = callable(on ? Reflect.get(on, "get") : void 0);
350
+ const set = callable(on ? Reflect.get(on, "set") : void 0);
351
+ if (on && get && set) {
352
+ /** What each port's `onmessage` was set to, as read back. */
353
+ const assigned = /* @__PURE__ */ new WeakMap();
354
+ Object.defineProperty(proto, "onmessage", {
355
+ configurable: true,
356
+ enumerable: on.enumerable ?? true,
357
+ get: like(function() {
358
+ if (typeof this === "object" && this !== null && assigned.has(this)) return assigned.get(this);
359
+ return get.call(this);
360
+ }, get),
361
+ set: like(function(fn) {
362
+ if (typeof this === "object" && this !== null) assigned.set(this, fn);
363
+ const cb = callable(fn);
364
+ set.call(this, cb ? billed(busy, busy.capture(), cb) : fn);
365
+ }, set)
366
+ });
367
+ }
368
+ const add = callable(Reflect.get(proto, "addEventListener"));
369
+ const remove = callable(Reflect.get(proto, "removeEventListener"));
370
+ if (!add || !remove) return;
371
+ /** Per port, per listener and capture flag: the wrapper `addEventListener` was given. */
372
+ const added = /* @__PURE__ */ new WeakMap();
373
+ Object.defineProperty(proto, "addEventListener", {
374
+ configurable: true,
375
+ writable: true,
376
+ enumerable: true,
377
+ value: like(function(...args) {
378
+ const [type, listener, options] = args;
379
+ if (type !== "message" && type !== "messageerror" || !isListener(listener) || typeof this !== "object" || this === null) return add.apply(this, args);
380
+ const capture = captureOf(options);
381
+ let byListener = added.get(this);
382
+ if (!byListener) added.set(this, byListener = /* @__PURE__ */ new Map());
383
+ let byCapture = byListener.get(listener);
384
+ if (!byCapture) byListener.set(listener, byCapture = /* @__PURE__ */ new Map());
385
+ let wrapper = byCapture.get(capture);
386
+ if (!wrapper) {
387
+ const fn = callable(listener);
388
+ const call = function(e) {
389
+ if (fn) return fn.call(this, e);
390
+ return callable(Reflect.get(listener, "handleEvent"))?.call(listener, e);
391
+ };
392
+ wrapper = billed(busy, busy.capture(), call);
393
+ byCapture.set(capture, wrapper);
394
+ }
395
+ return add.apply(this, [
396
+ type,
397
+ wrapper,
398
+ ...args.slice(2)
399
+ ]);
400
+ }, add)
401
+ });
402
+ Object.defineProperty(proto, "removeEventListener", {
403
+ configurable: true,
404
+ writable: true,
405
+ enumerable: true,
406
+ value: like(function(...args) {
407
+ const [type, listener, options] = args;
408
+ const byCapture = typeof this === "object" && this !== null && isListener(listener) ? added.get(this)?.get(listener) : void 0;
409
+ const capture = captureOf(options);
410
+ const wrapper = byCapture?.get(capture);
411
+ if (!wrapper || type !== "message" && type !== "messageerror") return remove.apply(this, args);
412
+ byCapture?.delete(capture);
413
+ return remove.apply(this, [
414
+ type,
415
+ wrapper,
416
+ ...args.slice(2)
417
+ ]);
418
+ }, remove)
419
+ });
420
+ }
421
+ /**
422
+ * React's devtools hook, the smallest one react-dom accepts (production
423
+ * builds call it too): it reports each committed root's member, and each
424
+ * root whose passive effects just ran, to the current frame.
425
+ */
426
+ function installReactHook(scope, busy) {
427
+ const KEY = "__REACT_DEVTOOLS_GLOBAL_HOOK__";
428
+ if (Reflect.get(scope, KEY) !== void 0) return;
429
+ let renderers = 0;
430
+ const committed = (_renderer, root) => {
431
+ if (typeof root !== "object" || root === null) return;
432
+ const key = busy.keyOf(Reflect.get(root, "containerInfo"));
433
+ if (key !== null) busy.report(key);
434
+ };
435
+ Reflect.set(scope, KEY, {
436
+ supportsFiber: true,
437
+ inject: () => ++renderers,
438
+ onCommitFiberRoot: committed,
439
+ onPostCommitFiberRoot: committed,
440
+ onCommitFiberUnmount: () => {},
441
+ checkDCE: () => {}
442
+ });
443
+ }
444
+ /**
445
+ * Installs attribution on a worker's global, once, before any member loads:
446
+ * the scheduling functions, `MessagePort` listeners and React's hook.
447
+ */
448
+ function installBusy(scope, busy) {
449
+ const q = Reflect.get(scope, "queueMicrotask");
450
+ if (typeof q === "function") nativeQueueMicrotask = (fn) => {
451
+ Reflect.apply(q, scope, [fn]);
452
+ };
453
+ for (const name of SCHEDULERS) wrapScheduler(scope, name, busy);
454
+ wrapPorts(scope, busy);
455
+ installReactHook(scope, busy);
456
+ }
457
+ var PENDING, SCHEDULERS, captureOf, isListener, nativeQueueMicrotask, busy, BUSY;
458
+ var init_busy = __esmMin((() => {
459
+ PENDING = Symbol("pending");
460
+ SCHEDULERS = [
461
+ "setTimeout",
462
+ "setInterval",
463
+ "requestAnimationFrame",
464
+ "queueMicrotask",
465
+ "requestIdleCallback"
466
+ ];
467
+ captureOf = (options) => typeof options === "boolean" ? options : typeof options === "object" && options !== null && Reflect.get(options, "capture") === true;
468
+ isListener = (l) => typeof l === "function" || typeof l === "object" && l !== null && typeof Reflect.get(l, "handleEvent") === "function";
469
+ nativeQueueMicrotask = (fn) => {
470
+ queueMicrotask(fn);
471
+ };
472
+ busy = createBusy();
473
+ BUSY = Symbol.for("isoloop.busy");
474
+ }));
155
475
  // src/freeze.ts
156
476
  init_dist();
477
+ init_busy();
157
478
  /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
158
479
  const NAMES = [
159
480
  "Object",
@@ -198,35 +519,86 @@ const NAMES = [
198
519
  /**
199
520
  * Freezing a prototype makes its data properties read-only, and in strict
200
521
  * code assigning a property of the same name on an instance then throws (the
201
- * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`).
202
- * As Hardened JS does, each data property becomes an accessor whose setter
203
- * defines the property on the instance instead, so overriding still works
204
- * while the prototype itself can't change.
522
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`,
523
+ * or `Object.assign({}, { constructor: x })`). As Hardened JS does, each data
524
+ * property becomes an accessor whose setter defines the property on the
525
+ * instance instead, so overriding still works while the prototype itself
526
+ * can't change.
527
+ *
528
+ * Except the properties V8 guards with "protectors": while they are still the
529
+ * original data properties, V8 keeps fast paths for iteration (`for…of`,
530
+ * spread, destructuring), species lookups and promise resolution. An accessor
531
+ * returning the same function is enough to turn a protector off for the whole
532
+ * worker: array iteration alone made a pool's app code 1.4–2.5× slower
533
+ * (docs/investigations/plant-one-pool.md). These stay plain frozen data, so
534
+ * overriding one of them on an instance throws in strict code instead
535
+ * (ADR 0001, "Override taming without the protected properties").
205
536
  */
537
+ const ITERATOR = Symbol.iterator;
538
+ /** The protected properties, per prototype, that are left as frozen data. */
539
+ function protectedProperties() {
540
+ const out = /* @__PURE__ */ new Map();
541
+ const add = (o, ...keys) => {
542
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
543
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
544
+ };
545
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
546
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
547
+ add(Array.prototype, ITERATOR, "constructor");
548
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
549
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
550
+ add(typedArray, ITERATOR, "constructor");
551
+ for (const c of [
552
+ Int8Array,
553
+ Uint8Array,
554
+ Uint8ClampedArray,
555
+ Int16Array,
556
+ Uint16Array,
557
+ Int32Array,
558
+ Uint32Array,
559
+ Float32Array,
560
+ Float64Array,
561
+ BigInt64Array,
562
+ BigUint64Array
563
+ ]) add(c.prototype, "constructor");
564
+ add(Map.prototype, ITERATOR);
565
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
566
+ add(Set.prototype, ITERATOR);
567
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
568
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
569
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
570
+ add(Promise.prototype, "then", "constructor");
571
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
572
+ return out;
573
+ }
574
+ let skip;
206
575
  function tameOverrides(proto) {
207
- for (const key of Reflect.ownKeys(proto)) {
208
- const d = Object.getOwnPropertyDescriptor(proto, key);
209
- if (!d || !("value" in d) || !d.configurable) continue;
210
- const value = d.value;
211
- Object.defineProperty(proto, key, {
212
- get() {
213
- return value;
214
- },
215
- set(v) {
216
- if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
217
- if (typeof this !== "object" && typeof this !== "function") return;
218
- if (this === null) return;
219
- Object.defineProperty(this, key, {
220
- value: v,
221
- writable: true,
222
- enumerable: true,
223
- configurable: true
224
- });
225
- },
226
- enumerable: d.enumerable ?? false,
227
- configurable: false
228
- });
229
- }
576
+ skip ??= protectedProperties();
577
+ const keep = skip.get(proto);
578
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
579
+ }
580
+ function tameOverride(proto, key) {
581
+ const d = Object.getOwnPropertyDescriptor(proto, key);
582
+ if (!d || !("value" in d) || !d.configurable) return;
583
+ const value = d.value;
584
+ Object.defineProperty(proto, key, {
585
+ get() {
586
+ return value;
587
+ },
588
+ set(v) {
589
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
590
+ if (typeof this !== "object" && typeof this !== "function") return;
591
+ if (this === null) return;
592
+ Object.defineProperty(this, key, {
593
+ value: v,
594
+ writable: true,
595
+ enumerable: true,
596
+ configurable: true
597
+ });
598
+ },
599
+ enumerable: d.enumerable ?? false,
600
+ configurable: false
601
+ });
230
602
  }
231
603
  function hardenProto(proto) {
232
604
  if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
@@ -301,15 +673,19 @@ function createBusClient(first, o = {}) {
301
673
  send(withId);
302
674
  });
303
675
  };
676
+ const committer = createCommitter({
677
+ send: (offsets) => {
678
+ send({
679
+ v: 1,
680
+ t: "commits",
681
+ p: { offsets }
682
+ });
683
+ },
684
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
685
+ ...o.credit === void 0 ? {} : { credit: o.credit }
686
+ });
304
687
  const commit = (topic, offset) => {
305
- send({
306
- v: 1,
307
- t: "commit",
308
- p: {
309
- topic,
310
- offset
311
- }
312
- });
688
+ committer.settle(topic, offset);
313
689
  };
314
690
  const drain = async (sub) => {
315
691
  if (sub.running) return;
@@ -319,7 +695,8 @@ function createBusClient(first, o = {}) {
319
695
  if (!r) break;
320
696
  topicOf.set(r, sub.topic);
321
697
  try {
322
- await sub.fn(r);
698
+ const done = sub.fn(r);
699
+ if (isThenable(done)) await done;
323
700
  } catch (err) {
324
701
  sub.stuck = true;
325
702
  o.onError?.(err);
@@ -370,6 +747,7 @@ function createBusClient(first, o = {}) {
370
747
  const sub = subs.get(msg.p.topic);
371
748
  if (!sub) return;
372
749
  sub.queue.length = 0;
750
+ committer.drop(msg.p.topic);
373
751
  try {
374
752
  sub.opts.onReset?.();
375
753
  } catch (err) {
@@ -418,6 +796,7 @@ function createBusClient(first, o = {}) {
418
796
  return () => {
419
797
  if (subs.get(topic.name) !== sub) return;
420
798
  subs.delete(topic.name);
799
+ committer.flush();
421
800
  send({
422
801
  v: 1,
423
802
  t: "unsubscribe",
@@ -493,14 +872,27 @@ function createBusClient(first, o = {}) {
493
872
  value: null
494
873
  });
495
874
  }
875
+ committer.take();
496
876
  for (const sub of subs.values()) {
497
877
  sub.queue.length = 0;
498
878
  sendSubscribe(sub);
499
879
  }
500
880
  for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
881
+ },
882
+ async close() {
883
+ const offsets = committer.take();
884
+ committer.dispose();
885
+ if (offsets) await call({
886
+ v: 1,
887
+ t: "commits",
888
+ p: { offsets }
889
+ });
501
890
  }
502
891
  };
503
892
  }
893
+ function isThenable(x) {
894
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
895
+ }
504
896
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
505
897
  var init_bus_client = __esmMin((() => {
506
898
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
@@ -1805,7 +2197,18 @@ function sharedDom(scope) {
1805
2197
  * `pooled`, the isolate gets its own root in the worker's shared document
1806
2198
  * instead (ADR 0015).
1807
2199
  */
1808
- function createRender(post, scope, pooled = false) {
2200
+ function createRender(post, scope, pooled = false, member = null) {
2201
+ const owner = member === null ? null : busy.of(member);
2202
+ const schedule = (flush) => {
2203
+ if (owner === null || member === null) {
2204
+ queueMicrotask(flush);
2205
+ return;
2206
+ }
2207
+ busy.report(member);
2208
+ nativeQueueMicrotask(() => {
2209
+ busy.run(owner, flush, void 0, []);
2210
+ });
2211
+ };
1809
2212
  let pendingStyles = [];
1810
2213
  let pendingHead = [];
1811
2214
  /** Head tags already reported: each goes to the host once. */
@@ -1845,19 +2248,22 @@ function createRender(post, scope, pooled = false) {
1845
2248
  };
1846
2249
  let target;
1847
2250
  if (pooled) {
1848
- const member = sharedDom(scope).addRoot({ onBatch: postPatch });
2251
+ const own = sharedDom(scope).addRoot({
2252
+ onBatch: postPatch,
2253
+ schedule
2254
+ });
1849
2255
  headListeners.add(onHead);
1850
2256
  target = {
1851
- ...member,
2257
+ ...own,
1852
2258
  dispose() {
1853
2259
  headListeners.delete(onHead);
1854
- member.dispose();
2260
+ own.dispose();
1855
2261
  }
1856
2262
  };
1857
2263
  } else {
1858
2264
  const dom = createDom({
1859
2265
  onBatch: postPatch,
1860
- schedule: (flush) => queueMicrotask(flush),
2266
+ schedule,
1861
2267
  onHead
1862
2268
  });
1863
2269
  if (scope) install(dom, scope);
@@ -1924,8 +2330,8 @@ function defineIsolate(def) {
1924
2330
  };
1925
2331
  }
1926
2332
  /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1927
- function createVanillaIsolate(init, post, scope, pooled = false) {
1928
- const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
2333
+ function createVanillaIsolate(init, post, scope, pooled = false, member = null) {
2334
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled, member);
1929
2335
  const calls = createHostCalls({
1930
2336
  post,
1931
2337
  beforeCall: () => render?.flush(),
@@ -1936,6 +2342,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1936
2342
  const awake = createKeepAwake();
1937
2343
  const bus = createBusClient(init.busPort, {
1938
2344
  ...init.wake ? { wake: true } : {},
2345
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
1939
2346
  onError: (err) => {
1940
2347
  post({
1941
2348
  v: 1,
@@ -1986,6 +2393,15 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1986
2393
  },
1987
2394
  keepAwake: () => awake.hold()
1988
2395
  };
2396
+ if (member !== null) Object.defineProperty(ctx, BUSY, {
2397
+ value: {
2398
+ claim: (container) => {
2399
+ busy.claim(container, member);
2400
+ },
2401
+ bind: (fn) => busy.bind(fn)
2402
+ },
2403
+ enumerable: false
2404
+ });
1989
2405
  Object.defineProperty(ctx, "portalRoot", {
1990
2406
  enumerable: false,
1991
2407
  get() {
@@ -2022,6 +2438,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
2022
2438
  },
2023
2439
  async shutdown(reason) {
2024
2440
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2441
+ await bus.close();
2025
2442
  render?.flush();
2026
2443
  render?.dispose();
2027
2444
  }
@@ -2031,6 +2448,7 @@ var REQUIRES;
2031
2448
  var init_vanilla = __esmMin((() => {
2032
2449
  init_dist();
2033
2450
  init_bus_client();
2451
+ init_busy();
2034
2452
  init_host_calls();
2035
2453
  init_keep_awake();
2036
2454
  init_worker();
@@ -2039,6 +2457,7 @@ var init_vanilla = __esmMin((() => {
2039
2457
  }));
2040
2458
  // src/bootstrap.ts
2041
2459
  init_dist();
2460
+ init_busy();
2042
2461
  let mode = null;
2043
2462
  const members = /* @__PURE__ */ new Map();
2044
2463
  const postWorker = (msg) => {
@@ -2102,7 +2521,8 @@ function startHeartbeat(everyMs) {
2102
2521
  function shutdownMember(m, graceMs, reason) {
2103
2522
  if (members.get(m.name) === m) members.delete(m.name);
2104
2523
  m.receive = null;
2105
- const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2524
+ const hook = m.shutdownHook;
2525
+ const done = (hook ? busy.run(busy.of(m.name), hook, void 0, [reason]) : void 0) ?? Promise.resolve();
2106
2526
  const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2107
2527
  Promise.race([done, grace]).finally(() => {
2108
2528
  m.post({
@@ -2118,7 +2538,7 @@ function route(msg) {
2118
2538
  const m = members.get(mode === "pool" ? msg.isolate : void 0);
2119
2539
  if (!m) return;
2120
2540
  if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2121
- else m.receive?.(msg);
2541
+ else if (m.receive) busy.run(busy.of(m.name), m.receive, void 0, [msg]);
2122
2542
  }
2123
2543
  async function boot(m, init) {
2124
2544
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
@@ -2127,7 +2547,13 @@ async function boot(m, init) {
2127
2547
  }
2128
2548
  startHeartbeat(init.heartbeatMs);
2129
2549
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
2130
- const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
2550
+ const runtime = busy.run(busy.of(m.name), createVanillaIsolate, void 0, [
2551
+ init,
2552
+ m.post,
2553
+ self,
2554
+ mode === "pool",
2555
+ m.name
2556
+ ]);
2131
2557
  let mod;
2132
2558
  try {
2133
2559
  mod = await import(
@@ -2156,7 +2582,10 @@ async function startIsolate(m, runtime, start, requires) {
2156
2582
  runtime.receive(msg);
2157
2583
  };
2158
2584
  m.shutdownHook = (reason) => runtime.shutdown(reason);
2159
- m.idleReport = () => runtime.idle();
2585
+ m.idleReport = () => ({
2586
+ ...runtime.idle(),
2587
+ busyMs: busy.take(m.name)
2588
+ });
2160
2589
  m.post({
2161
2590
  v: 1,
2162
2591
  t: "ready",
@@ -2168,12 +2597,13 @@ async function startIsolate(m, runtime, start, requires) {
2168
2597
  }
2169
2598
  });
2170
2599
  try {
2171
- await start(runtime.ctx);
2600
+ await busy.run(busy.of(m.name), start, void 0, [runtime.ctx]);
2172
2601
  } catch (err) {
2173
2602
  fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
2174
2603
  }
2175
2604
  }
2176
- self.addEventListener("message", (e) => {
2605
+ /** Handles one message from the host: `init` boots a member, the rest is routed. */
2606
+ function onMessage(e) {
2177
2607
  const msg = e.data;
2178
2608
  if (!isHostToIsolate(msg)) return;
2179
2609
  if (msg.t !== "init") {
@@ -2199,4 +2629,15 @@ self.addEventListener("message", (e) => {
2199
2629
  boot(m, msg.p).catch((err) => {
2200
2630
  fatal(m, err instanceof Error ? err.message : String(err));
2201
2631
  });
2202
- });
2632
+ }
2633
+ const STARTED = Symbol.for("isoloop.bootstrap");
2634
+ function startOnce() {
2635
+ installBusy(self, busy);
2636
+ self.addEventListener("message", onMessage);
2637
+ }
2638
+ if (Reflect.get(self, STARTED) === true) {
2639
+ if (import.meta.env?.DEV === true) console.warn("isoloop: worker entry evaluated twice; ignoring");
2640
+ } else {
2641
+ Reflect.set(self, STARTED, true);
2642
+ startOnce();
2643
+ }