@iso4/sandbox 0.8.0 → 0.9.0

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/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { a as isValidExportName, r as RUNTIME_OWNED_GLOBALS } from "./names-BY-6pKkh.mjs";
1
2
  import { access, mkdtemp, rm } from "node:fs/promises";
2
3
  import { existsSync, rmSync } from "node:fs";
3
4
  import { availableParallelism, tmpdir, totalmem } from "node:os";
@@ -1045,7 +1046,8 @@ var PayloadWriter = class {
1045
1046
  this.writeU32(rebinds.length);
1046
1047
  for (const rebind of rebinds) {
1047
1048
  this.writeString(rebind.specifier);
1048
- this.writeString(rebind.path);
1049
+ this.writeU32(rebind.path.length);
1050
+ for (const segment of rebind.path) this.writeString(segment);
1049
1051
  }
1050
1052
  return this;
1051
1053
  }
@@ -1091,6 +1093,10 @@ var PayloadDecodeError = class extends Error {
1091
1093
  var PayloadReader = class {
1092
1094
  view;
1093
1095
  offset = 0;
1096
+ /**
1097
+ * Byte length of the blob the last `readValueBlob()` consumed.
1098
+ */
1099
+ lastValueBlobBytes = 0;
1094
1100
  constructor(buf) {
1095
1101
  this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1096
1102
  }
@@ -1147,6 +1153,14 @@ var PayloadReader = class {
1147
1153
  this.offset += len;
1148
1154
  return slice;
1149
1155
  }
1156
+ /**
1157
+ * Advance past `len` bytes with the same bounds check as {@link readRawBytes}.
1158
+ * @param len
1159
+ */
1160
+ skipBytes(len) {
1161
+ if (this.remaining < len) throw new PayloadDecodeError(`unexpected end of payload: need ${len} bytes, have ${this.remaining}`);
1162
+ this.offset += len;
1163
+ }
1150
1164
  readString() {
1151
1165
  return Buffer.from(this.readRawBytes(this.readU32())).toString("utf8");
1152
1166
  }
@@ -1157,10 +1171,22 @@ var PayloadReader = class {
1157
1171
  return items;
1158
1172
  }
1159
1173
  /**
1174
+ * Read a `String specifier` + `List<String> path` and return exactly those
1175
+ * validated bytes as a latin1 string: the import key, see {@link encodeImportKey}.
1176
+ */
1177
+ readImportKey() {
1178
+ const start = this.offset;
1179
+ this.skipBytes(this.readU32());
1180
+ const count = this.readU32();
1181
+ for (let i = 0; i < count; i++) this.skipBytes(this.readU32());
1182
+ return Buffer.from(this.view.buffer, this.view.byteOffset + start, this.offset - start).toString("latin1");
1183
+ }
1184
+ /**
1160
1185
  * Read a value slot: `u32 byteLength` + V8 serialization blob.
1161
1186
  */
1162
1187
  readValueBlob() {
1163
- return deserializeValue(this.readRawBytes(this.readU32()));
1188
+ this.lastValueBlobBytes = this.readU32();
1189
+ return deserializeValue(this.readRawBytes(this.lastValueBlobBytes));
1164
1190
  }
1165
1191
  /**
1166
1192
  * Read an `Optional<value slot>`: a presence byte, then the slot when set.
@@ -1217,6 +1243,29 @@ function encodeTerminatePayload(runId, hard) {
1217
1243
  return new PayloadWriter().writeU32(runId).writeU8(hard ? 1 : 0).toBuffer();
1218
1244
  }
1219
1245
  /**
1246
+ * The handler-map key of a host-module function leaf: its specifier and path
1247
+ * in wire encoding (`String` + `List<String>`), as latin1. Unambiguous, and
1248
+ * equal to the bytes a `BridgeCall` carries, so dispatch needs no decoding.
1249
+ * @param specifier
1250
+ * @param path the leaf's key segments
1251
+ */
1252
+ function encodeImportKey(specifier, path) {
1253
+ const writer = new PayloadWriter().writeString(specifier).writeU32(path.length);
1254
+ for (const segment of path) writer.writeString(segment);
1255
+ return writer.toBuffer().toString("latin1");
1256
+ }
1257
+ /**
1258
+ * Decode an import key back to its specifier and path, for messages.
1259
+ * @param key a key from {@link encodeImportKey} or a `BridgeCall`
1260
+ */
1261
+ function decodeImportKey(key) {
1262
+ const reader = new PayloadReader(Buffer.from(key, "latin1"));
1263
+ return {
1264
+ specifier: reader.readString(),
1265
+ path: reader.readStringList()
1266
+ };
1267
+ }
1268
+ /**
1220
1269
  * Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
1221
1270
  * Per `docs/protocol.md` §5.4.
1222
1271
  *
@@ -1256,21 +1305,69 @@ function decodeBridgeCallPayload(buf) {
1256
1305
  const callId = reader.readU32();
1257
1306
  const targetKindRaw = reader.readU8();
1258
1307
  if (targetKindRaw !== 0 && targetKindRaw !== 1) throw new Error(`invalid bridge targetKind: ${targetKindRaw}`);
1259
- const targetKind = targetKindRaw;
1260
- const specifier = reader.readU8() === 1 ? reader.readString() : void 0;
1261
- const exportName = reader.readString();
1308
+ if (reader.readU8() === 1 !== (targetKindRaw === 1)) throw new PayloadDecodeError("BridgeCall specifier must be present exactly for an import target");
1309
+ const target = targetKindRaw === 0 ? {
1310
+ targetKind: 0,
1311
+ exportName: reader.readString()
1312
+ } : {
1313
+ targetKind: 1,
1314
+ key: reader.readImportKey()
1315
+ };
1262
1316
  const decoded = reader.readValueBlob();
1263
1317
  if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
1318
+ assertNoArrayHoles(decoded, reader.lastValueBlobBytes);
1264
1319
  return {
1265
1320
  runId,
1266
1321
  callId,
1267
- targetKind,
1268
- specifier,
1269
- exportName,
1322
+ target,
1270
1323
  args: decoded
1271
1324
  };
1272
1325
  }
1273
1326
  /**
1327
+ * Refuse bridge arguments holding an array with holes, at any depth
1328
+ * (DESIGN.md §12.1). A dense slot costs at least one wire byte, so array
1329
+ * lengths summing past the blob size prove a hole before any index is read.
1330
+ * @param args the decoded argument list
1331
+ * @param blobBytes byte length of the value blob the arguments arrived in
1332
+ */
1333
+ function assertNoArrayHoles(args, blobBytes) {
1334
+ const seen = /* @__PURE__ */ new Set();
1335
+ const stack = [args];
1336
+ let slots = 0;
1337
+ for (let v = stack.pop(); v !== void 0; v = stack.pop()) {
1338
+ if (seen.has(v)) continue;
1339
+ seen.add(v);
1340
+ if (Array.isArray(v)) {
1341
+ slots += v.length;
1342
+ if (slots > blobBytes) throw new PayloadDecodeError("bridge call argument contains an array with holes");
1343
+ for (let i = 0; i < v.length; i++) {
1344
+ if (!(i in v)) throw new PayloadDecodeError("bridge call argument contains an array with holes");
1345
+ const item = v[i];
1346
+ if (item !== null && typeof item === "object") stack.push(item);
1347
+ }
1348
+ const keys = Object.keys(v);
1349
+ for (let j = v.length; j < keys.length; j++) {
1350
+ const item = v[keys[j]];
1351
+ if (item !== null && typeof item === "object") stack.push(item);
1352
+ }
1353
+ continue;
1354
+ }
1355
+ const proto = Object.getPrototypeOf(v);
1356
+ if (proto === Object.prototype || proto === null) for (const key in v) {
1357
+ const item = v[key];
1358
+ if (item !== null && typeof item === "object") stack.push(item);
1359
+ }
1360
+ else if (v instanceof Map) {
1361
+ for (const k of v.keys()) if (k !== null && typeof k === "object") stack.push(k);
1362
+ for (const item of v.values()) if (item !== null && typeof item === "object") stack.push(item);
1363
+ } else if (v instanceof Set) {
1364
+ for (const item of v) if (item !== null && typeof item === "object") stack.push(item);
1365
+ } else if (v instanceof Error) {
1366
+ if (v.cause !== null && typeof v.cause === "object") stack.push(v.cause);
1367
+ }
1368
+ }
1369
+ }
1370
+ /**
1274
1371
  * Build a `BridgeErrorPayload` from whatever a host handler threw.
1275
1372
  *
1276
1373
  * Own-enumerable properties beyond `name`/`message`/`stack` travel as
@@ -1633,6 +1730,8 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1633
1730
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1634
1731
  const fields = reader.readOptionalValueBlob();
1635
1732
  const reset = readResetInfo(reader);
1733
+ const stage = readPrefixStage(reader);
1734
+ const prefixCause = readErrorCause(reader);
1636
1735
  const stdout = reader.readStringList();
1637
1736
  const stderr = reader.readStringList();
1638
1737
  const durationMs = reader.readF64();
@@ -1654,7 +1753,8 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1654
1753
  message,
1655
1754
  stack,
1656
1755
  fields,
1657
- ...reset
1756
+ ...reset,
1757
+ ...stage
1658
1758
  },
1659
1759
  stdout,
1660
1760
  stderr,
@@ -1663,7 +1763,45 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
1663
1763
  cpuTimeMs,
1664
1764
  bridgeCalls,
1665
1765
  heapUsedBytes
1666
- }
1766
+ },
1767
+ ...prefixCause === void 0 ? {} : { prefixCause }
1768
+ };
1769
+ }
1770
+ /**
1771
+ * The stage byte trailing every `RunErrorPayload`: `1` when the prefix failed
1772
+ * to evaluate on this run's cold start. A spreadable fragment, so run-stage
1773
+ * errors add nothing.
1774
+ * @param reader
1775
+ */
1776
+ function readPrefixStage(reader) {
1777
+ const byte = reader.readU8();
1778
+ if (byte === 0) return {};
1779
+ if (byte !== 1) throw new PayloadDecodeError(`invalid prefix-stage byte: ${byte}`);
1780
+ return { stage: "prefix" };
1781
+ }
1782
+ /**
1783
+ * The optional cause trailing every `RunErrorPayload`, present only on an
1784
+ * `ERR_PREFIX_BROKEN` refusal: the stored cold-start failure's code, name,
1785
+ * message and stack.
1786
+ * @param reader
1787
+ */
1788
+ function readErrorCause(reader) {
1789
+ const present = reader.readU8();
1790
+ if (present === 0) return void 0;
1791
+ if (present !== 1) throw new PayloadDecodeError(`invalid error-cause presence byte: ${present}`);
1792
+ const code = reader.readString();
1793
+ const name = reader.readString();
1794
+ const message = reader.readString();
1795
+ const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1796
+ return stack === void 0 ? {
1797
+ code,
1798
+ name,
1799
+ message
1800
+ } : {
1801
+ code,
1802
+ name,
1803
+ message,
1804
+ stack
1667
1805
  };
1668
1806
  }
1669
1807
  /**
@@ -1682,7 +1820,8 @@ function readResetInfo(reader) {
1682
1820
  "memory",
1683
1821
  "abort",
1684
1822
  "internal",
1685
- "wall"
1823
+ "wall",
1824
+ "unsupported"
1686
1825
  ][causeByte];
1687
1826
  if (resetCause === void 0) throw new PayloadDecodeError(`invalid instance-reset cause byte: ${causeByte}`);
1688
1827
  return {
@@ -1793,6 +1932,8 @@ function decodePrecompileResultPayload(buf) {
1793
1932
  const stack = reader.readU8() === 1 ? reader.readString() : void 0;
1794
1933
  reader.readOptionalValueBlob();
1795
1934
  readResetInfo(reader);
1935
+ readPrefixStage(reader);
1936
+ readErrorCause(reader);
1796
1937
  reader.assertDone();
1797
1938
  return {
1798
1939
  ok: false,
@@ -1883,580 +2024,84 @@ function formatByte(byte) {
1883
2024
  return `0x${byte.toString(16).padStart(2, "0")}`;
1884
2025
  }
1885
2026
  //#endregion
1886
- //#region src/globals.ts
2027
+ //#region src/client.ts
1887
2028
  /**
1888
- * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1889
- * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1890
- * A host global under one of these names replaces the built-in, or is
1891
- * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1892
- * forbids outright are in {@link RESERVED_WORDS}.
2029
+ * How long TS waits for Rust's `ERR_ABORTED` Result after sending a HARD
2030
+ * `Terminate`, before falling back to tearing the connection down.
2031
+ *
2032
+ * Hard aborts always answer promptly (a suspended run is abandoned on the
2033
+ * spot, executing JS is interrupted mid-turn), so no answer within this
2034
+ * window means the runtime cannot answer at all (wedged process). SOFT
2035
+ * aborts arm no fallback: a run spinning with no `cpuTimeMs` cap
2036
+ * legitimately cannot answer one until its own limits end the turn, and
2037
+ * tearing the connection down for that would fail every co-resident run of
2038
+ * a healthy runtime.
1893
2039
  */
1894
- const SANDBOX_GLOBALS = new Set([
1895
- "AggregateError",
1896
- "Array",
1897
- "ArrayBuffer",
1898
- "AsyncDisposableStack",
1899
- "Atomics",
1900
- "BigInt",
1901
- "BigInt64Array",
1902
- "BigUint64Array",
1903
- "Boolean",
1904
- "DataView",
1905
- "Date",
1906
- "DisposableStack",
1907
- "Error",
1908
- "EvalError",
1909
- "FinalizationRegistry",
1910
- "Float16Array",
1911
- "Float32Array",
1912
- "Float64Array",
1913
- "Function",
1914
- "Headers",
1915
- "Infinity",
1916
- "Int16Array",
1917
- "Int32Array",
1918
- "Int8Array",
1919
- "Intl",
1920
- "Iterator",
1921
- "JSON",
1922
- "Map",
1923
- "Math",
1924
- "NaN",
1925
- "Number",
1926
- "Object",
1927
- "Promise",
1928
- "Proxy",
1929
- "RangeError",
1930
- "ReferenceError",
1931
- "Reflect",
1932
- "RegExp",
1933
- "Request",
1934
- "Response",
1935
- "Set",
1936
- "String",
1937
- "SuppressedError",
1938
- "Symbol",
1939
- "SyntaxError",
1940
- "Temporal",
1941
- "TextDecoder",
1942
- "TextEncoder",
1943
- "TypeError",
1944
- "URIError",
1945
- "URL",
1946
- "URLSearchParams",
1947
- "Uint16Array",
1948
- "Uint32Array",
1949
- "Uint8Array",
1950
- "Uint8ClampedArray",
1951
- "WeakMap",
1952
- "WeakRef",
1953
- "WeakSet",
1954
- "clearTimeout",
1955
- "console",
1956
- "decodeURI",
1957
- "decodeURIComponent",
1958
- "encodeURI",
1959
- "encodeURIComponent",
1960
- "escape",
1961
- "eval",
1962
- "globalThis",
1963
- "isFinite",
1964
- "isNaN",
1965
- "parseFloat",
1966
- "parseInt",
1967
- "setTimeout",
1968
- "undefined",
1969
- "unescape",
1970
- "waitUntil"
1971
- ]);
2040
+ const TERMINATE_GRACE_MS = 100;
1972
2041
  /**
1973
- * Every name that cannot be a binding in module source, so it cannot be a
1974
- * host-module export name. As host global names, all but `eval` and
1975
- * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1976
- * included, though iso4 itself accepts it as a host-module export (emitted as
1977
- * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1978
- * are taken, these are names the grammar forbids.
2042
+ * How long `connect()` waits for the runtime's `Hello` frame before giving up.
2043
+ * The runtime answers a handshake without touching V8 (the probe is computed
2044
+ * once at process start), so this only bites when the binary is wedged.
1979
2045
  */
1980
- const RESERVED_WORDS = new Set([
1981
- "break",
1982
- "case",
1983
- "catch",
1984
- "class",
1985
- "const",
1986
- "continue",
1987
- "debugger",
1988
- "default",
1989
- "delete",
1990
- "do",
1991
- "else",
1992
- "export",
1993
- "extends",
1994
- "finally",
1995
- "for",
1996
- "function",
1997
- "if",
1998
- "import",
1999
- "in",
2000
- "instanceof",
2001
- "new",
2002
- "return",
2003
- "super",
2004
- "switch",
2005
- "this",
2006
- "throw",
2007
- "try",
2008
- "typeof",
2009
- "var",
2010
- "void",
2011
- "while",
2012
- "with",
2013
- "yield",
2014
- "let",
2015
- "static",
2016
- "enum",
2017
- "await",
2018
- "implements",
2019
- "package",
2020
- "protected",
2021
- "interface",
2022
- "private",
2023
- "public",
2024
- "null",
2025
- "true",
2026
- "false",
2027
- "eval",
2028
- "arguments"
2029
- ]);
2046
+ const HELLO_TIMEOUT_MS = 5e3;
2030
2047
  /**
2031
- * A JavaScript identifier name, Unicode included: ID_Start/ID_Continue plus
2032
- * `$`, `_`, ZWNJ and ZWJ.
2048
+ * Shared placeholder for `RunEntry` callbacks between wiring phases —
2049
+ * allocating fresh `() => {}` closures per run is avoidable hot-path churn.
2033
2050
  */
2034
- const IDENTIFIER_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
2051
+ function NOOP() {}
2035
2052
  /**
2036
- * A host global name sandbox code cannot reference by bare name. Carries the
2037
- * same code and message the runtime reports for it.
2053
+ * Thrown out of `createSandbox()` when the connection handshake fails.
2054
+ *
2055
+ * The common cause is a V8 serialization format-version mismatch between this
2056
+ * Node and the `@iso4/v8-*` binary: values cross the boundary as V8
2057
+ * serialization blobs, so the two V8s must agree on the format. Internal —
2058
+ * `@iso4/sandbox` does not export this type; it reaches callers as a plain
2059
+ * `Error` with `name = 'Iso4HandshakeError'`.
2038
2060
  */
2039
- var GlobalNameError = class extends Error {
2040
- code = "ERR_INVALID_GLOBAL_NAME";
2061
+ var HandshakeError = class extends Error {
2062
+ constructor(message) {
2063
+ super(`[@iso4/sandbox] ${message}`);
2064
+ this.name = "Iso4HandshakeError";
2065
+ }
2041
2066
  };
2042
- function isBridgeWithShim(v) {
2043
- return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
2044
- }
2045
- function isDataGlobal(v) {
2046
- return typeof v === "object" && v !== null && v.kind === "data";
2047
- }
2048
- function isBridgeGlobal(v) {
2049
- return typeof v === "object" && v !== null && v.kind === "bridge";
2050
- }
2051
- function isStringGlobal(v) {
2052
- return typeof v === "object" && v !== null && v.kind === "string";
2053
- }
2054
- /**
2055
- * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
2056
- * dispatch key and an object-property key — never interpolated into generated
2057
- * code — so any global name is safe. The runtime recognises the
2058
- * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
2059
- * bridge records under the public `<name>`.
2060
- * @param name public global name
2061
- */
2062
- function shimHandlerName(name) {
2063
- return `__iso4_${name}_h`;
2064
- }
2065
- /**
2066
- * Throw {@link GlobalNameError} unless sandbox code can reference `name` by
2067
- * bare name. Mirrored by `check_bare_global_name` in `v8.rs`.
2068
- * @param name host global name
2069
- */
2070
- function checkGlobalName(name) {
2071
- if (name !== "eval" && name !== "arguments" && (!IDENTIFIER_NAME.test(name) || RESERVED_WORDS.has(name))) throw new GlobalNameError(`global '${name}' cannot be referenced by bare name in sandbox code`);
2072
- }
2073
2067
  /**
2074
- * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
2075
- * map. See the module comment for the split. Throws {@link GlobalNameError}
2076
- * for a name sandbox code cannot reference by bare name.
2077
- * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
2078
- * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
2079
- * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
2080
- * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
2081
- * entry for the private handler under `handlerName`.
2082
- * @param globals
2068
+ * Thrown out of a run when a hard abort did not produce a Result within
2069
+ * {@link TERMINATE_GRACE_MS} (or when the pre-run abort race tears down
2070
+ * before the run settles). The
2071
+ * connection is torn down (so the Rust isolate is reclaimed) before this
2072
+ * propagates, and the client is marked unusable so the pool replaces it rather
2073
+ * than reusing a half-dead slot. `index.ts` catches this and synthesizes the
2074
+ * `ERR_ABORTED` `RunResult`. When the graceful path succeeds instead, no error
2075
+ * is thrown — the real `ERR_ABORTED` Result flows back through the router.
2083
2076
  */
2084
- function processGlobals(globals) {
2085
- const defs = [];
2086
- const dispatch = {};
2087
- for (const [name, value] of Object.entries(globals)) {
2088
- checkGlobalName(name);
2089
- if (typeof value === "function") {
2090
- defs.push({
2091
- kind: "bridge",
2092
- name,
2093
- enumerable: true
2094
- });
2095
- dispatch[name] = value;
2096
- } else if (typeof value === "string") defs.push({
2097
- kind: "string",
2098
- name,
2099
- expr: value,
2100
- enumerable: true
2101
- });
2102
- else if (isBridgeGlobal(value)) {
2103
- defs.push({
2104
- kind: "bridge",
2105
- name,
2106
- enumerable: value.enumerable ?? true
2107
- });
2108
- dispatch[name] = value.handler;
2109
- } else if (isStringGlobal(value)) defs.push({
2110
- kind: "string",
2111
- name,
2112
- expr: value.expr,
2113
- enumerable: value.enumerable ?? true
2114
- });
2115
- else if (isDataGlobal(value)) defs.push({
2116
- kind: "data",
2117
- name,
2118
- value: value.value,
2119
- enumerable: value.enumerable ?? true
2120
- });
2121
- else if (isBridgeWithShim(value)) {
2122
- const handlerName = shimHandlerName(name);
2123
- defs.push({
2124
- kind: "shim",
2125
- name,
2126
- shim: value.shim,
2127
- handlerName,
2128
- enumerable: value.enumerable ?? true
2129
- });
2130
- dispatch[handlerName] = value.handler;
2131
- }
2077
+ var RunAbortedError = class extends Error {
2078
+ /**
2079
+ * The value passed to `AbortController.abort(reason)`, if any.
2080
+ */
2081
+ reason;
2082
+ constructor(reason, message = "run was aborted") {
2083
+ super(message);
2084
+ this.name = "RunAbortedError";
2085
+ this.reason = reason;
2132
2086
  }
2133
- return {
2134
- defs,
2135
- dispatch
2136
- };
2137
- }
2138
- /**
2139
- * Resolve bridge globals for a `prefix.run()` call.
2140
- *
2141
- * String/data globals and shim *wrappers* are already compiled into the
2142
- * declared prefix state, replayed by the runtime when the prefix evaluates —
2143
- * only the bridge *stubs* they call need re-installing per run (bridge stubs
2144
- * are bound to the run's socket). So
2145
- * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
2146
- * their private `__iso4_<name>_h` key so rebinding updates the handler the
2147
- * shim calls, without touching the shim itself.
2148
- * @param runGlobals
2149
- * @param precompileGlobals
2150
- */
2087
+ };
2151
2088
  /**
2152
- * Resolve a per-run override for a declared bridge global.
2089
+ * Thrown when a frame arrives that cannot belong to any run in flight on this
2090
+ * connection: a `Result` or `RunComplete` carrying a run id nothing here is
2091
+ * waiting on, or a frame type with no place in the protocol. Either way the
2092
+ * two sides have lost agreement about what this connection is doing, so
2093
+ * nothing it delivers from now on can be attributed with confidence.
2153
2094
  *
2154
- * An omitted key falls back to the precompile-time handler (the intended
2155
- * default). But a key that IS supplied yet is not a function — the runtime
2156
- * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
2157
- * `undefined` — throws instead of silently reusing the (often broader) default,
2158
- * which would be a fail-open exactly where the API is used to narrow privilege.
2159
- * This matches the imports side, which already rejects a non-function rebind.
2160
- * @param runGlobals the per-run rebind map
2161
- * @param name the declared global's name
2162
- * @param fallback the precompile-time handler used when no override is supplied
2163
- */
2164
- function resolveOverride(runGlobals, name, fallback) {
2165
- if (!Object.hasOwn(runGlobals, name)) return fallback;
2166
- const override = runGlobals[name];
2167
- if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
2168
- return override;
2169
- }
2170
- function extractBridgeGlobals(runGlobals, precompileGlobals) {
2171
- const defs = [];
2172
- const dispatch = {};
2173
- for (const [name, value] of Object.entries(precompileGlobals)) {
2174
- if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
2175
- if (isBridgeWithShim(value)) {
2176
- const handlerName = shimHandlerName(name);
2177
- defs.push({
2178
- kind: "bridge",
2179
- name: handlerName,
2180
- enumerable: true
2181
- });
2182
- dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
2183
- } else if (isBridgeGlobal(value)) {
2184
- defs.push({
2185
- kind: "bridge",
2186
- name,
2187
- enumerable: value.enumerable ?? true
2188
- });
2189
- dispatch[name] = resolveOverride(runGlobals, name, value.handler);
2190
- } else if (typeof value === "function") {
2191
- defs.push({
2192
- kind: "bridge",
2193
- name,
2194
- enumerable: true
2195
- });
2196
- dispatch[name] = resolveOverride(runGlobals, name, value);
2197
- }
2198
- }
2199
- for (const [name, override] of Object.entries(runGlobals)) {
2200
- if (name in precompileGlobals) continue;
2201
- checkGlobalName(name);
2202
- if (typeof override === "function") {
2203
- defs.push({
2204
- kind: "bridge",
2205
- name,
2206
- enumerable: true
2207
- });
2208
- dispatch[name] = override;
2209
- }
2210
- }
2211
- return {
2212
- defs,
2213
- dispatch
2214
- };
2215
- }
2216
- /**
2217
- * The dispatch-map key for one host-module function leaf. The NUL separator
2218
- * cannot collide with anything a specifier or dot-joined path can contain in
2219
- * practice, so keys stay unambiguous.
2220
- * @param specifier
2221
- * @param path dot-joined function-leaf path
2222
- */
2223
- function importHandlerKey(specifier, path) {
2224
- return `${specifier}\u0000${path}`;
2225
- }
2226
- /**
2227
- * Thrown when the host's import configuration is structurally invalid in a
2228
- * way only the client can see. `PrefixImpl.run` converts it into a failed
2229
- * `RunResult` carrying `code`: `ERR_FROZEN_BINDING` for a rebind of a frozen
2230
- * location (a source module), `ERR_INVALID_REBIND` for a non-function rebind
2231
- * value. Matches the runtime-side enforcement for locations only Rust can see.
2095
+ * The connection is torn down before this propagates — every run in flight on
2096
+ * it fails with this error — because a peer that is mid-run on someone else's
2097
+ * frames must never be handed to the next caller. `index.ts` catches this and
2098
+ * synthesizes the `ERR_PROTOCOL_DESYNC` `RunResult` — a displaced run never
2099
+ * executed, so there is no partial telemetry to report.
2232
2100
  */
2233
- var ImportRebindError = class extends Error {
2234
- code;
2235
- constructor(code, message) {
2236
- super(message);
2237
- this.name = "ImportRebindError";
2238
- this.code = code;
2239
- }
2240
- };
2241
- function processImports(imports) {
2242
- if (imports === void 0) return {
2243
- bindings: [],
2244
- handlers: /* @__PURE__ */ new Map()
2245
- };
2246
- const bindings = [];
2247
- const handlers = /* @__PURE__ */ new Map();
2248
- for (const [specifier, value] of Object.entries(imports)) {
2249
- if (typeof value === "string") {
2250
- bindings.push({
2251
- specifier,
2252
- source: value
2253
- });
2254
- continue;
2255
- }
2256
- if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] must be a string (source module) or a plain object (host module); got ${describeKind(value)}`);
2257
- const module = [];
2258
- for (const [name, child] of Object.entries(value)) {
2259
- if (child === void 0) continue;
2260
- if (!isValidExportIdentifier(name)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] top-level key '${name}' is not a valid JavaScript identifier and cannot be exported as a named ESM export`);
2261
- module.push([name, lowerNode(specifier, child, [name], handlers)]);
2262
- }
2263
- bindings.push({
2264
- specifier,
2265
- module
2266
- });
2267
- }
2268
- return {
2269
- bindings,
2270
- handlers
2271
- };
2272
- }
2273
- /**
2274
- * Lower one host-module node to its wire shape, registering function leaves.
2275
- * @param specifier
2276
- * @param value
2277
- * @param path
2278
- * @param handlers
2279
- * @param seen
2280
- */
2281
- function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
2282
- if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
2283
- if (typeof value === "function") {
2284
- handlers.set(importHandlerKey(specifier, path.join(".")), value);
2285
- return { kind: "function" };
2286
- }
2287
- if (isPlainObject(value)) {
2288
- if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
2289
- seen.add(value);
2290
- const entries = [];
2291
- for (const [key, child] of Object.entries(value)) {
2292
- if (child === void 0) continue;
2293
- entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
2294
- }
2295
- seen.delete(value);
2296
- return {
2297
- kind: "object",
2298
- entries
2299
- };
2300
- }
2301
- return {
2302
- kind: "data",
2303
- value
2304
- };
2305
- }
2306
- /**
2307
- * Merge the handlers behind a `Prefix`'s host-module function leaves with the
2308
- * run's overrides and collect the rebind locations to send on the wire.
2309
- *
2310
- * Only client-visible shape problems throw here (a string value — source
2311
- * modules are frozen; a non-function leaf value — there is nothing to
2312
- * dispatch to). Whether each location was actually declared as a function
2313
- * leaf at precompile time is enforced by the Rust runtime against the stored
2314
- * prefix shape (`ERR_UNDECLARED_BINDING` for undeclared locations,
2315
- * `ERR_FROZEN_BINDING` for frozen ones).
2316
- *
2317
- * @param runImports
2318
- * @param defaults handler map captured at precompile time
2319
- */
2320
- function mergeRebindImports(runImports, defaults) {
2321
- if (runImports === void 0) return {
2322
- rebinds: [],
2323
- handlers: defaults
2324
- };
2325
- const handlers = new Map(defaults);
2326
- const rebinds = [];
2327
- for (const [specifier, value] of Object.entries(runImports)) {
2328
- if (typeof value === "string") throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}' is a source module — source imports are frozen with the prefix and cannot be rebound at prefix.run() time`);
2329
- if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
2330
- walkRebind(specifier, value, [], handlers, rebinds);
2331
- }
2332
- return {
2333
- rebinds,
2334
- handlers
2335
- };
2336
- }
2337
- function walkRebind(specifier, node, path, handlers, rebinds) {
2338
- for (const [key, value] of Object.entries(node)) {
2339
- if (value === void 0) continue;
2340
- const newPath = [...path, key];
2341
- if (typeof value === "function") {
2342
- const joined = newPath.join(".");
2343
- handlers.set(importHandlerKey(specifier, joined), value);
2344
- rebinds.push({
2345
- specifier,
2346
- path: joined
2347
- });
2348
- continue;
2349
- }
2350
- if (isPlainObject(value)) {
2351
- walkRebind(specifier, value, newPath, handlers, rebinds);
2352
- continue;
2353
- }
2354
- throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
2355
- }
2356
- }
2357
- function isPlainObject(value) {
2358
- if (value === null || typeof value !== "object") return false;
2359
- if (Array.isArray(value)) return false;
2360
- const proto = Object.getPrototypeOf(value);
2361
- return proto === null || proto === Object.prototype;
2362
- }
2363
- /**
2364
- * Whether `name` can appear as a named ESM export. JS identifier rules plus
2365
- * a reserved-word filter. `default` is allowed (the runtime emits it as
2366
- * `export default`). Mirrored by `is_valid_export_identifier` in the Rust
2367
- * runtime (`v8.rs`), which owns the final defensive check.
2368
- * @param name
2369
- */
2370
- function isValidExportIdentifier(name) {
2371
- if (name === "default") return true;
2372
- if (!IDENTIFIER_NAME.test(name)) return false;
2373
- if (RESERVED_WORDS.has(name)) return false;
2374
- return true;
2375
- }
2376
- function describeKind(value) {
2377
- if (value === null) return "null";
2378
- if (Array.isArray(value)) return "array";
2379
- return typeof value;
2380
- }
2381
- //#endregion
2382
- //#region src/client.ts
2383
- /**
2384
- * How long TS waits for Rust's `ERR_ABORTED` Result after sending a HARD
2385
- * `Terminate`, before falling back to tearing the connection down.
2386
- *
2387
- * Hard aborts always answer promptly (a suspended run is abandoned on the
2388
- * spot, executing JS is interrupted mid-turn), so no answer within this
2389
- * window means the runtime cannot answer at all (wedged process). SOFT
2390
- * aborts arm no fallback: a run spinning with no `cpuTimeMs` cap
2391
- * legitimately cannot answer one until its own limits end the turn, and
2392
- * tearing the connection down for that would fail every co-resident run of
2393
- * a healthy runtime.
2394
- */
2395
- const TERMINATE_GRACE_MS = 100;
2396
- /**
2397
- * How long `connect()` waits for the runtime's `Hello` frame before giving up.
2398
- * The runtime answers a handshake without touching V8 (the probe is computed
2399
- * once at process start), so this only bites when the binary is wedged.
2400
- */
2401
- const HELLO_TIMEOUT_MS = 5e3;
2402
- /**
2403
- * Shared placeholder for `RunEntry` callbacks between wiring phases —
2404
- * allocating fresh `() => {}` closures per run is avoidable hot-path churn.
2405
- */
2406
- function NOOP() {}
2407
- /**
2408
- * Thrown out of `createSandbox()` when the connection handshake fails.
2409
- *
2410
- * The common cause is a V8 serialization format-version mismatch between this
2411
- * Node and the `@iso4/v8-*` binary: values cross the boundary as V8
2412
- * serialization blobs, so the two V8s must agree on the format. Internal —
2413
- * `@iso4/sandbox` does not export this type; it reaches callers as a plain
2414
- * `Error` with `name = 'Iso4HandshakeError'`.
2415
- */
2416
- var HandshakeError = class extends Error {
2417
- constructor(message) {
2418
- super(`[@iso4/sandbox] ${message}`);
2419
- this.name = "Iso4HandshakeError";
2420
- }
2421
- };
2422
- /**
2423
- * Thrown out of a run when a hard abort did not produce a Result within
2424
- * {@link TERMINATE_GRACE_MS} (or when the pre-run abort race tears down
2425
- * before the run settles). The
2426
- * connection is torn down (so the Rust isolate is reclaimed) before this
2427
- * propagates, and the client is marked unusable so the pool replaces it rather
2428
- * than reusing a half-dead slot. `index.ts` catches this and synthesizes the
2429
- * `ERR_ABORTED` `RunResult`. When the graceful path succeeds instead, no error
2430
- * is thrown — the real `ERR_ABORTED` Result flows back through the router.
2431
- */
2432
- var RunAbortedError = class extends Error {
2433
- /**
2434
- * The value passed to `AbortController.abort(reason)`, if any.
2435
- */
2436
- reason;
2437
- constructor(reason, message = "run was aborted") {
2438
- super(message);
2439
- this.name = "RunAbortedError";
2440
- this.reason = reason;
2441
- }
2442
- };
2443
- /**
2444
- * Thrown when a frame arrives that cannot belong to any run in flight on this
2445
- * connection: a `Result` or `RunComplete` carrying a run id nothing here is
2446
- * waiting on, or a frame type with no place in the protocol. Either way the
2447
- * two sides have lost agreement about what this connection is doing, so
2448
- * nothing it delivers from now on can be attributed with confidence.
2449
- *
2450
- * The connection is torn down before this propagates — every run in flight on
2451
- * it fails with this error — because a peer that is mid-run on someone else's
2452
- * frames must never be handed to the next caller. `index.ts` catches this and
2453
- * synthesizes the `ERR_PROTOCOL_DESYNC` `RunResult` — a displaced run never
2454
- * executed, so there is no partial telemetry to report.
2455
- */
2456
- var ProtocolDesyncError = class extends Error {
2457
- constructor(message) {
2458
- super(`[@iso4/sandbox] ${message}`);
2459
- this.name = "Iso4ProtocolDesyncError";
2101
+ var ProtocolDesyncError = class extends Error {
2102
+ constructor(message) {
2103
+ super(`[@iso4/sandbox] ${message}`);
2104
+ this.name = "Iso4ProtocolDesyncError";
2460
2105
  }
2461
2106
  };
2462
2107
  var RuntimeIpcClient = class RuntimeIpcClient {
@@ -2507,10 +2152,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2507
2152
  */
2508
2153
  controlWaiters = [];
2509
2154
  /**
2510
- * Pending `precompile()` requests keyed by their wire `requestId`.
2511
- * Precompiles are answered on runtime worker threads, so with several in
2512
- * flight on one connection the replies can return out of request order —
2513
- * FIFO matching would cross-assign prefix ids between callers.
2155
+ * Pending `precompile()` requests keyed by their wire `requestId`, so a
2156
+ * reply is matched by id and never by arrival order.
2514
2157
  */
2515
2158
  precompileWaiters = /* @__PURE__ */ new Map();
2516
2159
  /**
@@ -3165,12 +2808,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
3165
2808
  })));
3166
2809
  else {
3167
2810
  const { runId: frameRunId, callId } = call;
3168
- dispatcher({
3169
- targetKind: call.targetKind,
3170
- specifier: call.specifier,
3171
- exportName: call.exportName,
3172
- args: call.args
3173
- }).then(async (value) => {
2811
+ dispatcher(call.target, call.args).then(async (value) => {
3174
2812
  let encoded;
3175
2813
  try {
3176
2814
  encoded = await serializeHostValue(value, this.brandKey, streams);
@@ -3217,14 +2855,17 @@ var RuntimeIpcClient = class RuntimeIpcClient {
3217
2855
  */
3218
2856
  function makeDispatcher(globals, imports) {
3219
2857
  if (Object.keys(globals).length === 0 && (imports === void 0 || imports.size === 0)) return void 0;
3220
- return async ({ targetKind, specifier, exportName, args }) => {
3221
- if (targetKind === 1) {
3222
- const handler = imports?.get(importHandlerKey(specifier ?? "", exportName));
3223
- if (handler === void 0) throw new Error(`no handler configured for host import '${specifier}'.${exportName}`);
2858
+ return async (target, args) => {
2859
+ if (target.targetKind === 1) {
2860
+ const handler = imports?.get(target.key);
2861
+ if (handler === void 0) {
2862
+ const { specifier, path } = decodeImportKey(target.key);
2863
+ throw new Error(`no handler configured for host import '${specifier}'.${path.join(".")}`);
2864
+ }
3224
2865
  return handler(...args);
3225
2866
  }
3226
- const handler = globals[exportName];
3227
- if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
2867
+ const handler = globals[target.exportName];
2868
+ if (handler === void 0) throw new Error(`no handler configured for bridge global '${target.exportName}'`);
3228
2869
  return handler(...args);
3229
2870
  };
3230
2871
  }
@@ -3589,6 +3230,345 @@ var RunPool = class {
3589
3230
  }
3590
3231
  };
3591
3232
  //#endregion
3233
+ //#region src/globals.ts
3234
+ /**
3235
+ * The error every setup refusal is thrown as, whichever side detects it: a
3236
+ * plain `Error` carrying the runtime's code.
3237
+ * @param code the setup code
3238
+ * @param message the runtime's message for it
3239
+ */
3240
+ function setupError(code, message) {
3241
+ const err = new Error(message);
3242
+ err.name = "Error";
3243
+ err.code = code;
3244
+ return err;
3245
+ }
3246
+ function isBridgeWithShim(v) {
3247
+ return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
3248
+ }
3249
+ function isDataGlobal(v) {
3250
+ return typeof v === "object" && v !== null && v.kind === "data";
3251
+ }
3252
+ function isBridgeGlobal(v) {
3253
+ return typeof v === "object" && v !== null && v.kind === "bridge";
3254
+ }
3255
+ function isStringGlobal(v) {
3256
+ return typeof v === "object" && v !== null && v.kind === "string";
3257
+ }
3258
+ /**
3259
+ * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
3260
+ * dispatch key and an object-property key — never interpolated into generated
3261
+ * code — so any global name is safe. The runtime recognises the
3262
+ * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
3263
+ * bridge records under the public `<name>`.
3264
+ * @param name public global name
3265
+ */
3266
+ function shimHandlerName(name) {
3267
+ return `__iso4_${name}_h`;
3268
+ }
3269
+ /**
3270
+ * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
3271
+ * map. See the module comment for the split. Throws a `TypeError` for a name
3272
+ * that is not a well-formed string and `ERR_RESERVED_NAME` for a runtime-owned
3273
+ * one.
3274
+ * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
3275
+ * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
3276
+ * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
3277
+ * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
3278
+ * entry for the private handler under `handlerName`.
3279
+ * @param globals
3280
+ */
3281
+ function processGlobals(globals) {
3282
+ const defs = [];
3283
+ const dispatch = {};
3284
+ for (const [name, value] of Object.entries(globals)) {
3285
+ if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
3286
+ if (RUNTIME_OWNED_GLOBALS.has(name)) throw setupError("ERR_RESERVED_NAME", `global '${name}' is reserved by the runtime and cannot be provided by the host`);
3287
+ if (typeof value === "function") {
3288
+ defs.push({
3289
+ kind: "bridge",
3290
+ name,
3291
+ enumerable: true
3292
+ });
3293
+ dispatch[name] = value;
3294
+ } else if (typeof value === "string") defs.push({
3295
+ kind: "string",
3296
+ name,
3297
+ expr: value,
3298
+ enumerable: true
3299
+ });
3300
+ else if (isBridgeGlobal(value)) {
3301
+ defs.push({
3302
+ kind: "bridge",
3303
+ name,
3304
+ enumerable: value.enumerable ?? true
3305
+ });
3306
+ dispatch[name] = value.handler;
3307
+ } else if (isStringGlobal(value)) defs.push({
3308
+ kind: "string",
3309
+ name,
3310
+ expr: value.expr,
3311
+ enumerable: value.enumerable ?? true
3312
+ });
3313
+ else if (isDataGlobal(value)) defs.push({
3314
+ kind: "data",
3315
+ name,
3316
+ value: value.value,
3317
+ enumerable: value.enumerable ?? true
3318
+ });
3319
+ else if (isBridgeWithShim(value)) {
3320
+ const handlerName = shimHandlerName(name);
3321
+ defs.push({
3322
+ kind: "shim",
3323
+ name,
3324
+ shim: value.shim,
3325
+ handlerName,
3326
+ enumerable: value.enumerable ?? true
3327
+ });
3328
+ dispatch[handlerName] = value.handler;
3329
+ }
3330
+ }
3331
+ return {
3332
+ defs,
3333
+ dispatch
3334
+ };
3335
+ }
3336
+ /**
3337
+ * Copy the declared global shape at `prepare()`, so later changes to the
3338
+ * caller's object change nothing. Kinds `processGlobals` ignores are left out.
3339
+ * @param globals the `globals` passed to `prepare()`
3340
+ */
3341
+ function declareGlobals(globals) {
3342
+ const declared = /* @__PURE__ */ new Map();
3343
+ for (const [name, value] of Object.entries(globals)) if (typeof value === "function") declared.set(name, {
3344
+ kind: "bridge",
3345
+ handler: value,
3346
+ enumerable: true
3347
+ });
3348
+ else if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) declared.set(name, { kind: "value" });
3349
+ else if (isBridgeWithShim(value)) declared.set(name, {
3350
+ kind: "shim",
3351
+ handler: value.handler
3352
+ });
3353
+ else if (isBridgeGlobal(value)) declared.set(name, {
3354
+ kind: "bridge",
3355
+ handler: value.handler,
3356
+ enumerable: value.enumerable ?? true
3357
+ });
3358
+ return declared;
3359
+ }
3360
+ /**
3361
+ * Resolve bridge globals for a `prefix.run()` call.
3362
+ *
3363
+ * Value globals and shim wrappers are replayed from the declared prefix
3364
+ * state, so every returned def is `kind: 'bridge'`; a shim override is routed
3365
+ * to its private `__iso4_<name>_h` key. Throws the setup error the runtime
3366
+ * would send for an undeclared or frozen name, and `ERR_INVALID_REBIND` for a
3367
+ * non-function override.
3368
+ * @param runGlobals the run's `globals` option
3369
+ * @param declared the shape kept from `prepare()` by {@link declareGlobals}
3370
+ */
3371
+ function extractBridgeGlobals(runGlobals, declared) {
3372
+ const overrides = runGlobals;
3373
+ for (const [name, override] of Object.entries(overrides)) {
3374
+ if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
3375
+ const shape = declared.get(name);
3376
+ if (shape === void 0) throw setupError("ERR_UNDECLARED_BINDING", `global '${name}' was not declared at precompile time`);
3377
+ if (shape.kind === "value") throw setupError("ERR_FROZEN_BINDING", `global '${name}' is a value global, frozen with the prefix — only function globals can be rebound`);
3378
+ if (typeof override !== "function") throw setupError("ERR_INVALID_REBIND", `global '${name}' can only be rebound with a function; got ${override === null ? "null" : typeof override}`);
3379
+ }
3380
+ const defs = [];
3381
+ const dispatch = {};
3382
+ for (const [name, shape] of declared) {
3383
+ if (shape.kind === "value") continue;
3384
+ const override = Object.hasOwn(overrides, name) ? overrides[name] : void 0;
3385
+ const stub = shape.kind === "shim" ? shimHandlerName(name) : name;
3386
+ defs.push({
3387
+ kind: "bridge",
3388
+ name: stub,
3389
+ enumerable: shape.kind === "shim" || shape.enumerable
3390
+ });
3391
+ dispatch[stub] = override ?? shape.handler;
3392
+ }
3393
+ return {
3394
+ defs,
3395
+ dispatch
3396
+ };
3397
+ }
3398
+ /**
3399
+ * The dispatch-map key for one host-module function leaf: the wire bytes of
3400
+ * its specifier and key segments, so `{ 'a.b': f }` and `{ a: { b: f } }` differ.
3401
+ * @param specifier
3402
+ * @param path the leaf's key segments
3403
+ */
3404
+ const importHandlerKey = encodeImportKey;
3405
+ /**
3406
+ * Thrown for an import rebind the prefix does not allow. `PrefixImpl.run`
3407
+ * rethrows it as the same coded `Error` the runtime's refusals become.
3408
+ */
3409
+ var ImportRebindError = class extends Error {
3410
+ code;
3411
+ constructor(code, message) {
3412
+ super(message);
3413
+ this.name = "ImportRebindError";
3414
+ this.code = code;
3415
+ }
3416
+ };
3417
+ function processImports(imports) {
3418
+ if (imports === void 0) return {
3419
+ bindings: [],
3420
+ handlers: /* @__PURE__ */ new Map()
3421
+ };
3422
+ const bindings = [];
3423
+ const handlers = /* @__PURE__ */ new Map();
3424
+ for (const [specifier, value] of Object.entries(imports)) {
3425
+ if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
3426
+ if (typeof value === "string") {
3427
+ bindings.push({
3428
+ specifier,
3429
+ source: value
3430
+ });
3431
+ continue;
3432
+ }
3433
+ if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] must be a string (source module) or a plain object (host module); got ${describeKind(value)}`);
3434
+ const module = [];
3435
+ for (const [name, child] of Object.entries(value)) {
3436
+ if (child === void 0) continue;
3437
+ if (!isValidExportName(name)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] top-level key '${name}' is not a valid JavaScript identifier and cannot be exported as a named ESM export`);
3438
+ module.push([name, lowerNode(specifier, child, [name], handlers)]);
3439
+ }
3440
+ bindings.push({
3441
+ specifier,
3442
+ module
3443
+ });
3444
+ }
3445
+ return {
3446
+ bindings,
3447
+ handlers
3448
+ };
3449
+ }
3450
+ /**
3451
+ * Lower one host-module node to its wire shape, registering function leaves.
3452
+ * @param specifier
3453
+ * @param value
3454
+ * @param path
3455
+ * @param handlers
3456
+ * @param seen
3457
+ */
3458
+ function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
3459
+ if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
3460
+ if (typeof value === "function") {
3461
+ handlers.set(importHandlerKey(specifier, path), value);
3462
+ return { kind: "function" };
3463
+ }
3464
+ if (isPlainObject(value)) {
3465
+ if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
3466
+ seen.add(value);
3467
+ const entries = [];
3468
+ for (const [key, child] of Object.entries(value)) {
3469
+ if (child === void 0) continue;
3470
+ if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
3471
+ entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
3472
+ }
3473
+ seen.delete(value);
3474
+ return {
3475
+ kind: "object",
3476
+ entries
3477
+ };
3478
+ }
3479
+ return {
3480
+ kind: "data",
3481
+ value
3482
+ };
3483
+ }
3484
+ /**
3485
+ * The declared import shape without data-leaf values or source text, kept by a
3486
+ * prefix for {@link mergeRebindImports} so it does not pin large data.
3487
+ * @param bindings the bindings sent at `prepare()`
3488
+ */
3489
+ function declaredImportShape(bindings) {
3490
+ const strip = (entries) => entries.map(([key, node]) => [key, node.kind === "object" ? {
3491
+ kind: "object",
3492
+ entries: strip(node.entries)
3493
+ } : node.kind === "data" ? {
3494
+ kind: "data",
3495
+ value: void 0
3496
+ } : node]);
3497
+ return bindings.map((b) => "source" in b ? {
3498
+ specifier: b.specifier,
3499
+ source: ""
3500
+ } : {
3501
+ specifier: b.specifier,
3502
+ module: strip(b.module)
3503
+ });
3504
+ }
3505
+ /**
3506
+ * Merge the handlers behind a `Prefix`'s host-module function leaves with the
3507
+ * run's overrides and collect the rebind locations to send on the wire.
3508
+ *
3509
+ * Every location is looked up in the declared shape before its value is
3510
+ * looked at, with the same codes and messages as `validate_import_rebinds` in
3511
+ * the runtime, which repeats the check: undeclared is `ERR_UNDECLARED_BINDING`,
3512
+ * a source module or data leaf `ERR_FROZEN_BINDING`. A declared location
3513
+ * given the wrong kind of value is `ERR_INVALID_REBIND`.
3514
+ *
3515
+ * @param runImports the run's `imports` option
3516
+ * @param defaults handler map captured at precompile time
3517
+ * @param declared the import shape declared at `prepare()`
3518
+ */
3519
+ function mergeRebindImports(runImports, defaults, declared) {
3520
+ if (runImports === void 0) return {
3521
+ rebinds: [],
3522
+ handlers: defaults
3523
+ };
3524
+ const handlers = new Map(defaults);
3525
+ const rebinds = [];
3526
+ for (const [specifier, value] of Object.entries(runImports)) {
3527
+ if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
3528
+ const binding = declared.find((b) => b.specifier === specifier);
3529
+ if (binding === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}' was not declared at precompile time`);
3530
+ if ("source" in binding) throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}' is a source module — source imports are frozen with the prefix and cannot be rebound at prefix.run() time`);
3531
+ if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}' can only be rebound with a plain object; got ${describeKind(value)}`);
3532
+ walkRebind(specifier, value, binding.module, [], handlers, rebinds);
3533
+ }
3534
+ return {
3535
+ rebinds,
3536
+ handlers
3537
+ };
3538
+ }
3539
+ function walkRebind(specifier, node, declared, path, handlers, rebinds) {
3540
+ for (const [key, value] of Object.entries(node)) {
3541
+ if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
3542
+ const segments = [...path, key];
3543
+ const joined = segments.join(".");
3544
+ const shape = declared.find(([name]) => name === key)?.[1];
3545
+ if (shape === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}'.${joined} was not declared at precompile time`);
3546
+ if (shape.kind === "data") throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
3547
+ if (shape.kind === "object") {
3548
+ if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a plain object; got ${describeKind(value)}`);
3549
+ walkRebind(specifier, value, shape.entries, segments, handlers, rebinds);
3550
+ continue;
3551
+ }
3552
+ if (typeof value !== "function") throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
3553
+ handlers.set(importHandlerKey(specifier, segments), value);
3554
+ rebinds.push({
3555
+ specifier,
3556
+ path: segments
3557
+ });
3558
+ }
3559
+ }
3560
+ function isPlainObject(value) {
3561
+ if (value === null || typeof value !== "object") return false;
3562
+ if (Array.isArray(value)) return false;
3563
+ const proto = Object.getPrototypeOf(value);
3564
+ return proto === null || proto === Object.prototype;
3565
+ }
3566
+ function describeKind(value) {
3567
+ if (value === null) return "null";
3568
+ if (Array.isArray(value)) return "array";
3569
+ return typeof value;
3570
+ }
3571
+ //#endregion
3592
3572
  //#region src/index.ts
3593
3573
  /**
3594
3574
  * \@iso4/sandbox - public entry point.
@@ -3822,6 +3802,43 @@ function waitUntilResultFrom(report) {
3822
3802
  return out;
3823
3803
  }
3824
3804
  /**
3805
+ * The `ResourceLimits` fields the wire carries as a `u32`; `0` disables each.
3806
+ */
3807
+ const U32_LIMIT_FIELDS = [
3808
+ "cpuTimeMs",
3809
+ "wallTimeMs",
3810
+ "maxBridgeCallBytes",
3811
+ "maxExportBytes",
3812
+ "maxStdoutBytes",
3813
+ "maxStderrBytes",
3814
+ "maxBridgeCalls",
3815
+ "graceMs"
3816
+ ];
3817
+ const U32_MAX = 4294967295;
3818
+ /**
3819
+ * Refuse a limit the wire cannot carry as a `u32` instead of letting the
3820
+ * encoder throw a `RangeError` or silently truncate a fraction.
3821
+ * @param limits the caller's `limits` option
3822
+ */
3823
+ function validateLimits(limits) {
3824
+ if (limits === void 0) return;
3825
+ if (limits === null || typeof limits !== "object") throw new TypeError("[@iso4/sandbox] limits must be an object");
3826
+ for (const field of U32_LIMIT_FIELDS) {
3827
+ const value = limits[field];
3828
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 0 && value <= U32_MAX)) throw new TypeError(`[@iso4/sandbox] limits.${field} must be an integer from 0 to ${U32_MAX}`);
3829
+ }
3830
+ }
3831
+ /**
3832
+ * Only the public `u32` fields; heap caps come from `heapCapsForWire`, so an
3833
+ * untyped caller cannot smuggle `memoryMb`/`hardMemoryMb` onto the wire.
3834
+ * @param limits the validated `limits` option
3835
+ */
3836
+ function wireLimits(limits) {
3837
+ const out = {};
3838
+ for (const field of U32_LIMIT_FIELDS) if (limits?.[field] !== void 0) out[field] = limits[field];
3839
+ return out;
3840
+ }
3841
+ /**
3825
3842
  * A heap cap must be an integer number of megabytes ≥ 0 (0 = uncapped):
3826
3843
  * the wire carries it as a u32, and a fractional or negative value would
3827
3844
  * silently misencode instead of capping.
@@ -3831,11 +3848,11 @@ function waitUntilResultFrom(report) {
3831
3848
  function validateMemoryMb(value, where) {
3832
3849
  if (value === void 0) return;
3833
3850
  if (typeof value === "number") {
3834
- if (!Number.isInteger(value) || value < 0) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer >= 0 (megabytes; 0 = uncapped)`);
3851
+ if (!Number.isInteger(value) || value < 0 || value > U32_MAX) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer from 0 to ${U32_MAX} (megabytes; 0 = uncapped)`);
3835
3852
  return;
3836
3853
  }
3837
3854
  if (value === null || typeof value !== "object") throw new TypeError(`[@iso4/sandbox] ${where} must be a number of megabytes or { soft?, hard }`);
3838
- if (!Number.isInteger(value.hard) || value.hard < 1) throw new TypeError(`[@iso4/sandbox] ${where}.hard must be an integer >= 1 (megabytes) — write memoryMb: 0 for uncapped`);
3855
+ if (!Number.isInteger(value.hard) || value.hard < 1 || value.hard > U32_MAX) throw new TypeError(`[@iso4/sandbox] ${where}.hard must be an integer from 1 to ${U32_MAX} (megabytes) — write memoryMb: 0 for uncapped`);
3839
3856
  if (value.soft === void 0) return;
3840
3857
  if (!Number.isInteger(value.soft) || value.soft < 1) throw new TypeError(`[@iso4/sandbox] ${where}.soft must be an integer >= 1 (megabytes) — omit it for a hard line only`);
3841
3858
  if (value.soft >= value.hard) throw new TypeError(`[@iso4/sandbox] ${where}.soft (${value.soft}) must be below ${where}.hard (${value.hard})`);
@@ -3927,6 +3944,31 @@ function desyncResult(error) {
3927
3944
  bridgeCalls: []
3928
3945
  };
3929
3946
  }
3947
+ /**
3948
+ * Codes the runtime reports for a run whose options are invalid. The client
3949
+ * checks first; this catches what it cannot know, such as a prefix the
3950
+ * runtime dropped. Runs throw these, like `prepare()`, instead of returning them.
3951
+ */
3952
+ const SETUP_ERROR_CODES = new Set([
3953
+ "ERR_RESERVED_NAME",
3954
+ "ERR_UNDECLARED_BINDING",
3955
+ "ERR_FROZEN_BINDING",
3956
+ "ERR_INVALID_REBIND",
3957
+ "ERR_PREFIX_DISPOSED",
3958
+ "ERR_PREFIX_BROKEN"
3959
+ ]);
3960
+ /**
3961
+ * The error `prepare()`, `readExports()` and `run()` throw for a failure the
3962
+ * runtime reported: an `Error` carrying the runtime's `code`, `name`, `stack`.
3963
+ * @param error the reported failure
3964
+ */
3965
+ function thrownRunError(error) {
3966
+ const err = new Error(error.message);
3967
+ err.name = error.name;
3968
+ err.code = error.code;
3969
+ if (error.stack) err.stack = error.stack;
3970
+ return err;
3971
+ }
3930
3972
  function abortedResult(reason, from) {
3931
3973
  return {
3932
3974
  status: "aborted",
@@ -4001,44 +4043,24 @@ var SandboxImpl = class {
4001
4043
  async run(options) {
4002
4044
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4003
4045
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4046
+ validateLimits(options.limits);
4004
4047
  if (typeof options.limits?.memoryMb === "object") throw new TypeError("[@iso4/sandbox] limits.memoryMb takes a number of megabytes — the { soft, hard } form belongs on createSandbox or prepare, whose instances are reused");
4005
4048
  validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
4006
4049
  const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
4007
- let processed;
4008
- try {
4009
- processed = processGlobals(options.globals ?? {});
4010
- } catch (e) {
4011
- if (e instanceof GlobalNameError) return {
4012
- status: "failed",
4013
- ok: false,
4014
- error: {
4015
- code: e.code,
4016
- name: "Error",
4017
- message: e.message
4018
- },
4019
- stdout: [],
4020
- stderr: [],
4021
- durationMs: 0,
4022
- wallTimeMs: 0,
4023
- cpuTimeMs: 0,
4024
- bridgeCalls: []
4025
- };
4026
- throw e;
4027
- }
4028
- const { defs, dispatch } = processed;
4050
+ const { defs, dispatch } = processGlobals(options.globals ?? {});
4029
4051
  await materializeHostTypesInGlobals(defs, this.brandKey);
4030
4052
  const { bindings, handlers } = processImports(options.imports);
4031
4053
  const streams = new StreamSourceRegistry();
4032
- const call = options.call === void 0 ? void 0 : {
4033
- exportPath: options.call.export,
4034
- argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
4035
- };
4036
4054
  try {
4055
+ const call = options.call === void 0 ? void 0 : {
4056
+ exportPath: options.call.export,
4057
+ argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
4058
+ };
4037
4059
  return await this.pool.withClient(async (client, queueWaitMs) => {
4038
4060
  const raw = await client.runRawCode(options.code, {
4039
4061
  filename: options.filename,
4040
4062
  limits: {
4041
- ...options.limits,
4063
+ ...wireLimits(options.limits),
4042
4064
  ...heapCapsForWire(runMemoryMb)
4043
4065
  },
4044
4066
  globals: defs,
@@ -4051,6 +4073,10 @@ var SandboxImpl = class {
4051
4073
  streams
4052
4074
  });
4053
4075
  const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds).result : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds).result);
4076
+ if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
4077
+ ...decoded.error,
4078
+ code: decoded.error.code
4079
+ });
4054
4080
  if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
4055
4081
  if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
4056
4082
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
@@ -4093,8 +4119,8 @@ var SandboxImpl = class {
4093
4119
  }
4094
4120
  /**
4095
4121
  * Load a module once and read its serializable exports — the deploy path.
4096
- * Function exports are skipped and reported; failures reject, like
4097
- * `prepare()`. See {@link Sandbox.readExports}.
4122
+ * Function exports are skipped and reported; failures reject. See
4123
+ * {@link Sandbox.readExports}.
4098
4124
  * @param options
4099
4125
  */
4100
4126
  async readExports(options) {
@@ -4103,13 +4129,7 @@ var SandboxImpl = class {
4103
4129
  filename: options.filename,
4104
4130
  limits: options.limits
4105
4131
  });
4106
- if (result.status !== "completed") {
4107
- const err = new Error(result.error.message);
4108
- err.name = result.error.name;
4109
- err.code = result.error.code;
4110
- if (result.error.stack) err.stack = result.error.stack;
4111
- throw err;
4112
- }
4132
+ if (result.status !== "completed") throw thrownRunError(result.error);
4113
4133
  return {
4114
4134
  exports: result.exports,
4115
4135
  skippedExports: result.skippedExports
@@ -4123,15 +4143,18 @@ var SandboxImpl = class {
4123
4143
  return this.prepare(options);
4124
4144
  }
4125
4145
  /**
4126
- * Validate and prepare a prefix for repeated runs. See
4146
+ * Store a prefix for repeated runs; nothing is evaluated. See
4127
4147
  * {@link Sandbox.prepare}.
4128
4148
  * @param options
4129
4149
  */
4130
4150
  async prepare(options) {
4151
+ if (typeof options.code !== "string") throw new TypeError(`prepare({ code }) must be a string, got ${options.code === null ? "null" : typeof options.code}`);
4131
4152
  validateMemoryMb(options.memoryMb, "memoryMb");
4153
+ validateLimits(options.limits);
4132
4154
  const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
4133
4155
  const rawGlobals = options.globals ?? {};
4134
4156
  const { defs } = processGlobals(rawGlobals);
4157
+ const declaredGlobals = declareGlobals(rawGlobals);
4135
4158
  return this.pool.withClient(async (client) => {
4136
4159
  await materializeHostTypesInGlobals(defs, this.brandKey);
4137
4160
  const { bindings, handlers } = processImports(options.imports);
@@ -4139,20 +4162,14 @@ var SandboxImpl = class {
4139
4162
  code: options.code,
4140
4163
  filename: options.filename,
4141
4164
  limits: {
4142
- ...options.limits,
4165
+ ...wireLimits(options.limits),
4143
4166
  ...heapCapsForWire(prefixMemoryMb)
4144
4167
  },
4145
4168
  globals: defs,
4146
4169
  imports: bindings
4147
4170
  }));
4148
- if (!result.ok) {
4149
- const err = new Error(result.error.message);
4150
- err.name = result.error.name;
4151
- err.code = result.error.code;
4152
- if (result.error.stack) err.stack = result.error.stack;
4153
- throw err;
4154
- }
4155
- return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers, this.brandKey, prefixMemoryMb);
4171
+ if (!result.ok) throw thrownRunError(result.error);
4172
+ return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb, wireLimits(options.limits));
4156
4173
  });
4157
4174
  }
4158
4175
  async dispose() {
@@ -4177,23 +4194,20 @@ var PrefixImpl = class {
4177
4194
  id;
4178
4195
  pool;
4179
4196
  /**
4180
- * Handlers declared at precompile time. Used as defaults for any run that
4181
- * does not supply its own override, per DESIGN.md §11.4 "Rebinding rules":
4182
- * "If the prefix declared a global the run doesn't supply, the
4183
- * precompile-time implementation is reused."
4197
+ * The global shape declared at `prepare()`, with the default handlers a run
4198
+ * falls back to when it does not override them (DESIGN.md §11.4).
4184
4199
  */
4185
- defaultGlobals;
4200
+ declaredGlobals;
4186
4201
  /**
4187
- * Host-import function-leaf handlers declared at precompile time, keyed by
4188
- * `(specifier, path)`. Same rebinding rules as `defaultGlobals` — a
4189
- * `prefix.run()` may override a subset of function leaves; everything else
4190
- * falls back to these. Source modules and data leaves are frozen in the
4191
- * declared prefix state and not represented here. The declared shape itself lives with
4192
- * the prefix in the Rust runtime, which rejects rebind attempts outside it
4193
- * (`ERR_UNDECLARED_BINDING`) or at frozen locations (`ERR_FROZEN_BINDING`).
4202
+ * Host-import function-leaf handlers declared at `prepare()`, keyed by
4203
+ * `(specifier, path)`; a run's overrides apply on top.
4194
4204
  */
4195
4205
  defaultImportHandlers;
4196
4206
  /**
4207
+ * The import shape declared at `prepare()`, for client-side rebind checks.
4208
+ */
4209
+ declaredImports;
4210
+ /**
4197
4211
  * THIS prefix's heap cap (`prepare({ memoryMb })`, falling back to the
4198
4212
  * sandbox default). Warm instances serving the prefix are created with
4199
4213
  * it; a per-run value stays impossible — the cap is baked into the
@@ -4201,20 +4215,55 @@ var PrefixImpl = class {
4201
4215
  */
4202
4216
  memoryMb;
4203
4217
  /**
4218
+ * `prepare({ limits })` snapshot: the per-run defaults, overridden field by field.
4219
+ */
4220
+ defaultLimits;
4221
+ /**
4204
4222
  * Session brand key for host-type descriptors — see `SandboxImpl`.
4205
4223
  */
4206
4224
  brandKey;
4207
- _alive = true;
4208
- constructor(id, pool, defaultGlobals, defaultImportHandlers, brandKey, memoryMb) {
4225
+ _status = "ready";
4226
+ /**
4227
+ * The cold-start failure that broke this prefix, cached from the first
4228
+ * result or refusal that reported it; later runs throw it without a round trip.
4229
+ */
4230
+ _error;
4231
+ constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb, defaultLimits = {}) {
4209
4232
  this.id = id;
4210
4233
  this.pool = pool;
4211
- this.defaultGlobals = defaultGlobals;
4234
+ this.declaredGlobals = declaredGlobals;
4212
4235
  this.defaultImportHandlers = defaultImportHandlers;
4236
+ this.declaredImports = declaredImports;
4213
4237
  this.brandKey = brandKey;
4214
4238
  this.memoryMb = memoryMb;
4239
+ this.defaultLimits = defaultLimits;
4215
4240
  }
4216
4241
  get alive() {
4217
- return this._alive;
4242
+ return this._status !== "disposed";
4243
+ }
4244
+ get status() {
4245
+ return this._status;
4246
+ }
4247
+ get error() {
4248
+ return this._error;
4249
+ }
4250
+ /**
4251
+ * Remember the prefix-stage failure that broke this prefix. Disposal wins.
4252
+ * @param error the stored cold-start failure
4253
+ */
4254
+ markBroken(error) {
4255
+ if (this._status !== "ready") return;
4256
+ this._status = "broken";
4257
+ this._error = error;
4258
+ }
4259
+ /**
4260
+ * The `ERR_PREFIX_BROKEN` refusal, with the cold-start failure as `cause`.
4261
+ * @param cause the stored failure, or the one a runtime refusal carried
4262
+ */
4263
+ brokenError(cause = this._error) {
4264
+ const err = setupError("ERR_PREFIX_BROKEN", `prefix '${this.id}' is broken: its cold start failed with ${cause?.code}: ${cause?.message}`);
4265
+ err.cause = cause;
4266
+ return err;
4218
4267
  }
4219
4268
  /**
4220
4269
  * Execute dynamic code against this prefix. See
@@ -4229,7 +4278,7 @@ var PrefixImpl = class {
4229
4278
  * @deprecated Renamed to {@link PrefixImpl.execute}; kept as an alias.
4230
4279
  */
4231
4280
  async run(options) {
4232
- return await this.dispatch(options, { code: options.code });
4281
+ return await this.dispatch(options, async () => ({ code: options.code }));
4233
4282
  }
4234
4283
  /**
4235
4284
  * Call a function exported by this prefix's module — no postfix compiled.
@@ -4237,21 +4286,17 @@ var PrefixImpl = class {
4237
4286
  * @param options
4238
4287
  */
4239
4288
  async call(options) {
4240
- const streams = new StreamSourceRegistry();
4241
- const call = {
4289
+ return await this.dispatch(options, async (streams) => ({ call: {
4242
4290
  exportPath: options.export,
4243
4291
  argsBlob: await serializeHostValue(options.args ?? [], this.brandKey, streams)
4244
- };
4245
- return await this.dispatch(options, {
4246
- call,
4247
- streams
4248
- });
4292
+ } }));
4249
4293
  }
4250
4294
  /**
4251
4295
  * Shared body of {@link run} and {@link call}: disposal/abort guards,
4252
4296
  * bridge-global extraction, import-rebind merging, and the PrefixRun round
4253
- * trip. `payload` carries the postfix source or the call — exactly one, as
4254
- * the wire demands; it also selects how the result blob decodes.
4297
+ * trip. `buildPayload` yields the postfix source or the call — exactly one,
4298
+ * as the wire demands; it also selects how the result blob decodes. It runs
4299
+ * after the checks, so a refused run never registers a stream source.
4255
4300
  * @param options
4256
4301
  * @param options.globals
4257
4302
  * @param options.imports
@@ -4259,60 +4304,34 @@ var PrefixImpl = class {
4259
4304
  * @param options.signal
4260
4305
  * @param options.hardAbortSignal
4261
4306
  * @param options.filename
4262
- * @param payload
4307
+ * @param buildPayload
4263
4308
  */
4264
- async dispatch(options, payload) {
4265
- if (!this._alive) return {
4266
- status: "failed",
4267
- ok: false,
4268
- error: {
4269
- code: "ERR_PREFIX_DISPOSED",
4270
- name: "Error",
4271
- message: `prefix '${this.id}' has been disposed`
4272
- },
4273
- stdout: [],
4274
- stderr: [],
4275
- durationMs: 0,
4276
- wallTimeMs: 0,
4277
- cpuTimeMs: 0,
4278
- bridgeCalls: []
4279
- };
4309
+ async dispatch(options, buildPayload) {
4310
+ if (this._status === "disposed") throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
4311
+ if (this._status === "broken") throw this.brokenError();
4280
4312
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4281
4313
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4314
+ validateLimits(options.limits);
4282
4315
  if (options.limits !== void 0 && "memoryMb" in options.limits) throw new TypeError("[@iso4/sandbox] limits.memoryMb is not a per-run option for prefix runs: the cap is baked into the shared warm isolates at creation — set it per prefix via prepare({ memoryMb }), or the sandbox default via createSandbox({ memoryMb })");
4283
- let defs;
4284
- let dispatch;
4316
+ const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.declaredGlobals);
4285
4317
  let merged;
4286
4318
  try {
4287
- ({defs, dispatch} = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals));
4288
- merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
4319
+ merged = mergeRebindImports(options.imports, this.defaultImportHandlers, this.declaredImports);
4289
4320
  } catch (e) {
4290
- if (e instanceof ImportRebindError || e instanceof GlobalNameError) return {
4291
- status: "failed",
4292
- ok: false,
4293
- error: {
4294
- code: e.code,
4295
- name: "Error",
4296
- message: e.message
4297
- },
4298
- stdout: [],
4299
- stderr: [],
4300
- durationMs: 0,
4301
- wallTimeMs: 0,
4302
- cpuTimeMs: 0,
4303
- bridgeCalls: []
4304
- };
4321
+ if (e instanceof ImportRebindError) throw setupError(e.code, e.message);
4305
4322
  throw e;
4306
4323
  }
4307
- const streams = payload.streams ?? new StreamSourceRegistry();
4324
+ const streams = new StreamSourceRegistry();
4308
4325
  try {
4326
+ const payload = await buildPayload(streams);
4309
4327
  return await this.pool.withClient(async (client, queueWaitMs) => {
4310
4328
  const raw = await client.prefixRun({
4311
4329
  prefixId: this.id,
4312
4330
  code: payload.code,
4313
4331
  filename: options.filename,
4314
4332
  limits: {
4315
- ...options.limits,
4333
+ ...this.defaultLimits,
4334
+ ...wireLimits(options.limits),
4316
4335
  ...heapCapsForWire(this.memoryMb)
4317
4336
  },
4318
4337
  globals: defs,
@@ -4324,7 +4343,17 @@ var PrefixImpl = class {
4324
4343
  call: payload.call,
4325
4344
  streams
4326
4345
  });
4327
- const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds).result : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds).result);
4346
+ const completion = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds) : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds));
4347
+ const decoded = completion.result;
4348
+ if (decoded.status === "failed" && decoded.error.code === "ERR_PREFIX_BROKEN") {
4349
+ if (completion.prefixCause !== void 0) this.markBroken(completion.prefixCause);
4350
+ throw this.brokenError(completion.prefixCause ?? this._error);
4351
+ }
4352
+ if (decoded.status === "failed" && decoded.error.stage === "prefix") this.markBroken(decoded.error);
4353
+ if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
4354
+ ...decoded.error,
4355
+ code: decoded.error.code
4356
+ });
4328
4357
  if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
4329
4358
  if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
4330
4359
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
@@ -4341,8 +4370,11 @@ var PrefixImpl = class {
4341
4370
  }
4342
4371
  }
4343
4372
  async dispose() {
4344
- if (!this._alive) return;
4345
- this._alive = false;
4373
+ if (this._status === "disposed") return;
4374
+ this._status = "disposed";
4375
+ this.declaredGlobals = /* @__PURE__ */ new Map();
4376
+ this.defaultImportHandlers = /* @__PURE__ */ new Map();
4377
+ this.declaredImports = [];
4346
4378
  await this.pool.withClient((client) => client.disposePrefix(this.id));
4347
4379
  }
4348
4380
  async [Symbol.asyncDispose]() {
@@ -4350,4 +4382,4 @@ var PrefixImpl = class {
4350
4382
  }
4351
4383
  };
4352
4384
  //#endregion
4353
- export { RESERVED_WORDS, SANDBOX_GLOBALS, createSandbox };
4385
+ export { createSandbox };