@iso4/sandbox 0.0.2 → 0.0.4

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.d.mts CHANGED
@@ -181,51 +181,86 @@ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H>
181
181
  */
182
182
  type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string ? never : K]?: RebindValue<G[K]> };
183
183
  /**
184
- * Resolution order: static map → dynamic resolver → ERR_MODULE_NOT_FOUND.
184
+ * Top-level `imports` shape. Keys are import specifiers; values are either
185
+ * a source string or a host-module description object.
186
+ *
187
+ * `M` is the literal shape of the map. `precompile()` infers it from the
188
+ * object literal so the declared specifiers and their value shapes flow
189
+ * into `Prefix<G, M>` and feed `RebindImports<M>`.
185
190
  */
186
- interface ImportsConfig {
187
- static?: Record<string, ImportDefinition>;
188
- resolve?: (specifier: string, importer: string | null) => Promise<ImportDefinition | null> | ImportDefinition | null;
189
- }
190
- type ImportDefinition = SourceImport | HostImport;
191
+ type Imports<M extends Record<string, ImportValue> = Record<string, ImportValue>> = M;
191
192
  /**
192
- * Host provides ESM source; V8 compiles and caches it in-isolate.
193
+ * A single import value. String = source module. Object = host module
194
+ * description (the recursive walker handles all nesting).
193
195
  */
194
- interface SourceImport {
195
- kind: "source";
196
- source: string;
197
- }
196
+ type ImportValue = string | HostModuleObject;
198
197
  /**
199
- * Host provides an object; each function becomes a bridge-call stub.
198
+ * A host-module description object. Each property is either:
199
+ *
200
+ * - A function — becomes an async bridge stub in the generated module.
201
+ * - A plain data value (primitive, plain object/array, `Date`, `BigInt`,
202
+ * `Uint8Array`) — becomes a JS literal in the generated module.
203
+ * - A nested object that itself contains a mix of functions and data —
204
+ * walked recursively.
205
+ *
206
+ * `Map`, `Set`, circular references, class instances with prototype
207
+ * methods, and stateful handles (streams, sockets) are rejected at
208
+ * registration with a clear error.
200
209
  */
201
- interface HostImport {
202
- kind: "host";
203
- exports: HostExports;
204
- }
205
- interface HostExports {
206
- default?: HostExportValue;
207
- [name: string]: HostExportValue | undefined;
210
+ interface HostModuleObject {
211
+ [name: string]: HostModuleValue;
208
212
  }
209
- type HostExportValue = HostExportData | HostExportFunction;
210
213
  /**
211
- * Represents the plain-data values that cross the bridge.
212
- * Kept for `HostExports` / import system typing.
214
+ * Any node the recursive walker may encounter inside a `HostModuleObject`.
213
215
  */
214
- type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | HostExportData[] | {
216
+ type HostModuleValue = HostExportFunction | HostExportData | HostModuleObject;
217
+ /**
218
+ * The set of plain-data values supported as data leaves in the host-module
219
+ * shape. The JS-literal emitter knows how to emit each of these.
220
+ */
221
+ type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | Date | HostExportData[] | {
215
222
  [key: string]: HostExportData;
216
223
  };
217
224
  /**
218
- * A host-side function exposed as a global or import export.
225
+ * A host-side function exposed as a global or import-tree leaf.
219
226
  *
220
227
  * Args and return are `unknown` — the bridge serialises/deserialises values
221
228
  * with V8 ValueSerializer; we don't try to model that at the type level.
222
- * The one invariant that matters (functions cannot cross the boundary) is
223
- * enforced at runtime by the V8 layer, not here.
229
+ * The one invariant that matters (functions cannot cross the boundary as
230
+ * argument values) is enforced at runtime by the V8 layer, not here.
224
231
  *
225
232
  * Use specific function types for your handlers and let TypeScript infer
226
- * them through `HostGlobals` and `RebindGlobals<G>`.
233
+ * them through `HostGlobals`, `RebindGlobals<G>`, and `RebindImports<M>`.
227
234
  */
228
235
  type HostExportFunction = (...args: unknown[]) => unknown;
236
+ /**
237
+ * The rebindable subset of an `Imports<M>` declared at precompile time.
238
+ *
239
+ * Mirrors `RebindGlobals<G>` over the recursive host-module shape:
240
+ *
241
+ * - **Source imports** (string values) are compiled into the snapshot and
242
+ * cannot be rebound — their keys are excluded from the result.
243
+ * - **Host imports** (object values) are walked recursively. Only function
244
+ * leaves survive; data leaves are excluded because their values are
245
+ * emitted as JS literals into the generated module.
246
+ *
247
+ * Passing a specifier or export name that was not declared at precompile
248
+ * is a TypeScript error at compile time and `ERR_UNDECLARED_BINDING` at
249
+ * runtime.
250
+ *
251
+ * When `M` is left at its wide default (no `imports` declared, or no
252
+ * literal shape inferred), the rebind keyspace collapses to
253
+ * `Record<string, never>` — the walker only kicks in for literal shapes,
254
+ * which have finite depth.
255
+ */
256
+ type RebindImports<M extends Record<string, ImportValue>> = Record<string, ImportValue> extends M ? Record<string, never> : { [K in keyof M as M[K] extends string ? never : K]?: M[K] extends HostModuleObject ? RebindHostModule<M[K]> : never };
257
+ /**
258
+ * Recursive walker over a `HostModuleObject`. Function leaves keep
259
+ * their declared signature; nested objects recurse; data leaves drop out
260
+ * entirely. Only used against literal shapes inferred by `precompile`, so
261
+ * the recursion is always finite.
262
+ */
263
+ type RebindHostModule<T> = T extends HostExportFunction ? T : T extends HostModuleObject ? { [K in keyof T as T[K] extends HostExportFunction ? K : T[K] extends HostModuleObject ? K : never]?: T[K] extends HostExportFunction ? T[K] : T[K] extends HostModuleObject ? RebindHostModule<T[K]> : never } : never;
229
264
  interface SandboxOptions {
230
265
  /**
231
266
  * Maximum number of isolates (UDS connection slots) running concurrently.
@@ -270,7 +305,10 @@ interface Sandbox {
270
305
  * Globals declared here serve as **default** implementations for all runs.
271
306
  * `prefix.run()` may override any subset; omitted names reuse the default.
272
307
  */
273
- precompile: <G extends HostGlobals = {}>(options: PrecompileOptions<G>) => Promise<Prefix<G>>;
308
+ /**
309
+ * eslint-disable \@typescript-eslint/no-empty-object-type
310
+ */
311
+ precompile: <G extends HostGlobals = {}, M extends Imports = {}>(options: PrecompileOptions<G, M>) => Promise<Prefix<G, M>>;
274
312
  /**
275
313
  * Tear down the Rust process. Outstanding prefixes are invalidated.
276
314
  */
@@ -289,7 +327,7 @@ type CreateSandbox = (options?: SandboxOptions) => Promise<Sandbox>;
289
327
  * from the `globals` field, so the returned `Prefix<G>` is typed to allow
290
328
  * only those names to be rebound in subsequent `prefix.run()` calls.
291
329
  */
292
- interface PrecompileOptions<G extends HostGlobals> {
330
+ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
293
331
  /**
294
332
  * ESM source code to evaluate before snapshotting. Top-level await works.
295
333
  *
@@ -313,7 +351,13 @@ interface PrecompileOptions<G extends HostGlobals> {
313
351
  * any `prefix.run()` call that does not override them.
314
352
  */
315
353
  globals?: G;
316
- imports?: ImportsConfig;
354
+ /**
355
+ * Declares the imports the sandbox code may resolve.
356
+ *
357
+ * The inferred shape feeds `Prefix<G, M>` so `prefix.run()` knows which
358
+ * specifiers exist and which exports may be rebound.
359
+ */
360
+ imports?: M;
317
361
  /**
318
362
  * Resource limits applied to prefix code evaluation.
319
363
  *
@@ -337,21 +381,22 @@ interface PrecompileOptions<G extends HostGlobals> {
337
381
  * declared global's implementation per run, but you cannot add names that
338
382
  * were not declared at precompile time.
339
383
  */
340
- interface Prefix<G extends HostGlobals> {
384
+ interface Prefix<G extends HostGlobals, M extends Imports> {
341
385
  readonly id: string;
342
386
  /**
343
387
  * Execute dynamic code against this prefix's snapshot state.
344
388
  *
345
389
  * Globals declared at precompile time are active. You may rebind any subset
346
390
  * of them via `options.globals`; the precompile-time handler is used for
347
- * any name not overridden here.
391
+ * any name not overridden here. Same rule for `imports`, restricted to
392
+ * host-import function exports declared in `I`.
348
393
  *
349
394
  * @example
350
395
  * const result = await prefix.run({
351
396
  * code: `export default await (${agentFn})()`,
352
397
  * })
353
398
  */
354
- run: (options: PrefixRunOptions<G>) => Promise<RunResult>;
399
+ run: (options: PrefixRunOptions<G, M>) => Promise<RunResult>;
355
400
  /**
356
401
  * Release the snapshot. Subsequent run() calls reject. Idempotent.
357
402
  */
@@ -370,7 +415,7 @@ interface Prefix<G extends HostGlobals> {
370
415
  * may be overridden. Passing any other name is a TypeScript error at compile
371
416
  * time and `ERR_UNDECLARED_BINDING` at runtime.
372
417
  */
373
- interface PrefixRunOptions<G extends HostGlobals> {
418
+ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
374
419
  /**
375
420
  * Dynamic ESM source code to compile and run against the prefix state.
376
421
  */
@@ -384,11 +429,13 @@ interface PrefixRunOptions<G extends HostGlobals> {
384
429
  */
385
430
  globals?: RebindGlobals<G>;
386
431
  /**
387
- * Rebind host-module imports declared at precompile time.
388
- * Source module imports are frozen in the snapshot and cannot be rebound.
389
- * (Phase 6/7 — not yet implemented.)
432
+ * Rebind host-module function exports declared at precompile time.
433
+ * Source module imports are frozen in the snapshot and cannot be rebound;
434
+ * data exports are baked into the synthetic module. TypeScript enforces
435
+ * this at the type level via `RebindImports<M>`; the runtime rejects
436
+ * anything that slips through with `ERR_UNDECLARED_BINDING`.
390
437
  */
391
- imports?: ImportsConfig;
438
+ imports?: RebindImports<M>;
392
439
  limits?: Partial<ResourceLimits>;
393
440
  signal?: AbortSignal;
394
441
  filename?: string;
@@ -397,7 +444,7 @@ interface RunOptions {
397
444
  code: string;
398
445
  limits?: Partial<ResourceLimits>;
399
446
  globals?: HostGlobals;
400
- imports?: ImportsConfig;
447
+ imports?: Imports;
401
448
  signal?: AbortSignal;
402
449
  filename?: string;
403
450
  }
@@ -438,4 +485,4 @@ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "
438
485
  //#region src/index.d.ts
439
486
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
440
487
  //#endregion
441
- export { type BridgeWithShim, type CreateSandbox, type HostExportData, type HostExportFunction, type HostExportValue, type HostExports, type HostGlobalValue, type HostGlobals, type HostImport, type ImportDefinition, type ImportsConfig, type PrecompileOptions, type Prefix, type PrefixRunOptions, type RebindGlobals, type RebindValue, type ResourceLimits, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SourceImport, createSandbox };
488
+ export { type BridgeWithShim, type CreateSandbox, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type PrecompileOptions, type Prefix, type PrefixRunOptions, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResourceLimits, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, createSandbox };
package/dist/index.mjs CHANGED
@@ -571,6 +571,14 @@ var PayloadWriter = class {
571
571
  }
572
572
  return this;
573
573
  }
574
+ writeImports(imports) {
575
+ this.writeU32(imports.length);
576
+ for (const imp of imports) {
577
+ this.writeString(imp.specifier);
578
+ this.writeString(imp.source);
579
+ }
580
+ return this;
581
+ }
574
582
  writeResourceLimits(limits) {
575
583
  this.writeU32(limits.memoryMb ?? 0);
576
584
  this.writeU32(limits.cpuTimeMs ?? 0);
@@ -595,7 +603,7 @@ function encodeRunPayload(options) {
595
603
  const globals = options.globals ?? [];
596
604
  w.writeU32(globals.length);
597
605
  for (const name of globals) w.writeString(name);
598
- w.writeU32(0);
606
+ w.writeImports(options.imports ?? []);
599
607
  return w.toBuffer();
600
608
  }
601
609
  /**
@@ -608,7 +616,7 @@ function encodePrecompilePayload(options) {
608
616
  const globals = options.globals ?? [];
609
617
  w.writeU32(globals.length);
610
618
  for (const name of globals) w.writeString(name);
611
- w.writeU32(0);
619
+ w.writeImports(options.imports ?? []);
612
620
  return w.toBuffer();
613
621
  }
614
622
  /**
@@ -622,7 +630,7 @@ function encodePrefixRunPayload(options) {
622
630
  const globals = options.globals ?? [];
623
631
  w.writeU32(globals.length);
624
632
  for (const name of globals) w.writeString(name);
625
- w.writeU32(0);
633
+ w.writeImports(options.imports ?? []);
626
634
  return w.toBuffer();
627
635
  }
628
636
  /**
@@ -766,7 +774,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
766
774
  code,
767
775
  filename: options?.filename,
768
776
  limits: options?.limits,
769
- globals: globalNames
777
+ globals: globalNames,
778
+ imports: options?.imports
770
779
  })));
771
780
  return this.drainUntilResult(makeDispatcher(globals));
772
781
  }
@@ -776,7 +785,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
776
785
  code: options.code,
777
786
  filename: options.filename,
778
787
  limits: options.limits,
779
- globals: Object.keys(options.globals ?? {})
788
+ globals: Object.keys(options.globals ?? {}),
789
+ imports: options.imports
780
790
  })));
781
791
  for await (const frame of this.reader) {
782
792
  if (frame.messageType === RustToTsMessageTypes.PrecompileResult) return frame.payload;
@@ -794,6 +804,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
794
804
  filename: options.filename,
795
805
  limits: options.limits,
796
806
  globals: globalNames,
807
+ imports: options.imports,
797
808
  runId: this.nextRunIdValue()
798
809
  })));
799
810
  return this.drainUntilResult(makeDispatcher(globals));
@@ -839,7 +850,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
839
850
  if (dispatcher === void 0) await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(call.callId, false, void 0, "no bridge dispatcher configured")));
840
851
  else {
841
852
  const { callId } = call;
842
- dispatcher(call.exportName, call.args).then((value) => {
853
+ dispatcher({
854
+ exportName: call.exportName,
855
+ args: call.args
856
+ }).then((value) => {
843
857
  let encoded;
844
858
  try {
845
859
  encoded = encodeWireValue(value);
@@ -867,14 +881,20 @@ var RuntimeIpcClient = class RuntimeIpcClient {
867
881
  }
868
882
  };
869
883
  /**
870
- * Build a dispatcher from a globals map; returns undefined when map is empty.
884
+ * Build a dispatcher that looks up a handler by `exportName` in the
885
+ * per-run globals map. Host-module imports are bridged through the same
886
+ * map via the reserved `__iso4_call` global, so a single lookup table
887
+ * handles every bridge call.
888
+ *
889
+ * Returns `undefined` when the map is empty so the loop short-circuits to
890
+ * an "unconfigured bridge" error response.
871
891
  * @param globals
872
892
  */
873
893
  function makeDispatcher(globals) {
874
894
  if (Object.keys(globals).length === 0) return void 0;
875
- return async (name, args) => {
876
- const handler = globals[name];
877
- if (handler === void 0) throw new Error(`no handler configured for global '${name}'`);
895
+ return async ({ exportName, args }) => {
896
+ const handler = globals[exportName];
897
+ if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
878
898
  return handler(...args);
879
899
  };
880
900
  }
@@ -999,6 +1019,298 @@ function extractBridgeGlobals(runGlobals, precompileGlobals) {
999
1019
  return out;
1000
1020
  }
1001
1021
  //#endregion
1022
+ //#region src/imports.ts
1023
+ /**
1024
+ * The reserved global name of the bridge dispatcher. User globals may not
1025
+ * use this name. The generated host-module source calls it as
1026
+ * `globalThis.__iso4_call(id, ...args)`.
1027
+ */
1028
+ const BRIDGE_DISPATCH_GLOBAL = "__iso4_call";
1029
+ /**
1030
+ * Thrown when the host's import configuration is structurally invalid
1031
+ * (mixed types, unsupported data values, undeclared rebindings, …).
1032
+ * `PrefixImpl.run` converts the undeclared-binding variant into an
1033
+ * `ERR_UNDECLARED_BINDING` `RunResult`, matching the globals path.
1034
+ */
1035
+ var UndeclaredImportBindingError = class extends Error {
1036
+ code = "ERR_UNDECLARED_BINDING";
1037
+ constructor(message) {
1038
+ super(message);
1039
+ this.name = "UndeclaredImportBindingError";
1040
+ }
1041
+ };
1042
+ /**
1043
+ * Build the `__iso4_call` global handler that backs all host-module
1044
+ * function leaves for a run. It peels the leading handle ID and routes to
1045
+ * the registry.
1046
+ * @param registry
1047
+ */
1048
+ function createDispatchGlobal(registry) {
1049
+ return (...args) => {
1050
+ const id = args[0];
1051
+ const fn = registry.get(id);
1052
+ if (fn === void 0) throw new Error(`[@iso4/sandbox] no host handler for import handle ${String(id)}`);
1053
+ return fn(...args.slice(1));
1054
+ };
1055
+ }
1056
+ function processImports(imports) {
1057
+ const shape = {
1058
+ sourceSpecifiers: /* @__PURE__ */ new Set(),
1059
+ hostFunctionIds: {},
1060
+ hostDataPaths: {}
1061
+ };
1062
+ if (imports === void 0) return {
1063
+ bindings: [],
1064
+ registry: /* @__PURE__ */ new Map(),
1065
+ shape
1066
+ };
1067
+ const bindings = [];
1068
+ const registry = /* @__PURE__ */ new Map();
1069
+ let nextId = 0;
1070
+ const allocId = () => nextId++;
1071
+ for (const [specifier, value] of Object.entries(imports)) {
1072
+ if (typeof value === "string") {
1073
+ bindings.push({
1074
+ specifier,
1075
+ source: value
1076
+ });
1077
+ shape.sourceSpecifiers.add(specifier);
1078
+ continue;
1079
+ }
1080
+ 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)}`);
1081
+ const fnIds = {};
1082
+ const dataPaths = /* @__PURE__ */ new Set();
1083
+ const source = generateHostModuleSource(specifier, value, registry, allocId, fnIds, dataPaths);
1084
+ bindings.push({
1085
+ specifier,
1086
+ source
1087
+ });
1088
+ shape.hostFunctionIds[specifier] = fnIds;
1089
+ shape.hostDataPaths[specifier] = dataPaths;
1090
+ }
1091
+ return {
1092
+ bindings,
1093
+ registry,
1094
+ shape
1095
+ };
1096
+ }
1097
+ /**
1098
+ * Override the handlers behind a `Prefix`'s declared host-module function
1099
+ * leaves. Only declared paths may be rebound; everything else throws
1100
+ * `UndeclaredImportBindingError`. Source modules are frozen.
1101
+ *
1102
+ * Returns a fresh registry keyed by the same handle IDs the prefix assigned
1103
+ * at precompile time, with the new handler installed where provided.
1104
+ *
1105
+ * @param runImports
1106
+ * @param defaults
1107
+ * @param shape
1108
+ */
1109
+ function extractRebindImports(runImports, defaults, shape) {
1110
+ if (runImports === void 0) return defaults;
1111
+ const merged = new Map(defaults);
1112
+ for (const [specifier, value] of Object.entries(runImports)) {
1113
+ if (typeof value === "string" || shape.sourceSpecifiers.has(specifier)) throw new UndeclaredImportBindingError(`import '${specifier}' is a source module — source imports are frozen in the snapshot and cannot be rebound at prefix.run() time`);
1114
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
1115
+ if (shape.hostFunctionIds[specifier] === void 0) throw new UndeclaredImportBindingError(`import '${specifier}' was not declared at precompile time`);
1116
+ walkRebind(specifier, value, [], shape, merged);
1117
+ }
1118
+ return merged;
1119
+ }
1120
+ function walkRebind(specifier, node, path, shape, merged) {
1121
+ const fnIds = shape.hostFunctionIds[specifier];
1122
+ const dataPaths = shape.hostDataPaths[specifier];
1123
+ for (const [key, value] of Object.entries(node)) {
1124
+ if (value === void 0) continue;
1125
+ const newPath = [...path, key];
1126
+ const joined = newPath.join(".");
1127
+ if (typeof value === "function") {
1128
+ if (dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
1129
+ const id = fnIds[joined];
1130
+ if (id === void 0) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
1131
+ merged.set(id, value);
1132
+ continue;
1133
+ }
1134
+ if (isPlainObject(value)) {
1135
+ walkRebind(specifier, value, newPath, shape, merged);
1136
+ continue;
1137
+ }
1138
+ if (fnIds[joined] !== void 0 || dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
1139
+ throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Generate the ESM source for a host module specifier. Walks `desc`
1144
+ * recursively and emits one `export const <name> = <expr>;` per top-level
1145
+ * entry. Function leaves become `__iso4_call(<id>, ...args)` stubs; data
1146
+ * leaves become JS literals.
1147
+ *
1148
+ * @param specifier
1149
+ * @param desc
1150
+ * @param registry
1151
+ * @param allocId
1152
+ * @param fnIds
1153
+ * @param dataPaths
1154
+ */
1155
+ function generateHostModuleSource(specifier, desc, registry, allocId, fnIds, dataPaths) {
1156
+ const parts = [];
1157
+ for (const [key, value] of Object.entries(desc)) {
1158
+ if (value === void 0) continue;
1159
+ if (!isValidExportIdentifier(key)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] top-level key '${key}' is not a valid JavaScript identifier and cannot be exported as a named ESM export`);
1160
+ const expr = emitValue(specifier, value, [key], registry, allocId, fnIds, dataPaths);
1161
+ if (key === "default") parts.push(`export default ${expr};`);
1162
+ else parts.push(`export const ${key} = ${expr};`);
1163
+ }
1164
+ return parts.join("\n");
1165
+ }
1166
+ function emitValue(specifier, value, path, registry, allocId, fnIds, dataPaths, seen = /* @__PURE__ */ new Set()) {
1167
+ if (typeof value === "function") {
1168
+ const id = allocId();
1169
+ registry.set(id, value);
1170
+ fnIds[path.join(".")] = id;
1171
+ return `(async (...args) => await globalThis.${BRIDGE_DISPATCH_GLOBAL}(${id}, ...args))`;
1172
+ }
1173
+ if (isPlainObject(value)) {
1174
+ if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
1175
+ seen.add(value);
1176
+ const fields = [];
1177
+ for (const [key, child] of Object.entries(value)) {
1178
+ if (child === void 0) continue;
1179
+ const childExpr = emitValue(specifier, child, [...path, key], registry, allocId, fnIds, dataPaths, seen);
1180
+ fields.push(`${jsObjectKey(key)}: ${childExpr}`);
1181
+ }
1182
+ seen.delete(value);
1183
+ return `({ ${fields.join(", ")} })`;
1184
+ }
1185
+ dataPaths.add(path.join("."));
1186
+ return emitDataLiteral(specifier, value, path);
1187
+ }
1188
+ /**
1189
+ * Emit a `HostExportData` value as a JS expression that reproduces the
1190
+ * original value in the sandbox. Supports primitives, plain objects/arrays,
1191
+ * `Date`, `BigInt`, `Uint8Array`. `Map`, `Set`, circular refs, and class
1192
+ * instances throw with a clear pointer.
1193
+ *
1194
+ * @param specifier
1195
+ * @param value
1196
+ * @param path
1197
+ * @param seen
1198
+ */
1199
+ function emitDataLiteral(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
1200
+ if (value === null) return "null";
1201
+ if (value === void 0) return "undefined";
1202
+ switch (typeof value) {
1203
+ case "boolean": return value ? "true" : "false";
1204
+ case "number":
1205
+ if (Number.isNaN(value)) return "NaN";
1206
+ if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
1207
+ return String(value);
1208
+ case "bigint": return `${value.toString()}n`;
1209
+ case "string": return JSON.stringify(value);
1210
+ }
1211
+ if (value instanceof Uint8Array) return `new Uint8Array([${Array.from(value).join(", ")}])`;
1212
+ if (value instanceof Date) return `new Date(${value.getTime()})`;
1213
+ if (value instanceof Map || value instanceof Set) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: Map / Set values are not yet supported as data leaves`);
1214
+ if (typeof value === "object") {
1215
+ if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
1216
+ seen.add(value);
1217
+ if (Array.isArray(value)) {
1218
+ const parts = value.map((item, i) => emitDataLiteral(specifier, item, [...path, String(i)], seen));
1219
+ seen.delete(value);
1220
+ return `[${parts.join(", ")}]`;
1221
+ }
1222
+ const proto = Object.getPrototypeOf(value);
1223
+ if (proto !== null && proto !== Object.prototype) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: class instances are not supported as data leaves; copy the data into a plain object explicitly`);
1224
+ const fields = [];
1225
+ for (const [key, child] of Object.entries(value)) fields.push(`${jsObjectKey(key)}: ${emitDataLiteral(specifier, child, [...path, key], seen)}`);
1226
+ seen.delete(value);
1227
+ return `({ ${fields.join(", ")} })`;
1228
+ }
1229
+ throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
1230
+ }
1231
+ function isPlainObject(value) {
1232
+ if (value === null || typeof value !== "object") return false;
1233
+ if (Array.isArray(value)) return false;
1234
+ if (value instanceof Uint8Array || value instanceof Date) return false;
1235
+ if (value instanceof Map || value instanceof Set) return false;
1236
+ const proto = Object.getPrototypeOf(value);
1237
+ return proto === null || proto === Object.prototype;
1238
+ }
1239
+ const RESERVED_WORDS = new Set([
1240
+ "break",
1241
+ "case",
1242
+ "catch",
1243
+ "class",
1244
+ "const",
1245
+ "continue",
1246
+ "debugger",
1247
+ "default",
1248
+ "delete",
1249
+ "do",
1250
+ "else",
1251
+ "export",
1252
+ "extends",
1253
+ "finally",
1254
+ "for",
1255
+ "function",
1256
+ "if",
1257
+ "import",
1258
+ "in",
1259
+ "instanceof",
1260
+ "new",
1261
+ "return",
1262
+ "super",
1263
+ "switch",
1264
+ "this",
1265
+ "throw",
1266
+ "try",
1267
+ "typeof",
1268
+ "var",
1269
+ "void",
1270
+ "while",
1271
+ "with",
1272
+ "yield",
1273
+ "let",
1274
+ "static",
1275
+ "enum",
1276
+ "await",
1277
+ "implements",
1278
+ "package",
1279
+ "protected",
1280
+ "interface",
1281
+ "private",
1282
+ "public",
1283
+ "null",
1284
+ "true",
1285
+ "false"
1286
+ ]);
1287
+ /**
1288
+ * Whether `name` can appear as a named ESM export. JS identifier rules plus
1289
+ * a reserved-word filter. `default` is handled separately by the emitter.
1290
+ * @param name
1291
+ */
1292
+ function isValidExportIdentifier(name) {
1293
+ if (name === "default") return true;
1294
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
1295
+ if (RESERVED_WORDS.has(name)) return false;
1296
+ return true;
1297
+ }
1298
+ /**
1299
+ * Emit `key` as a JS object property key: a bare identifier when possible,
1300
+ * otherwise a quoted string. Object keys (unlike export names) may be any
1301
+ * string, so this never rejects.
1302
+ * @param key
1303
+ */
1304
+ function jsObjectKey(key) {
1305
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) && !RESERVED_WORDS.has(key)) return key;
1306
+ return JSON.stringify(key);
1307
+ }
1308
+ function describeKind(value) {
1309
+ if (value === null) return "null";
1310
+ if (Array.isArray(value)) return "array";
1311
+ return typeof value;
1312
+ }
1313
+ //#endregion
1002
1314
  //#region src/index.ts
1003
1315
  /**
1004
1316
  * \@iso4/sandbox - public entry point.
@@ -1087,25 +1399,40 @@ var SandboxImpl = class {
1087
1399
  durationMs: 0
1088
1400
  };
1089
1401
  const { bridgeGlobals, preamble } = processGlobals(options.globals ?? {});
1402
+ const { bindings, registry, shape: _shape } = processImports(options.imports);
1403
+ const allGlobals = registry.size > 0 ? {
1404
+ ...bridgeGlobals,
1405
+ [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1406
+ } : bridgeGlobals;
1090
1407
  const code = preamble ? `${preamble}\n${options.code}` : options.code;
1091
1408
  return this.pool.withClient(async (client) => {
1092
1409
  return decodeRunCompletionPayload((await client.runRawCode(code, {
1093
1410
  filename: options.filename,
1094
1411
  limits: toWireLimits(options.limits),
1095
- globals: bridgeGlobals
1412
+ globals: allGlobals,
1413
+ imports: bindings
1096
1414
  })).result).result;
1097
1415
  });
1098
1416
  }
1417
+ /**
1418
+ * @param options
1419
+ */
1099
1420
  async precompile(options) {
1100
1421
  return this.pool.withClient(async (client) => {
1101
1422
  const rawGlobals = options.globals ?? {};
1102
1423
  const { bridgeGlobals, preamble } = processGlobals(rawGlobals);
1424
+ const { bindings, registry, shape } = processImports(options.imports);
1425
+ const allGlobals = registry.size > 0 ? {
1426
+ ...bridgeGlobals,
1427
+ [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1428
+ } : bridgeGlobals;
1103
1429
  const code = preamble ? `${preamble}\n${options.code}` : options.code;
1104
1430
  const result = decodePrecompileResultPayload(await client.precompile({
1105
1431
  code,
1106
1432
  filename: options.filename,
1107
1433
  limits: toWireLimits(options.limits),
1108
- globals: bridgeGlobals
1434
+ globals: allGlobals,
1435
+ imports: bindings
1109
1436
  }));
1110
1437
  if (!result.ok) {
1111
1438
  const err = new Error(result.error.message);
@@ -1114,7 +1441,7 @@ var SandboxImpl = class {
1114
1441
  if (result.error.stack) err.stack = result.error.stack;
1115
1442
  throw err;
1116
1443
  }
1117
- return new PrefixImpl(result.prefixId, this.pool, rawGlobals);
1444
+ return new PrefixImpl(result.prefixId, this.pool, rawGlobals, registry, shape);
1118
1445
  });
1119
1446
  }
1120
1447
  async dispose() {
@@ -1140,11 +1467,27 @@ var PrefixImpl = class {
1140
1467
  * precompile-time implementation is reused."
1141
1468
  */
1142
1469
  defaultGlobals;
1470
+ /**
1471
+ * Handle registry declared at precompile time: handle ID → host function.
1472
+ * Same rebinding rules as `defaultGlobals` — a `prefix.run()` may override
1473
+ * a subset of function leaves; everything else falls back to these. Source
1474
+ * modules and data leaves are frozen in the snapshot and not represented
1475
+ * here.
1476
+ */
1477
+ defaultRegistry;
1478
+ /**
1479
+ * Declared shape captured at precompile time. Drives type-level rebinding
1480
+ * via `RebindImports<M>` and runtime `ERR_UNDECLARED_BINDING` enforcement
1481
+ * inside `extractRebindImports`.
1482
+ */
1483
+ declaredImportShape;
1143
1484
  _alive = true;
1144
- constructor(id, pool, defaultGlobals) {
1485
+ constructor(id, pool, defaultGlobals, defaultRegistry, declaredImportShape) {
1145
1486
  this.id = id;
1146
1487
  this.pool = pool;
1147
1488
  this.defaultGlobals = defaultGlobals;
1489
+ this.defaultRegistry = defaultRegistry;
1490
+ this.declaredImportShape = declaredImportShape;
1148
1491
  }
1149
1492
  get alive() {
1150
1493
  return this._alive;
@@ -1173,13 +1516,34 @@ var PrefixImpl = class {
1173
1516
  durationMs: 0
1174
1517
  };
1175
1518
  const bridgeGlobals = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
1519
+ let registry;
1520
+ try {
1521
+ registry = extractRebindImports(options.imports, this.defaultRegistry, this.declaredImportShape);
1522
+ } catch (e) {
1523
+ if (e instanceof UndeclaredImportBindingError) return {
1524
+ ok: false,
1525
+ error: {
1526
+ code: "ERR_UNDECLARED_BINDING",
1527
+ name: "Error",
1528
+ message: e.message
1529
+ },
1530
+ stdout: [],
1531
+ stderr: [],
1532
+ durationMs: 0
1533
+ };
1534
+ throw e;
1535
+ }
1536
+ const allGlobals = registry.size > 0 ? {
1537
+ ...bridgeGlobals,
1538
+ [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1539
+ } : bridgeGlobals;
1176
1540
  return this.pool.withClient(async (client) => {
1177
1541
  return decodeRunCompletionPayload((await client.prefixRun({
1178
1542
  prefixId: this.id,
1179
1543
  code: options.code,
1180
1544
  filename: options.filename,
1181
1545
  limits: toWireLimits(options.limits),
1182
- globals: bridgeGlobals
1546
+ globals: allGlobals
1183
1547
  })).result).result;
1184
1548
  });
1185
1549
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
6
6
  "keywords": [
@@ -47,10 +47,10 @@
47
47
  "vitest": "^4.1.5"
48
48
  },
49
49
  "optionalDependencies": {
50
- "@iso4/v8-darwin-arm64": "^0.0.2",
51
- "@iso4/v8-darwin-x64": "^0.0.2",
52
- "@iso4/v8-linux-arm64-gnu": "^0.0.2",
53
- "@iso4/v8-linux-x64-gnu": "^0.0.2"
50
+ "@iso4/v8-darwin-arm64": "^0.0.4",
51
+ "@iso4/v8-darwin-x64": "^0.0.4",
52
+ "@iso4/v8-linux-arm64-gnu": "^0.0.4",
53
+ "@iso4/v8-linux-x64-gnu": "^0.0.4"
54
54
  },
55
55
  "engines": {
56
56
  "node": ">=24.0.0"