@isoloop/runtime 0.0.0-next.69da74b → 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/bootstrap.js CHANGED
@@ -8,23 +8,24 @@ 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
  /**
22
22
  * True for a well-formed envelope this build can read: `v` is a supported
23
- * version, `t` is a string, `id`/`re` are absent or strings, and `p` is present.
23
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
24
+ * is present.
24
25
  * Says nothing about whether `t` is known; see the per-port guards.
25
26
  */
26
27
  function isEnvelope(x) {
27
- return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]);
28
+ return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
28
29
  }
29
30
  /**
30
31
  * Builds a guard for one port's union from its message types. Each side drops
@@ -37,6 +38,69 @@ function envelopeGuard(types) {
37
38
  function isSystemTopic(topic) {
38
39
  return topic.startsWith(SYSTEM_TOPIC_PREFIX);
39
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
+ }
40
104
  /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
41
105
  function systemSchema(check) {
42
106
  return { "~standard": {
@@ -151,6 +215,482 @@ var init_dist = __esmMin((() => {
151
215
  retention: { kind: "compacted" }
152
216
  });
153
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
+ /** 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
+ }
351
+ /**
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).
358
+ */
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)
422
+ });
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
+ init_dist();
533
+ init_busy();
534
+ /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
535
+ const NAMES = [
536
+ "Object",
537
+ "Function",
538
+ "Array",
539
+ "String",
540
+ "Number",
541
+ "Boolean",
542
+ "Symbol",
543
+ "BigInt",
544
+ "Date",
545
+ "RegExp",
546
+ "Error",
547
+ "EvalError",
548
+ "RangeError",
549
+ "ReferenceError",
550
+ "SyntaxError",
551
+ "TypeError",
552
+ "URIError",
553
+ "AggregateError",
554
+ "Promise",
555
+ "Map",
556
+ "Set",
557
+ "WeakMap",
558
+ "WeakSet",
559
+ "WeakRef",
560
+ "FinalizationRegistry",
561
+ "ArrayBuffer",
562
+ "DataView",
563
+ "Int8Array",
564
+ "Uint8Array",
565
+ "Uint8ClampedArray",
566
+ "Int16Array",
567
+ "Uint16Array",
568
+ "Int32Array",
569
+ "Uint32Array",
570
+ "Float32Array",
571
+ "Float64Array",
572
+ "BigInt64Array",
573
+ "BigUint64Array"
574
+ ];
575
+ /**
576
+ * Freezing a prototype makes its data properties read-only, and in strict
577
+ * code assigning a property of the same name on an instance then throws (the
578
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`,
579
+ * or `Object.assign({}, { constructor: x })`). As Hardened JS does, each data
580
+ * property becomes an accessor whose setter defines the property on the
581
+ * instance instead, so overriding still works while the prototype itself
582
+ * can't change.
583
+ *
584
+ * Except the properties V8 guards with "protectors": while they are still the
585
+ * original data properties, V8 keeps fast paths for iteration (`for…of`,
586
+ * spread, destructuring), species lookups and promise resolution. An accessor
587
+ * returning the same function is enough to turn a protector off for the whole
588
+ * worker: array iteration alone made a pool's app code 1.4–2.5× slower
589
+ * (docs/investigations/plant-one-pool.md). These stay plain frozen data, so
590
+ * overriding one of them on an instance throws in strict code instead
591
+ * (ADR 0001, "Override taming without the protected properties").
592
+ */
593
+ const ITERATOR = Symbol.iterator;
594
+ /** The protected properties, per prototype, that are left as frozen data. */
595
+ function protectedProperties() {
596
+ const out = /* @__PURE__ */ new Map();
597
+ const add = (o, ...keys) => {
598
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
599
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
600
+ };
601
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
602
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
603
+ add(Array.prototype, ITERATOR, "constructor");
604
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
605
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
606
+ add(typedArray, ITERATOR, "constructor");
607
+ for (const c of [
608
+ Int8Array,
609
+ Uint8Array,
610
+ Uint8ClampedArray,
611
+ Int16Array,
612
+ Uint16Array,
613
+ Int32Array,
614
+ Uint32Array,
615
+ Float32Array,
616
+ Float64Array,
617
+ BigInt64Array,
618
+ BigUint64Array
619
+ ]) add(c.prototype, "constructor");
620
+ add(Map.prototype, ITERATOR);
621
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
622
+ add(Set.prototype, ITERATOR);
623
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
624
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
625
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
626
+ add(Promise.prototype, "then", "constructor");
627
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
628
+ return out;
629
+ }
630
+ let skip;
631
+ function tameOverrides(proto) {
632
+ skip ??= protectedProperties();
633
+ const keep = skip.get(proto);
634
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
635
+ }
636
+ function tameOverride(proto, key) {
637
+ const d = Object.getOwnPropertyDescriptor(proto, key);
638
+ if (!d || !("value" in d) || !d.configurable) return;
639
+ const value = d.value;
640
+ Object.defineProperty(proto, key, {
641
+ get() {
642
+ return value;
643
+ },
644
+ set(v) {
645
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
646
+ if (typeof this !== "object" && typeof this !== "function") return;
647
+ if (this === null) return;
648
+ Object.defineProperty(this, key, {
649
+ value: v,
650
+ writable: true,
651
+ enumerable: true,
652
+ configurable: true
653
+ });
654
+ },
655
+ enumerable: d.enumerable ?? false,
656
+ configurable: false
657
+ });
658
+ }
659
+ function hardenProto(proto) {
660
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
661
+ if (Object.isFrozen(proto)) return;
662
+ tameOverrides(proto);
663
+ Object.freeze(proto);
664
+ }
665
+ function freezeWithPrototype(c) {
666
+ if (typeof c !== "function") return;
667
+ hardenProto(Reflect.get(c, "prototype"));
668
+ if (c !== Error) Object.freeze(c);
669
+ }
670
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
671
+ function freezeBuiltins() {
672
+ const g = globalThis;
673
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
674
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
675
+ const protos = [
676
+ Object.getPrototypeOf([][Symbol.iterator]()),
677
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
678
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
679
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
680
+ Object.getPrototypeOf(""[Symbol.iterator]()),
681
+ Object.getPrototypeOf(function* () {}),
682
+ Object.getPrototypeOf(async function() {}),
683
+ Object.getPrototypeOf(async function* () {})
684
+ ];
685
+ for (const p of protos) {
686
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
687
+ hardenProto(Reflect.get(p, "prototype"));
688
+ hardenProto(p);
689
+ }
690
+ Object.freeze(Math);
691
+ Object.freeze(JSON);
692
+ Object.freeze(Reflect);
693
+ }
154
694
  // src/bus-client.ts
155
695
  function createBusClient(first, o = {}) {
156
696
  const limit = o.inboxLimit ?? 1e3;
@@ -189,15 +729,19 @@ function createBusClient(first, o = {}) {
189
729
  send(withId);
190
730
  });
191
731
  };
732
+ const committer = createCommitter({
733
+ send: (offsets) => {
734
+ send({
735
+ v: 1,
736
+ t: "commits",
737
+ p: { offsets }
738
+ });
739
+ },
740
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
741
+ ...o.credit === void 0 ? {} : { credit: o.credit }
742
+ });
192
743
  const commit = (topic, offset) => {
193
- send({
194
- v: 1,
195
- t: "commit",
196
- p: {
197
- topic,
198
- offset
199
- }
200
- });
744
+ committer.settle(topic, offset);
201
745
  };
202
746
  const drain = async (sub) => {
203
747
  if (sub.running) return;
@@ -207,7 +751,8 @@ function createBusClient(first, o = {}) {
207
751
  if (!r) break;
208
752
  topicOf.set(r, sub.topic);
209
753
  try {
210
- await sub.fn(r);
754
+ const done = sub.fn(r);
755
+ if (isThenable(done)) await done;
211
756
  } catch (err) {
212
757
  sub.stuck = true;
213
758
  o.onError?.(err);
@@ -258,6 +803,7 @@ function createBusClient(first, o = {}) {
258
803
  const sub = subs.get(msg.p.topic);
259
804
  if (!sub) return;
260
805
  sub.queue.length = 0;
806
+ committer.drop(msg.p.topic);
261
807
  try {
262
808
  sub.opts.onReset?.();
263
809
  } catch (err) {
@@ -306,6 +852,7 @@ function createBusClient(first, o = {}) {
306
852
  return () => {
307
853
  if (subs.get(topic.name) !== sub) return;
308
854
  subs.delete(topic.name);
855
+ committer.flush();
309
856
  send({
310
857
  v: 1,
311
858
  t: "unsubscribe",
@@ -381,17 +928,29 @@ function createBusClient(first, o = {}) {
381
928
  value: null
382
929
  });
383
930
  }
931
+ committer.take();
384
932
  for (const sub of subs.values()) {
385
933
  sub.queue.length = 0;
386
934
  sendSubscribe(sub);
387
935
  }
388
936
  for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
937
+ },
938
+ async close() {
939
+ const offsets = committer.take();
940
+ committer.dispose();
941
+ if (offsets) await call({
942
+ v: 1,
943
+ t: "commits",
944
+ p: { offsets }
945
+ });
389
946
  }
390
947
  };
391
948
  }
949
+ function isThenable(x) {
950
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
951
+ }
392
952
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
393
953
  var init_bus_client = __esmMin((() => {
394
- init_dist();
395
954
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
396
955
  check = (r) => {
397
956
  if (!r.ok) throw new BusError(r.error);
@@ -516,7 +1075,7 @@ var ISOLOOP_DOM_FMT;
516
1075
  var init_records_wVZrPpqr = __esmMin((() => {
517
1076
  ISOLOOP_DOM_FMT = "isoloop-dom@1";
518
1077
  }));
519
- // ../dom/dist/dom-9S5T0UVQ.js
1078
+ // ../dom/dist/dom-yLsf0Z4e.js
520
1079
  function createStyle(el) {
521
1080
  const decls = /* @__PURE__ */ new Map();
522
1081
  const write = () => {
@@ -643,78 +1202,131 @@ function serialize(n) {
643
1202
  children: n.childNodes.map(serialize)
644
1203
  };
645
1204
  }
646
- function learn(n, core) {
1205
+ /** Whether `n` or anything under it was rendered under a root other than `owner`. */
1206
+ function ownedElsewhere(n, owner) {
1207
+ if (n.isoOwner && n.isoOwner !== owner) return true;
1208
+ return !n.isoKnown && n.childNodes.some((c) => ownedElsewhere(c, owner));
1209
+ }
1210
+ function learn(n, core, owner) {
647
1211
  n.isoKnown = true;
1212
+ n.isoOwner = owner;
648
1213
  core.known.set(n.isoId, n);
649
- for (const c of n.childNodes) learn(c, core);
1214
+ for (const c of n.childNodes) learn(c, core, owner);
650
1215
  }
651
1216
  function forget(n, core) {
652
1217
  n.isoKnown = false;
653
1218
  core.known.delete(n.isoId);
654
1219
  for (const c of n.childNodes) forget(c, core);
655
1220
  }
656
- function createDom(opts) {
657
- const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
1221
+ function setValueOf(node, value, o) {
1222
+ if (!isControl(node)) throw new TypeError("setValue: not an input, textarea or select");
1223
+ if (!o.force) {
1224
+ node.value = value;
1225
+ return;
1226
+ }
1227
+ node.isoSetProp("value", value, false);
1228
+ if (node.isoKnown) emit(node, [
1229
+ "prop",
1230
+ node.isoWire,
1231
+ "value",
1232
+ value,
1233
+ true
1234
+ ]);
1235
+ }
1236
+ function deliverTo(node, event) {
1237
+ if (!node) return;
1238
+ if (isControl(node) && event.value !== void 0) node.isoSetProp("value", event.value, false);
1239
+ if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
1240
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
1241
+ top: event.scrollTop ?? 0,
1242
+ left: event.scrollLeft ?? 0
1243
+ };
1244
+ node.dispatchEvent(toEvent(event));
1245
+ }
1246
+ /** A root's recorder: records batched per microtask (or `schedule`) into `onBatch`. */
1247
+ function recorder(root, onBatch, schedule) {
658
1248
  let pending = [];
659
1249
  let scheduled = false;
1250
+ let live = true;
660
1251
  const flush = () => {
661
1252
  scheduled = false;
662
1253
  if (pending.length === 0) return;
663
1254
  const batch = pending;
664
1255
  pending = [];
665
- opts.onBatch(batch);
1256
+ if (live) onBatch(batch);
666
1257
  };
1258
+ return {
1259
+ owner: {
1260
+ root,
1261
+ push(r) {
1262
+ if (!live) return;
1263
+ pending.push(r);
1264
+ if (!scheduled) {
1265
+ scheduled = true;
1266
+ schedule(flush);
1267
+ }
1268
+ }
1269
+ },
1270
+ flush,
1271
+ stop: () => {
1272
+ live = false;
1273
+ pending = [];
1274
+ }
1275
+ };
1276
+ }
1277
+ function createDom(opts) {
1278
+ const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
667
1279
  const core = {
668
- root: null,
1280
+ roots: /* @__PURE__ */ new Set(),
669
1281
  nextId: 1,
670
1282
  known: /* @__PURE__ */ new Map(),
671
- onHead: opts.onHead ?? (() => {}),
672
- record(r) {
673
- pending.push(r);
674
- if (!scheduled) {
675
- scheduled = true;
676
- schedule(flush);
677
- }
678
- }
1283
+ onHead: opts.onHead ?? (() => {})
679
1284
  };
680
1285
  const document = new WDocument(core);
681
- const root = new WHTMLElement(document, 0, "iso-root", "html");
682
- root.isoKnown = true;
683
- core.known.set(0, root);
684
- core.root = root;
1286
+ const makeRoot = (id) => {
1287
+ const root = new WHTMLElement(document, id, "iso-root", "html");
1288
+ root.isoKnown = true;
1289
+ core.known.set(id, root);
1290
+ core.roots.add(root);
1291
+ return root;
1292
+ };
1293
+ const root = makeRoot(0);
1294
+ const main = recorder(root, (b) => opts.onBatch(b), schedule);
1295
+ root.isoOwner = main.owner;
685
1296
  return {
686
1297
  document,
687
1298
  root,
688
- flush,
1299
+ flush: main.flush,
689
1300
  idOf: (node) => node.isoId,
690
- setValue(node, value, o = {}) {
691
- if (!(node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement)) throw new TypeError("setValue: not an input, textarea or select");
692
- if (!o.force) {
693
- node.value = value;
694
- return;
695
- }
696
- node.isoSetProp("value", value, false);
697
- if (node.isoKnown) core.record([
698
- "prop",
699
- node.isoId,
700
- "value",
701
- value,
702
- true
703
- ]);
704
- },
705
- deliver(event) {
706
- const node = core.known.get(event.target);
707
- if (!node) return;
708
- if ((node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement) && event.value !== void 0) node.isoSetProp("value", event.value, false);
709
- if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
710
- node.dispatchEvent(toEvent(event));
1301
+ setValue: (node, value, o = {}) => setValueOf(node, value, o),
1302
+ deliver: (event) => deliverTo(core.known.get(event.target), event),
1303
+ addRoot(o) {
1304
+ const member = makeRoot(core.nextId++);
1305
+ const rec = recorder(member, (b) => o.onBatch(b), o.schedule ?? schedule);
1306
+ member.isoOwner = rec.owner;
1307
+ const mine = (node) => node?.isoKnown && node.isoOwner === rec.owner ? node : void 0;
1308
+ return {
1309
+ root: member,
1310
+ flush: rec.flush,
1311
+ idOf: (node) => mine(node) ? node.isoWire : void 0,
1312
+ setValue(node, value, so = {}) {
1313
+ if (node.isoOwner && node.isoOwner !== rec.owner) throw new TypeError("setValue: not a node of this member's root");
1314
+ setValueOf(node, value, so);
1315
+ },
1316
+ deliver: (event) => deliverTo(mine(event.target === 0 ? member : core.known.get(event.target)), event),
1317
+ dispose() {
1318
+ rec.stop();
1319
+ core.roots.delete(member);
1320
+ forget(member, core);
1321
+ }
1322
+ };
711
1323
  }
712
1324
  };
713
1325
  }
714
1326
  /** A real `Event` with the fields frameworks read from mouse and keyboard events. */
715
1327
  function toEvent(e) {
716
1328
  const ev = new Event(e.type, {
717
- bubbles: true,
1329
+ bubbles: e.type !== "scroll",
718
1330
  cancelable: true
719
1331
  });
720
1332
  const mods = {
@@ -739,8 +1351,8 @@ function toEvent(e) {
739
1351
  });
740
1352
  return ev;
741
1353
  }
742
- var HTML_NS, SVG_NS, str, domError, WEventTarget, WNode, WCharacterData, WText, WComment, kebab, WDOMTokenList, dataAttr, dataKey, WParentNode, WDocumentFragment, WElement, HANDLER_EVENTS, WHTMLElement, WSVGElement, WHTMLIFrameElement, WHTMLInputElement, WHTMLTextAreaElement, WHTMLSelectElement, WHTMLOptionElement, HTML_CLASSES, WDocument;
743
- var init_dom_9S5T0UVQ = __esmMin((() => {
1354
+ var HTML_NS, SVG_NS, str, domError, emit, WEventTarget, WNode, WCharacterData, WText, WComment, kebab, WDOMTokenList, dataAttr, dataKey, WParentNode, WDocumentFragment, WElement, HANDLER_EVENTS, WHTMLElement, WSVGElement, WHTMLIFrameElement, WHTMLInputElement, WHTMLTextAreaElement, WHTMLSelectElement, WHTMLOptionElement, HTML_CLASSES, WDocument, isControl;
1355
+ var init_dom_yLsf0Z4e = __esmMin((() => {
744
1356
  HTML_NS = "http://www.w3.org/1999/xhtml";
745
1357
  SVG_NS = "http://www.w3.org/2000/svg";
746
1358
  str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
@@ -749,6 +1361,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
749
1361
  e.name = name;
750
1362
  return e;
751
1363
  };
1364
+ emit = (n, r) => {
1365
+ n.isoOwner?.push(r);
1366
+ };
752
1367
  WEventTarget = class {
753
1368
  /** @internal */ isoListeners = /* @__PURE__ */ new Map();
754
1369
  /** @internal */ isoParentTarget() {
@@ -891,6 +1506,12 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
891
1506
  /** @internal */ isoNext = null;
892
1507
  /** @internal Whether the host knows this node (it's in the tree under the root). */
893
1508
  isoKnown = false;
1509
+ /**
1510
+ * @internal The root this node was rendered under, once it has been. Kept
1511
+ * after the node leaves the tree, so it can't move to another member's root
1512
+ * in a pool (ADR 0015, decision 3).
1513
+ */
1514
+ isoOwner = null;
894
1515
  constructor(doc, id) {
895
1516
  super();
896
1517
  this.ownerDocument = doc;
@@ -899,10 +1520,17 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
899
1520
  /** @internal */ isoParentTarget() {
900
1521
  return this.isoParent;
901
1522
  }
1523
+ /**
1524
+ * @internal The id the host knows this node by: a render root is always
1525
+ * `ROOT_ID` to its own surface, whatever its id in the document.
1526
+ */
1527
+ get isoWire() {
1528
+ return this.isoOwner?.root === this ? 0 : this.isoId;
1529
+ }
902
1530
  /** @internal */ isoListenChanged(type, on) {
903
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1531
+ if (this.isoKnown) emit(this, [
904
1532
  "listen",
905
- this.isoId,
1533
+ this.isoWire,
906
1534
  type,
907
1535
  on
908
1536
  ]);
@@ -955,9 +1583,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
955
1583
  const data = str(v);
956
1584
  if (data === this.isoData) return;
957
1585
  this.isoData = data;
958
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1586
+ if (this.isoKnown) emit(this, [
959
1587
  "text",
960
- this.isoId,
1588
+ this.isoWire,
961
1589
  data
962
1590
  ]);
963
1591
  }
@@ -1092,27 +1720,28 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1092
1720
  return child;
1093
1721
  }
1094
1722
  if (this.ownerDocument.head === this && child instanceof WElement) this.ownerDocument.isoCore.onHead(child.localName);
1723
+ if (this.isoKnown && ownedElsewhere(child, this.isoOwner)) throw domError("HierarchyRequestError", "insertBefore: a node can't move to another member's root in a pool");
1095
1724
  const wasKnown = child.isoKnown;
1096
1725
  child.isoParent?.isoUnlink(child);
1097
1726
  this.isoLink(child, ref);
1098
1727
  const core = this.ownerDocument.isoCore;
1099
- if (wasKnown && this.isoKnown) core.record([
1728
+ if (wasKnown && this.isoKnown) emit(this, [
1100
1729
  "move",
1101
- this.isoId,
1730
+ this.isoWire,
1102
1731
  child.isoId,
1103
1732
  ref?.isoId ?? null
1104
1733
  ]);
1105
1734
  else if (wasKnown) {
1106
- core.record(["remove", child.isoId]);
1735
+ emit(child, ["remove", child.isoId]);
1107
1736
  forget(child, core);
1108
1737
  } else if (this.isoKnown) {
1109
- core.record([
1738
+ emit(this, [
1110
1739
  "insert",
1111
- this.isoId,
1740
+ this.isoWire,
1112
1741
  serialize(child),
1113
1742
  ref?.isoId ?? null
1114
1743
  ]);
1115
- learn(child, core);
1744
+ learn(child, core, this.isoOwner);
1116
1745
  }
1117
1746
  return child;
1118
1747
  }
@@ -1120,9 +1749,8 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1120
1749
  if (child.isoParent !== this) throw domError("NotFoundError", "removeChild: not a child");
1121
1750
  this.isoUnlink(child);
1122
1751
  if (child.isoKnown) {
1123
- const core = this.ownerDocument.isoCore;
1124
- core.record(["remove", child.isoId]);
1125
- forget(child, core);
1752
+ emit(child, ["remove", child.isoId]);
1753
+ forget(child, this.ownerDocument.isoCore);
1126
1754
  }
1127
1755
  return child;
1128
1756
  }
@@ -1172,6 +1800,11 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1172
1800
  /** @internal */ isoStyle = null;
1173
1801
  /** @internal */ isoClassList = null;
1174
1802
  /** @internal */ isoDataset = null;
1803
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
1804
+ isoScroll = {
1805
+ top: 0,
1806
+ left: 0
1807
+ };
1175
1808
  constructor(doc, id, localName, ns) {
1176
1809
  super(doc, id);
1177
1810
  this.localName = localName;
@@ -1205,9 +1838,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1205
1838
  const v = str(value);
1206
1839
  if (this.isoAttrs.get(n) === v) return;
1207
1840
  this.isoAttrs.set(n, v);
1208
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1841
+ if (this.isoKnown) emit(this, [
1209
1842
  "attr",
1210
- this.isoId,
1843
+ this.isoWire,
1211
1844
  n,
1212
1845
  v
1213
1846
  ]);
@@ -1215,9 +1848,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1215
1848
  removeAttribute(name) {
1216
1849
  const n = this.isoAttrName(name);
1217
1850
  if (!this.isoAttrs.delete(n)) return;
1218
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1851
+ if (this.isoKnown) emit(this, [
1219
1852
  "attr",
1220
- this.isoId,
1853
+ this.isoWire,
1221
1854
  n,
1222
1855
  null
1223
1856
  ]);
@@ -1238,6 +1871,16 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1238
1871
  this.isoDataset ??= createDataset(this);
1239
1872
  return this.isoDataset;
1240
1873
  }
1874
+ /**
1875
+ * Read only, and as of the last `scroll` event the element got: the host
1876
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
1877
+ */
1878
+ get scrollTop() {
1879
+ return this.isoScroll.top;
1880
+ }
1881
+ get scrollLeft() {
1882
+ return this.isoScroll.left;
1883
+ }
1241
1884
  get id() {
1242
1885
  return this.getAttribute("id") ?? "";
1243
1886
  }
@@ -1247,9 +1890,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1247
1890
  /** @internal */ isoSetProp(name, value, record) {
1248
1891
  if (this.isoProps.get(name) === value) return;
1249
1892
  this.isoProps.set(name, value);
1250
- if (record && this.isoKnown) this.ownerDocument.isoCore.record([
1893
+ if (record && this.isoKnown) emit(this, [
1251
1894
  "prop",
1252
- this.isoId,
1895
+ this.isoWire,
1253
1896
  name,
1254
1897
  value
1255
1898
  ]);
@@ -1506,8 +2149,11 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1506
2149
  }
1507
2150
  return null;
1508
2151
  };
1509
- const root = this.isoCore.root;
1510
- return (root ? walk(root) : null) ?? walk(this.head);
2152
+ for (const root of this.isoCore.roots) {
2153
+ const hit = walk(root);
2154
+ if (hit) return hit;
2155
+ }
2156
+ return walk(this.head);
1511
2157
  }
1512
2158
  /**
1513
2159
  * Type selectors only, alone or as a `head > title` child chain: what React
@@ -1542,8 +2188,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1542
2188
  }
1543
2189
  };
1544
2190
  defineHandlers(WDocument.prototype);
2191
+ isControl = (node) => node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement;
1545
2192
  }));
1546
- // ../dom/dist/install-DBKGtAel.js
2193
+ // ../dom/dist/install-D7m7By8i.js
1547
2194
  /**
1548
2195
  * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
1549
2196
  * frameworks find them where they look. Only for isolates with a surface; a
@@ -1563,8 +2210,8 @@ function install(dom, scope) {
1563
2210
  dom.document.defaultView = scope;
1564
2211
  }
1565
2212
  var DOM_GLOBALS;
1566
- var init_install_DBKGtAel = __esmMin((() => {
1567
- init_dom_9S5T0UVQ();
2213
+ var init_install_D7m7By8i = __esmMin((() => {
2214
+ init_dom_yLsf0Z4e();
1568
2215
  DOM_GLOBALS = {
1569
2216
  Node: WNode,
1570
2217
  Element: WElement,
@@ -1584,15 +2231,40 @@ var init_install_DBKGtAel = __esmMin((() => {
1584
2231
  // ../dom/dist/worker.js
1585
2232
  var init_worker = __esmMin((() => {
1586
2233
  init_records_wVZrPpqr();
1587
- init_dom_9S5T0UVQ();
1588
- init_install_DBKGtAel();
2234
+ init_dom_yLsf0Z4e();
2235
+ init_install_D7m7By8i();
1589
2236
  }));
1590
2237
  // src/render/index.ts
2238
+ function sharedDom(scope) {
2239
+ if (!shared) {
2240
+ shared = createDom({
2241
+ onBatch: () => {},
2242
+ onHead: (tag) => {
2243
+ for (const fn of headListeners) fn(tag);
2244
+ }
2245
+ });
2246
+ if (scope) install(shared, scope);
2247
+ }
2248
+ return shared;
2249
+ }
1591
2250
  /**
1592
2251
  * Builds the DOM subset and posts its batches. With `scope`, also installs it
1593
- * as that global's `document` and DOM classes, which frameworks need.
2252
+ * as that global's `document` and DOM classes, which frameworks need. With
2253
+ * `pooled`, the isolate gets its own root in the worker's shared document
2254
+ * instead (ADR 0015).
1594
2255
  */
1595
- function createRender(post, scope) {
2256
+ function createRender(post, scope, pooled = false, member = null) {
2257
+ const owner = member === null ? null : busy.of(member);
2258
+ const schedule = (flush) => {
2259
+ if (owner === null || member === null) {
2260
+ queueMicrotask(flush);
2261
+ return;
2262
+ }
2263
+ busy.report(member, owner.life);
2264
+ nativeQueueMicrotask(() => {
2265
+ busy.run(owner, flush, void 0, []);
2266
+ });
2267
+ };
1596
2268
  let pendingStyles = [];
1597
2269
  let pendingHead = [];
1598
2270
  /** Head tags already reported: each goes to the host once. */
@@ -1620,47 +2292,80 @@ function createRender(post, scope) {
1620
2292
  extrasScheduled = true;
1621
2293
  queueMicrotask(() => {
1622
2294
  extrasScheduled = false;
1623
- dom.flush();
2295
+ target.flush();
1624
2296
  if (pendingStyles.length > 0 || pendingHead.length > 0) postPatch([]);
1625
2297
  });
1626
2298
  };
1627
- const dom = createDom({
1628
- onBatch: postPatch,
1629
- schedule: (flush) => queueMicrotask(flush),
1630
- onHead(tag) {
1631
- if (headSeen.has(tag)) return;
1632
- headSeen.add(tag);
1633
- pendingHead.push(tag);
1634
- scheduleExtras();
1635
- }
1636
- });
1637
- if (scope) install(dom, scope);
2299
+ const onHead = (tag) => {
2300
+ if (headSeen.has(tag)) return;
2301
+ headSeen.add(tag);
2302
+ pendingHead.push(tag);
2303
+ scheduleExtras();
2304
+ };
2305
+ let target;
2306
+ if (pooled) {
2307
+ const own = sharedDom(scope).addRoot({
2308
+ onBatch: postPatch,
2309
+ schedule
2310
+ });
2311
+ headListeners.add(onHead);
2312
+ target = {
2313
+ ...own,
2314
+ dispose() {
2315
+ headListeners.delete(onHead);
2316
+ own.dispose();
2317
+ }
2318
+ };
2319
+ } else {
2320
+ const dom = createDom({
2321
+ onBatch: postPatch,
2322
+ schedule,
2323
+ onHead
2324
+ });
2325
+ if (scope) install(dom, scope);
2326
+ target = {
2327
+ root: dom.root,
2328
+ flush: () => dom.flush(),
2329
+ deliver: (event) => dom.deliver(event),
2330
+ idOf: (node) => node.isConnected ? dom.idOf(node) : void 0,
2331
+ setValue: (node, value, o) => dom.setValue(node, value, o),
2332
+ dispose: () => {}
2333
+ };
2334
+ }
1638
2335
  return {
1639
2336
  fmt: ISOLOOP_DOM_FMT,
1640
- root: dom.root,
1641
- dom,
2337
+ root: target.root,
2338
+ flush: () => target.flush(),
2339
+ setValue: (node, value, o) => target.setValue(node, value, o),
2340
+ dispose: () => target.dispose(),
1642
2341
  styles(css) {
1643
2342
  pendingStyles.push(...typeof css === "string" ? [css] : css);
1644
2343
  scheduleExtras();
1645
2344
  },
1646
- idOf: (node) => node instanceof WNode && node.isConnected ? String(dom.idOf(node)) : void 0,
2345
+ idOf(node) {
2346
+ if (!(node instanceof WNode)) return void 0;
2347
+ const id = target.idOf(node);
2348
+ return id === void 0 ? void 0 : String(id);
2349
+ },
1647
2350
  receive(e) {
1648
- const target = nodeId(e.target);
1649
- if (target === void 0) return;
2351
+ const t = nodeId(e.target);
2352
+ if (t === void 0) return;
1650
2353
  const currentTargets = e.currentTargets.map(nodeId).filter((n) => n !== void 0);
1651
2354
  const { target: _t, currentTargets: _c, ...rest } = e;
1652
- dom.deliver({
2355
+ target.deliver({
1653
2356
  ...rest,
1654
- target,
2357
+ target: t,
1655
2358
  currentTargets
1656
2359
  });
1657
2360
  }
1658
2361
  };
1659
2362
  }
1660
- var nodeId;
2363
+ var nodeId, shared, headListeners;
1661
2364
  var init_render = __esmMin((() => {
1662
2365
  init_worker();
1663
2366
  nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
2367
+ shared = null;
2368
+ headListeners = /* @__PURE__ */ new Set();
1664
2369
  }));
1665
2370
  // package.json
1666
2371
  var version = "0.0.0";
@@ -1681,11 +2386,11 @@ function defineIsolate(def) {
1681
2386
  };
1682
2387
  }
1683
2388
  /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1684
- function createVanillaIsolate(init, post, scope) {
1685
- const render = init.renderFmt === "none" ? null : createRender(post, scope);
2389
+ function createVanillaIsolate(init, post, scope, pooled = false, member = null) {
2390
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled, member);
1686
2391
  const calls = createHostCalls({
1687
2392
  post,
1688
- beforeCall: () => render?.dom.flush(),
2393
+ beforeCall: () => render?.flush(),
1689
2394
  idOf: (node) => render ? render.idOf(node) : void 0,
1690
2395
  surface: render !== null,
1691
2396
  navigate: init.grants.navigate === true
@@ -1693,6 +2398,7 @@ function createVanillaIsolate(init, post, scope) {
1693
2398
  const awake = createKeepAwake();
1694
2399
  const bus = createBusClient(init.busPort, {
1695
2400
  ...init.wake ? { wake: true } : {},
2401
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
1696
2402
  onError: (err) => {
1697
2403
  post({
1698
2404
  v: 1,
@@ -1709,24 +2415,67 @@ function createVanillaIsolate(init, post, scope) {
1709
2415
  }
1710
2416
  });
1711
2417
  const onShutdown = [];
1712
- return {
1713
- ctx: {
1714
- id: init.isolateId,
1715
- config: init.config,
1716
- root: render?.root,
1717
- host: calls.api,
1718
- bus: bus.client,
1719
- styles: (css) => render?.styles(css),
1720
- setValue(node, value, o) {
1721
- if (!render) return;
1722
- if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
1723
- render.dom.setValue(node, value, o);
1724
- },
1725
- onShutdown: (fn) => {
1726
- onShutdown.push(fn);
2418
+ let portal;
2419
+ const ctx = {
2420
+ id: init.isolateId,
2421
+ config: init.config,
2422
+ root: render?.root,
2423
+ portalRoot: void 0,
2424
+ reportError(error, o = {}) {
2425
+ const fatal = o.fatal ?? true;
2426
+ post({
2427
+ v: 1,
2428
+ t: "error",
2429
+ p: error instanceof Error ? {
2430
+ message: error.message,
2431
+ ...error.stack === void 0 ? {} : { stack: error.stack },
2432
+ fatal
2433
+ } : {
2434
+ message: String(error),
2435
+ fatal
2436
+ }
2437
+ });
2438
+ },
2439
+ host: calls.api,
2440
+ bus: bus.client,
2441
+ styles: (css) => render?.styles(css),
2442
+ setValue(node, value, o) {
2443
+ if (!render) return;
2444
+ if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
2445
+ render.setValue(node, value, o);
2446
+ },
2447
+ onShutdown: (fn) => {
2448
+ onShutdown.push(fn);
2449
+ },
2450
+ keepAwake: () => awake.hold()
2451
+ };
2452
+ if (member !== null) Object.defineProperty(ctx, BUSY, {
2453
+ value: {
2454
+ claim: (container) => {
2455
+ busy.claim(container, member);
1727
2456
  },
1728
- keepAwake: () => awake.hold()
2457
+ bind: (fn) => busy.bind(fn)
1729
2458
  },
2459
+ enumerable: false
2460
+ });
2461
+ Object.defineProperty(ctx, "portalRoot", {
2462
+ enumerable: false,
2463
+ get() {
2464
+ if (!render) return void 0;
2465
+ if (!portal) {
2466
+ const { root } = render;
2467
+ const div = root.ownerDocument.createElement("div");
2468
+ div.setAttribute("data-isoloop-portal", "");
2469
+ queueMicrotask(() => {
2470
+ if (div.parentNode !== root) root.appendChild(div);
2471
+ });
2472
+ portal = div;
2473
+ }
2474
+ return portal;
2475
+ }
2476
+ });
2477
+ return {
2478
+ ctx,
1730
2479
  renderFmt: render ? render.fmt : "none",
1731
2480
  receive(msg) {
1732
2481
  if (isHostToIsolate(msg)) {
@@ -1745,7 +2494,9 @@ function createVanillaIsolate(init, post, scope) {
1745
2494
  },
1746
2495
  async shutdown(reason) {
1747
2496
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
1748
- render?.dom.flush();
2497
+ await bus.close();
2498
+ render?.flush();
2499
+ render?.dispose();
1749
2500
  }
1750
2501
  };
1751
2502
  }
@@ -1753,6 +2504,7 @@ var REQUIRES;
1753
2504
  var init_vanilla = __esmMin((() => {
1754
2505
  init_dist();
1755
2506
  init_bus_client();
2507
+ init_busy();
1756
2508
  init_host_calls();
1757
2509
  init_keep_awake();
1758
2510
  init_worker();
@@ -1761,11 +2513,20 @@ var init_vanilla = __esmMin((() => {
1761
2513
  }));
1762
2514
  // src/bootstrap.ts
1763
2515
  init_dist();
1764
- const post = (msg) => {
2516
+ init_busy();
2517
+ let mode = null;
2518
+ const members = /* @__PURE__ */ new Map();
2519
+ const postWorker = (msg) => {
1765
2520
  self.postMessage(msg);
1766
2521
  };
1767
- const fatal = (message, code) => {
1768
- post({
2522
+ const memberPost = (name) => (msg) => {
2523
+ self.postMessage(name === void 0 ? msg : {
2524
+ ...msg,
2525
+ isolate: name
2526
+ });
2527
+ };
2528
+ const fatal = (m, message, code) => {
2529
+ m.post({
1769
2530
  v: 1,
1770
2531
  t: "error",
1771
2532
  p: code ? {
@@ -1778,46 +2539,78 @@ const fatal = (message, code) => {
1778
2539
  }
1779
2540
  });
1780
2541
  };
1781
- /** Set once the isolate has started: what the beat reports for suspension (ADR 0001). */
1782
- let idleReport = null;
2542
+ let beating = false;
2543
+ /** Once per worker, after the first isolate's protocol check. */
1783
2544
  function startHeartbeat(everyMs) {
2545
+ if (beating) return;
2546
+ beating = true;
1784
2547
  let last = performance.now();
1785
2548
  setInterval(() => {
1786
2549
  const now = performance.now();
1787
2550
  const lagMs = Math.max(0, now - last - everyMs);
1788
- post({
1789
- v: 1,
1790
- t: "beat",
1791
- p: idleReport ? {
1792
- lagMs,
1793
- idle: idleReport()
1794
- } : { lagMs }
1795
- });
2551
+ if (mode === "pool") {
2552
+ const reports = {};
2553
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
2554
+ postWorker({
2555
+ v: 1,
2556
+ t: "beat",
2557
+ p: {
2558
+ lagMs,
2559
+ members: reports
2560
+ }
2561
+ });
2562
+ } else {
2563
+ const idle = members.get(void 0)?.idleReport?.();
2564
+ postWorker({
2565
+ v: 1,
2566
+ t: "beat",
2567
+ p: idle ? {
2568
+ lagMs,
2569
+ idle
2570
+ } : { lagMs }
2571
+ });
2572
+ }
1796
2573
  last = now;
1797
2574
  }, everyMs);
1798
2575
  }
1799
- async function boot(init) {
2576
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
2577
+ function shutdownMember(m, graceMs, reason) {
2578
+ if (members.get(m.name) === m) members.delete(m.name);
2579
+ m.receive = null;
2580
+ const hook = m.shutdownHook;
2581
+ const done = (hook ? busy.run(busy.of(m.name, m.life), hook, void 0, [reason]) : void 0) ?? Promise.resolve();
2582
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2583
+ Promise.race([done, grace]).finally(() => {
2584
+ busy.end(m.life);
2585
+ m.post({
2586
+ v: 1,
2587
+ t: "bye",
2588
+ p: {}
2589
+ });
2590
+ if (members.size === 0) self.close();
2591
+ });
2592
+ }
2593
+ /** Routes one message from the host to the member it is for. */
2594
+ function route(msg) {
2595
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
2596
+ if (!m) return;
2597
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2598
+ else if (m.receive) busy.run(busy.of(m.name, m.life), m.receive, void 0, [msg]);
2599
+ }
2600
+ async function boot(m, init) {
1800
2601
  if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
1801
- fatal(`Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
2602
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
1802
2603
  return;
1803
2604
  }
1804
- self.addEventListener("message", (e) => {
1805
- const msg = e.data;
1806
- if (!isHostToIsolate(msg) || msg.t !== "shutdown") return;
1807
- const done = shutdownHook?.(msg.p.reason) ?? Promise.resolve();
1808
- const grace = new Promise((r) => setTimeout(r, Math.max(0, msg.p.graceMs - 50)));
1809
- Promise.race([done, grace]).finally(() => {
1810
- post({
1811
- v: 1,
1812
- t: "bye",
1813
- p: {}
1814
- });
1815
- self.close();
1816
- });
1817
- });
1818
2605
  startHeartbeat(init.heartbeatMs);
1819
2606
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
1820
- const runtime = createVanillaIsolate(init, post, self);
2607
+ const runtime = busy.run(busy.of(m.name, m.life), createVanillaIsolate, void 0, [
2608
+ init,
2609
+ m.post,
2610
+ self,
2611
+ mode === "pool",
2612
+ m.name
2613
+ ]);
1821
2614
  let mod;
1822
2615
  try {
1823
2616
  mod = await import(
@@ -1827,7 +2620,7 @@ async function boot(init) {
1827
2620
  } catch (err) {
1828
2621
  const why = err instanceof Error ? err.message : String(err);
1829
2622
  const cross = new URL(init.src).origin !== self.location.origin;
1830
- fatal(`Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
2623
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
1831
2624
  return;
1832
2625
  }
1833
2626
  const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
@@ -1835,21 +2628,22 @@ async function boot(init) {
1835
2628
  const start = main.start;
1836
2629
  if (typeof start === "function") {
1837
2630
  const requires = "requires" in main ? main.requires : void 0;
1838
- await startIsolate(runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
2631
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
1839
2632
  return;
1840
2633
  }
1841
2634
  }
1842
- fatal(`${init.src} has no default export with start(ctx)`);
2635
+ fatal(m, `${init.src} has no default export with start(ctx)`);
1843
2636
  }
1844
- /** Set by a `{ start(ctx) }` isolate: runs its onShutdown handlers. */
1845
- let shutdownHook = null;
1846
- async function startIsolate(runtime, start, requires) {
1847
- self.addEventListener("message", (e) => {
1848
- runtime.receive(e.data);
2637
+ async function startIsolate(m, runtime, start, requires) {
2638
+ m.receive = (msg) => {
2639
+ runtime.receive(msg);
2640
+ };
2641
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2642
+ m.idleReport = () => ({
2643
+ ...runtime.idle(),
2644
+ busyMs: busy.take(m.name)
1849
2645
  });
1850
- shutdownHook = (reason) => runtime.shutdown(reason);
1851
- idleReport = () => runtime.idle();
1852
- post({
2646
+ m.post({
1853
2647
  v: 1,
1854
2648
  t: "ready",
1855
2649
  p: {
@@ -1860,17 +2654,48 @@ async function startIsolate(runtime, start, requires) {
1860
2654
  }
1861
2655
  });
1862
2656
  try {
1863
- await start(runtime.ctx);
2657
+ await busy.run(busy.of(m.name, m.life), start, void 0, [runtime.ctx]);
1864
2658
  } catch (err) {
1865
- fatal(`start() threw: ${err instanceof Error ? err.message : String(err)}`);
2659
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
1866
2660
  }
1867
2661
  }
1868
- const onInit = (e) => {
2662
+ /** Handles one message from the host: `init` boots a member, the rest is routed. */
2663
+ function onMessage(e) {
1869
2664
  const msg = e.data;
1870
- if (!isHostToIsolate(msg) || msg.t !== "init") return;
1871
- self.removeEventListener("message", onInit);
1872
- boot(msg.p).catch((err) => {
1873
- fatal(err instanceof Error ? err.message : String(err));
2665
+ if (!isHostToIsolate(msg)) return;
2666
+ if (msg.t !== "init") {
2667
+ route(msg);
2668
+ return;
2669
+ }
2670
+ const name = msg.isolate;
2671
+ const wants = name === void 0 ? "own" : "pool";
2672
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2673
+ if (mode === null) {
2674
+ mode = wants;
2675
+ if (mode === "pool") freezeBuiltins();
2676
+ }
2677
+ if (members.has(name)) return;
2678
+ const m = {
2679
+ name,
2680
+ life: busy.begin(name),
2681
+ post: memberPost(name),
2682
+ shutdownHook: null,
2683
+ idleReport: null,
2684
+ receive: null
2685
+ };
2686
+ members.set(name, m);
2687
+ boot(m, msg.p).catch((err) => {
2688
+ fatal(m, err instanceof Error ? err.message : String(err));
1874
2689
  });
1875
- };
1876
- self.addEventListener("message", onInit);
2690
+ }
2691
+ const STARTED = Symbol.for("isoloop.bootstrap");
2692
+ function startOnce() {
2693
+ installBusy(self, busy);
2694
+ self.addEventListener("message", onMessage);
2695
+ }
2696
+ if (Reflect.get(self, STARTED) === true) {
2697
+ if (import.meta.env?.DEV === true) console.warn("isoloop: worker entry evaluated twice; ignoring");
2698
+ } else {
2699
+ Reflect.set(self, STARTED, true);
2700
+ startOnce();
2701
+ }