@isoloop/runtime 0.0.0-next.69da74b → 0.0.0-next.b8ffdcf

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,168 @@ var init_dist = __esmMin((() => {
151
215
  retention: { kind: "compacted" }
152
216
  });
153
217
  }));
218
+ // src/freeze.ts
219
+ init_dist();
220
+ /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
221
+ const NAMES = [
222
+ "Object",
223
+ "Function",
224
+ "Array",
225
+ "String",
226
+ "Number",
227
+ "Boolean",
228
+ "Symbol",
229
+ "BigInt",
230
+ "Date",
231
+ "RegExp",
232
+ "Error",
233
+ "EvalError",
234
+ "RangeError",
235
+ "ReferenceError",
236
+ "SyntaxError",
237
+ "TypeError",
238
+ "URIError",
239
+ "AggregateError",
240
+ "Promise",
241
+ "Map",
242
+ "Set",
243
+ "WeakMap",
244
+ "WeakSet",
245
+ "WeakRef",
246
+ "FinalizationRegistry",
247
+ "ArrayBuffer",
248
+ "DataView",
249
+ "Int8Array",
250
+ "Uint8Array",
251
+ "Uint8ClampedArray",
252
+ "Int16Array",
253
+ "Uint16Array",
254
+ "Int32Array",
255
+ "Uint32Array",
256
+ "Float32Array",
257
+ "Float64Array",
258
+ "BigInt64Array",
259
+ "BigUint64Array"
260
+ ];
261
+ /**
262
+ * Freezing a prototype makes its data properties read-only, and in strict
263
+ * code assigning a property of the same name on an instance then throws (the
264
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`,
265
+ * or `Object.assign({}, { constructor: x })`). As Hardened JS does, each data
266
+ * property becomes an accessor whose setter defines the property on the
267
+ * instance instead, so overriding still works while the prototype itself
268
+ * can't change.
269
+ *
270
+ * Except the properties V8 guards with "protectors": while they are still the
271
+ * original data properties, V8 keeps fast paths for iteration (`for…of`,
272
+ * spread, destructuring), species lookups and promise resolution. An accessor
273
+ * returning the same function is enough to turn a protector off for the whole
274
+ * worker: array iteration alone made a pool's app code 1.4–2.5× slower
275
+ * (docs/investigations/plant-one-pool.md). These stay plain frozen data, so
276
+ * overriding one of them on an instance throws in strict code instead
277
+ * (ADR 0001, "Override taming without the protected properties").
278
+ */
279
+ const ITERATOR = Symbol.iterator;
280
+ /** The protected properties, per prototype, that are left as frozen data. */
281
+ function protectedProperties() {
282
+ const out = /* @__PURE__ */ new Map();
283
+ const add = (o, ...keys) => {
284
+ if (typeof o !== "object" && typeof o !== "function" || o === null) return;
285
+ out.set(o, /* @__PURE__ */ new Set([...out.get(o) ?? [], ...keys]));
286
+ };
287
+ const typedArrayCtor = Object.getPrototypeOf(Int8Array);
288
+ const typedArray = typeof typedArrayCtor === "function" ? Reflect.get(typedArrayCtor, "prototype") : void 0;
289
+ add(Array.prototype, ITERATOR, "constructor");
290
+ add(Object.getPrototypeOf([][Symbol.iterator]()), "next");
291
+ add(Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())), ITERATOR);
292
+ add(typedArray, ITERATOR, "constructor");
293
+ for (const c of [
294
+ Int8Array,
295
+ Uint8Array,
296
+ Uint8ClampedArray,
297
+ Int16Array,
298
+ Uint16Array,
299
+ Int32Array,
300
+ Uint32Array,
301
+ Float32Array,
302
+ Float64Array,
303
+ BigInt64Array,
304
+ BigUint64Array
305
+ ]) add(c.prototype, "constructor");
306
+ add(Map.prototype, ITERATOR);
307
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), "next");
308
+ add(Set.prototype, ITERATOR);
309
+ add(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), "next");
310
+ add(String.prototype, ...Reflect.ownKeys(String.prototype));
311
+ add(Object.getPrototypeOf(""[Symbol.iterator]()), "next");
312
+ add(Promise.prototype, "then", "constructor");
313
+ add(RegExp.prototype, ...Reflect.ownKeys(RegExp.prototype));
314
+ return out;
315
+ }
316
+ let skip;
317
+ function tameOverrides(proto) {
318
+ skip ??= protectedProperties();
319
+ const keep = skip.get(proto);
320
+ for (const key of Reflect.ownKeys(proto)) if (!keep?.has(key)) tameOverride(proto, key);
321
+ }
322
+ function tameOverride(proto, key) {
323
+ const d = Object.getOwnPropertyDescriptor(proto, key);
324
+ if (!d || !("value" in d) || !d.configurable) return;
325
+ const value = d.value;
326
+ Object.defineProperty(proto, key, {
327
+ get() {
328
+ return value;
329
+ },
330
+ set(v) {
331
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
332
+ if (typeof this !== "object" && typeof this !== "function") return;
333
+ if (this === null) return;
334
+ Object.defineProperty(this, key, {
335
+ value: v,
336
+ writable: true,
337
+ enumerable: true,
338
+ configurable: true
339
+ });
340
+ },
341
+ enumerable: d.enumerable ?? false,
342
+ configurable: false
343
+ });
344
+ }
345
+ function hardenProto(proto) {
346
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
347
+ if (Object.isFrozen(proto)) return;
348
+ tameOverrides(proto);
349
+ Object.freeze(proto);
350
+ }
351
+ function freezeWithPrototype(c) {
352
+ if (typeof c !== "function") return;
353
+ hardenProto(Reflect.get(c, "prototype"));
354
+ if (c !== Error) Object.freeze(c);
355
+ }
356
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
357
+ function freezeBuiltins() {
358
+ const g = globalThis;
359
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
360
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
361
+ const protos = [
362
+ Object.getPrototypeOf([][Symbol.iterator]()),
363
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
364
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
365
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
366
+ Object.getPrototypeOf(""[Symbol.iterator]()),
367
+ Object.getPrototypeOf(function* () {}),
368
+ Object.getPrototypeOf(async function() {}),
369
+ Object.getPrototypeOf(async function* () {})
370
+ ];
371
+ for (const p of protos) {
372
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
373
+ hardenProto(Reflect.get(p, "prototype"));
374
+ hardenProto(p);
375
+ }
376
+ Object.freeze(Math);
377
+ Object.freeze(JSON);
378
+ Object.freeze(Reflect);
379
+ }
154
380
  // src/bus-client.ts
155
381
  function createBusClient(first, o = {}) {
156
382
  const limit = o.inboxLimit ?? 1e3;
@@ -189,15 +415,19 @@ function createBusClient(first, o = {}) {
189
415
  send(withId);
190
416
  });
191
417
  };
418
+ const committer = createCommitter({
419
+ send: (offsets) => {
420
+ send({
421
+ v: 1,
422
+ t: "commits",
423
+ p: { offsets }
424
+ });
425
+ },
426
+ ...o.commitIntervalMs === void 0 ? {} : { intervalMs: o.commitIntervalMs },
427
+ ...o.credit === void 0 ? {} : { credit: o.credit }
428
+ });
192
429
  const commit = (topic, offset) => {
193
- send({
194
- v: 1,
195
- t: "commit",
196
- p: {
197
- topic,
198
- offset
199
- }
200
- });
430
+ committer.settle(topic, offset);
201
431
  };
202
432
  const drain = async (sub) => {
203
433
  if (sub.running) return;
@@ -207,7 +437,8 @@ function createBusClient(first, o = {}) {
207
437
  if (!r) break;
208
438
  topicOf.set(r, sub.topic);
209
439
  try {
210
- await sub.fn(r);
440
+ const done = sub.fn(r);
441
+ if (isThenable(done)) await done;
211
442
  } catch (err) {
212
443
  sub.stuck = true;
213
444
  o.onError?.(err);
@@ -258,6 +489,7 @@ function createBusClient(first, o = {}) {
258
489
  const sub = subs.get(msg.p.topic);
259
490
  if (!sub) return;
260
491
  sub.queue.length = 0;
492
+ committer.drop(msg.p.topic);
261
493
  try {
262
494
  sub.opts.onReset?.();
263
495
  } catch (err) {
@@ -306,6 +538,7 @@ function createBusClient(first, o = {}) {
306
538
  return () => {
307
539
  if (subs.get(topic.name) !== sub) return;
308
540
  subs.delete(topic.name);
541
+ committer.flush();
309
542
  send({
310
543
  v: 1,
311
544
  t: "unsubscribe",
@@ -381,17 +614,29 @@ function createBusClient(first, o = {}) {
381
614
  value: null
382
615
  });
383
616
  }
617
+ committer.take();
384
618
  for (const sub of subs.values()) {
385
619
  sub.queue.length = 0;
386
620
  sendSubscribe(sub);
387
621
  }
388
622
  for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
623
+ },
624
+ async close() {
625
+ const offsets = committer.take();
626
+ committer.dispose();
627
+ if (offsets) await call({
628
+ v: 1,
629
+ t: "commits",
630
+ p: { offsets }
631
+ });
389
632
  }
390
633
  };
391
634
  }
635
+ function isThenable(x) {
636
+ return (typeof x === "object" || typeof x === "function") && x !== null && typeof x.then === "function";
637
+ }
392
638
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
393
639
  var init_bus_client = __esmMin((() => {
394
- init_dist();
395
640
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
396
641
  check = (r) => {
397
642
  if (!r.ok) throw new BusError(r.error);
@@ -516,7 +761,7 @@ var ISOLOOP_DOM_FMT;
516
761
  var init_records_wVZrPpqr = __esmMin((() => {
517
762
  ISOLOOP_DOM_FMT = "isoloop-dom@1";
518
763
  }));
519
- // ../dom/dist/dom-9S5T0UVQ.js
764
+ // ../dom/dist/dom-yLsf0Z4e.js
520
765
  function createStyle(el) {
521
766
  const decls = /* @__PURE__ */ new Map();
522
767
  const write = () => {
@@ -643,78 +888,131 @@ function serialize(n) {
643
888
  children: n.childNodes.map(serialize)
644
889
  };
645
890
  }
646
- function learn(n, core) {
891
+ /** Whether `n` or anything under it was rendered under a root other than `owner`. */
892
+ function ownedElsewhere(n, owner) {
893
+ if (n.isoOwner && n.isoOwner !== owner) return true;
894
+ return !n.isoKnown && n.childNodes.some((c) => ownedElsewhere(c, owner));
895
+ }
896
+ function learn(n, core, owner) {
647
897
  n.isoKnown = true;
898
+ n.isoOwner = owner;
648
899
  core.known.set(n.isoId, n);
649
- for (const c of n.childNodes) learn(c, core);
900
+ for (const c of n.childNodes) learn(c, core, owner);
650
901
  }
651
902
  function forget(n, core) {
652
903
  n.isoKnown = false;
653
904
  core.known.delete(n.isoId);
654
905
  for (const c of n.childNodes) forget(c, core);
655
906
  }
656
- function createDom(opts) {
657
- const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
907
+ function setValueOf(node, value, o) {
908
+ if (!isControl(node)) throw new TypeError("setValue: not an input, textarea or select");
909
+ if (!o.force) {
910
+ node.value = value;
911
+ return;
912
+ }
913
+ node.isoSetProp("value", value, false);
914
+ if (node.isoKnown) emit(node, [
915
+ "prop",
916
+ node.isoWire,
917
+ "value",
918
+ value,
919
+ true
920
+ ]);
921
+ }
922
+ function deliverTo(node, event) {
923
+ if (!node) return;
924
+ if (isControl(node) && event.value !== void 0) node.isoSetProp("value", event.value, false);
925
+ if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
926
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
927
+ top: event.scrollTop ?? 0,
928
+ left: event.scrollLeft ?? 0
929
+ };
930
+ node.dispatchEvent(toEvent(event));
931
+ }
932
+ /** A root's recorder: records batched per microtask (or `schedule`) into `onBatch`. */
933
+ function recorder(root, onBatch, schedule) {
658
934
  let pending = [];
659
935
  let scheduled = false;
936
+ let live = true;
660
937
  const flush = () => {
661
938
  scheduled = false;
662
939
  if (pending.length === 0) return;
663
940
  const batch = pending;
664
941
  pending = [];
665
- opts.onBatch(batch);
942
+ if (live) onBatch(batch);
666
943
  };
944
+ return {
945
+ owner: {
946
+ root,
947
+ push(r) {
948
+ if (!live) return;
949
+ pending.push(r);
950
+ if (!scheduled) {
951
+ scheduled = true;
952
+ schedule(flush);
953
+ }
954
+ }
955
+ },
956
+ flush,
957
+ stop: () => {
958
+ live = false;
959
+ pending = [];
960
+ }
961
+ };
962
+ }
963
+ function createDom(opts) {
964
+ const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
667
965
  const core = {
668
- root: null,
966
+ roots: /* @__PURE__ */ new Set(),
669
967
  nextId: 1,
670
968
  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
- }
969
+ onHead: opts.onHead ?? (() => {})
679
970
  };
680
971
  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;
972
+ const makeRoot = (id) => {
973
+ const root = new WHTMLElement(document, id, "iso-root", "html");
974
+ root.isoKnown = true;
975
+ core.known.set(id, root);
976
+ core.roots.add(root);
977
+ return root;
978
+ };
979
+ const root = makeRoot(0);
980
+ const main = recorder(root, (b) => opts.onBatch(b), schedule);
981
+ root.isoOwner = main.owner;
685
982
  return {
686
983
  document,
687
984
  root,
688
- flush,
985
+ flush: main.flush,
689
986
  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));
987
+ setValue: (node, value, o = {}) => setValueOf(node, value, o),
988
+ deliver: (event) => deliverTo(core.known.get(event.target), event),
989
+ addRoot(o) {
990
+ const member = makeRoot(core.nextId++);
991
+ const rec = recorder(member, (b) => o.onBatch(b), o.schedule ?? schedule);
992
+ member.isoOwner = rec.owner;
993
+ const mine = (node) => node?.isoKnown && node.isoOwner === rec.owner ? node : void 0;
994
+ return {
995
+ root: member,
996
+ flush: rec.flush,
997
+ idOf: (node) => mine(node) ? node.isoWire : void 0,
998
+ setValue(node, value, so = {}) {
999
+ if (node.isoOwner && node.isoOwner !== rec.owner) throw new TypeError("setValue: not a node of this member's root");
1000
+ setValueOf(node, value, so);
1001
+ },
1002
+ deliver: (event) => deliverTo(mine(event.target === 0 ? member : core.known.get(event.target)), event),
1003
+ dispose() {
1004
+ rec.stop();
1005
+ core.roots.delete(member);
1006
+ forget(member, core);
1007
+ }
1008
+ };
711
1009
  }
712
1010
  };
713
1011
  }
714
1012
  /** A real `Event` with the fields frameworks read from mouse and keyboard events. */
715
1013
  function toEvent(e) {
716
1014
  const ev = new Event(e.type, {
717
- bubbles: true,
1015
+ bubbles: e.type !== "scroll",
718
1016
  cancelable: true
719
1017
  });
720
1018
  const mods = {
@@ -739,8 +1037,8 @@ function toEvent(e) {
739
1037
  });
740
1038
  return ev;
741
1039
  }
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((() => {
1040
+ 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;
1041
+ var init_dom_yLsf0Z4e = __esmMin((() => {
744
1042
  HTML_NS = "http://www.w3.org/1999/xhtml";
745
1043
  SVG_NS = "http://www.w3.org/2000/svg";
746
1044
  str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
@@ -749,6 +1047,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
749
1047
  e.name = name;
750
1048
  return e;
751
1049
  };
1050
+ emit = (n, r) => {
1051
+ n.isoOwner?.push(r);
1052
+ };
752
1053
  WEventTarget = class {
753
1054
  /** @internal */ isoListeners = /* @__PURE__ */ new Map();
754
1055
  /** @internal */ isoParentTarget() {
@@ -891,6 +1192,12 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
891
1192
  /** @internal */ isoNext = null;
892
1193
  /** @internal Whether the host knows this node (it's in the tree under the root). */
893
1194
  isoKnown = false;
1195
+ /**
1196
+ * @internal The root this node was rendered under, once it has been. Kept
1197
+ * after the node leaves the tree, so it can't move to another member's root
1198
+ * in a pool (ADR 0015, decision 3).
1199
+ */
1200
+ isoOwner = null;
894
1201
  constructor(doc, id) {
895
1202
  super();
896
1203
  this.ownerDocument = doc;
@@ -899,10 +1206,17 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
899
1206
  /** @internal */ isoParentTarget() {
900
1207
  return this.isoParent;
901
1208
  }
1209
+ /**
1210
+ * @internal The id the host knows this node by: a render root is always
1211
+ * `ROOT_ID` to its own surface, whatever its id in the document.
1212
+ */
1213
+ get isoWire() {
1214
+ return this.isoOwner?.root === this ? 0 : this.isoId;
1215
+ }
902
1216
  /** @internal */ isoListenChanged(type, on) {
903
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1217
+ if (this.isoKnown) emit(this, [
904
1218
  "listen",
905
- this.isoId,
1219
+ this.isoWire,
906
1220
  type,
907
1221
  on
908
1222
  ]);
@@ -955,9 +1269,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
955
1269
  const data = str(v);
956
1270
  if (data === this.isoData) return;
957
1271
  this.isoData = data;
958
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1272
+ if (this.isoKnown) emit(this, [
959
1273
  "text",
960
- this.isoId,
1274
+ this.isoWire,
961
1275
  data
962
1276
  ]);
963
1277
  }
@@ -1092,27 +1406,28 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1092
1406
  return child;
1093
1407
  }
1094
1408
  if (this.ownerDocument.head === this && child instanceof WElement) this.ownerDocument.isoCore.onHead(child.localName);
1409
+ 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
1410
  const wasKnown = child.isoKnown;
1096
1411
  child.isoParent?.isoUnlink(child);
1097
1412
  this.isoLink(child, ref);
1098
1413
  const core = this.ownerDocument.isoCore;
1099
- if (wasKnown && this.isoKnown) core.record([
1414
+ if (wasKnown && this.isoKnown) emit(this, [
1100
1415
  "move",
1101
- this.isoId,
1416
+ this.isoWire,
1102
1417
  child.isoId,
1103
1418
  ref?.isoId ?? null
1104
1419
  ]);
1105
1420
  else if (wasKnown) {
1106
- core.record(["remove", child.isoId]);
1421
+ emit(child, ["remove", child.isoId]);
1107
1422
  forget(child, core);
1108
1423
  } else if (this.isoKnown) {
1109
- core.record([
1424
+ emit(this, [
1110
1425
  "insert",
1111
- this.isoId,
1426
+ this.isoWire,
1112
1427
  serialize(child),
1113
1428
  ref?.isoId ?? null
1114
1429
  ]);
1115
- learn(child, core);
1430
+ learn(child, core, this.isoOwner);
1116
1431
  }
1117
1432
  return child;
1118
1433
  }
@@ -1120,9 +1435,8 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1120
1435
  if (child.isoParent !== this) throw domError("NotFoundError", "removeChild: not a child");
1121
1436
  this.isoUnlink(child);
1122
1437
  if (child.isoKnown) {
1123
- const core = this.ownerDocument.isoCore;
1124
- core.record(["remove", child.isoId]);
1125
- forget(child, core);
1438
+ emit(child, ["remove", child.isoId]);
1439
+ forget(child, this.ownerDocument.isoCore);
1126
1440
  }
1127
1441
  return child;
1128
1442
  }
@@ -1172,6 +1486,11 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1172
1486
  /** @internal */ isoStyle = null;
1173
1487
  /** @internal */ isoClassList = null;
1174
1488
  /** @internal */ isoDataset = null;
1489
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
1490
+ isoScroll = {
1491
+ top: 0,
1492
+ left: 0
1493
+ };
1175
1494
  constructor(doc, id, localName, ns) {
1176
1495
  super(doc, id);
1177
1496
  this.localName = localName;
@@ -1205,9 +1524,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1205
1524
  const v = str(value);
1206
1525
  if (this.isoAttrs.get(n) === v) return;
1207
1526
  this.isoAttrs.set(n, v);
1208
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1527
+ if (this.isoKnown) emit(this, [
1209
1528
  "attr",
1210
- this.isoId,
1529
+ this.isoWire,
1211
1530
  n,
1212
1531
  v
1213
1532
  ]);
@@ -1215,9 +1534,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1215
1534
  removeAttribute(name) {
1216
1535
  const n = this.isoAttrName(name);
1217
1536
  if (!this.isoAttrs.delete(n)) return;
1218
- if (this.isoKnown) this.ownerDocument.isoCore.record([
1537
+ if (this.isoKnown) emit(this, [
1219
1538
  "attr",
1220
- this.isoId,
1539
+ this.isoWire,
1221
1540
  n,
1222
1541
  null
1223
1542
  ]);
@@ -1238,6 +1557,16 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1238
1557
  this.isoDataset ??= createDataset(this);
1239
1558
  return this.isoDataset;
1240
1559
  }
1560
+ /**
1561
+ * Read only, and as of the last `scroll` event the element got: the host
1562
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
1563
+ */
1564
+ get scrollTop() {
1565
+ return this.isoScroll.top;
1566
+ }
1567
+ get scrollLeft() {
1568
+ return this.isoScroll.left;
1569
+ }
1241
1570
  get id() {
1242
1571
  return this.getAttribute("id") ?? "";
1243
1572
  }
@@ -1247,9 +1576,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1247
1576
  /** @internal */ isoSetProp(name, value, record) {
1248
1577
  if (this.isoProps.get(name) === value) return;
1249
1578
  this.isoProps.set(name, value);
1250
- if (record && this.isoKnown) this.ownerDocument.isoCore.record([
1579
+ if (record && this.isoKnown) emit(this, [
1251
1580
  "prop",
1252
- this.isoId,
1581
+ this.isoWire,
1253
1582
  name,
1254
1583
  value
1255
1584
  ]);
@@ -1506,8 +1835,11 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1506
1835
  }
1507
1836
  return null;
1508
1837
  };
1509
- const root = this.isoCore.root;
1510
- return (root ? walk(root) : null) ?? walk(this.head);
1838
+ for (const root of this.isoCore.roots) {
1839
+ const hit = walk(root);
1840
+ if (hit) return hit;
1841
+ }
1842
+ return walk(this.head);
1511
1843
  }
1512
1844
  /**
1513
1845
  * Type selectors only, alone or as a `head > title` child chain: what React
@@ -1542,8 +1874,9 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1542
1874
  }
1543
1875
  };
1544
1876
  defineHandlers(WDocument.prototype);
1877
+ isControl = (node) => node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement;
1545
1878
  }));
1546
- // ../dom/dist/install-DBKGtAel.js
1879
+ // ../dom/dist/install-D7m7By8i.js
1547
1880
  /**
1548
1881
  * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
1549
1882
  * frameworks find them where they look. Only for isolates with a surface; a
@@ -1563,8 +1896,8 @@ function install(dom, scope) {
1563
1896
  dom.document.defaultView = scope;
1564
1897
  }
1565
1898
  var DOM_GLOBALS;
1566
- var init_install_DBKGtAel = __esmMin((() => {
1567
- init_dom_9S5T0UVQ();
1899
+ var init_install_D7m7By8i = __esmMin((() => {
1900
+ init_dom_yLsf0Z4e();
1568
1901
  DOM_GLOBALS = {
1569
1902
  Node: WNode,
1570
1903
  Element: WElement,
@@ -1584,15 +1917,29 @@ var init_install_DBKGtAel = __esmMin((() => {
1584
1917
  // ../dom/dist/worker.js
1585
1918
  var init_worker = __esmMin((() => {
1586
1919
  init_records_wVZrPpqr();
1587
- init_dom_9S5T0UVQ();
1588
- init_install_DBKGtAel();
1920
+ init_dom_yLsf0Z4e();
1921
+ init_install_D7m7By8i();
1589
1922
  }));
1590
1923
  // src/render/index.ts
1924
+ function sharedDom(scope) {
1925
+ if (!shared) {
1926
+ shared = createDom({
1927
+ onBatch: () => {},
1928
+ onHead: (tag) => {
1929
+ for (const fn of headListeners) fn(tag);
1930
+ }
1931
+ });
1932
+ if (scope) install(shared, scope);
1933
+ }
1934
+ return shared;
1935
+ }
1591
1936
  /**
1592
1937
  * 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.
1938
+ * as that global's `document` and DOM classes, which frameworks need. With
1939
+ * `pooled`, the isolate gets its own root in the worker's shared document
1940
+ * instead (ADR 0015).
1594
1941
  */
1595
- function createRender(post, scope) {
1942
+ function createRender(post, scope, pooled = false) {
1596
1943
  let pendingStyles = [];
1597
1944
  let pendingHead = [];
1598
1945
  /** Head tags already reported: each goes to the host once. */
@@ -1620,47 +1967,77 @@ function createRender(post, scope) {
1620
1967
  extrasScheduled = true;
1621
1968
  queueMicrotask(() => {
1622
1969
  extrasScheduled = false;
1623
- dom.flush();
1970
+ target.flush();
1624
1971
  if (pendingStyles.length > 0 || pendingHead.length > 0) postPatch([]);
1625
1972
  });
1626
1973
  };
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);
1974
+ const onHead = (tag) => {
1975
+ if (headSeen.has(tag)) return;
1976
+ headSeen.add(tag);
1977
+ pendingHead.push(tag);
1978
+ scheduleExtras();
1979
+ };
1980
+ let target;
1981
+ if (pooled) {
1982
+ const member = sharedDom(scope).addRoot({ onBatch: postPatch });
1983
+ headListeners.add(onHead);
1984
+ target = {
1985
+ ...member,
1986
+ dispose() {
1987
+ headListeners.delete(onHead);
1988
+ member.dispose();
1989
+ }
1990
+ };
1991
+ } else {
1992
+ const dom = createDom({
1993
+ onBatch: postPatch,
1994
+ schedule: (flush) => queueMicrotask(flush),
1995
+ onHead
1996
+ });
1997
+ if (scope) install(dom, scope);
1998
+ target = {
1999
+ root: dom.root,
2000
+ flush: () => dom.flush(),
2001
+ deliver: (event) => dom.deliver(event),
2002
+ idOf: (node) => node.isConnected ? dom.idOf(node) : void 0,
2003
+ setValue: (node, value, o) => dom.setValue(node, value, o),
2004
+ dispose: () => {}
2005
+ };
2006
+ }
1638
2007
  return {
1639
2008
  fmt: ISOLOOP_DOM_FMT,
1640
- root: dom.root,
1641
- dom,
2009
+ root: target.root,
2010
+ flush: () => target.flush(),
2011
+ setValue: (node, value, o) => target.setValue(node, value, o),
2012
+ dispose: () => target.dispose(),
1642
2013
  styles(css) {
1643
2014
  pendingStyles.push(...typeof css === "string" ? [css] : css);
1644
2015
  scheduleExtras();
1645
2016
  },
1646
- idOf: (node) => node instanceof WNode && node.isConnected ? String(dom.idOf(node)) : void 0,
2017
+ idOf(node) {
2018
+ if (!(node instanceof WNode)) return void 0;
2019
+ const id = target.idOf(node);
2020
+ return id === void 0 ? void 0 : String(id);
2021
+ },
1647
2022
  receive(e) {
1648
- const target = nodeId(e.target);
1649
- if (target === void 0) return;
2023
+ const t = nodeId(e.target);
2024
+ if (t === void 0) return;
1650
2025
  const currentTargets = e.currentTargets.map(nodeId).filter((n) => n !== void 0);
1651
2026
  const { target: _t, currentTargets: _c, ...rest } = e;
1652
- dom.deliver({
2027
+ target.deliver({
1653
2028
  ...rest,
1654
- target,
2029
+ target: t,
1655
2030
  currentTargets
1656
2031
  });
1657
2032
  }
1658
2033
  };
1659
2034
  }
1660
- var nodeId;
2035
+ var nodeId, shared, headListeners;
1661
2036
  var init_render = __esmMin((() => {
1662
2037
  init_worker();
1663
2038
  nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
2039
+ shared = null;
2040
+ headListeners = /* @__PURE__ */ new Set();
1664
2041
  }));
1665
2042
  // package.json
1666
2043
  var version = "0.0.0";
@@ -1681,11 +2058,11 @@ function defineIsolate(def) {
1681
2058
  };
1682
2059
  }
1683
2060
  /** 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);
2061
+ function createVanillaIsolate(init, post, scope, pooled = false) {
2062
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
1686
2063
  const calls = createHostCalls({
1687
2064
  post,
1688
- beforeCall: () => render?.dom.flush(),
2065
+ beforeCall: () => render?.flush(),
1689
2066
  idOf: (node) => render ? render.idOf(node) : void 0,
1690
2067
  surface: render !== null,
1691
2068
  navigate: init.grants.navigate === true
@@ -1693,6 +2070,7 @@ function createVanillaIsolate(init, post, scope) {
1693
2070
  const awake = createKeepAwake();
1694
2071
  const bus = createBusClient(init.busPort, {
1695
2072
  ...init.wake ? { wake: true } : {},
2073
+ ...init.commitIntervalMs === void 0 ? {} : { commitIntervalMs: init.commitIntervalMs },
1696
2074
  onError: (err) => {
1697
2075
  post({
1698
2076
  v: 1,
@@ -1709,24 +2087,58 @@ function createVanillaIsolate(init, post, scope) {
1709
2087
  }
1710
2088
  });
1711
2089
  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);
1727
- },
1728
- keepAwake: () => awake.hold()
2090
+ let portal;
2091
+ const ctx = {
2092
+ id: init.isolateId,
2093
+ config: init.config,
2094
+ root: render?.root,
2095
+ portalRoot: void 0,
2096
+ reportError(error, o = {}) {
2097
+ const fatal = o.fatal ?? true;
2098
+ post({
2099
+ v: 1,
2100
+ t: "error",
2101
+ p: error instanceof Error ? {
2102
+ message: error.message,
2103
+ ...error.stack === void 0 ? {} : { stack: error.stack },
2104
+ fatal
2105
+ } : {
2106
+ message: String(error),
2107
+ fatal
2108
+ }
2109
+ });
2110
+ },
2111
+ host: calls.api,
2112
+ bus: bus.client,
2113
+ styles: (css) => render?.styles(css),
2114
+ setValue(node, value, o) {
2115
+ if (!render) return;
2116
+ if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
2117
+ render.setValue(node, value, o);
2118
+ },
2119
+ onShutdown: (fn) => {
2120
+ onShutdown.push(fn);
1729
2121
  },
2122
+ keepAwake: () => awake.hold()
2123
+ };
2124
+ Object.defineProperty(ctx, "portalRoot", {
2125
+ enumerable: false,
2126
+ get() {
2127
+ if (!render) return void 0;
2128
+ if (!portal) {
2129
+ const { root } = render;
2130
+ const div = root.ownerDocument.createElement("div");
2131
+ div.setAttribute("data-isoloop-portal", "");
2132
+ queueMicrotask(() => {
2133
+ if (div.parentNode !== root) root.appendChild(div);
2134
+ });
2135
+ portal = div;
2136
+ }
2137
+ return portal;
2138
+ }
2139
+ });
2140
+ return {
2141
+ ctx,
1730
2142
  renderFmt: render ? render.fmt : "none",
1731
2143
  receive(msg) {
1732
2144
  if (isHostToIsolate(msg)) {
@@ -1745,7 +2157,9 @@ function createVanillaIsolate(init, post, scope) {
1745
2157
  },
1746
2158
  async shutdown(reason) {
1747
2159
  await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
1748
- render?.dom.flush();
2160
+ await bus.close();
2161
+ render?.flush();
2162
+ render?.dispose();
1749
2163
  }
1750
2164
  };
1751
2165
  }
@@ -1761,11 +2175,19 @@ var init_vanilla = __esmMin((() => {
1761
2175
  }));
1762
2176
  // src/bootstrap.ts
1763
2177
  init_dist();
1764
- const post = (msg) => {
2178
+ let mode = null;
2179
+ const members = /* @__PURE__ */ new Map();
2180
+ const postWorker = (msg) => {
1765
2181
  self.postMessage(msg);
1766
2182
  };
1767
- const fatal = (message, code) => {
1768
- post({
2183
+ const memberPost = (name) => (msg) => {
2184
+ self.postMessage(name === void 0 ? msg : {
2185
+ ...msg,
2186
+ isolate: name
2187
+ });
2188
+ };
2189
+ const fatal = (m, message, code) => {
2190
+ m.post({
1769
2191
  v: 1,
1770
2192
  t: "error",
1771
2193
  p: code ? {
@@ -1778,46 +2200,70 @@ const fatal = (message, code) => {
1778
2200
  }
1779
2201
  });
1780
2202
  };
1781
- /** Set once the isolate has started: what the beat reports for suspension (ADR 0001). */
1782
- let idleReport = null;
2203
+ let beating = false;
2204
+ /** Once per worker, after the first isolate's protocol check. */
1783
2205
  function startHeartbeat(everyMs) {
2206
+ if (beating) return;
2207
+ beating = true;
1784
2208
  let last = performance.now();
1785
2209
  setInterval(() => {
1786
2210
  const now = performance.now();
1787
2211
  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
- });
2212
+ if (mode === "pool") {
2213
+ const reports = {};
2214
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
2215
+ postWorker({
2216
+ v: 1,
2217
+ t: "beat",
2218
+ p: {
2219
+ lagMs,
2220
+ members: reports
2221
+ }
2222
+ });
2223
+ } else {
2224
+ const idle = members.get(void 0)?.idleReport?.();
2225
+ postWorker({
2226
+ v: 1,
2227
+ t: "beat",
2228
+ p: idle ? {
2229
+ lagMs,
2230
+ idle
2231
+ } : { lagMs }
2232
+ });
2233
+ }
1796
2234
  last = now;
1797
2235
  }, everyMs);
1798
2236
  }
1799
- async function boot(init) {
2237
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
2238
+ function shutdownMember(m, graceMs, reason) {
2239
+ if (members.get(m.name) === m) members.delete(m.name);
2240
+ m.receive = null;
2241
+ const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2242
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2243
+ Promise.race([done, grace]).finally(() => {
2244
+ m.post({
2245
+ v: 1,
2246
+ t: "bye",
2247
+ p: {}
2248
+ });
2249
+ if (members.size === 0) self.close();
2250
+ });
2251
+ }
2252
+ /** Routes one message from the host to the member it is for. */
2253
+ function route(msg) {
2254
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
2255
+ if (!m) return;
2256
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2257
+ else m.receive?.(msg);
2258
+ }
2259
+ async function boot(m, init) {
1800
2260
  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");
2261
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
1802
2262
  return;
1803
2263
  }
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
2264
  startHeartbeat(init.heartbeatMs);
1819
2265
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
1820
- const runtime = createVanillaIsolate(init, post, self);
2266
+ const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
1821
2267
  let mod;
1822
2268
  try {
1823
2269
  mod = await import(
@@ -1827,7 +2273,7 @@ async function boot(init) {
1827
2273
  } catch (err) {
1828
2274
  const why = err instanceof Error ? err.message : String(err);
1829
2275
  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)" : ""}`);
2276
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
1831
2277
  return;
1832
2278
  }
1833
2279
  const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
@@ -1835,21 +2281,19 @@ async function boot(init) {
1835
2281
  const start = main.start;
1836
2282
  if (typeof start === "function") {
1837
2283
  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);
2284
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
1839
2285
  return;
1840
2286
  }
1841
2287
  }
1842
- fatal(`${init.src} has no default export with start(ctx)`);
2288
+ fatal(m, `${init.src} has no default export with start(ctx)`);
1843
2289
  }
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);
1849
- });
1850
- shutdownHook = (reason) => runtime.shutdown(reason);
1851
- idleReport = () => runtime.idle();
1852
- post({
2290
+ async function startIsolate(m, runtime, start, requires) {
2291
+ m.receive = (msg) => {
2292
+ runtime.receive(msg);
2293
+ };
2294
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2295
+ m.idleReport = () => runtime.idle();
2296
+ m.post({
1853
2297
  v: 1,
1854
2298
  t: "ready",
1855
2299
  p: {
@@ -1862,15 +2306,44 @@ async function startIsolate(runtime, start, requires) {
1862
2306
  try {
1863
2307
  await start(runtime.ctx);
1864
2308
  } catch (err) {
1865
- fatal(`start() threw: ${err instanceof Error ? err.message : String(err)}`);
2309
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
1866
2310
  }
1867
2311
  }
1868
- const onInit = (e) => {
2312
+ /** Handles one message from the host: `init` boots a member, the rest is routed. */
2313
+ function onMessage(e) {
1869
2314
  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));
2315
+ if (!isHostToIsolate(msg)) return;
2316
+ if (msg.t !== "init") {
2317
+ route(msg);
2318
+ return;
2319
+ }
2320
+ const name = msg.isolate;
2321
+ const wants = name === void 0 ? "own" : "pool";
2322
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2323
+ if (mode === null) {
2324
+ mode = wants;
2325
+ if (mode === "pool") freezeBuiltins();
2326
+ }
2327
+ if (members.has(name)) return;
2328
+ const m = {
2329
+ name,
2330
+ post: memberPost(name),
2331
+ shutdownHook: null,
2332
+ idleReport: null,
2333
+ receive: null
2334
+ };
2335
+ members.set(name, m);
2336
+ boot(m, msg.p).catch((err) => {
2337
+ fatal(m, err instanceof Error ? err.message : String(err));
1874
2338
  });
1875
- };
1876
- self.addEventListener("message", onInit);
2339
+ }
2340
+ const STARTED = Symbol.for("isoloop.bootstrap");
2341
+ function startOnce() {
2342
+ self.addEventListener("message", onMessage);
2343
+ }
2344
+ if (Reflect.get(self, STARTED) === true) {
2345
+ if (import.meta.env?.DEV === true) console.warn("isoloop: worker entry evaluated twice; ignoring");
2346
+ } else {
2347
+ Reflect.set(self, STARTED, true);
2348
+ startOnce();
2349
+ }