@iso4/sandbox 0.8.0 → 0.8.1
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/README.md +72 -13
- package/dist/index.d.mts +63 -48
- package/dist/index.mjs +622 -726
- package/dist/names-BY-6pKkh.mjs +199 -0
- package/dist/utils.d.mts +45 -0
- package/dist/utils.mjs +2 -0
- package/package.json +9 -5
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.
|
|
1049
|
+
this.writeU32(rebind.path.length);
|
|
1050
|
+
for (const segment of rebind.path) this.writeString(segment);
|
|
1049
1051
|
}
|
|
1050
1052
|
return this;
|
|
1051
1053
|
}
|
|
@@ -1147,6 +1149,14 @@ var PayloadReader = class {
|
|
|
1147
1149
|
this.offset += len;
|
|
1148
1150
|
return slice;
|
|
1149
1151
|
}
|
|
1152
|
+
/**
|
|
1153
|
+
* Advance past `len` bytes with the same bounds check as {@link readRawBytes}.
|
|
1154
|
+
* @param len
|
|
1155
|
+
*/
|
|
1156
|
+
skipBytes(len) {
|
|
1157
|
+
if (this.remaining < len) throw new PayloadDecodeError(`unexpected end of payload: need ${len} bytes, have ${this.remaining}`);
|
|
1158
|
+
this.offset += len;
|
|
1159
|
+
}
|
|
1150
1160
|
readString() {
|
|
1151
1161
|
return Buffer.from(this.readRawBytes(this.readU32())).toString("utf8");
|
|
1152
1162
|
}
|
|
@@ -1157,6 +1167,17 @@ var PayloadReader = class {
|
|
|
1157
1167
|
return items;
|
|
1158
1168
|
}
|
|
1159
1169
|
/**
|
|
1170
|
+
* Read a `String specifier` + `List<String> path` and return exactly those
|
|
1171
|
+
* validated bytes as a latin1 string: the import key, see {@link encodeImportKey}.
|
|
1172
|
+
*/
|
|
1173
|
+
readImportKey() {
|
|
1174
|
+
const start = this.offset;
|
|
1175
|
+
this.skipBytes(this.readU32());
|
|
1176
|
+
const count = this.readU32();
|
|
1177
|
+
for (let i = 0; i < count; i++) this.skipBytes(this.readU32());
|
|
1178
|
+
return Buffer.from(this.view.buffer, this.view.byteOffset + start, this.offset - start).toString("latin1");
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1160
1181
|
* Read a value slot: `u32 byteLength` + V8 serialization blob.
|
|
1161
1182
|
*/
|
|
1162
1183
|
readValueBlob() {
|
|
@@ -1217,6 +1238,29 @@ function encodeTerminatePayload(runId, hard) {
|
|
|
1217
1238
|
return new PayloadWriter().writeU32(runId).writeU8(hard ? 1 : 0).toBuffer();
|
|
1218
1239
|
}
|
|
1219
1240
|
/**
|
|
1241
|
+
* The handler-map key of a host-module function leaf: its specifier and path
|
|
1242
|
+
* in wire encoding (`String` + `List<String>`), as latin1. Unambiguous, and
|
|
1243
|
+
* equal to the bytes a `BridgeCall` carries, so dispatch needs no decoding.
|
|
1244
|
+
* @param specifier
|
|
1245
|
+
* @param path the leaf's key segments
|
|
1246
|
+
*/
|
|
1247
|
+
function encodeImportKey(specifier, path) {
|
|
1248
|
+
const writer = new PayloadWriter().writeString(specifier).writeU32(path.length);
|
|
1249
|
+
for (const segment of path) writer.writeString(segment);
|
|
1250
|
+
return writer.toBuffer().toString("latin1");
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Decode an import key back to its specifier and path, for messages.
|
|
1254
|
+
* @param key a key from {@link encodeImportKey} or a `BridgeCall`
|
|
1255
|
+
*/
|
|
1256
|
+
function decodeImportKey(key) {
|
|
1257
|
+
const reader = new PayloadReader(Buffer.from(key, "latin1"));
|
|
1258
|
+
return {
|
|
1259
|
+
specifier: reader.readString(),
|
|
1260
|
+
path: reader.readStringList()
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1220
1264
|
* Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
|
|
1221
1265
|
* Per `docs/protocol.md` §5.4.
|
|
1222
1266
|
*
|
|
@@ -1256,17 +1300,20 @@ function decodeBridgeCallPayload(buf) {
|
|
|
1256
1300
|
const callId = reader.readU32();
|
|
1257
1301
|
const targetKindRaw = reader.readU8();
|
|
1258
1302
|
if (targetKindRaw !== 0 && targetKindRaw !== 1) throw new Error(`invalid bridge targetKind: ${targetKindRaw}`);
|
|
1259
|
-
|
|
1260
|
-
const
|
|
1261
|
-
|
|
1303
|
+
if (reader.readU8() === 1 !== (targetKindRaw === 1)) throw new PayloadDecodeError("BridgeCall specifier must be present exactly for an import target");
|
|
1304
|
+
const target = targetKindRaw === 0 ? {
|
|
1305
|
+
targetKind: 0,
|
|
1306
|
+
exportName: reader.readString()
|
|
1307
|
+
} : {
|
|
1308
|
+
targetKind: 1,
|
|
1309
|
+
key: reader.readImportKey()
|
|
1310
|
+
};
|
|
1262
1311
|
const decoded = reader.readValueBlob();
|
|
1263
1312
|
if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
|
|
1264
1313
|
return {
|
|
1265
1314
|
runId,
|
|
1266
1315
|
callId,
|
|
1267
|
-
|
|
1268
|
-
specifier,
|
|
1269
|
-
exportName,
|
|
1316
|
+
target,
|
|
1270
1317
|
args: decoded
|
|
1271
1318
|
};
|
|
1272
1319
|
}
|
|
@@ -1883,622 +1930,126 @@ function formatByte(byte) {
|
|
|
1883
1930
|
return `0x${byte.toString(16).padStart(2, "0")}`;
|
|
1884
1931
|
}
|
|
1885
1932
|
//#endregion
|
|
1886
|
-
//#region src/
|
|
1933
|
+
//#region src/client.ts
|
|
1887
1934
|
/**
|
|
1888
|
-
*
|
|
1889
|
-
*
|
|
1890
|
-
*
|
|
1891
|
-
*
|
|
1892
|
-
*
|
|
1935
|
+
* How long TS waits for Rust's `ERR_ABORTED` Result after sending a HARD
|
|
1936
|
+
* `Terminate`, before falling back to tearing the connection down.
|
|
1937
|
+
*
|
|
1938
|
+
* Hard aborts always answer promptly (a suspended run is abandoned on the
|
|
1939
|
+
* spot, executing JS is interrupted mid-turn), so no answer within this
|
|
1940
|
+
* window means the runtime cannot answer at all (wedged process). SOFT
|
|
1941
|
+
* aborts arm no fallback: a run spinning with no `cpuTimeMs` cap
|
|
1942
|
+
* legitimately cannot answer one until its own limits end the turn, and
|
|
1943
|
+
* tearing the connection down for that would fail every co-resident run of
|
|
1944
|
+
* a healthy runtime.
|
|
1893
1945
|
*/
|
|
1894
|
-
const
|
|
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
|
-
]);
|
|
1946
|
+
const TERMINATE_GRACE_MS = 100;
|
|
1972
1947
|
/**
|
|
1973
|
-
*
|
|
1974
|
-
*
|
|
1975
|
-
*
|
|
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.
|
|
1948
|
+
* How long `connect()` waits for the runtime's `Hello` frame before giving up.
|
|
1949
|
+
* The runtime answers a handshake without touching V8 (the probe is computed
|
|
1950
|
+
* once at process start), so this only bites when the binary is wedged.
|
|
1979
1951
|
*/
|
|
1980
|
-
const
|
|
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
|
-
]);
|
|
1952
|
+
const HELLO_TIMEOUT_MS = 5e3;
|
|
2030
1953
|
/**
|
|
2031
|
-
*
|
|
2032
|
-
*
|
|
1954
|
+
* Shared placeholder for `RunEntry` callbacks between wiring phases —
|
|
1955
|
+
* allocating fresh `() => {}` closures per run is avoidable hot-path churn.
|
|
2033
1956
|
*/
|
|
2034
|
-
|
|
1957
|
+
function NOOP() {}
|
|
2035
1958
|
/**
|
|
2036
|
-
*
|
|
2037
|
-
*
|
|
1959
|
+
* Thrown out of `createSandbox()` when the connection handshake fails.
|
|
1960
|
+
*
|
|
1961
|
+
* The common cause is a V8 serialization format-version mismatch between this
|
|
1962
|
+
* Node and the `@iso4/v8-*` binary: values cross the boundary as V8
|
|
1963
|
+
* serialization blobs, so the two V8s must agree on the format. Internal —
|
|
1964
|
+
* `@iso4/sandbox` does not export this type; it reaches callers as a plain
|
|
1965
|
+
* `Error` with `name = 'Iso4HandshakeError'`.
|
|
2038
1966
|
*/
|
|
2039
|
-
var
|
|
2040
|
-
|
|
1967
|
+
var HandshakeError = class extends Error {
|
|
1968
|
+
constructor(message) {
|
|
1969
|
+
super(`[@iso4/sandbox] ${message}`);
|
|
1970
|
+
this.name = "Iso4HandshakeError";
|
|
1971
|
+
}
|
|
2041
1972
|
};
|
|
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
1973
|
/**
|
|
2066
|
-
*
|
|
2067
|
-
*
|
|
2068
|
-
*
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
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
|
|
1974
|
+
* Thrown out of a run when a hard abort did not produce a Result within
|
|
1975
|
+
* {@link TERMINATE_GRACE_MS} (or when the pre-run abort race tears down
|
|
1976
|
+
* before the run settles). The
|
|
1977
|
+
* connection is torn down (so the Rust isolate is reclaimed) before this
|
|
1978
|
+
* propagates, and the client is marked unusable so the pool replaces it rather
|
|
1979
|
+
* than reusing a half-dead slot. `index.ts` catches this and synthesizes the
|
|
1980
|
+
* `ERR_ABORTED` `RunResult`. When the graceful path succeeds instead, no error
|
|
1981
|
+
* is thrown — the real `ERR_ABORTED` Result flows back through the router.
|
|
2083
1982
|
*/
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
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
|
-
}
|
|
1983
|
+
var RunAbortedError = class extends Error {
|
|
1984
|
+
/**
|
|
1985
|
+
* The value passed to `AbortController.abort(reason)`, if any.
|
|
1986
|
+
*/
|
|
1987
|
+
reason;
|
|
1988
|
+
constructor(reason, message = "run was aborted") {
|
|
1989
|
+
super(message);
|
|
1990
|
+
this.name = "RunAbortedError";
|
|
1991
|
+
this.reason = reason;
|
|
2132
1992
|
}
|
|
2133
|
-
|
|
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
|
-
*/
|
|
1993
|
+
};
|
|
2151
1994
|
/**
|
|
2152
|
-
*
|
|
1995
|
+
* Thrown when a frame arrives that cannot belong to any run in flight on this
|
|
1996
|
+
* connection: a `Result` or `RunComplete` carrying a run id nothing here is
|
|
1997
|
+
* waiting on, or a frame type with no place in the protocol. Either way the
|
|
1998
|
+
* two sides have lost agreement about what this connection is doing, so
|
|
1999
|
+
* nothing it delivers from now on can be attributed with confidence.
|
|
2153
2000
|
*
|
|
2154
|
-
*
|
|
2155
|
-
*
|
|
2156
|
-
*
|
|
2157
|
-
* `
|
|
2158
|
-
*
|
|
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
|
|
2001
|
+
* The connection is torn down before this propagates — every run in flight on
|
|
2002
|
+
* it fails with this error — because a peer that is mid-run on someone else's
|
|
2003
|
+
* frames must never be handed to the next caller. `index.ts` catches this and
|
|
2004
|
+
* synthesizes the `ERR_PROTOCOL_DESYNC` `RunResult` — a displaced run never
|
|
2005
|
+
* executed, so there is no partial telemetry to report.
|
|
2163
2006
|
*/
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
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
|
-
}
|
|
2007
|
+
var ProtocolDesyncError = class extends Error {
|
|
2008
|
+
constructor(message) {
|
|
2009
|
+
super(`[@iso4/sandbox] ${message}`);
|
|
2010
|
+
this.name = "Iso4ProtocolDesyncError";
|
|
2198
2011
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2012
|
+
};
|
|
2013
|
+
var RuntimeIpcClient = class RuntimeIpcClient {
|
|
2014
|
+
socket;
|
|
2015
|
+
reader;
|
|
2016
|
+
disposed = false;
|
|
2017
|
+
/**
|
|
2018
|
+
* Set when this connection was torn down (abort fallback, desync, peer
|
|
2019
|
+
* close). A broken client must not be returned to the pool's idle list —
|
|
2020
|
+
* the connection registry checks `usable` and drops it instead.
|
|
2021
|
+
*/
|
|
2022
|
+
broken = false;
|
|
2023
|
+
/**
|
|
2024
|
+
* Runs in flight on this connection, keyed by run id — the router's only
|
|
2025
|
+
* routing table. Several runs share one connection; every frame finds its
|
|
2026
|
+
* owner by run id alone.
|
|
2027
|
+
*/
|
|
2028
|
+
runs = /* @__PURE__ */ new Map();
|
|
2029
|
+
/**
|
|
2030
|
+
* How many of {@link runs} are in their `waitUntil` grace phase. A counter
|
|
2031
|
+
* rather than a scan so {@link load} stays O(1).
|
|
2032
|
+
*/
|
|
2033
|
+
graceRuns = 0;
|
|
2034
|
+
/**
|
|
2035
|
+
* What the pool's per-connection cap bounds: foreground runs plus in-flight
|
|
2036
|
+
* control requests. Grace-phase runs are deliberately excluded — counting
|
|
2037
|
+
* an epilogue for its whole grace wall opens fresh connections (2 runtime
|
|
2038
|
+
* threads each) for traffic that rides an existing one, and their frames
|
|
2039
|
+
* are mux-routed by run id anyway. The counts move synchronously from the
|
|
2040
|
+
* call that adds them (`runRawCode`/`prefixRun`/`precompile`), which keeps
|
|
2041
|
+
* the pool's same-tick load observation exact.
|
|
2042
|
+
*/
|
|
2043
|
+
get load() {
|
|
2044
|
+
return this.runs.size - this.graceRuns + this.precompileWaiters.size + this.controlWaiters.length;
|
|
2210
2045
|
}
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
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.
|
|
2232
|
-
*/
|
|
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";
|
|
2460
|
-
}
|
|
2461
|
-
};
|
|
2462
|
-
var RuntimeIpcClient = class RuntimeIpcClient {
|
|
2463
|
-
socket;
|
|
2464
|
-
reader;
|
|
2465
|
-
disposed = false;
|
|
2466
|
-
/**
|
|
2467
|
-
* Set when this connection was torn down (abort fallback, desync, peer
|
|
2468
|
-
* close). A broken client must not be returned to the pool's idle list —
|
|
2469
|
-
* the connection registry checks `usable` and drops it instead.
|
|
2470
|
-
*/
|
|
2471
|
-
broken = false;
|
|
2472
|
-
/**
|
|
2473
|
-
* Runs in flight on this connection, keyed by run id — the router's only
|
|
2474
|
-
* routing table. Several runs share one connection; every frame finds its
|
|
2475
|
-
* owner by run id alone.
|
|
2476
|
-
*/
|
|
2477
|
-
runs = /* @__PURE__ */ new Map();
|
|
2478
|
-
/**
|
|
2479
|
-
* How many of {@link runs} are in their `waitUntil` grace phase. A counter
|
|
2480
|
-
* rather than a scan so {@link load} stays O(1).
|
|
2481
|
-
*/
|
|
2482
|
-
graceRuns = 0;
|
|
2483
|
-
/**
|
|
2484
|
-
* What the pool's per-connection cap bounds: foreground runs plus in-flight
|
|
2485
|
-
* control requests. Grace-phase runs are deliberately excluded — counting
|
|
2486
|
-
* an epilogue for its whole grace wall opens fresh connections (2 runtime
|
|
2487
|
-
* threads each) for traffic that rides an existing one, and their frames
|
|
2488
|
-
* are mux-routed by run id anyway. The counts move synchronously from the
|
|
2489
|
-
* call that adds them (`runRawCode`/`prefixRun`/`precompile`), which keeps
|
|
2490
|
-
* the pool's same-tick load observation exact.
|
|
2491
|
-
*/
|
|
2492
|
-
get load() {
|
|
2493
|
-
return this.runs.size - this.graceRuns + this.precompileWaiters.size + this.controlWaiters.length;
|
|
2494
|
-
}
|
|
2495
|
-
/**
|
|
2496
|
-
* Nothing is routed here at all — grace phases included — and nothing is
|
|
2497
|
-
* left in the socket's write buffer. The pool reaps only quiescent
|
|
2498
|
-
* connections, so closing one never drops a frame already written.
|
|
2499
|
-
*/
|
|
2500
|
-
get quiescent() {
|
|
2501
|
-
return this.load === 0 && this.graceRuns === 0 && this.socket.writableLength === 0;
|
|
2046
|
+
/**
|
|
2047
|
+
* Nothing is routed here at all — grace phases included — and nothing is
|
|
2048
|
+
* left in the socket's write buffer. The pool reaps only quiescent
|
|
2049
|
+
* connections, so closing one never drops a frame already written.
|
|
2050
|
+
*/
|
|
2051
|
+
get quiescent() {
|
|
2052
|
+
return this.load === 0 && this.graceRuns === 0 && this.socket.writableLength === 0;
|
|
2502
2053
|
}
|
|
2503
2054
|
/**
|
|
2504
2055
|
* Pending `stats()` requests, FIFO — sound because the runtime answers
|
|
@@ -3165,12 +2716,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
3165
2716
|
})));
|
|
3166
2717
|
else {
|
|
3167
2718
|
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) => {
|
|
2719
|
+
dispatcher(call.target, call.args).then(async (value) => {
|
|
3174
2720
|
let encoded;
|
|
3175
2721
|
try {
|
|
3176
2722
|
encoded = await serializeHostValue(value, this.brandKey, streams);
|
|
@@ -3217,14 +2763,17 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
3217
2763
|
*/
|
|
3218
2764
|
function makeDispatcher(globals, imports) {
|
|
3219
2765
|
if (Object.keys(globals).length === 0 && (imports === void 0 || imports.size === 0)) return void 0;
|
|
3220
|
-
return async (
|
|
3221
|
-
if (targetKind === 1) {
|
|
3222
|
-
const handler = imports?.get(
|
|
3223
|
-
if (handler === void 0)
|
|
2766
|
+
return async (target, args) => {
|
|
2767
|
+
if (target.targetKind === 1) {
|
|
2768
|
+
const handler = imports?.get(target.key);
|
|
2769
|
+
if (handler === void 0) {
|
|
2770
|
+
const { specifier, path } = decodeImportKey(target.key);
|
|
2771
|
+
throw new Error(`no handler configured for host import '${specifier}'.${path.join(".")}`);
|
|
2772
|
+
}
|
|
3224
2773
|
return handler(...args);
|
|
3225
2774
|
}
|
|
3226
|
-
const handler = globals[exportName];
|
|
3227
|
-
if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
|
|
2775
|
+
const handler = globals[target.exportName];
|
|
2776
|
+
if (handler === void 0) throw new Error(`no handler configured for bridge global '${target.exportName}'`);
|
|
3228
2777
|
return handler(...args);
|
|
3229
2778
|
};
|
|
3230
2779
|
}
|
|
@@ -3589,6 +3138,345 @@ var RunPool = class {
|
|
|
3589
3138
|
}
|
|
3590
3139
|
};
|
|
3591
3140
|
//#endregion
|
|
3141
|
+
//#region src/globals.ts
|
|
3142
|
+
/**
|
|
3143
|
+
* The error every setup refusal is thrown as, whichever side detects it: a
|
|
3144
|
+
* plain `Error` carrying the runtime's code.
|
|
3145
|
+
* @param code the setup code
|
|
3146
|
+
* @param message the runtime's message for it
|
|
3147
|
+
*/
|
|
3148
|
+
function setupError(code, message) {
|
|
3149
|
+
const err = new Error(message);
|
|
3150
|
+
err.name = "Error";
|
|
3151
|
+
err.code = code;
|
|
3152
|
+
return err;
|
|
3153
|
+
}
|
|
3154
|
+
function isBridgeWithShim(v) {
|
|
3155
|
+
return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
|
|
3156
|
+
}
|
|
3157
|
+
function isDataGlobal(v) {
|
|
3158
|
+
return typeof v === "object" && v !== null && v.kind === "data";
|
|
3159
|
+
}
|
|
3160
|
+
function isBridgeGlobal(v) {
|
|
3161
|
+
return typeof v === "object" && v !== null && v.kind === "bridge";
|
|
3162
|
+
}
|
|
3163
|
+
function isStringGlobal(v) {
|
|
3164
|
+
return typeof v === "object" && v !== null && v.kind === "string";
|
|
3165
|
+
}
|
|
3166
|
+
/**
|
|
3167
|
+
* Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
|
|
3168
|
+
* dispatch key and an object-property key — never interpolated into generated
|
|
3169
|
+
* code — so any global name is safe. The runtime recognises the
|
|
3170
|
+
* `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
|
|
3171
|
+
* bridge records under the public `<name>`.
|
|
3172
|
+
* @param name public global name
|
|
3173
|
+
*/
|
|
3174
|
+
function shimHandlerName(name) {
|
|
3175
|
+
return `__iso4_${name}_h`;
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
|
|
3179
|
+
* map. See the module comment for the split. Throws a `TypeError` for a name
|
|
3180
|
+
* that is not a well-formed string and `ERR_RESERVED_NAME` for a runtime-owned
|
|
3181
|
+
* one.
|
|
3182
|
+
* - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
|
|
3183
|
+
* - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
|
|
3184
|
+
* - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
|
|
3185
|
+
* - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
|
|
3186
|
+
* entry for the private handler under `handlerName`.
|
|
3187
|
+
* @param globals
|
|
3188
|
+
*/
|
|
3189
|
+
function processGlobals(globals) {
|
|
3190
|
+
const defs = [];
|
|
3191
|
+
const dispatch = {};
|
|
3192
|
+
for (const [name, value] of Object.entries(globals)) {
|
|
3193
|
+
if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
|
|
3194
|
+
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`);
|
|
3195
|
+
if (typeof value === "function") {
|
|
3196
|
+
defs.push({
|
|
3197
|
+
kind: "bridge",
|
|
3198
|
+
name,
|
|
3199
|
+
enumerable: true
|
|
3200
|
+
});
|
|
3201
|
+
dispatch[name] = value;
|
|
3202
|
+
} else if (typeof value === "string") defs.push({
|
|
3203
|
+
kind: "string",
|
|
3204
|
+
name,
|
|
3205
|
+
expr: value,
|
|
3206
|
+
enumerable: true
|
|
3207
|
+
});
|
|
3208
|
+
else if (isBridgeGlobal(value)) {
|
|
3209
|
+
defs.push({
|
|
3210
|
+
kind: "bridge",
|
|
3211
|
+
name,
|
|
3212
|
+
enumerable: value.enumerable ?? true
|
|
3213
|
+
});
|
|
3214
|
+
dispatch[name] = value.handler;
|
|
3215
|
+
} else if (isStringGlobal(value)) defs.push({
|
|
3216
|
+
kind: "string",
|
|
3217
|
+
name,
|
|
3218
|
+
expr: value.expr,
|
|
3219
|
+
enumerable: value.enumerable ?? true
|
|
3220
|
+
});
|
|
3221
|
+
else if (isDataGlobal(value)) defs.push({
|
|
3222
|
+
kind: "data",
|
|
3223
|
+
name,
|
|
3224
|
+
value: value.value,
|
|
3225
|
+
enumerable: value.enumerable ?? true
|
|
3226
|
+
});
|
|
3227
|
+
else if (isBridgeWithShim(value)) {
|
|
3228
|
+
const handlerName = shimHandlerName(name);
|
|
3229
|
+
defs.push({
|
|
3230
|
+
kind: "shim",
|
|
3231
|
+
name,
|
|
3232
|
+
shim: value.shim,
|
|
3233
|
+
handlerName,
|
|
3234
|
+
enumerable: value.enumerable ?? true
|
|
3235
|
+
});
|
|
3236
|
+
dispatch[handlerName] = value.handler;
|
|
3237
|
+
}
|
|
3238
|
+
}
|
|
3239
|
+
return {
|
|
3240
|
+
defs,
|
|
3241
|
+
dispatch
|
|
3242
|
+
};
|
|
3243
|
+
}
|
|
3244
|
+
/**
|
|
3245
|
+
* Copy the declared global shape at `prepare()`, so later changes to the
|
|
3246
|
+
* caller's object change nothing. Kinds `processGlobals` ignores are left out.
|
|
3247
|
+
* @param globals the `globals` passed to `prepare()`
|
|
3248
|
+
*/
|
|
3249
|
+
function declareGlobals(globals) {
|
|
3250
|
+
const declared = /* @__PURE__ */ new Map();
|
|
3251
|
+
for (const [name, value] of Object.entries(globals)) if (typeof value === "function") declared.set(name, {
|
|
3252
|
+
kind: "bridge",
|
|
3253
|
+
handler: value,
|
|
3254
|
+
enumerable: true
|
|
3255
|
+
});
|
|
3256
|
+
else if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) declared.set(name, { kind: "value" });
|
|
3257
|
+
else if (isBridgeWithShim(value)) declared.set(name, {
|
|
3258
|
+
kind: "shim",
|
|
3259
|
+
handler: value.handler
|
|
3260
|
+
});
|
|
3261
|
+
else if (isBridgeGlobal(value)) declared.set(name, {
|
|
3262
|
+
kind: "bridge",
|
|
3263
|
+
handler: value.handler,
|
|
3264
|
+
enumerable: value.enumerable ?? true
|
|
3265
|
+
});
|
|
3266
|
+
return declared;
|
|
3267
|
+
}
|
|
3268
|
+
/**
|
|
3269
|
+
* Resolve bridge globals for a `prefix.run()` call.
|
|
3270
|
+
*
|
|
3271
|
+
* Value globals and shim wrappers are replayed from the declared prefix
|
|
3272
|
+
* state, so every returned def is `kind: 'bridge'`; a shim override is routed
|
|
3273
|
+
* to its private `__iso4_<name>_h` key. Throws the setup error the runtime
|
|
3274
|
+
* would send for an undeclared or frozen name, and `ERR_INVALID_REBIND` for a
|
|
3275
|
+
* non-function override.
|
|
3276
|
+
* @param runGlobals the run's `globals` option
|
|
3277
|
+
* @param declared the shape kept from `prepare()` by {@link declareGlobals}
|
|
3278
|
+
*/
|
|
3279
|
+
function extractBridgeGlobals(runGlobals, declared) {
|
|
3280
|
+
const overrides = runGlobals;
|
|
3281
|
+
for (const [name, override] of Object.entries(overrides)) {
|
|
3282
|
+
if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
|
|
3283
|
+
const shape = declared.get(name);
|
|
3284
|
+
if (shape === void 0) throw setupError("ERR_UNDECLARED_BINDING", `global '${name}' was not declared at precompile time`);
|
|
3285
|
+
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`);
|
|
3286
|
+
if (typeof override !== "function") throw setupError("ERR_INVALID_REBIND", `global '${name}' can only be rebound with a function; got ${override === null ? "null" : typeof override}`);
|
|
3287
|
+
}
|
|
3288
|
+
const defs = [];
|
|
3289
|
+
const dispatch = {};
|
|
3290
|
+
for (const [name, shape] of declared) {
|
|
3291
|
+
if (shape.kind === "value") continue;
|
|
3292
|
+
const override = Object.hasOwn(overrides, name) ? overrides[name] : void 0;
|
|
3293
|
+
const stub = shape.kind === "shim" ? shimHandlerName(name) : name;
|
|
3294
|
+
defs.push({
|
|
3295
|
+
kind: "bridge",
|
|
3296
|
+
name: stub,
|
|
3297
|
+
enumerable: shape.kind === "shim" || shape.enumerable
|
|
3298
|
+
});
|
|
3299
|
+
dispatch[stub] = override ?? shape.handler;
|
|
3300
|
+
}
|
|
3301
|
+
return {
|
|
3302
|
+
defs,
|
|
3303
|
+
dispatch
|
|
3304
|
+
};
|
|
3305
|
+
}
|
|
3306
|
+
/**
|
|
3307
|
+
* The dispatch-map key for one host-module function leaf: the wire bytes of
|
|
3308
|
+
* its specifier and key segments, so `{ 'a.b': f }` and `{ a: { b: f } }` differ.
|
|
3309
|
+
* @param specifier
|
|
3310
|
+
* @param path the leaf's key segments
|
|
3311
|
+
*/
|
|
3312
|
+
const importHandlerKey = encodeImportKey;
|
|
3313
|
+
/**
|
|
3314
|
+
* Thrown for an import rebind the prefix does not allow. `PrefixImpl.run`
|
|
3315
|
+
* rethrows it as the same coded `Error` the runtime's refusals become.
|
|
3316
|
+
*/
|
|
3317
|
+
var ImportRebindError = class extends Error {
|
|
3318
|
+
code;
|
|
3319
|
+
constructor(code, message) {
|
|
3320
|
+
super(message);
|
|
3321
|
+
this.name = "ImportRebindError";
|
|
3322
|
+
this.code = code;
|
|
3323
|
+
}
|
|
3324
|
+
};
|
|
3325
|
+
function processImports(imports) {
|
|
3326
|
+
if (imports === void 0) return {
|
|
3327
|
+
bindings: [],
|
|
3328
|
+
handlers: /* @__PURE__ */ new Map()
|
|
3329
|
+
};
|
|
3330
|
+
const bindings = [];
|
|
3331
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
3332
|
+
for (const [specifier, value] of Object.entries(imports)) {
|
|
3333
|
+
if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
|
|
3334
|
+
if (typeof value === "string") {
|
|
3335
|
+
bindings.push({
|
|
3336
|
+
specifier,
|
|
3337
|
+
source: value
|
|
3338
|
+
});
|
|
3339
|
+
continue;
|
|
3340
|
+
}
|
|
3341
|
+
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)}`);
|
|
3342
|
+
const module = [];
|
|
3343
|
+
for (const [name, child] of Object.entries(value)) {
|
|
3344
|
+
if (child === void 0) continue;
|
|
3345
|
+
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`);
|
|
3346
|
+
module.push([name, lowerNode(specifier, child, [name], handlers)]);
|
|
3347
|
+
}
|
|
3348
|
+
bindings.push({
|
|
3349
|
+
specifier,
|
|
3350
|
+
module
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
return {
|
|
3354
|
+
bindings,
|
|
3355
|
+
handlers
|
|
3356
|
+
};
|
|
3357
|
+
}
|
|
3358
|
+
/**
|
|
3359
|
+
* Lower one host-module node to its wire shape, registering function leaves.
|
|
3360
|
+
* @param specifier
|
|
3361
|
+
* @param value
|
|
3362
|
+
* @param path
|
|
3363
|
+
* @param handlers
|
|
3364
|
+
* @param seen
|
|
3365
|
+
*/
|
|
3366
|
+
function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
|
|
3367
|
+
if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
|
|
3368
|
+
if (typeof value === "function") {
|
|
3369
|
+
handlers.set(importHandlerKey(specifier, path), value);
|
|
3370
|
+
return { kind: "function" };
|
|
3371
|
+
}
|
|
3372
|
+
if (isPlainObject(value)) {
|
|
3373
|
+
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
|
|
3374
|
+
seen.add(value);
|
|
3375
|
+
const entries = [];
|
|
3376
|
+
for (const [key, child] of Object.entries(value)) {
|
|
3377
|
+
if (child === void 0) continue;
|
|
3378
|
+
if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
|
|
3379
|
+
entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
|
|
3380
|
+
}
|
|
3381
|
+
seen.delete(value);
|
|
3382
|
+
return {
|
|
3383
|
+
kind: "object",
|
|
3384
|
+
entries
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
return {
|
|
3388
|
+
kind: "data",
|
|
3389
|
+
value
|
|
3390
|
+
};
|
|
3391
|
+
}
|
|
3392
|
+
/**
|
|
3393
|
+
* The declared import shape without data-leaf values or source text, kept by a
|
|
3394
|
+
* prefix for {@link mergeRebindImports} so it does not pin large data.
|
|
3395
|
+
* @param bindings the bindings sent at `prepare()`
|
|
3396
|
+
*/
|
|
3397
|
+
function declaredImportShape(bindings) {
|
|
3398
|
+
const strip = (entries) => entries.map(([key, node]) => [key, node.kind === "object" ? {
|
|
3399
|
+
kind: "object",
|
|
3400
|
+
entries: strip(node.entries)
|
|
3401
|
+
} : node.kind === "data" ? {
|
|
3402
|
+
kind: "data",
|
|
3403
|
+
value: void 0
|
|
3404
|
+
} : node]);
|
|
3405
|
+
return bindings.map((b) => "source" in b ? {
|
|
3406
|
+
specifier: b.specifier,
|
|
3407
|
+
source: ""
|
|
3408
|
+
} : {
|
|
3409
|
+
specifier: b.specifier,
|
|
3410
|
+
module: strip(b.module)
|
|
3411
|
+
});
|
|
3412
|
+
}
|
|
3413
|
+
/**
|
|
3414
|
+
* Merge the handlers behind a `Prefix`'s host-module function leaves with the
|
|
3415
|
+
* run's overrides and collect the rebind locations to send on the wire.
|
|
3416
|
+
*
|
|
3417
|
+
* Every location is looked up in the declared shape before its value is
|
|
3418
|
+
* looked at, with the same codes and messages as `validate_import_rebinds` in
|
|
3419
|
+
* the runtime, which repeats the check: undeclared is `ERR_UNDECLARED_BINDING`,
|
|
3420
|
+
* a source module or data leaf `ERR_FROZEN_BINDING`. A declared location
|
|
3421
|
+
* given the wrong kind of value is `ERR_INVALID_REBIND`.
|
|
3422
|
+
*
|
|
3423
|
+
* @param runImports the run's `imports` option
|
|
3424
|
+
* @param defaults handler map captured at precompile time
|
|
3425
|
+
* @param declared the import shape declared at `prepare()`
|
|
3426
|
+
*/
|
|
3427
|
+
function mergeRebindImports(runImports, defaults, declared) {
|
|
3428
|
+
if (runImports === void 0) return {
|
|
3429
|
+
rebinds: [],
|
|
3430
|
+
handlers: defaults
|
|
3431
|
+
};
|
|
3432
|
+
const handlers = new Map(defaults);
|
|
3433
|
+
const rebinds = [];
|
|
3434
|
+
for (const [specifier, value] of Object.entries(runImports)) {
|
|
3435
|
+
if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
|
|
3436
|
+
const binding = declared.find((b) => b.specifier === specifier);
|
|
3437
|
+
if (binding === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}' was not declared at precompile time`);
|
|
3438
|
+
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`);
|
|
3439
|
+
if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}' can only be rebound with a plain object; got ${describeKind(value)}`);
|
|
3440
|
+
walkRebind(specifier, value, binding.module, [], handlers, rebinds);
|
|
3441
|
+
}
|
|
3442
|
+
return {
|
|
3443
|
+
rebinds,
|
|
3444
|
+
handlers
|
|
3445
|
+
};
|
|
3446
|
+
}
|
|
3447
|
+
function walkRebind(specifier, node, declared, path, handlers, rebinds) {
|
|
3448
|
+
for (const [key, value] of Object.entries(node)) {
|
|
3449
|
+
if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
|
|
3450
|
+
const segments = [...path, key];
|
|
3451
|
+
const joined = segments.join(".");
|
|
3452
|
+
const shape = declared.find(([name]) => name === key)?.[1];
|
|
3453
|
+
if (shape === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}'.${joined} was not declared at precompile time`);
|
|
3454
|
+
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`);
|
|
3455
|
+
if (shape.kind === "object") {
|
|
3456
|
+
if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a plain object; got ${describeKind(value)}`);
|
|
3457
|
+
walkRebind(specifier, value, shape.entries, segments, handlers, rebinds);
|
|
3458
|
+
continue;
|
|
3459
|
+
}
|
|
3460
|
+
if (typeof value !== "function") throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
|
|
3461
|
+
handlers.set(importHandlerKey(specifier, segments), value);
|
|
3462
|
+
rebinds.push({
|
|
3463
|
+
specifier,
|
|
3464
|
+
path: segments
|
|
3465
|
+
});
|
|
3466
|
+
}
|
|
3467
|
+
}
|
|
3468
|
+
function isPlainObject(value) {
|
|
3469
|
+
if (value === null || typeof value !== "object") return false;
|
|
3470
|
+
if (Array.isArray(value)) return false;
|
|
3471
|
+
const proto = Object.getPrototypeOf(value);
|
|
3472
|
+
return proto === null || proto === Object.prototype;
|
|
3473
|
+
}
|
|
3474
|
+
function describeKind(value) {
|
|
3475
|
+
if (value === null) return "null";
|
|
3476
|
+
if (Array.isArray(value)) return "array";
|
|
3477
|
+
return typeof value;
|
|
3478
|
+
}
|
|
3479
|
+
//#endregion
|
|
3592
3480
|
//#region src/index.ts
|
|
3593
3481
|
/**
|
|
3594
3482
|
* \@iso4/sandbox - public entry point.
|
|
@@ -3822,6 +3710,43 @@ function waitUntilResultFrom(report) {
|
|
|
3822
3710
|
return out;
|
|
3823
3711
|
}
|
|
3824
3712
|
/**
|
|
3713
|
+
* The `ResourceLimits` fields the wire carries as a `u32`; `0` disables each.
|
|
3714
|
+
*/
|
|
3715
|
+
const U32_LIMIT_FIELDS = [
|
|
3716
|
+
"cpuTimeMs",
|
|
3717
|
+
"wallTimeMs",
|
|
3718
|
+
"maxBridgeCallBytes",
|
|
3719
|
+
"maxExportBytes",
|
|
3720
|
+
"maxStdoutBytes",
|
|
3721
|
+
"maxStderrBytes",
|
|
3722
|
+
"maxBridgeCalls",
|
|
3723
|
+
"graceMs"
|
|
3724
|
+
];
|
|
3725
|
+
const U32_MAX = 4294967295;
|
|
3726
|
+
/**
|
|
3727
|
+
* Refuse a limit the wire cannot carry as a `u32` instead of letting the
|
|
3728
|
+
* encoder throw a `RangeError` or silently truncate a fraction.
|
|
3729
|
+
* @param limits the caller's `limits` option
|
|
3730
|
+
*/
|
|
3731
|
+
function validateLimits(limits) {
|
|
3732
|
+
if (limits === void 0) return;
|
|
3733
|
+
if (limits === null || typeof limits !== "object") throw new TypeError("[@iso4/sandbox] limits must be an object");
|
|
3734
|
+
for (const field of U32_LIMIT_FIELDS) {
|
|
3735
|
+
const value = limits[field];
|
|
3736
|
+
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}`);
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
/**
|
|
3740
|
+
* Only the public `u32` fields; heap caps come from `heapCapsForWire`, so an
|
|
3741
|
+
* untyped caller cannot smuggle `memoryMb`/`hardMemoryMb` onto the wire.
|
|
3742
|
+
* @param limits the validated `limits` option
|
|
3743
|
+
*/
|
|
3744
|
+
function wireLimits(limits) {
|
|
3745
|
+
const out = {};
|
|
3746
|
+
for (const field of U32_LIMIT_FIELDS) if (limits?.[field] !== void 0) out[field] = limits[field];
|
|
3747
|
+
return out;
|
|
3748
|
+
}
|
|
3749
|
+
/**
|
|
3825
3750
|
* A heap cap must be an integer number of megabytes ≥ 0 (0 = uncapped):
|
|
3826
3751
|
* the wire carries it as a u32, and a fractional or negative value would
|
|
3827
3752
|
* silently misencode instead of capping.
|
|
@@ -3831,11 +3756,11 @@ function waitUntilResultFrom(report) {
|
|
|
3831
3756
|
function validateMemoryMb(value, where) {
|
|
3832
3757
|
if (value === void 0) return;
|
|
3833
3758
|
if (typeof value === "number") {
|
|
3834
|
-
if (!Number.isInteger(value) || value < 0) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer
|
|
3759
|
+
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
3760
|
return;
|
|
3836
3761
|
}
|
|
3837
3762
|
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
|
|
3763
|
+
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
3764
|
if (value.soft === void 0) return;
|
|
3840
3765
|
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
3766
|
if (value.soft >= value.hard) throw new TypeError(`[@iso4/sandbox] ${where}.soft (${value.soft}) must be below ${where}.hard (${value.hard})`);
|
|
@@ -3927,6 +3852,30 @@ function desyncResult(error) {
|
|
|
3927
3852
|
bridgeCalls: []
|
|
3928
3853
|
};
|
|
3929
3854
|
}
|
|
3855
|
+
/**
|
|
3856
|
+
* Codes the runtime reports for a run whose options are invalid. The client
|
|
3857
|
+
* checks first; this catches what it cannot know, such as a prefix the
|
|
3858
|
+
* runtime dropped. Runs throw these, like `prepare()`, instead of returning them.
|
|
3859
|
+
*/
|
|
3860
|
+
const SETUP_ERROR_CODES = new Set([
|
|
3861
|
+
"ERR_RESERVED_NAME",
|
|
3862
|
+
"ERR_UNDECLARED_BINDING",
|
|
3863
|
+
"ERR_FROZEN_BINDING",
|
|
3864
|
+
"ERR_INVALID_REBIND",
|
|
3865
|
+
"ERR_PREFIX_DISPOSED"
|
|
3866
|
+
]);
|
|
3867
|
+
/**
|
|
3868
|
+
* The error `prepare()`, `readExports()` and `run()` throw for a failure the
|
|
3869
|
+
* runtime reported: an `Error` carrying the runtime's `code`, `name`, `stack`.
|
|
3870
|
+
* @param error the reported failure
|
|
3871
|
+
*/
|
|
3872
|
+
function thrownRunError(error) {
|
|
3873
|
+
const err = new Error(error.message);
|
|
3874
|
+
err.name = error.name;
|
|
3875
|
+
err.code = error.code;
|
|
3876
|
+
if (error.stack) err.stack = error.stack;
|
|
3877
|
+
return err;
|
|
3878
|
+
}
|
|
3930
3879
|
function abortedResult(reason, from) {
|
|
3931
3880
|
return {
|
|
3932
3881
|
status: "aborted",
|
|
@@ -4001,44 +3950,24 @@ var SandboxImpl = class {
|
|
|
4001
3950
|
async run(options) {
|
|
4002
3951
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
4003
3952
|
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
|
|
3953
|
+
validateLimits(options.limits);
|
|
4004
3954
|
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
3955
|
validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
|
|
4006
3956
|
const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
|
|
4007
|
-
|
|
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;
|
|
3957
|
+
const { defs, dispatch } = processGlobals(options.globals ?? {});
|
|
4029
3958
|
await materializeHostTypesInGlobals(defs, this.brandKey);
|
|
4030
3959
|
const { bindings, handlers } = processImports(options.imports);
|
|
4031
3960
|
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
3961
|
try {
|
|
3962
|
+
const call = options.call === void 0 ? void 0 : {
|
|
3963
|
+
exportPath: options.call.export,
|
|
3964
|
+
argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
|
|
3965
|
+
};
|
|
4037
3966
|
return await this.pool.withClient(async (client, queueWaitMs) => {
|
|
4038
3967
|
const raw = await client.runRawCode(options.code, {
|
|
4039
3968
|
filename: options.filename,
|
|
4040
3969
|
limits: {
|
|
4041
|
-
...options.limits,
|
|
3970
|
+
...wireLimits(options.limits),
|
|
4042
3971
|
...heapCapsForWire(runMemoryMb)
|
|
4043
3972
|
},
|
|
4044
3973
|
globals: defs,
|
|
@@ -4051,6 +3980,10 @@ var SandboxImpl = class {
|
|
|
4051
3980
|
streams
|
|
4052
3981
|
});
|
|
4053
3982
|
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);
|
|
3983
|
+
if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
|
|
3984
|
+
...decoded.error,
|
|
3985
|
+
code: decoded.error.code
|
|
3986
|
+
});
|
|
4054
3987
|
if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
|
|
4055
3988
|
if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
|
|
4056
3989
|
if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
|
|
@@ -4103,13 +4036,7 @@ var SandboxImpl = class {
|
|
|
4103
4036
|
filename: options.filename,
|
|
4104
4037
|
limits: options.limits
|
|
4105
4038
|
});
|
|
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
|
-
}
|
|
4039
|
+
if (result.status !== "completed") throw thrownRunError(result.error);
|
|
4113
4040
|
return {
|
|
4114
4041
|
exports: result.exports,
|
|
4115
4042
|
skippedExports: result.skippedExports
|
|
@@ -4129,9 +4056,11 @@ var SandboxImpl = class {
|
|
|
4129
4056
|
*/
|
|
4130
4057
|
async prepare(options) {
|
|
4131
4058
|
validateMemoryMb(options.memoryMb, "memoryMb");
|
|
4059
|
+
validateLimits(options.limits);
|
|
4132
4060
|
const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
|
|
4133
4061
|
const rawGlobals = options.globals ?? {};
|
|
4134
4062
|
const { defs } = processGlobals(rawGlobals);
|
|
4063
|
+
const declaredGlobals = declareGlobals(rawGlobals);
|
|
4135
4064
|
return this.pool.withClient(async (client) => {
|
|
4136
4065
|
await materializeHostTypesInGlobals(defs, this.brandKey);
|
|
4137
4066
|
const { bindings, handlers } = processImports(options.imports);
|
|
@@ -4139,20 +4068,14 @@ var SandboxImpl = class {
|
|
|
4139
4068
|
code: options.code,
|
|
4140
4069
|
filename: options.filename,
|
|
4141
4070
|
limits: {
|
|
4142
|
-
...options.limits,
|
|
4071
|
+
...wireLimits(options.limits),
|
|
4143
4072
|
...heapCapsForWire(prefixMemoryMb)
|
|
4144
4073
|
},
|
|
4145
4074
|
globals: defs,
|
|
4146
4075
|
imports: bindings
|
|
4147
4076
|
}));
|
|
4148
|
-
if (!result.ok)
|
|
4149
|
-
|
|
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);
|
|
4077
|
+
if (!result.ok) throw thrownRunError(result.error);
|
|
4078
|
+
return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb);
|
|
4156
4079
|
});
|
|
4157
4080
|
}
|
|
4158
4081
|
async dispose() {
|
|
@@ -4177,23 +4100,20 @@ var PrefixImpl = class {
|
|
|
4177
4100
|
id;
|
|
4178
4101
|
pool;
|
|
4179
4102
|
/**
|
|
4180
|
-
*
|
|
4181
|
-
*
|
|
4182
|
-
* "If the prefix declared a global the run doesn't supply, the
|
|
4183
|
-
* precompile-time implementation is reused."
|
|
4103
|
+
* The global shape declared at `prepare()`, with the default handlers a run
|
|
4104
|
+
* falls back to when it does not override them (DESIGN.md §11.4).
|
|
4184
4105
|
*/
|
|
4185
|
-
|
|
4106
|
+
declaredGlobals;
|
|
4186
4107
|
/**
|
|
4187
|
-
* Host-import function-leaf handlers declared at
|
|
4188
|
-
* `(specifier, path)
|
|
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`).
|
|
4108
|
+
* Host-import function-leaf handlers declared at `prepare()`, keyed by
|
|
4109
|
+
* `(specifier, path)`; a run's overrides apply on top.
|
|
4194
4110
|
*/
|
|
4195
4111
|
defaultImportHandlers;
|
|
4196
4112
|
/**
|
|
4113
|
+
* The import shape declared at `prepare()`, for client-side rebind checks.
|
|
4114
|
+
*/
|
|
4115
|
+
declaredImports;
|
|
4116
|
+
/**
|
|
4197
4117
|
* THIS prefix's heap cap (`prepare({ memoryMb })`, falling back to the
|
|
4198
4118
|
* sandbox default). Warm instances serving the prefix are created with
|
|
4199
4119
|
* it; a per-run value stays impossible — the cap is baked into the
|
|
@@ -4205,11 +4125,12 @@ var PrefixImpl = class {
|
|
|
4205
4125
|
*/
|
|
4206
4126
|
brandKey;
|
|
4207
4127
|
_alive = true;
|
|
4208
|
-
constructor(id, pool,
|
|
4128
|
+
constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb) {
|
|
4209
4129
|
this.id = id;
|
|
4210
4130
|
this.pool = pool;
|
|
4211
|
-
this.
|
|
4131
|
+
this.declaredGlobals = declaredGlobals;
|
|
4212
4132
|
this.defaultImportHandlers = defaultImportHandlers;
|
|
4133
|
+
this.declaredImports = declaredImports;
|
|
4213
4134
|
this.brandKey = brandKey;
|
|
4214
4135
|
this.memoryMb = memoryMb;
|
|
4215
4136
|
}
|
|
@@ -4229,7 +4150,7 @@ var PrefixImpl = class {
|
|
|
4229
4150
|
* @deprecated Renamed to {@link PrefixImpl.execute}; kept as an alias.
|
|
4230
4151
|
*/
|
|
4231
4152
|
async run(options) {
|
|
4232
|
-
return await this.dispatch(options, { code: options.code });
|
|
4153
|
+
return await this.dispatch(options, async () => ({ code: options.code }));
|
|
4233
4154
|
}
|
|
4234
4155
|
/**
|
|
4235
4156
|
* Call a function exported by this prefix's module — no postfix compiled.
|
|
@@ -4237,21 +4158,17 @@ var PrefixImpl = class {
|
|
|
4237
4158
|
* @param options
|
|
4238
4159
|
*/
|
|
4239
4160
|
async call(options) {
|
|
4240
|
-
|
|
4241
|
-
const call = {
|
|
4161
|
+
return await this.dispatch(options, async (streams) => ({ call: {
|
|
4242
4162
|
exportPath: options.export,
|
|
4243
4163
|
argsBlob: await serializeHostValue(options.args ?? [], this.brandKey, streams)
|
|
4244
|
-
};
|
|
4245
|
-
return await this.dispatch(options, {
|
|
4246
|
-
call,
|
|
4247
|
-
streams
|
|
4248
|
-
});
|
|
4164
|
+
} }));
|
|
4249
4165
|
}
|
|
4250
4166
|
/**
|
|
4251
4167
|
* Shared body of {@link run} and {@link call}: disposal/abort guards,
|
|
4252
4168
|
* bridge-global extraction, import-rebind merging, and the PrefixRun round
|
|
4253
|
-
* trip. `
|
|
4254
|
-
* the wire demands; it also selects how the result blob decodes.
|
|
4169
|
+
* trip. `buildPayload` yields the postfix source or the call — exactly one,
|
|
4170
|
+
* as the wire demands; it also selects how the result blob decodes. It runs
|
|
4171
|
+
* after the checks, so a refused run never registers a stream source.
|
|
4255
4172
|
* @param options
|
|
4256
4173
|
* @param options.globals
|
|
4257
4174
|
* @param options.imports
|
|
@@ -4259,60 +4176,32 @@ var PrefixImpl = class {
|
|
|
4259
4176
|
* @param options.signal
|
|
4260
4177
|
* @param options.hardAbortSignal
|
|
4261
4178
|
* @param options.filename
|
|
4262
|
-
* @param
|
|
4179
|
+
* @param buildPayload
|
|
4263
4180
|
*/
|
|
4264
|
-
async dispatch(options,
|
|
4265
|
-
if (!this._alive)
|
|
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
|
-
};
|
|
4181
|
+
async dispatch(options, buildPayload) {
|
|
4182
|
+
if (!this._alive) throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
|
|
4280
4183
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
4281
4184
|
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
|
|
4185
|
+
validateLimits(options.limits);
|
|
4282
4186
|
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
|
-
|
|
4284
|
-
let dispatch;
|
|
4187
|
+
const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.declaredGlobals);
|
|
4285
4188
|
let merged;
|
|
4286
4189
|
try {
|
|
4287
|
-
|
|
4288
|
-
merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
|
|
4190
|
+
merged = mergeRebindImports(options.imports, this.defaultImportHandlers, this.declaredImports);
|
|
4289
4191
|
} catch (e) {
|
|
4290
|
-
if (e instanceof ImportRebindError
|
|
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
|
-
};
|
|
4192
|
+
if (e instanceof ImportRebindError) throw setupError(e.code, e.message);
|
|
4305
4193
|
throw e;
|
|
4306
4194
|
}
|
|
4307
|
-
const streams =
|
|
4195
|
+
const streams = new StreamSourceRegistry();
|
|
4308
4196
|
try {
|
|
4197
|
+
const payload = await buildPayload(streams);
|
|
4309
4198
|
return await this.pool.withClient(async (client, queueWaitMs) => {
|
|
4310
4199
|
const raw = await client.prefixRun({
|
|
4311
4200
|
prefixId: this.id,
|
|
4312
4201
|
code: payload.code,
|
|
4313
4202
|
filename: options.filename,
|
|
4314
4203
|
limits: {
|
|
4315
|
-
...options.limits,
|
|
4204
|
+
...wireLimits(options.limits),
|
|
4316
4205
|
...heapCapsForWire(this.memoryMb)
|
|
4317
4206
|
},
|
|
4318
4207
|
globals: defs,
|
|
@@ -4325,6 +4214,10 @@ var PrefixImpl = class {
|
|
|
4325
4214
|
streams
|
|
4326
4215
|
});
|
|
4327
4216
|
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);
|
|
4217
|
+
if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
|
|
4218
|
+
...decoded.error,
|
|
4219
|
+
code: decoded.error.code
|
|
4220
|
+
});
|
|
4328
4221
|
if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
|
|
4329
4222
|
if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
|
|
4330
4223
|
if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
|
|
@@ -4343,6 +4236,9 @@ var PrefixImpl = class {
|
|
|
4343
4236
|
async dispose() {
|
|
4344
4237
|
if (!this._alive) return;
|
|
4345
4238
|
this._alive = false;
|
|
4239
|
+
this.declaredGlobals = /* @__PURE__ */ new Map();
|
|
4240
|
+
this.defaultImportHandlers = /* @__PURE__ */ new Map();
|
|
4241
|
+
this.declaredImports = [];
|
|
4346
4242
|
await this.pool.withClient((client) => client.disposePrefix(this.id));
|
|
4347
4243
|
}
|
|
4348
4244
|
async [Symbol.asyncDispose]() {
|
|
@@ -4350,4 +4246,4 @@ var PrefixImpl = class {
|
|
|
4350
4246
|
}
|
|
4351
4247
|
};
|
|
4352
4248
|
//#endregion
|
|
4353
|
-
export {
|
|
4249
|
+
export { createSandbox };
|