@isoloop/runtime 0.0.0-next.62ef495 → 0.0.0-next.800569e

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/worker.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,39 +215,383 @@ var init_dist = __esmMin((() => {
152
215
  retention: { kind: "compacted" }
153
216
  });
154
217
  }));
155
- // src/freeze.ts
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
+ /** Each key's current life. */
224
+ const lives = /* @__PURE__ */ new Map();
225
+ const lifeOf = (key) => lives.get(key) ?? null;
226
+ const bill = (key, ms) => {
227
+ spent.set(key, (spent.get(key) ?? 0) + ms);
228
+ };
229
+ const settle = (f) => {
230
+ const fallback = f.owner.key === PENDING ? null : f.owner.key;
231
+ if (f.pending) for (const o of f.pending) {
232
+ o.key = fallback;
233
+ o.life = f.owner.life;
234
+ }
235
+ if (f.roots && f.roots.length > 0) {
236
+ const unique = [...new Set(f.roots)];
237
+ const share = f.spent / unique.length;
238
+ for (const key of unique) bill(key, share);
239
+ } else if (fallback !== null) bill(fallback, f.spent);
240
+ };
241
+ const busy = {
242
+ run(owner, fn, self, args) {
243
+ const t = now();
244
+ const outer = frame;
245
+ if (outer) outer.spent += t - outer.start;
246
+ const f = {
247
+ owner,
248
+ start: t,
249
+ spent: 0,
250
+ parent: outer,
251
+ roots: null,
252
+ pending: null
253
+ };
254
+ frame = f;
255
+ try {
256
+ return fn.apply(self, args);
257
+ } finally {
258
+ const end = now();
259
+ f.spent += end - f.start;
260
+ frame = outer;
261
+ if (outer) outer.start = end;
262
+ settle(f);
263
+ }
264
+ },
265
+ capture() {
266
+ const f = frame;
267
+ if (!f) return {
268
+ key: null,
269
+ life: null
270
+ };
271
+ const o = {
272
+ key: PENDING,
273
+ life: null
274
+ };
275
+ (f.pending ??= []).push(o);
276
+ return o;
277
+ },
278
+ of: (key, life) => ({
279
+ key,
280
+ life: life === void 0 ? lifeOf(key) : life
281
+ }),
282
+ begin(key) {
283
+ const life = {
284
+ key,
285
+ ended: false
286
+ };
287
+ lives.set(key, life);
288
+ return life;
289
+ },
290
+ end(life) {
291
+ life.ended = true;
292
+ if (lives.get(life.key) === life) {
293
+ lives.delete(life.key);
294
+ spent.delete(life.key);
295
+ }
296
+ },
297
+ bind(fn) {
298
+ const owner = busy.capture();
299
+ return (...args) => busy.run(owner, fn, void 0, args);
300
+ },
301
+ report(key, life) {
302
+ const f = frame;
303
+ if (!f) return;
304
+ (f.roots ??= []).push(key);
305
+ if (f.pending) {
306
+ const l = life === void 0 ? lifeOf(key) : life;
307
+ for (const o of f.pending) {
308
+ o.key = key;
309
+ o.life = l;
310
+ }
311
+ f.pending = null;
312
+ }
313
+ },
314
+ take(key) {
315
+ const ms = spent.get(key) ?? 0;
316
+ spent.delete(key);
317
+ return ms;
318
+ },
319
+ claim(container, key) {
320
+ containers.set(container, {
321
+ key,
322
+ life: lifeOf(key)
323
+ });
324
+ },
325
+ keyOf(container) {
326
+ return busy.rootOf(container)?.key ?? null;
327
+ },
328
+ rootOf(container) {
329
+ if (typeof container !== "object" || container === null) return null;
330
+ return containers.get(container) ?? null;
331
+ }
332
+ };
333
+ return busy;
334
+ }
335
+ /** Keeps a wrapper's `name` and `length` the native function's. */
336
+ function like(wrapper, native) {
337
+ Object.defineProperty(wrapper, "name", {
338
+ value: native.name,
339
+ configurable: true
340
+ });
341
+ Object.defineProperty(wrapper, "length", {
342
+ value: native.length,
343
+ configurable: true
344
+ });
345
+ return wrapper;
346
+ }
347
+ /** `f` as a callback, when it is a function: schedulers call any function. */
348
+ function callable(f) {
349
+ return typeof f === "function" ? f : null;
350
+ }
156
351
  /**
157
- * Freezing a prototype makes its data properties read-only, and in strict
158
- * code assigning a property of the same name on an instance then throws (the
159
- * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`).
160
- * As Hardened JS does, each data property becomes an accessor whose setter
161
- * defines the property on the instance instead, so overriding still works
162
- * while the prototype itself can't change.
352
+ * `cb` run as `owner` when the scheduler calls it, with the scheduler's `this`
353
+ * and arguments. Always in a frame, even for nobody: a shared framework's
354
+ * task (React's scheduler port, set up while its module loaded) still splits
355
+ * among the roots it reports. Once the owner's life ended it doesn't run;
356
+ * `stale` gets the scheduler's `this` instead, to stop what would call it
357
+ * again (ADR 0015, decision 9).
163
358
  */
164
- function tameOverrides(proto) {
165
- for (const key of Reflect.ownKeys(proto)) {
166
- const d = Object.getOwnPropertyDescriptor(proto, key);
167
- if (!d || !("value" in d) || !d.configurable) continue;
168
- const value = d.value;
169
- Object.defineProperty(proto, key, {
170
- get() {
171
- return value;
172
- },
173
- set(v) {
174
- if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
175
- if (typeof this !== "object" && typeof this !== "function") return;
176
- if (this === null) return;
177
- Object.defineProperty(this, key, {
178
- value: v,
179
- writable: true,
180
- enumerable: true,
181
- configurable: true
182
- });
183
- },
184
- enumerable: d.enumerable ?? false,
185
- configurable: false
359
+ function billed(busy, owner, cb, stale) {
360
+ return function(...args) {
361
+ if (owner.life?.ended === true) {
362
+ stale?.(this);
363
+ return;
364
+ }
365
+ return busy.run(owner, cb, this, args);
366
+ };
367
+ }
368
+ /**
369
+ * Wraps a scheduling function on `scope` so the callback in argument 0 is
370
+ * billed to the owner current at registration. Everything else (the return
371
+ * value, ids, `clear*`, other arguments) is the native's.
372
+ */
373
+ function wrapScheduler(scope, name, busy) {
374
+ const native = Reflect.get(scope, name);
375
+ if (typeof native !== "function") return;
376
+ const clear = name === "setInterval" ? callable(Reflect.get(scope, "clearInterval")) : null;
377
+ const wrapper = like(function(...args) {
378
+ const cb = callable(args[0]);
379
+ let id;
380
+ if (cb) args[0] = billed(busy, busy.capture(), cb, clear ? () => {
381
+ clear.call(scope, id);
382
+ } : void 0);
383
+ const r = Reflect.apply(native, this ?? scope, args);
384
+ id = r;
385
+ return r;
386
+ }, native);
387
+ Reflect.set(scope, name, wrapper);
388
+ }
389
+ /**
390
+ * Wraps `MessagePort`'s `onmessage` and its `message` listeners, so a port
391
+ * a member creates (a scheduler's `MessageChannel`, say) bills its messages
392
+ * to that member. `onmessage` still reads back the function that was set,
393
+ * and `removeEventListener` still removes what `addEventListener` added.
394
+ */
395
+ function wrapPorts(scope, busy) {
396
+ const Port = Reflect.get(scope, "MessagePort");
397
+ if (typeof Port !== "function") return;
398
+ const proto = Reflect.get(Port, "prototype");
399
+ if (typeof proto !== "object" || proto === null) return;
400
+ const close = callable(Reflect.get(proto, "close"));
401
+ const shut = (port) => {
402
+ if (close && typeof port === "object" && port !== null) close.call(port);
403
+ };
404
+ const on = Object.getOwnPropertyDescriptor(proto, "onmessage");
405
+ const get = callable(on ? Reflect.get(on, "get") : void 0);
406
+ const set = callable(on ? Reflect.get(on, "set") : void 0);
407
+ if (on && get && set) {
408
+ /** What each port's `onmessage` was set to, as read back. */
409
+ const assigned = /* @__PURE__ */ new WeakMap();
410
+ Object.defineProperty(proto, "onmessage", {
411
+ configurable: true,
412
+ enumerable: on.enumerable ?? true,
413
+ get: like(function() {
414
+ if (typeof this === "object" && this !== null && assigned.has(this)) return assigned.get(this);
415
+ return get.call(this);
416
+ }, get),
417
+ set: like(function(fn) {
418
+ if (typeof this === "object" && this !== null) assigned.set(this, fn);
419
+ const cb = callable(fn);
420
+ set.call(this, cb ? billed(busy, busy.capture(), cb, shut) : fn);
421
+ }, set)
186
422
  });
187
423
  }
424
+ const add = callable(Reflect.get(proto, "addEventListener"));
425
+ const remove = callable(Reflect.get(proto, "removeEventListener"));
426
+ if (!add || !remove) return;
427
+ /** Per port, per listener and capture flag: the wrapper `addEventListener` was given. */
428
+ const added = /* @__PURE__ */ new WeakMap();
429
+ Object.defineProperty(proto, "addEventListener", {
430
+ configurable: true,
431
+ writable: true,
432
+ enumerable: true,
433
+ value: like(function(...args) {
434
+ const [type, listener, options] = args;
435
+ if (type !== "message" && type !== "messageerror" || !isListener(listener) || typeof this !== "object" || this === null) return add.apply(this, args);
436
+ const capture = captureOf(options);
437
+ let byListener = added.get(this);
438
+ if (!byListener) added.set(this, byListener = /* @__PURE__ */ new Map());
439
+ let byCapture = byListener.get(listener);
440
+ if (!byCapture) byListener.set(listener, byCapture = /* @__PURE__ */ new Map());
441
+ let wrapper = byCapture.get(capture);
442
+ if (!wrapper) {
443
+ const fn = callable(listener);
444
+ const call = function(e) {
445
+ if (fn) return fn.call(this, e);
446
+ return callable(Reflect.get(listener, "handleEvent"))?.call(listener, e);
447
+ };
448
+ wrapper = billed(busy, busy.capture(), call, shut);
449
+ byCapture.set(capture, wrapper);
450
+ }
451
+ return add.apply(this, [
452
+ type,
453
+ wrapper,
454
+ ...args.slice(2)
455
+ ]);
456
+ }, add)
457
+ });
458
+ Object.defineProperty(proto, "removeEventListener", {
459
+ configurable: true,
460
+ writable: true,
461
+ enumerable: true,
462
+ value: like(function(...args) {
463
+ const [type, listener, options] = args;
464
+ const byCapture = typeof this === "object" && this !== null && isListener(listener) ? added.get(this)?.get(listener) : void 0;
465
+ const capture = captureOf(options);
466
+ const wrapper = byCapture?.get(capture);
467
+ if (!wrapper || type !== "message" && type !== "messageerror") return remove.apply(this, args);
468
+ byCapture?.delete(capture);
469
+ return remove.apply(this, [
470
+ type,
471
+ wrapper,
472
+ ...args.slice(2)
473
+ ]);
474
+ }, remove)
475
+ });
476
+ }
477
+ /**
478
+ * React's devtools hook, the smallest one react-dom accepts (production
479
+ * builds call it too): it reports each committed root's member, and each
480
+ * root whose passive effects just ran, to the current frame.
481
+ */
482
+ function installReactHook(scope, busy) {
483
+ const KEY = "__REACT_DEVTOOLS_GLOBAL_HOOK__";
484
+ if (Reflect.get(scope, KEY) !== void 0) return;
485
+ let renderers = 0;
486
+ const committed = (_renderer, root) => {
487
+ if (typeof root !== "object" || root === null) return;
488
+ const at = busy.rootOf(Reflect.get(root, "containerInfo"));
489
+ if (at !== null) busy.report(at.key, at.life);
490
+ };
491
+ Reflect.set(scope, KEY, {
492
+ supportsFiber: true,
493
+ inject: () => ++renderers,
494
+ onCommitFiberRoot: committed,
495
+ onPostCommitFiberRoot: committed,
496
+ onCommitFiberUnmount: () => {},
497
+ checkDCE: () => {}
498
+ });
499
+ }
500
+ /**
501
+ * Installs attribution on a worker's global, once, before any member loads:
502
+ * the scheduling functions, `MessagePort` listeners and React's hook.
503
+ */
504
+ function installBusy(scope, busy) {
505
+ const q = Reflect.get(scope, "queueMicrotask");
506
+ if (typeof q === "function") nativeQueueMicrotask = (fn) => {
507
+ Reflect.apply(q, scope, [fn]);
508
+ };
509
+ for (const name of SCHEDULERS) wrapScheduler(scope, name, busy);
510
+ wrapPorts(scope, busy);
511
+ installReactHook(scope, busy);
512
+ }
513
+ var PENDING, SCHEDULERS, captureOf, isListener, nativeQueueMicrotask, busy, BUSY;
514
+ var init_busy = __esmMin((() => {
515
+ PENDING = Symbol("pending");
516
+ SCHEDULERS = [
517
+ "setTimeout",
518
+ "setInterval",
519
+ "requestAnimationFrame",
520
+ "queueMicrotask",
521
+ "requestIdleCallback"
522
+ ];
523
+ captureOf = (options) => typeof options === "boolean" ? options : typeof options === "object" && options !== null && Reflect.get(options, "capture") === true;
524
+ isListener = (l) => typeof l === "function" || typeof l === "object" && l !== null && typeof Reflect.get(l, "handleEvent") === "function";
525
+ nativeQueueMicrotask = (fn) => {
526
+ queueMicrotask(fn);
527
+ };
528
+ busy = createBusy();
529
+ BUSY = Symbol.for("isoloop.busy");
530
+ }));
531
+ // src/freeze.ts
532
+ /** The protected properties, per prototype, that are left as frozen data. */
533
+ function protectedProperties() {
534
+ const out = /* @__PURE__ */ new Map();
535
+ const add = (o, ...keys) => {
536
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
537
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
538
+ };
539
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
540
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
541
+ add(Array.prototype, ITERATOR, "constructor");
542
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
543
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
544
+ add(typedArray, ITERATOR, "constructor");
545
+ for (const c of [
546
+ Int8Array,
547
+ Uint8Array,
548
+ Uint8ClampedArray,
549
+ Int16Array,
550
+ Uint16Array,
551
+ Int32Array,
552
+ Uint32Array,
553
+ Float32Array,
554
+ Float64Array,
555
+ BigInt64Array,
556
+ BigUint64Array
557
+ ]) add(c.prototype, "constructor");
558
+ add(Map.prototype, ITERATOR);
559
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
560
+ add(Set.prototype, ITERATOR);
561
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
562
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
563
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
564
+ add(Promise.prototype, "then", "constructor");
565
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
566
+ return out;
567
+ }
568
+ function tameOverrides(proto) {
569
+ skip ??= protectedProperties();
570
+ const keep = skip.get(proto);
571
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
572
+ }
573
+ function tameOverride(proto, key) {
574
+ const d = Object.getOwnPropertyDescriptor(proto, key);
575
+ if (!d || !("value" in d) || !d.configurable) return;
576
+ const value = d.value;
577
+ Object.defineProperty(proto, key, {
578
+ get() {
579
+ return value;
580
+ },
581
+ set(v) {
582
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
583
+ if (typeof this !== "object" && typeof this !== "function") return;
584
+ if (this === null) return;
585
+ Object.defineProperty(this, key, {
586
+ value: v,
587
+ writable: true,
588
+ enumerable: true,
589
+ configurable: true
590
+ });
591
+ },
592
+ enumerable: d.enumerable ?? false,
593
+ configurable: false
594
+ });
188
595
  }
189
596
  function hardenProto(proto) {
190
597
  if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
@@ -221,7 +628,7 @@ function freezeBuiltins() {
221
628
  Object.freeze(JSON);
222
629
  Object.freeze(Reflect);
223
630
  }
224
- var NAMES;
631
+ var NAMES, ITERATOR, skip;
225
632
  var init_freeze = __esmMin((() => {
226
633
  NAMES = [
227
634
  "Object",
@@ -263,6 +670,7 @@ var init_freeze = __esmMin((() => {
263
670
  "BigInt64Array",
264
671
  "BigUint64Array"
265
672
  ];
673
+ ITERATOR = Symbol.iterator;
266
674
  }));
267
675
  // src/bus-client.ts
268
676
  function createBusClient(first, o = {}) {
@@ -302,15 +710,19 @@ function createBusClient(first, o = {}) {
302
710
  send(withId);
303
711
  });
304
712
  };
713
+ const committer = createCommitter({
714
+ send: (offsets) => {
715
+ send({
716
+ v: 1,
717
+ t: "commits",
718
+ p: { offsets }
719
+ });
720
+ },
721
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
722
+ ...o.credit === void 0 ? {} : { credit: o.credit }
723
+ });
305
724
  const commit = (topic, offset) => {
306
- send({
307
- v: 1,
308
- t: "commit",
309
- p: {
310
- topic,
311
- offset
312
- }
313
- });
725
+ committer.settle(topic, offset);
314
726
  };
315
727
  const drain = async (sub) => {
316
728
  if (sub.running) return;
@@ -320,7 +732,8 @@ function createBusClient(first, o = {}) {
320
732
  if (!r) break;
321
733
  topicOf.set(r, sub.topic);
322
734
  try {
323
- await sub.fn(r);
735
+ const done = sub.fn(r);
736
+ if (isThenable(done)) await done;
324
737
  } catch (err) {
325
738
  sub.stuck = true;
326
739
  o.onError?.(err);
@@ -371,6 +784,7 @@ function createBusClient(first, o = {}) {
371
784
  const sub = subs.get(msg.p.topic);
372
785
  if (!sub) return;
373
786
  sub.queue.length = 0;
787
+ committer.drop(msg.p.topic);
374
788
  try {
375
789
  sub.opts.onReset?.();
376
790
  } catch (err) {
@@ -419,6 +833,7 @@ function createBusClient(first, o = {}) {
419
833
  return () => {
420
834
  if (subs.get(topic.name) !== sub) return;
421
835
  subs.delete(topic.name);
836
+ committer.flush();
422
837
  send({
423
838
  v: 1,
424
839
  t: "unsubscribe",
@@ -494,14 +909,27 @@ function createBusClient(first, o = {}) {
494
909
  value: null
495
910
  });
496
911
  }
912
+ committer.take();
497
913
  for (const sub of subs.values()) {
498
914
  sub.queue.length = 0;
499
915
  sendSubscribe(sub);
500
916
  }
501
917
  for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
918
+ },
919
+ async close() {
920
+ const offsets = committer.take();
921
+ committer.dispose();
922
+ if (offsets) await call({
923
+ v: 1,
924
+ t: "commits",
925
+ p: { offsets }
926
+ });
502
927
  }
503
928
  };
504
929
  }
930
+ function isThenable(x) {
931
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
932
+ }
505
933
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
506
934
  var init_bus_client = __esmMin((() => {
507
935
  init_dist();
@@ -1807,7 +2235,18 @@ function sharedDom(scope) {
1807
2235
  * `pooled`, the isolate gets its own root in the worker's shared document
1808
2236
  * instead (ADR 0015).
1809
2237
  */
1810
- function createRender(post, scope, pooled = false) {
2238
+ function createRender(post, scope, pooled = false, member = null) {
2239
+ const owner = member === null ? null : busy.of(member);
2240
+ const schedule = (flush) => {
2241
+ if (owner === null || member === null) {
2242
+ queueMicrotask(flush);
2243
+ return;
2244
+ }
2245
+ busy.report(member, owner.life);
2246
+ nativeQueueMicrotask(() => {
2247
+ busy.run(owner, flush, void 0, []);
2248
+ });
2249
+ };
1811
2250
  let pendingStyles = [];
1812
2251
  let pendingHead = [];
1813
2252
  /** Head tags already reported: each goes to the host once. */
@@ -1847,19 +2286,22 @@ function createRender(post, scope, pooled = false) {
1847
2286
  };
1848
2287
  let target;
1849
2288
  if (pooled) {
1850
- const member = sharedDom(scope).addRoot({ onBatch: postPatch });
2289
+ const own = sharedDom(scope).addRoot({
2290
+ onBatch: postPatch,
2291
+ schedule
2292
+ });
1851
2293
  headListeners.add(onHead);
1852
2294
  target = {
1853
- ...member,
2295
+ ...own,
1854
2296
  dispose() {
1855
2297
  headListeners.delete(onHead);
1856
- member.dispose();
2298
+ own.dispose();
1857
2299
  }
1858
2300
  };
1859
2301
  } else {
1860
2302
  const dom = createDom({
1861
2303
  onBatch: postPatch,
1862
- schedule: (flush) => queueMicrotask(flush),
2304
+ schedule,
1863
2305
  onHead
1864
2306
  });
1865
2307
  if (scope) install(dom, scope);
@@ -1903,6 +2345,7 @@ function createRender(post, scope, pooled = false) {
1903
2345
  var nodeId, shared, headListeners;
1904
2346
  var init_render = __esmMin((() => {
1905
2347
  init_worker();
2348
+ init_busy();
1906
2349
  nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
1907
2350
  shared = null;
1908
2351
  headListeners = /* @__PURE__ */ new Set();
@@ -1926,8 +2369,8 @@ function defineIsolate(def) {
1926
2369
  };
1927
2370
  }
1928
2371
  /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1929
- function createVanillaIsolate(init, post, scope, pooled = false) {
1930
- const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
2372
+ function createVanillaIsolate(init, post, scope, pooled = false, member = null) {
2373
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled, member);
1931
2374
  const calls = createHostCalls({
1932
2375
  post,
1933
2376
  beforeCall: () => render?.flush(),
@@ -1938,6 +2381,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1938
2381
  const awake = createKeepAwake();
1939
2382
  const bus = createBusClient(init.busPort, {
1940
2383
  ...init.wake ? { wake: true } : {},
2384
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
1941
2385
  onError: (err) => {
1942
2386
  post({
1943
2387
  v: 1,
@@ -1988,6 +2432,15 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
1988
2432
  },
1989
2433
  keepAwake: () => awake.hold()
1990
2434
  };
2435
+ if (member !== null) Object.defineProperty(ctx, BUSY, {
2436
+ value: {
2437
+ claim: (container) => {
2438
+ busy.claim(container, member);
2439
+ },
2440
+ bind: (fn) => busy.bind(fn)
2441
+ },
2442
+ enumerable: false
2443
+ });
1991
2444
  Object.defineProperty(ctx, "portalRoot", {
1992
2445
  enumerable: false,
1993
2446
  get() {
@@ -2024,6 +2477,7 @@ function createVanillaIsolate(init, post, scope, pooled = false) {
2024
2477
  },
2025
2478
  async shutdown(reason) {
2026
2479
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2480
+ await bus.close();
2027
2481
  render?.flush();
2028
2482
  render?.dispose();
2029
2483
  }
@@ -2033,6 +2487,7 @@ var REQUIRES;
2033
2487
  var init_vanilla = __esmMin((() => {
2034
2488
  init_dist();
2035
2489
  init_bus_client();
2490
+ init_busy();
2036
2491
  init_host_calls();
2037
2492
  init_keep_awake();
2038
2493
  init_worker();
@@ -2078,9 +2533,11 @@ function startHeartbeat(everyMs) {
2078
2533
  function shutdownMember(m, graceMs, reason) {
2079
2534
  if (members.get(m.name) === m) members.delete(m.name);
2080
2535
  m.receive = null;
2081
- const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2536
+ const hook = m.shutdownHook;
2537
+ const done = (hook ? busy.run(busy.of(m.name, m.life), hook, void 0, [reason]) : void 0) ?? Promise.resolve();
2082
2538
  const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2083
2539
  Promise.race([done, grace]).finally(() => {
2540
+ busy.end(m.life);
2084
2541
  m.post({
2085
2542
  v: 1,
2086
2543
  t: "bye",
@@ -2094,7 +2551,7 @@ function route(msg) {
2094
2551
  const m = members.get(mode === "pool" ? msg.isolate : void 0);
2095
2552
  if (!m) return;
2096
2553
  if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2097
- else m.receive?.(msg);
2554
+ else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2098
2555
  }
2099
2556
  async function boot(m, init) {
2100
2557
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
@@ -2103,7 +2560,13 @@ async function boot(m, init) {
2103
2560
  }
2104
2561
  startHeartbeat(init.heartbeatMs);
2105
2562
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
2106
- const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
2563
+ const runtime = busy.run(busy.of(m.name, m.life), createVanillaIsolate, void 0, [
2564
+ init,
2565
+ m.post,
2566
+ self,
2567
+ mode === "pool",
2568
+ m.name
2569
+ ]);
2107
2570
  let mod;
2108
2571
  try {
2109
2572
  mod = await import(
@@ -2132,7 +2595,10 @@ async function startIsolate(m, runtime, start, requires) {
2132
2595
  runtime.receive(msg);
2133
2596
  };
2134
2597
  m.shutdownHook = (reason) => runtime.shutdown(reason);
2135
- m.idleReport = () => runtime.idle();
2598
+ m.idleReport = () => ({
2599
+ ...runtime.idle(),
2600
+ busyMs: busy.take(m.name)
2601
+ });
2136
2602
  m.post({
2137
2603
  v: 1,
2138
2604
  t: "ready",
@@ -2144,7 +2610,7 @@ async function startIsolate(m, runtime, start, requires) {
2144
2610
  }
2145
2611
  });
2146
2612
  try {
2147
- await start(runtime.ctx);
2613
+ await busy.run(busy.of(m.name, m.life), start, void 0, [runtime.ctx]);
2148
2614
  } catch (err) {
2149
2615
  fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
2150
2616
  }
@@ -2167,6 +2633,7 @@ function onMessage(e) {
2167
2633
  if (members.has(name)) return;
2168
2634
  const m = {
2169
2635
  name,
2636
+ life: busy.begin(name),
2170
2637
  post: memberPost(name),
2171
2638
  shutdownHook: null,
2172
2639
  idleReport: null,
@@ -2178,11 +2645,13 @@ function onMessage(e) {
2178
2645
  });
2179
2646
  }
2180
2647
  function startOnce() {
2648
+ installBusy(self, busy);
2181
2649
  self.addEventListener("message", onMessage);
2182
2650
  }
2183
2651
  var mode, members, postWorker, memberPost, fatal, beating, STARTED;
2184
2652
  var init_bootstrap = __esmMin((() => {
2185
2653
  init_dist();
2654
+ init_busy();
2186
2655
  init_freeze();
2187
2656
  mode = null;
2188
2657
  members = /* @__PURE__ */ new Map();