@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 CHANGED
@@ -70,7 +70,7 @@ await sandbox.dispose()
70
70
 
71
71
  ## How globals work
72
72
 
73
- `globals` wires any non-reserved identifier directly into the sandbox's global
73
+ `globals` wires any non-reserved name directly into the sandbox's global
74
74
  object as a bridge stub. The bridge is fully generic — `fetch` is not
75
75
  special-cased:
76
76
 
@@ -88,16 +88,43 @@ const options = {
88
88
  Functions in bridge return values are currently dropped — return plain data,
89
89
  not class instances with methods.
90
90
 
91
- Global names must be usable by bare name: iso4 refuses one that is not a
92
- JavaScript identifier (`my-tool`) or is a reserved word (`class`, `true`)
93
- with `ERR_INVALID_GLOBAL_NAME`. Unicode identifiers (`café`) and `eval` and
94
- `arguments` are allowed.
91
+ A global name can be any well-formed string the runtime does not reserve.
92
+ One that is not a JavaScript identifier
93
+ (`my-tool`, `user.lookup`) or is a reserved word (`class`) is reachable only
94
+ as `globalThis['my-tool']`, not by bare name.
95
95
 
96
- `SANDBOX_GLOBALS` is a `Set` of every name a fresh sandbox already defines.
97
- Check generated names against it before installing them. `RESERVED_WORDS`
98
- is a `Set` of names that cannot be a binding in module source, such as
99
- `class` or `eval`; iso4 refuses host-module export names in it, and global
100
- names in it other than `eval` and `arguments`.
96
+ `@iso4/sandbox/utils` exports the name rules. `SANDBOX_GLOBALS` is a `Set`
97
+ of every name a fresh sandbox already defines. Check generated names against
98
+ it before installing them. `RESERVED_WORDS` is a `Set` of names that cannot be
99
+ a binding in module source, such as `class` or `eval`; iso4 refuses
100
+ host-module export names in it, except `default`.
101
+
102
+ To check generated names before `prepare()` instead of getting a failed
103
+ setup back, import the predicates from `@iso4/sandbox/utils`. That entry
104
+ never loads the client or the native binary:
105
+
106
+ ```ts
107
+ import { isValidExportName, isValidGlobalName } from '@iso4/sandbox/utils'
108
+
109
+ for (const name of Object.keys(tools)) {
110
+ if (!isValidExportName(name))
111
+ throw new Error(`'${name}' cannot be a host-module export`)
112
+ }
113
+ if (!isValidGlobalName(globalName))
114
+ throw new Error(`'${globalName}' cannot be a host global`)
115
+ ```
116
+
117
+ `isValidExportName` answers whether a string can be a key of a host-module
118
+ object in `imports`: an identifier per `IDENTIFIER_NAME` (Unicode included,
119
+ so `café` is fine) that is not in `RESERVED_WORDS`, or `default`, which maps
120
+ to the module's default export. `default` cannot be written as
121
+ `export const default` in generated source. `isValidGlobalName` is the check `prepare()` and
122
+ `run()` apply to host global names: any well-formed string except the
123
+ runtime-owned names (`console`, `Response`, `NaN`, …), a copy of the
124
+ runtime's list that a test checks against the runtime. Names starting with
125
+ `__iso4_` are iso4's internal namespace (the dispatcher, shim handlers): a
126
+ host global there may be silently overwritten or dropped, and
127
+ `isValidGlobalName` does not flag it.
101
128
 
102
129
  ## TypeScript-checked rebinding
103
130
 
@@ -391,9 +418,41 @@ interface RunError {
391
418
  }
392
419
  ```
393
420
 
394
- `run()` never throws for sandboxed failures — only for infrastructure errors
395
- (subprocess crashed, binary not found). `ok: false` with an error code is the
396
- normal failure path.
421
+ `run()` never throws for sandboxed failures. `ok: false` with an error code is
422
+ the normal failure path. It throws only for infrastructure errors (subprocess
423
+ crashed, binary not found) and for invalid options, the same way `prepare()`
424
+ does. `sandbox.run()`, `prefix.run()` and `prefix.call()` reject with an
425
+ `Error` whose `code` is a `SetupErrorCode`: `ERR_RESERVED_NAME` (a global
426
+ name the runtime owns), `ERR_UNDECLARED_BINDING`, `ERR_FROZEN_BINDING` or
427
+ `ERR_INVALID_REBIND` (a rebind the prefix does not allow), or
428
+ `ERR_PREFIX_DISPOSED`. The client checks these before anything is sent, and
429
+ the runtime repeats the checks. A malformed option, such as a limit out of range or a
430
+ global name that is not a well-formed string, rejects with a plain
431
+ `TypeError`. Nothing ran, so retrying with the same options can never
432
+ succeed. Every other code, including `ERR_COMPILE`, is a
433
+ result.
434
+
435
+ ```ts
436
+ import type { SetupErrorCode } from '@iso4/sandbox'
437
+
438
+ const setupCodes: readonly string[] = [
439
+ 'ERR_RESERVED_NAME',
440
+ 'ERR_UNDECLARED_BINDING',
441
+ 'ERR_FROZEN_BINDING',
442
+ 'ERR_INVALID_REBIND',
443
+ 'ERR_PREFIX_DISPOSED',
444
+ ] satisfies SetupErrorCode[]
445
+
446
+ try {
447
+ const result = await sandbox.run({ code, globals })
448
+ if (!result.ok)
449
+ console.log('the program failed:', result.error.code)
450
+ } catch (error) {
451
+ if (!(error instanceof Error && 'code' in error && setupCodes.includes(error.code as string)))
452
+ throw error
453
+ console.log('the options are wrong:', error.code as SetupErrorCode)
454
+ }
455
+ ```
397
456
 
398
457
  One code is about a _neighbor_, not your own run: `ERR_INSTANCE_RESET` means a
399
458
  run sharing the same warm instance had to be terminated mid-execution
package/dist/index.d.mts CHANGED
@@ -12,18 +12,6 @@
12
12
  * parallel. See DESIGN.md §1 and §13.
13
13
  */
14
14
  /**
15
- * Per-run resource caps. Every field is optional at the call site
16
- * (`limits?: ResourceLimits`): pass only the limits you want to
17
- * override. The client sends just those over the wire and the **runtime owns
18
- * the defaults** — it fills in any field you leave unset. The `@default` values
19
- * documented below mirror the runtime's defaults (defined in
20
- * `native/v8-runtime/src/ipc.rs`, the source of truth); if they ever drift, the
21
- * runtime wins.
22
- *
23
- * A field set to `0` is not the same as leaving it unset: `0` explicitly
24
- * disables that limit, whereas unset yields the runtime default.
25
- */
26
- /**
27
15
  * The two heap lines a REUSED isolate is held to, when the managed default
28
16
  * is not what you want. One-off `run()` isolates are never reused and take a
29
17
  * plain `memoryMb` number, enforced exactly.
@@ -78,6 +66,22 @@ interface OneOffResourceLimits extends ResourceLimits {
78
66
  */
79
67
  memoryMb?: number;
80
68
  }
69
+ /**
70
+ * Per-run resource caps. Every field is optional at the call site
71
+ * (`limits?: ResourceLimits`): pass only the limits you want to
72
+ * override. The client sends just those over the wire and the **runtime owns
73
+ * the defaults** — it fills in any field you leave unset. The `@default` values
74
+ * documented below mirror the runtime's defaults (defined in
75
+ * `native/v8-runtime/src/ipc.rs`, the source of truth); if they ever drift, the
76
+ * runtime wins.
77
+ *
78
+ * A field set to `0` is not the same as leaving it unset: `0` explicitly
79
+ * disables that limit, whereas unset yields the runtime default.
80
+ *
81
+ * Every field must be an integer from `0` to `2³² − 1`. Anything else
82
+ * (negative, fractional, `NaN`, `Infinity`, a non-number) rejects the call
83
+ * with a `TypeError` before anything runs.
84
+ */
81
85
  interface ResourceLimits {
82
86
  /**
83
87
  * Maximum CPU time in milliseconds — what the run's own thread actually
@@ -161,24 +165,29 @@ interface ResourceLimits {
161
165
  graceMs?: number;
162
166
  }
163
167
  /**
164
- * Host-provided globals. Any name not reserved by the runtime that sandbox
165
- * code can reference by bare name is permitted. Each value becomes a bridge
166
- * stub in the sandbox global object.
168
+ * Host-provided globals. Any string not reserved by the runtime is permitted
169
+ * as a name. Each value becomes a property of the sandbox's `globalThis`.
167
170
  *
168
171
  * Reserved names (rejected with `ERR_RESERVED_NAME`): `console`,
169
172
  * `waitUntil`, `setTimeout`, `clearTimeout`, `Headers`, `Request`,
170
- * `Response`, `TextEncoder`, `TextDecoder`, `URL`, `URLSearchParams`. These
171
- * are owned by the runtime; shadowing `Response` would silently break
172
- * serialization.
173
+ * `Response`, `TextEncoder`, `TextDecoder`, `URL`, `URLSearchParams`, plus
174
+ * `NaN`, `undefined`, `Infinity` and `__proto__`. The first are owned by the
175
+ * runtime; shadowing `Response` would silently break serialization. `NaN`,
176
+ * `undefined` and `Infinity` are non-writable on the global object, so a host
177
+ * global could never take effect; assigning `__proto__` replaces a prototype
178
+ * instead of creating a property.
173
179
  *
174
- * A name sandbox code cannot reference by bare name is rejected with
175
- * `ERR_INVALID_GLOBAL_NAME`: one that is not a JavaScript identifier
176
- * (`my-tool`, `1abc`; Unicode identifiers such as `café` are fine), or one in
177
- * {@link RESERVED_WORDS} other than `eval` and `arguments`. Keys nested inside
178
- * a global's value are unrestricted.
180
+ * A name that is not a JavaScript identifier (`my-tool`, `user.lookup`), or
181
+ * is in `RESERVED_WORDS` other than `eval` and `arguments`, is
182
+ * reachable only as `globalThis[name]`, not by bare name. A name that is
183
+ * not a well-formed string (`'y\uD800'`) throws a `TypeError` before
184
+ * anything is sent. Names starting with `__iso4_` are iso4's internal
185
+ * namespace (the dispatcher, shim handlers): a host global there may be
186
+ * silently overwritten or dropped, and `isValidGlobalName` does not flag it.
179
187
  *
180
- * {@link SANDBOX_GLOBALS} holds every name a fresh sandbox defines, V8
181
- * built-ins included.
188
+ * `SANDBOX_GLOBALS` holds every name a fresh sandbox defines, V8 built-ins
189
+ * included. Both sets and `isValidGlobalName`, which checks a name before
190
+ * `prepare()`, come from `@iso4/sandbox/utils`.
182
191
  *
183
192
  * Common usage:
184
193
  * ```ts
@@ -357,7 +366,9 @@ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H>
357
366
  type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string | DataGlobal | StringGlobal ? never : K]?: RebindValue<G[K]> };
358
367
  /**
359
368
  * Top-level `imports` shape. Keys are import specifiers; values are either
360
- * a source string or a host-module description object.
369
+ * a source string or a host-module description object. A specifier that is
370
+ * not a well-formed string (`'x\uD800'`) throws a `TypeError` before
371
+ * anything is sent.
361
372
  *
362
373
  * `M` is the literal shape of the map. `precompile()` infers it from the
363
374
  * object literal so the declared specifiers and their value shapes flow
@@ -703,6 +714,14 @@ interface Sandbox {
703
714
  * call: { export: 'default.fetch', args: [request] },
704
715
  * })
705
716
  * ```
717
+ *
718
+ * Invalid options reject, like `prepare()`: a global name the runtime owns
719
+ * rejects with an `Error` whose `code` is `ERR_RESERVED_NAME`; a malformed
720
+ * option (a bad limit or `memoryMb`, a global name that is not a
721
+ * well-formed string, an invalid host-module shape) rejects with a plain
722
+ * `Error`/`TypeError`.
723
+ * Nothing ran. Everything that happens once the run starts resolves as
724
+ * `{ ok: false, error }` — see {@link RunErrorCode}.
706
725
  */
707
726
  run: {
708
727
  (options: RunCallOptions): Promise<CallResult>;
@@ -908,8 +927,8 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
908
927
  * `G` is the declared-globals shape from the matching `precompile()` call.
909
928
  * The `globals` field is typed as `Partial<G>` — only names present in `G`
910
929
  * may be overridden. Passing any other name is a TypeScript error at compile
911
- * time and `ERR_UNDECLARED_BINDING` at runtime (`ERR_INVALID_GLOBAL_NAME`
912
- * first, for a name sandbox code cannot reference by bare name).
930
+ * time and rejects with `ERR_UNDECLARED_BINDING` at runtime. Every rebind
931
+ * refusal rejects; nothing runs.
913
932
  */
914
933
  interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
915
934
  /**
@@ -919,8 +938,8 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
919
938
  /**
920
939
  * Override implementations for a **subset** of globals declared at
921
940
  * precompile time. Only names present in `G` are accepted (TypeScript
922
- * error + runtime `ERR_UNDECLARED_BINDING` for anything else, or
923
- * `ERR_INVALID_GLOBAL_NAME` for a name unusable by bare name), but the
941
+ * error + a runtime rejection with `ERR_UNDECLARED_BINDING` for anything
942
+ * else), but the
924
943
  * function signature does not need to match the precompile-time handler
925
944
  * exactly — any `HostExportFunction`-compatible value is accepted.
926
945
  */
@@ -930,7 +949,7 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
930
949
  * Source module imports are frozen at prepare() time and cannot be rebound;
931
950
  * data exports are baked into the synthetic module. TypeScript enforces
932
951
  * this at the type level via `RebindImports<M>`; anything that slips
933
- * through is rejected at runtime — `ERR_UNDECLARED_BINDING` for locations
952
+ * through rejects the run at runtime — `ERR_UNDECLARED_BINDING` for locations
934
953
  * never declared, `ERR_FROZEN_BINDING` for source modules and data leaves,
935
954
  * `ERR_INVALID_REBIND` for a non-function override value.
936
955
  */
@@ -1473,28 +1492,24 @@ interface RunError {
1473
1492
  * `RunError.resetCause`.
1474
1493
  */
1475
1494
  type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1476
- type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_INVALID_GLOBAL_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1477
- //#endregion
1478
- //#region src/globals.d.ts
1479
1495
  /**
1480
- * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1481
- * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1482
- * A host global under one of these names replaces the built-in, or is
1483
- * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1484
- * forbids outright are in {@link RESERVED_WORDS}.
1496
+ * Why a run's options were refused before anything ran. `sandbox.run()`,
1497
+ * `prefix.run()`, `prefix.call()` and `prepare()` reject with an `Error`
1498
+ * whose `code` is one of these; a run never returns them as a result. The
1499
+ * client checks first and throws without a runtime round trip; the runtime
1500
+ * repeats every check (except `ERR_INVALID_REBIND`) and the client throws its
1501
+ * answer the same way. `ERR_PREFIX_DISPOSED`: the prefix was disposed, or the
1502
+ * runtime no longer holds it.
1485
1503
  */
1486
- declare const SANDBOX_GLOBALS: ReadonlySet<string>;
1504
+ type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
1487
1505
  /**
1488
- * Every name that cannot be a binding in module source, so it cannot be a
1489
- * host-module export name. As host global names, all but `eval` and
1490
- * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1491
- * included, though iso4 itself accepts it as a host-module export (emitted as
1492
- * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1493
- * are taken, these are names the grammar forbids.
1506
+ * Why a run failed, in a `{ ok: false }` result. Setup refusals are thrown
1507
+ * instead and carry a {@link SetupErrorCode}. `prepare()` and
1508
+ * `readExports()` reject on any failure.
1494
1509
  */
1495
- declare const RESERVED_WORDS: ReadonlySet<string>;
1510
+ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1496
1511
  //#endregion
1497
1512
  //#region src/index.d.ts
1498
1513
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1499
1514
  //#endregion
1500
- export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, RESERVED_WORDS, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, SANDBOX_GLOBALS, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };
1515
+ export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type SetupErrorCode, type StringGlobal, type WaitUntilResult, createSandbox };