@isoloop/runtime 0.0.0-next.56111e3 → 0.0.0-next.5aa1a15

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.
Files changed (2) hide show
  1. package/dist/bootstrap.js +239 -61
  2. package/package.json +3 -3
package/dist/bootstrap.js CHANGED
@@ -20,11 +20,12 @@ var __exportAll = (all, no_symbols) => {
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
@@ -151,6 +152,117 @@ var init_dist = __esmMin((() => {
151
152
  retention: { kind: "compacted" }
152
153
  });
153
154
  }));
155
+ // src/freeze.ts
156
+ init_dist();
157
+ /** Constructors whose `prototype` and statics are frozen, if this engine has them. */
158
+ const NAMES = [
159
+ "Object",
160
+ "Function",
161
+ "Array",
162
+ "String",
163
+ "Number",
164
+ "Boolean",
165
+ "Symbol",
166
+ "BigInt",
167
+ "Date",
168
+ "RegExp",
169
+ "Error",
170
+ "EvalError",
171
+ "RangeError",
172
+ "ReferenceError",
173
+ "SyntaxError",
174
+ "TypeError",
175
+ "URIError",
176
+ "AggregateError",
177
+ "Promise",
178
+ "Map",
179
+ "Set",
180
+ "WeakMap",
181
+ "WeakSet",
182
+ "WeakRef",
183
+ "FinalizationRegistry",
184
+ "ArrayBuffer",
185
+ "DataView",
186
+ "Int8Array",
187
+ "Uint8Array",
188
+ "Uint8ClampedArray",
189
+ "Int16Array",
190
+ "Uint16Array",
191
+ "Int32Array",
192
+ "Uint32Array",
193
+ "Float32Array",
194
+ "Float64Array",
195
+ "BigInt64Array",
196
+ "BigUint64Array"
197
+ ];
198
+ /**
199
+ * Freezing a prototype makes its data properties read-only, and in strict
200
+ * code assigning a property of the same name on an instance then throws (the
201
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`).
202
+ * As Hardened JS does, each data property becomes an accessor whose setter
203
+ * defines the property on the instance instead, so overriding still works
204
+ * while the prototype itself can't change.
205
+ */
206
+ function tameOverrides(proto) {
207
+ for (const key of Reflect.ownKeys(proto)) {
208
+ const d = Object.getOwnPropertyDescriptor(proto, key);
209
+ if (!d || !("value" in d) || !d.configurable) continue;
210
+ const value = d.value;
211
+ Object.defineProperty(proto, key, {
212
+ get() {
213
+ return value;
214
+ },
215
+ set(v) {
216
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
217
+ if (typeof this !== "object" && typeof this !== "function") return;
218
+ if (this === null) return;
219
+ Object.defineProperty(this, key, {
220
+ value: v,
221
+ writable: true,
222
+ enumerable: true,
223
+ configurable: true
224
+ });
225
+ },
226
+ enumerable: d.enumerable ?? false,
227
+ configurable: false
228
+ });
229
+ }
230
+ }
231
+ function hardenProto(proto) {
232
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
233
+ if (Object.isFrozen(proto)) return;
234
+ tameOverrides(proto);
235
+ Object.freeze(proto);
236
+ }
237
+ function freezeWithPrototype(c) {
238
+ if (typeof c !== "function") return;
239
+ hardenProto(Reflect.get(c, "prototype"));
240
+ if (c !== Error) Object.freeze(c);
241
+ }
242
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
243
+ function freezeBuiltins() {
244
+ const g = globalThis;
245
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
246
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
247
+ const protos = [
248
+ Object.getPrototypeOf([][Symbol.iterator]()),
249
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
250
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
251
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
252
+ Object.getPrototypeOf(""[Symbol.iterator]()),
253
+ Object.getPrototypeOf(function* () {}),
254
+ Object.getPrototypeOf(async function() {}),
255
+ Object.getPrototypeOf(async function* () {})
256
+ ];
257
+ for (const p of protos) {
258
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
259
+ hardenProto(Reflect.get(p, "prototype"));
260
+ hardenProto(p);
261
+ }
262
+ Object.freeze(Math);
263
+ Object.freeze(JSON);
264
+ Object.freeze(Reflect);
265
+ }
154
266
  // src/bus-client.ts
155
267
  function createBusClient(first, o = {}) {
156
268
  const limit = o.inboxLimit ?? 1e3;
@@ -391,7 +503,6 @@ function createBusClient(first, o = {}) {
391
503
  }
392
504
  var randomEpoch, check, REQUEST_TIMEOUT_MS;
393
505
  var init_bus_client = __esmMin((() => {
394
- init_dist();
395
506
  randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
396
507
  check = (r) => {
397
508
  if (!r.ok) throw new BusError(r.error);
@@ -516,7 +627,7 @@ var ISOLOOP_DOM_FMT;
516
627
  var init_records_wVZrPpqr = __esmMin((() => {
517
628
  ISOLOOP_DOM_FMT = "isoloop-dom@1";
518
629
  }));
519
- // ../dom/dist/dom-9S5T0UVQ.js
630
+ // ../dom/dist/dom-7EzPoV0N.js
520
631
  function createStyle(el) {
521
632
  const decls = /* @__PURE__ */ new Map();
522
633
  const write = () => {
@@ -707,6 +818,10 @@ function createDom(opts) {
707
818
  if (!node) return;
708
819
  if ((node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement) && event.value !== void 0) node.isoSetProp("value", event.value, false);
709
820
  if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
821
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
822
+ top: event.scrollTop ?? 0,
823
+ left: event.scrollLeft ?? 0
824
+ };
710
825
  node.dispatchEvent(toEvent(event));
711
826
  }
712
827
  };
@@ -714,7 +829,7 @@ function createDom(opts) {
714
829
  /** A real `Event` with the fields frameworks read from mouse and keyboard events. */
715
830
  function toEvent(e) {
716
831
  const ev = new Event(e.type, {
717
- bubbles: true,
832
+ bubbles: e.type !== "scroll",
718
833
  cancelable: true
719
834
  });
720
835
  const mods = {
@@ -740,7 +855,7 @@ function toEvent(e) {
740
855
  return ev;
741
856
  }
742
857
  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((() => {
858
+ var init_dom_7EzPoV0N = __esmMin((() => {
744
859
  HTML_NS = "http://www.w3.org/1999/xhtml";
745
860
  SVG_NS = "http://www.w3.org/2000/svg";
746
861
  str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
@@ -1172,6 +1287,11 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1172
1287
  /** @internal */ isoStyle = null;
1173
1288
  /** @internal */ isoClassList = null;
1174
1289
  /** @internal */ isoDataset = null;
1290
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
1291
+ isoScroll = {
1292
+ top: 0,
1293
+ left: 0
1294
+ };
1175
1295
  constructor(doc, id, localName, ns) {
1176
1296
  super(doc, id);
1177
1297
  this.localName = localName;
@@ -1238,6 +1358,16 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1238
1358
  this.isoDataset ??= createDataset(this);
1239
1359
  return this.isoDataset;
1240
1360
  }
1361
+ /**
1362
+ * Read only, and as of the last `scroll` event the element got: the host
1363
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
1364
+ */
1365
+ get scrollTop() {
1366
+ return this.isoScroll.top;
1367
+ }
1368
+ get scrollLeft() {
1369
+ return this.isoScroll.left;
1370
+ }
1241
1371
  get id() {
1242
1372
  return this.getAttribute("id") ?? "";
1243
1373
  }
@@ -1543,7 +1673,7 @@ var init_dom_9S5T0UVQ = __esmMin((() => {
1543
1673
  };
1544
1674
  defineHandlers(WDocument.prototype);
1545
1675
  }));
1546
- // ../dom/dist/install-DBKGtAel.js
1676
+ // ../dom/dist/install-DE1VIvyG.js
1547
1677
  /**
1548
1678
  * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
1549
1679
  * frameworks find them where they look. Only for isolates with a surface; a
@@ -1563,8 +1693,8 @@ function install(dom, scope) {
1563
1693
  dom.document.defaultView = scope;
1564
1694
  }
1565
1695
  var DOM_GLOBALS;
1566
- var init_install_DBKGtAel = __esmMin((() => {
1567
- init_dom_9S5T0UVQ();
1696
+ var init_install_DE1VIvyG = __esmMin((() => {
1697
+ init_dom_7EzPoV0N();
1568
1698
  DOM_GLOBALS = {
1569
1699
  Node: WNode,
1570
1700
  Element: WElement,
@@ -1584,8 +1714,8 @@ var init_install_DBKGtAel = __esmMin((() => {
1584
1714
  // ../dom/dist/worker.js
1585
1715
  var init_worker = __esmMin((() => {
1586
1716
  init_records_wVZrPpqr();
1587
- init_dom_9S5T0UVQ();
1588
- init_install_DBKGtAel();
1717
+ init_dom_7EzPoV0N();
1718
+ init_install_DE1VIvyG();
1589
1719
  }));
1590
1720
  // src/render/index.ts
1591
1721
  /**
@@ -1761,11 +1891,19 @@ var init_vanilla = __esmMin((() => {
1761
1891
  }));
1762
1892
  // src/bootstrap.ts
1763
1893
  init_dist();
1764
- const post = (msg) => {
1894
+ let mode = null;
1895
+ const members = /* @__PURE__ */ new Map();
1896
+ const postWorker = (msg) => {
1765
1897
  self.postMessage(msg);
1766
1898
  };
1767
- const fatal = (message, code) => {
1768
- post({
1899
+ const memberPost = (name) => (msg) => {
1900
+ self.postMessage(name === void 0 ? msg : {
1901
+ ...msg,
1902
+ isolate: name
1903
+ });
1904
+ };
1905
+ const fatal = (m, message, code) => {
1906
+ m.post({
1769
1907
  v: 1,
1770
1908
  t: "error",
1771
1909
  p: code ? {
@@ -1778,46 +1916,70 @@ const fatal = (message, code) => {
1778
1916
  }
1779
1917
  });
1780
1918
  };
1781
- /** Set once the isolate has started: what the beat reports for suspension (ADR 0001). */
1782
- let idleReport = null;
1919
+ let beating = false;
1920
+ /** Once per worker, after the first isolate's protocol check. */
1783
1921
  function startHeartbeat(everyMs) {
1922
+ if (beating) return;
1923
+ beating = true;
1784
1924
  let last = performance.now();
1785
1925
  setInterval(() => {
1786
1926
  const now = performance.now();
1787
1927
  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
- });
1928
+ if (mode === "pool") {
1929
+ const reports = {};
1930
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
1931
+ postWorker({
1932
+ v: 1,
1933
+ t: "beat",
1934
+ p: {
1935
+ lagMs,
1936
+ members: reports
1937
+ }
1938
+ });
1939
+ } else {
1940
+ const idle = members.get(void 0)?.idleReport?.();
1941
+ postWorker({
1942
+ v: 1,
1943
+ t: "beat",
1944
+ p: idle ? {
1945
+ lagMs,
1946
+ idle
1947
+ } : { lagMs }
1948
+ });
1949
+ }
1796
1950
  last = now;
1797
1951
  }, everyMs);
1798
1952
  }
1799
- async function boot(init) {
1953
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
1954
+ function shutdownMember(m, graceMs, reason) {
1955
+ if (members.get(m.name) === m) members.delete(m.name);
1956
+ m.receive = null;
1957
+ const done = m.shutdownHook?.(reason) ?? Promise.resolve();
1958
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
1959
+ Promise.race([done, grace]).finally(() => {
1960
+ m.post({
1961
+ v: 1,
1962
+ t: "bye",
1963
+ p: {}
1964
+ });
1965
+ if (members.size === 0) self.close();
1966
+ });
1967
+ }
1968
+ /** Routes one message from the host to the member it is for. */
1969
+ function route(msg) {
1970
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
1971
+ if (!m) return;
1972
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
1973
+ else m.receive?.(msg);
1974
+ }
1975
+ async function boot(m, init) {
1800
1976
  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");
1977
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
1802
1978
  return;
1803
1979
  }
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
1980
  startHeartbeat(init.heartbeatMs);
1819
1981
  const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
1820
- const runtime = createVanillaIsolate(init, post, self);
1982
+ const runtime = createVanillaIsolate(init, m.post, self);
1821
1983
  let mod;
1822
1984
  try {
1823
1985
  mod = await import(
@@ -1827,7 +1989,7 @@ async function boot(init) {
1827
1989
  } catch (err) {
1828
1990
  const why = err instanceof Error ? err.message : String(err);
1829
1991
  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)" : ""}`);
1992
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
1831
1993
  return;
1832
1994
  }
1833
1995
  const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
@@ -1835,21 +1997,19 @@ async function boot(init) {
1835
1997
  const start = main.start;
1836
1998
  if (typeof start === "function") {
1837
1999
  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);
2000
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
1839
2001
  return;
1840
2002
  }
1841
2003
  }
1842
- fatal(`${init.src} has no default export with start(ctx)`);
2004
+ fatal(m, `${init.src} has no default export with start(ctx)`);
1843
2005
  }
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({
2006
+ async function startIsolate(m, runtime, start, requires) {
2007
+ m.receive = (msg) => {
2008
+ runtime.receive(msg);
2009
+ };
2010
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2011
+ m.idleReport = () => runtime.idle();
2012
+ m.post({
1853
2013
  v: 1,
1854
2014
  t: "ready",
1855
2015
  p: {
@@ -1862,15 +2022,33 @@ async function startIsolate(runtime, start, requires) {
1862
2022
  try {
1863
2023
  await start(runtime.ctx);
1864
2024
  } catch (err) {
1865
- fatal(`start() threw: ${err instanceof Error ? err.message : String(err)}`);
2025
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
1866
2026
  }
1867
2027
  }
1868
- const onInit = (e) => {
2028
+ self.addEventListener("message", (e) => {
1869
2029
  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));
2030
+ if (!isHostToIsolate(msg)) return;
2031
+ if (msg.t !== "init") {
2032
+ route(msg);
2033
+ return;
2034
+ }
2035
+ const name = msg.isolate;
2036
+ const wants = name === void 0 ? "own" : "pool";
2037
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2038
+ if (mode === null) {
2039
+ mode = wants;
2040
+ if (mode === "pool") freezeBuiltins();
2041
+ }
2042
+ if (members.has(name)) return;
2043
+ const m = {
2044
+ name,
2045
+ post: memberPost(name),
2046
+ shutdownHook: null,
2047
+ idleReport: null,
2048
+ receive: null
2049
+ };
2050
+ members.set(name, m);
2051
+ boot(m, msg.p).catch((err) => {
2052
+ fatal(m, err instanceof Error ? err.message : String(err));
1874
2053
  });
1875
- };
1876
- self.addEventListener("message", onInit);
2054
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isoloop/runtime",
3
- "version": "0.0.0-next.56111e3",
3
+ "version": "0.0.0-next.5aa1a15",
4
4
  "description": "Isolate-side runtime that runs inside each worker.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,8 +27,8 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@isoloop/dom": "0.0.0-next.56111e3",
31
- "@isoloop/protocol": "0.0.0-next.56111e3"
30
+ "@isoloop/dom": "0.0.0-next.5aa1a15",
31
+ "@isoloop/protocol": "0.0.0-next.5aa1a15"
32
32
  },
33
33
  "devDependencies": {
34
34
  "typescript": "7.0.2"