[API reference](https://jsprismarine.dev/api/index.md) / @jsprismarine/script-host

# @jsprismarine/script-host

[![Join the Discord Server](https://img.shields.io/discord/704967868885762108?color=%237289DA&label=Discord)](https://discord.gg/kZZCDyCBbW)
[![npm](https://img.shields.io/npm/dt/@jsprismarine/script-host)](https://www.npmjs.com/package/@jsprismarine/script-host)

The engine JSPrismarine runs Bedrock behavior pack scripts in. It holds one native library, Fabrice
Bellard's [QuickJS](https://bellard.org/quickjs/) with a small C layer of our own, and the
TypeScript that binds it through `node:ffi`. Each world will own one engine and run it on its own
thread, as [ADR 0020](https://jsprismarine.dev/adr/0020-scripts-run-in-quickjs-on-the-world-thread.md) decides.
The plan that builds the rest of the script host on top of this package is
[script-api-host.md](https://jsprismarine.dev/plans/script-api-host.md).

This release has the engine, with evaluation, host calls, limits and the sandbox; the shape of the
Script API, every module, class and member of `@minecraft/server` and the other modules, stable and
beta, generated from Mojang's metadata; and the runtime that loads a world's behavior packs and runs
their scripts, with the first members that have behavior.

## Installing

```bash
npm install @jsprismarine/script-host
```

The package holds no native code. Its install script downloads the library's build for the
machine from the project's GitHub releases, checks its SHA-256 against `native/manifest.json`, and
writes it to `prebuilds/<platform>/`. Loading the library downloads nothing. Builds exist for
<!-- fact:scripting.buildPlatforms -->macOS on Apple silicon, Linux on arm64 with glibc, Linux on arm64 with musl, Linux on x64 with glibc, Linux on x64 with musl and Windows on x64<!-- /fact -->.

npm 12, pnpm and Bun run a dependency's install script only once the project approves it. Until
then, loading the library throws a `NativeLibraryError` that names the command for each:
`npm install-scripts approve @jsprismarine/script-host`, `pnpm approve-builds`, or
`trustedDependencies` in Bun's `package.json`. Set `JSP_SCRIPT_HOST_LIBRARY` to a library file to
load it instead; the file must be the published build or a local build. [Building it](#building-it)
covers a local build.

## Running a script

```ts
import { ScriptHostLibrary } from '@jsprismarine/script-host';

const library = ScriptHostLibrary.load();
const engine = library.createEngine({ memoryLimit: 64 * 1024 * 1024 });

try {
    engine.defineGlobalFunction('add', (a, b) => Number(a) + Number(b));
    engine.evaluate('add(1, 2)'); // 3

    engine.setBudget({ perCallback: 1000 });
    engine.evaluate('while (true) {}'); // throws ScriptTerminatedError
} finally {
    engine.destroy();
}
```

An engine runs only on the thread that created it, and every call into it is synchronous. Engines
on different threads share nothing, so two worlds on two worker threads each run their own.

Primitive values cross between TypeScript and a script as copies. Objects and functions stay in
the engine, and the host holds a `ScriptHandle` to each one it receives. A handle that a call
returns belongs to the caller, who frees it with `engine.free`. A handle passed to a host function
lasts until that function returns; `engine.duplicate` makes one that outlives it. A host function
that makes an object to return passes it through `engine.release`, which frees the handle once the
script has the object.

## How it is called

The library has a flat C interface, `native/include/jsp_script_host.h`, with an ABI version the
binding checks when it loads. It passes only integers, doubles and pointers, so the same interface
fits `node:ffi` today and scriptc's FFI later
([ADR 0023](https://jsprismarine.dev/adr/0023-quickjs-through-one-c-layer-and-ffi.md)).

Values cross as bytes in a transfer buffer, a `SharedArrayBuffer` that the engine writes and reads
in place. A host call from a script is one crossing: the engine writes the arguments into the
buffer and calls the engine's one `node:ffi` callback with the host function's id. The callback
runs the TypeScript function on the same thread and writes the result into the same buffer. A host
function may call back into the script it serves. The engine counts host calls and the bytes each
way, which `engine.stats()` reports.

Module imports go through the same callback in two steps. `createEngine({ resolveModule })` names
the module a specifier reaches from the importing module, and the engine loads each name once per
context, so two spellings given one name share a module. QuickJS's own rule, `defaultModuleName`,
applies when it is absent. `createEngine({ loadModule })` then returns a module's source for its
name, or an object whose own enumerable properties become the module's exports.

A world's behavior pack scripts resolve as BDS does: a specifier that starts with `.` is read from
the importing file's folder and any other from the pack's `scripts` folder, and a path that names
no file gains `.js`. So `items/item.handler`, imported from anywhere in the pack, and
`../items/item.handler.js`, imported from `scripts/events/`, are one module.

## Contexts

An engine can hold several contexts, each with a global object and built-ins of its own, so packs
in one world never share a `globalThis` while they share one runtime, one step budget and one
memory limit. `engine.createContext()` makes one, and `engine.inContext(id, run)` runs host code
with it current. While a script calls the host, the caller's context is current, and the module
loader is told which context imports. `engine.runJobs(id)` runs one context's promise jobs and
leaves the other contexts' jobs queued in their order, which the version 1 and version 2
lifecycles need.

## Limits

Every limit counts work, not time, so a script stops at the same point on every machine and in
every replay ([ADR 0021](https://jsprismarine.dev/adr/0021-the-script-watchdog-counts-steps.md)).

- **Steps.** QuickJS polls for interrupts at backward jumps and calls, and calls its interrupt
  handler once every `JS_INTERRUPT_COUNTER_INIT` polls, a constant in `quickjs.c`. Each handler call
  is a step. `engine.setBudget` sets how many
  steps one call from the host may take, counting everything it calls, and how many one tick may
  take, counted from `engine.beginTick()`. The step past a budget throws an error no script can
  catch, and the call throws `ScriptTerminatedError`. Each call from the host counts its steps from
  zero, so earlier calls do not move where a later one stops.
- **Memory.** `memoryLimit` caps the bytes the engine allocates. An allocation past it fails, the
  engine counts the refusal, and an error that reaches the host throws `ScriptOutOfMemoryError`.
- **Stack.** `stackSize` sets the native stack a script may use, `DEFAULT_STACK_SIZE` unless set.
  Past it, the script gets `InternalError: stack overflow`, as on Bedrock Dedicated Server (BDS).
  The engine counts every overflow, including one a script catches, because BDS treats a caught
  overflow as critical too.

The errors the host throws, such as `ScriptError` and `ScriptTerminatedError`, come from
`@jsprismarine/errors/script-host`. Its [error reference](https://jsprismarine.dev/errors/script-host.md) lists
each one's code and cause. `NativeLibraryError`, which every library loading error extends, comes
from `@jsprismarine/errors/native-library`, with
[its own reference](https://jsprismarine.dev/errors/native-library.md).

## The sandbox

A script sees only what the host gives it: no Node.js API, no filesystem and no network. Each new
context also matches the language that BDS's older QuickJS offers. The `globals` scenario of the
parity suite's `scripting.engine` family records that language on the pinned BDS: every global
name, the own keys of every built-in and its prototype, and the errors below. Its row compares the
engine with that record.

- The C layer deletes every global and member listed in `src/absentGlobals.ts`, such as `eval`,
  `Iterator` and its helpers, `Float16Array`, `Atomics`, the newer `Set` methods, resizable
  `ArrayBuffer`, the `Uint8Array` base64 and hex methods and `Map.prototype.getOrInsert`. The list
  holds exactly what the pinned QuickJS defines and BDS lacks. The native build writes it into a C
  header, so the list exists once.
- It adds `Object.__getClass` and `String.prototype.__quote`, which BDS's older QuickJS has.
- `eval` is not defined, so calling it throws `ReferenceError: 'eval' is not defined`.
- `Function`, and the generator and async function constructors, throw
  `TypeError: Function from string is not supported` instead of compiling a string.
- A regular expression with the `v` flag, a modifier group such as `(?i:a)` or a group name used
  twice throws the `SyntaxError` BDS throws, in a literal or through `RegExp`.

## The Script API's shape

The modules a pack imports, such as `@minecraft/server`, are generated rather than written by hand
([ADR 0022](https://jsprismarine.dev/adr/0022-the-script-api-surface-is-generated.md)). `generate:shape` reads
`metadata/script_modules` from the `bedrock-samples` checkout that
`packages/bedrock-data/sources.json` pins, and writes one file per module to
`src/generated/script-modules/`. Each file keeps every version of its module as history, the beta
the pinned metadata ships included, such as `@minecraft/server`
<!-- fact:scripting.serverBeta -->2.12.0-beta<!-- /fact -->. A
class or member is a list of segments, each with the first version it appears in and, once Mojang
removes or changes it, the last. A regeneration after a version bump therefore shows each added,
changed or removed member as its own line in the diff.

```sh
pnpm --filter @jsprismarine/script-host run generate:shape   # fetches the checkout if needed
pnpm --filter @jsprismarine/script-host run check:shape      # fails when src/generated is stale
```

The metadata has gaps, such as the privilege `CustomCommandRegistry.registerCommand`'s callback
runs under. `scripts/shape/overrides.mts` fills them, each with its evidence, and the generator fails
once the metadata records a value of its own, so a stale override cannot linger.

A pack gets the newest stable minor version of the major version it declares, as on Bedrock
Dedicated Server, so a pack that declares 2.0.0 sees every 2.x member the pinned server ships. Beta
versions do not follow semver. With the world's Beta APIs experiment on, a pack that declares a
beta gets it only when it is the one beta the pinned server ships, such as `@minecraft/server`
<!-- fact:scripting.serverBeta -->2.12.0-beta<!-- /fact -->, and the version `beta` names that one.
Any other version, beta or stable, is refused, as an older or newer beta is on BDS. `resolveDependency` does that resolution, and returns BDS's own content
log message when it refuses a module.

```ts
import { ScriptHostLibrary } from '@jsprismarine/script-host';
import { ScriptApiContext } from '@jsprismarine/script-host/shape/binding';
import { ScriptApiImplementations } from '@jsprismarine/script-host/shape/implementations';
import { resolveDependency } from '@jsprismarine/script-host/shape/resolve';

const resolution = resolveDependency(
    { module_name: '@minecraft/server', version: '2.0.0' },
    { pack: { name: 'my pack', version: '1.0.0' }, allowedModules: ['@minecraft/server'] }
);

const implementations = new ScriptApiImplementations().implement(
    '@minecraft/server',
    'World',
    'getDimension',
    (call) => `the ${call.args[0]} dimension`
);
const engine = ScriptHostLibrary.load().createEngine();
const context = new ScriptApiContext(engine, { pack: 'my pack - 1.0.0', implementations, logger: console });
try {
    // A namespace handle. A script's import reaches it only through the engine's `loadModule`.
    if (resolution.ok) context.bind(resolution.shape);
} finally {
    context.destroy();
    engine.destroy();
}
```

`ScriptApiContext` installs a module into a namespace object with every class, enum, constant and
error class the served version has. Every member is present, so `typeof world.sendMessage` and other
feature tests see what they see on BDS. Before anything else runs, a member checks its arguments
against the metadata and throws a `TypeError` or an `ArgumentOutOfBoundsError` worded the way BDS
words them, as the `argument-errors` scenario of the parity suite records them. An instance member
called on an object the host did not make throws BDS's `object bound to prototype does not exist`
error. With a `privilege` option, a member whose metadata does not list the privilege the running
script has, such as early or restricted execution, throws BDS's `cannot be used in` error. Then it calls the implementation registered for its module, class and member. A member with none throws `NotImplementedError`, which names the module, the class
and the member, and the context logs it the first time each pack uses it.

`implement` takes the names the generated `ScriptApiMembers` lists, so a misspelled member does not
compile, and the form a member needs: a function for a method or constructor, `{ get }` for a
read-only property and `{ get, set }` for a writable one. An implementation throws one of the API's
own error classes, such as `LocationInUnloadedChunkError`, by throwing a `ScriptApiError`.

An object the host makes with `context.create(module, className, tag, state)` carries a number and
a string, which every call of its members receives as `call.tag` and `call.state`: an entity's id,
or an item stack's contents. The state lives in the engine for as long as the object does, so the
host keeps no table that a script's garbage would grow. `call.setState` replaces it, and a
constructor's implementation returns the new object's state. A member whose metadata returns plain
data, an interface such as `Vector3` or an array such as `string[]`, returns it as one JSON string,
and the binding parses it inside the engine, so `entity.location` costs one host call.

## The add-on corpus

The order in which members get behavior comes from what real add-ons use. `corpus/packs.json` pins
open-source behavior packs with scripts: each repository by its GitHub URL, a full commit hash, the
sha256 of GitHub's zip of that commit, and its license. Only permissive licenses such as MIT and
Apache-2.0 are accepted, and `scripts/corpus/manifest.mts` lists them. The file also records the
candidates the corpus leaves out and why. The repository holds no copy of any add-on.

```sh
pnpm --filter @jsprismarine/script-host run count:corpus   # fetches what is missing, then counts
pnpm --filter @jsprismarine/script-host run check:corpus   # fails when the counts are stale
```

`count:corpus` downloads each pinned commit into `node_modules/.cache/jsprismarine/addon-corpus/`
through `@jsprismarine/bedrock-data`'s fetch, which checks the digest before unpacking anything, and
reuses the cached copy after that. A commit that no longer exists upstream fails with HTTP 404 and an
error naming the packs it holds. The counter then reads each pack's `manifest.json` for the modules
and versions it declares, and walks its scripts. It writes two files beside the manifest:
`corpus/usage.json`, every pack's uses with one key per line, and `corpus/ranking.md`, the modules,
declarations, events, members and interface fields ordered by how many packs use them, split by
whether the pack declares the module as stable or beta.

The counter reads a TypeScript pack from its TypeScript sources and never runs its build. A build
would mean installing the pack's npm dependencies and running its scripts, and the bundle it makes
mixes the pack's code with the libraries it bundles. The sources also carry type annotations, which
tell the counter what a value is. A pack's `build` field in the manifest says what its build step
would do. Libraries a pack bundles from npm, such as `@minecraft/math`, are not counted.

The counter parses each file with oxc and follows values through the generated shape: from an
import, through property types and method return types, `await`, array elements and destructuring,
into a callback whose parameters the shape types, and from `getComponent('minecraft:inventory')` to
`EntityInventoryComponent`. It counts a member on the class that declares it, so `player.kill()`
counts as `Entity.kill`. A value it cannot follow, such as one passed in from another file, goes
uncounted, so the counts are a lower bound. A member a pack adds to an API type through
`declare module` is the pack's own and is not counted. A beta pack resolves against the beta the
pinned server ships when that beta has the pack's major version, whichever beta the pack names,
since BDS serves only that one. A beta of another major version resolves against the newest
stable version of its own major version.

`scripts/corpus/corpus.test.mts` checks the counts against the corpus when every pinned repository
is already cached, and skips otherwise, so an ordinary test run needs no network. Set
`JSP_ADDON_CORPUS_TESTS=1` to fetch what is missing and run it anyway.

## The debugger

`engine.attachDebugger(listener)` attaches a debugger to an engine. From then on, every function
the engine enters reports each new line, and the engine stops the script at a breakpoint, after a
step, on a pause request, and, when asked, on every value the script throws. A stop calls
`listener.paused(reason)` on the engine's thread, inside the engine call that ran the script, so
that call, and the world tick that made it, stays blocked until the listener returns. Before it
returns, the listener reads the stopped script and calls `resume` with `continue`, `stepOver`,
`stepIn` or `stepOut`.

```ts
import { ScriptHandle } from '@jsprismarine/script-host/values';

const debug = engine.attachDebugger({
    paused(reason) {
        const [top] = debug.frames(); // { name, file, line, column }
        const locals = debug.scope(0, 'local');
        const { properties } = debug.properties(locals);
        try {
            console.log(reason, top, properties);
        } finally {
            // Each object among the values is a handle of its own, as the scope is.
            for (const { value } of properties) if (value instanceof ScriptHandle) engine.free(value);
            engine.free(locals);
        }
        debug.resume('stepOver');
        return 'resume';
    },
    poll() {} // read the debugger's messages without waiting
});
debug.setBreakpoints('main.js', [12]);
```

Nothing reads a clock. A script stops at the same line on every run, a running script calls
`poll` once every `pollLines` lines (`DEFAULT_POLL_LINES` unless set) so a debugger can pause a
loop that never ends, and stopping costs no steps. `evaluate(frame, source)` runs source with
a frame's variables in scope and writes through to them. It gets its own budget of
`JSH_DEBUG_EVALUATE_STEPS` steps, and the stopped script keeps its step counts. `describe` and
`properties` read values without running a getter or a proxy's handler. A replay never attaches
a debugger. Functions already running when a debugger attaches do not report lines, so attach
between calls into the engine.

### The VS Code extension's protocol

`src/debugger/` speaks the protocol of Mojang's Minecraft Bedrock Debugger for VS Code
(`Mojang/minecraft-debugger`), at version `DEBUGGER_PROTOCOL_VERSION`, so the extension attaches
to JSPrismarine as it attaches to Bedrock Dedicated Server (BDS). The work splits across two
threads, because a stopped script blocks the thread its engine runs on, and that thread cannot
read a socket while the extension inspects the script:

- `DebuggerThread` (`./debugger/thread`) starts a worker that owns the sockets. Its `listen`
  waits for the extension (the extension's `connect` mode, `/script debugger listen`) and its
  `connect` reaches one that listens (its `listen` mode, `/script debugger connect`). Both
  default to `DEFAULT_DEBUGGER_PORT`, and each closes the listener and connection the thread
  held before. A listener on an address other than loopback needs a passcode, and refuses to
  start without one with BDS's message. The worker frames each message as its length in 8
  hexadecimal digits, a newline, and the JSON with a newline after it, and it closes a
  connection whose header states a body over `MAX_RECEIVED_FRAME_LENGTH` before the body
  arrives. The worker does not keep the process alive.
- For each connection, the thread's `connected` event hands the starting thread a
  `DebuggerChannelEndpoint`, with the extension's address and port. A `DebuggerChannelBridge`
  in the worker feeds it, and `PortDebuggerChannel` reads it with `receiveMessageOnPort`,
  waiting on a shared counter while a script is stopped, since the engine thread's event loop
  does not run then. The `activity` event follows every message the extension sends and the
  connection's close, so the engine's thread knows when to poll without a timer.
- `ScriptDebugSession` runs on the engine's thread. `offer` sends the protocol event, with the
  passcode requirement and the packs, without waiting, and `handshake` checks the answer:
  it refuses a wrong version, a wrong passcode or an unknown `targetModuleUUID` with BDS's
  messages. A host that must not block on an extension that never answers calls `handshake`
  only once a message has arrived. `attach` takes the engine and the context of the pack the
  extension picked, which `WorldScripts.debugTarget` finds, and handles its breakpoints until
  it sends `resume`. Only that context's scripts stop, so another pack's `scripts/main.js` never
  hits a breakpoint set for this one. While a script is stopped, the session answers
  `stackTrace`, `scopes`, `variables`, `evaluate`, `continue`, `next`, `stepIn`, `stepOut` and
  `pause`, and `poll` handles what arrives between ticks. When the connection closes, at any of
  these points, the session detaches from the engine, so a new debugger can attach.
- The session speaks the rest of the protocol as the pinned BDS does on the wire. A passed
  handshake is followed by a `SchemaEvent` with BDS's diagnostics tabs (`DIAGNOSTICS_TABS`), and
  `stats` sends a tick's `StatEvent2`. `detachEngine` sends `ThreadEvent` `exited` and keeps the
  session open, as BDS does around `/reload`; the next `attach`, to the new engine, sends `new`
  and sets the breakpoints and exception setting again without waiting for another `resume`.
  `detach` sends `terminated` before the session ends, unless the handshake was refused. A
  `minecraftCommand` goes to the `runCommand` option. `startProfiler` and `stopProfiler` record
  the debugged pack's stack at each poll, every `pollLines` lines, and send it back as a
  `ProfilerCapture` holding a `.cpuprofile`, so a script that runs fewer lines between ticks
  than the poll interval leaves no samples.

```ts
import { ScriptDebugSession } from '@jsprismarine/script-host/debugger/DebugSession';
import { PortDebuggerChannel } from '@jsprismarine/script-host/debugger/channel';
import { DebuggerThread } from '@jsprismarine/script-host/debugger/thread';

let session: ScriptDebugSession | undefined;
let attached = false;
const thread = new DebuggerThread({
    connected({ endpoint }) {
        session = new ScriptDebugSession(new PortDebuggerChannel(endpoint), { plugins, passcode });
        session.offer();
    },
    activity() {
        if (session === undefined) return;
        if (attached) {
            session.poll(); // between ticks
            return;
        }
        const target = session.handshake(); // the script module UUID the extension picked
        const picked = target === undefined ? undefined : worldScripts.debugTarget(target);
        if (picked !== undefined) session.attach(picked.engine, picked.context);
        attached = picked !== undefined;
    }
});
await thread.listen({ port: 19144, address: '127.0.0.1', passcode });
// session.detach() and thread.close() for /script debugger close
```

The sketch leaves out what JSPrismarine's world host adds: a peek at the channel, so `handshake`
never waits, BDS's refusal printed to the debug console, and an attach that waits for
`WorldScripts`' `onPackLoaded` when the picked pack has not loaded yet, which is how a debugger
attached at startup stops at a pack's first line, and that keeps the session across `/reload`.
The host does not implement the extension's `debugger-request` or `diagnostics-set-active`
messages yet. It answers a `debugger-request` as refused.

## Running a world's scripts

`WorldScripts` is the script runtime of one world: one engine, a context for each pack, and the
lifecycle, system tasks, events and watchdog around them. It reaches the world only through
`ScriptWorld` (`@jsprismarine/script-host/host/world`), a narrow interface the server implements
with plain data: the dimensions, the players and entities by id, each read in one call, the blocks
and their permutations, the item types, commands, `sendMessage`, the weather and its guard, the
guard on the players' chat, the changes the world committed, and the clock the tick admitted. The
host imports no world class.

A script's `Entity` or `Block` is a handle: an object whose state names the entity's id or the
block's position, and whose members read the world each time they run. Once an entity is gone,
`isValid` is false, `id` and `typeId` still answer, and its other members throw BDS's
`InvalidEntityError`. A pack gets one object per entity, so `===` compares two. An item stack is a
value the script owns, held in its object's state. A pack's
dynamic properties on the world and on an entity live in the world, keyed by the pack's header
UUID, and a script writes them through `ScriptWorld.setDynamicProperties`; an item stack keeps
its own in its state, keyed by the script module UUID, as BDS keys them on disk. The scripts'
`world.scoreboard` is `ScriptWorld.scoreboard`, which the server shares with `/scoreboard`.
`src/testing/memoryWorld.test-utils.ts` is a `ScriptWorld`
in memory, which counts what the host reads, for tests that bound the world calls a member makes.

```ts
import { readScriptConfig, readScriptPack } from '@jsprismarine/script-host/host/pack';
import { WorldScripts, watchdogSettings } from '@jsprismarine/script-host/host/WorldScripts';

const scripts = new WorldScripts({
    library,
    world, // a ScriptWorld
    packs: directories.map(readScriptPack).filter((pack) => pack !== undefined),
    config: readScriptConfig('config'), // BDS's config/ folder
    log: console,
    server: { version, minecraftVersion, protocolVersion }, // what @jsprismarine/server reports
    randomSeed: () => drawSeed(), // asked once each time the packs load
    watchdog: watchdogSettings({ 'script-watchdog-hang-threshold': '10000' }),
    onShutdown: (reason) => server.stop()
});
scripts.startEarly(); // version 2 packs: top level, promise jobs once, startup
scripts.startWorld(); // version 1 packs, once the world has loaded: top level, worldInitialize
// at the end of every tick, before its change log closes:
scripts.flush();
```

The order of everything matches the pinned BDS, as the `scripting.*` families of the parity suite
record it:

- **Packs.** `readScriptPack` reads a pack's manifest. A pack gets each native module it declares
  at the newest stable minor of the declared major version, when `config/default/permissions.json`
  or `config/<script module uuid>/permissions.json` allows the module, and otherwise logs BDS's
  message and does not load. A beta version loads only when the `betaApis` option says the world
  has the Beta APIs experiment on, as `resolveDependency` describes. For a module or version the
  pinned server does not ship, the runtime logs BDS's `failed to create context` and, once every
  pack of the lifecycle has loaded, `run failed`. A pack declaring `@minecraft/server` 1.x runs the version 1
  lifecycle, any other the version 2 one. Each pack runs in a context of its own. An `import()`
  of a module the manifest does not declare rejects as on BDS, except `@jsprismarine/server`,
  which resolves, so a pack can detect JSPrismarine and fall back on BDS.
- **The flush.** `flush` runs the version 1 promise jobs once, then until nothing is left: the
  version 2 promise jobs, the system tasks due, each followed by version 2 promise jobs, and the
  after-events, each type followed by version 2 promise jobs. A `system.run` that a running task
  queues waits for the next tick, which stops a task that queues itself from running for ever.
- **Privileges.** Top levels of version 2 packs, their first promise jobs and `startup` run in
  early execution, before-events in restricted execution, and the rest with the default
  privilege. A member whose metadata does not list the privilege throws BDS's error.
- **Inputs.** `Math.random` in each context draws from a generator seeded from the load's seed,
  which `randomSeed` gives at the start and at each reload, and the pack's place. `Date` reads
  `ScriptWorld.clock()`. A replay that gives the same seeds and clock runs the same.
- **The watchdog.** A callback that takes more than its step budget stops with an error no script
  catches. `watchdogSettings` converts BDS's millisecond threshold at `STEPS_PER_MILLISECOND`. A
  hang, a stack overflow, even a caught one, and an allocation past the memory limit are critical:
  the runtime logs BDS's lines and, unless `script-watchdog-enable-shutdown` is `false`, stops and
  calls `onShutdown`. Before it shuts down for a hang or a stack overflow, it sends the beta
  `system.beforeEvents.watchdogTerminate`, and a script that cancels it keeps the server and its
  packs running, as on BDS.
- **Chat.** `world.beforeEvents.chatSend`, a beta event, is a guard the runtime adds to the
  world's chat action through `ScriptWorld.guardChat`. It runs in restricted execution while the
  line is sent, and a cancel drops the line before anyone gets it.
- **Coverage.** When a pack loads, the runtime logs how many of the members its scripts name are
  implemented, and which are not.
- **Reload.** `reload` sends `system.beforeEvents.shutdown`, then runs every pack again from its
  top level, as BDS's `/reload` does. `system.currentTick` carries on.
- **Debugging.** `debugTarget` finds the engine and context of a loaded pack by its script module
  UUID. The `onPackLoaded` option names each pack once its context is ready and before its top
  level runs, so a debugger attached there stops at the pack's first line. `reload` replaces the
  engine, so a debugger session detaches from the old one first and attaches to the new one
  when `onPackLoaded` names its pack again.

### Forms

A pack that declares `@minecraft/server-ui` gets `ActionFormData`, `ModalFormData`,
`MessageFormData`, their responses and `uiManager.closeAllForms`, in the version 1 and version 2
shapes and the beta. It also gets the data-driven `CustomForm`, `MessageBox` and four `Observable*`
classes, described under [Data-driven screens](#data-driven-screens). Forms reach the world through
`ScriptWorld.forms`, a `ScriptFormChannel` that sends a player a form, closes a player's forms, and
hands back the answers the input step admitted. A world without one sends no form.

The `scripting.ui` family of the parity suite records each rule below on the pinned BDS, and its
scenarios compare the form JSON a client receives byte for byte.

- **The JSON.** `src/host/formJson.ts` writes what BDS's JSON writer writes: keys in byte order,
  a newline at the end, only `"`, `\` and control characters escaped, and a slider's 32-bit
  float bounds in BDS's float format, so 0.5 is `0.50` and 0.1 is `0.1000000014901161`. A
  `RawMessage` becomes a `rawtext` list, and one that holds nothing throws BDS's
  `RawMessageError`. A builder call turns its arguments into JSON at once, so a script that
  changes a `RawMessage` afterwards does not change the form.
- **Where the state lives.** A form's parts and a response's data live beside the objects in the
  pack's realm, in a `WeakMap` the host reaches through `src/host/formKit.ts`, so a form a script
  drops goes with it. Reading an argument runs inside the engine, under the watchdog.
- **The answer.** `show()` returns a promise, and the client's answer settles it in the next
  script flush, before its promise jobs run. A cancel reason wins over JSON: 1 is `UserBusy` and
  any other byte `UserClosed`. An action form takes an integer, read as a 32-bit unsigned
  number, or a boolean; a modal form takes a flat list, with `null` read as `undefined` in
  version 2 only; a message form reads `true` as its first button in version 2 and as its
  second in version 1, whose JSON swaps the two buttons. Anything else rejects with
  `FormRejectError` and `MalformedResponse`. An answer for a form the player was not sent, or
  with neither JSON nor a reason, is dropped.
- **Leaving.** A player who leaves rejects each of their open forms with `PlayerQuit`, the
  newest first. `show()` for that player then throws `InvalidEntityError`, and `closeAllForms`
  throws `Error: Invalid Player handle.`. `closeAllForms` closes a player's forms and settles
  none of them.

#### Data-driven screens

A `CustomForm` or `MessageBox` is one property of the client's `minecraft` data store, laid out
as the pinned BDS lays it out, and the screen that reads it. The `data-driven-forms` scenario of
the parity suite records both ends on the pinned BDS: the property and every update the client
receives, and what the scripts see of the client's clicks, writes and closes.

- **The property.** `show()` hands the world a `DataDrivenScreen`: the screen id
  (`minecraft:custom_form` or `minecraft:message_box`), the property's name
  (`custom_form_data_<n>` or `message_box_data_<n>`) and its value. A custom form lists its
  controls under `layout` by index, each with its own fields and a marker such as
  `slider_visible`, and carries `title`, `style_id` and `closeButton`. A message box carries
  `body` and `button1` to `button3`. A `UIRawMessage` is a map, and one without `rawtext` is put
  into a `rawtext` list.
- **Updates.** `setData()` on an observable a shown form binds sends the new value to each path
  it fills, such as `layout[7].value`, through `updateDataDriven`; a `UIRawMessage` travels as its
  JSON text and a newline. A dropdown item's text is copied when the dropdown is built.
- **The client's writes.** A write to a path arrives as a `DataDrivenResponse`. A write to a
  button's or image's `onClick` runs its callback without closing the form, disabled or not; one to
  `button1.onClick` or `button2.onClick` picks a message box button; one to a client-writable
  observable's path sets it when the type fits, tells its subscribers and updates the observable's
  other paths. Any other write is dropped.
- **Closing.** `close()` asks the client to close the screen, and the screen shows until the
  client reports it closed, as `show()` settles only then. A client's `programmaticclose` or
  `programmaticcloseall` settles `ServerClosed`, `clientcanceled` `ClientClosed` and `userbusy`
  `UserBusy`; a message box settles with a `MessageBoxResult` that holds the button the client
  clicked last. `invalidform` rejects with `InvalidFormError`. `uiManager.closeAllForms` leaves
  data-driven screens open.
- **Leaving.** A player who leaves rejects their screens with `PlayerLeftError`, newest first,
  and a form for a player who left throws `InvalidEntityError` from its constructor.
- **A world that cannot show one.** When `showDataDriven` is missing or returns false, `show()`
  settles with `UserBusy`.

### GameTests

A pack that declares `@minecraft/server-gametest` gets `register`, `registerAsync`,
`RegistrationBuilder`, a running test's `Test`, `spawnSimulatedPlayer` and `SimulatedPlayer`.
`WorldScripts.gametest` takes BDS's `/gametest` subcommands: `run <name>`, `runset [tag]`,
`stopall` and `clearall`. BDS has no `runall`; `runset` with no tag runs `suite:default`, which
a test is in only when it says so, and a tag also matches every test of the class it names.

The `gametest` scenario of the parity suite's `scripting.gametest` family records the runner on
the pinned BDS, and `src/host/gametest.ts` follows it:

- **Batches.** The tests that name a batch run first, a batch per name, then the rest as one
  batch. Each batch starts in a script flush, and the next one four ticks after the last test of
  the one before ends.
- **A test.** Starting a batch places each test's structure through
  `ScriptWorld.placeStructure` and calls each test function in registration order. A test whose
  `structures/<namespace>/<name>.mcstructure` no pack has fails without running.
- **Ticks.** In each later flush, before any system task, a running test's due `runAfterDelay`
  callbacks and `idle` promises run, then its `succeedWhen` callbacks, the first of which also
  runs when `succeedWhen` is called. A `succeedWhen` callback that returns without throwing passes
  the test.
- **The end.** `succeed` and `fail` end a test at once, an uncaught error fails it, and a test
  still running `maxTicks` ticks after it started fails with BDS's `Didn't succeed or fail within`
  message. A failed `assert` throws `GameTestError`, which a script may catch. Once a test has
  ended, every `Test` member but `isCompleted` throws `GameTestCompletedError`.
- **Cleanup.** The next flush takes an ended test's simulated players out of the world, and its
  `Test` object stops working. A test that runs out of ticks is cleaned up as it fails.

A simulated player is a player of the world with no client, which the world adds through
`ScriptWorld.simulatedPlayers`. Every `Player` and `Entity` member works on it, and a pack that
declares the module gets a `SimulatedPlayer` object for it. Its `chat`, moves, jumps, looks,
attacks and item uses reach the world as `SimulatedPlayerAction`s, and `simulatedPlayers.tick`
moves it once per flush.

### Custom commands and components

A version 2 pack registers custom commands, command enums and custom components in
`system.beforeEvents.startup`, through the event's `customCommandRegistry`,
`blockComponentRegistry` and `itemComponentRegistry`. A version 1 pack registers components in
`world.beforeEvents.worldInitialize`. `src/host/customContent.ts` checks each registration as BDS
does, and the `custom-commands` and `custom-components` scenarios of the parity suite record BDS's
errors: a name needs a namespace other than `minecraft`, a name registers once, an `Enum`
parameter needs its enum registered first, and a registration outside `startup` throws
`CustomCommandError` or `CustomComponentInvalidRegistryError`. A component's hooks are read when it
registers, and a hook that is not a function throws BDS's conversion error.

- **Commands.** After `startup` the runtime hands the world its commands through
  `ScriptWorld.registerCommands`, with their parameters, permission levels, `cheatsRequired` and
  enums, and logs and leaves out a command whose name has an upper-case letter, as BDS does. The
  world parses a command's arguments and calls the set's `run`, which runs the callback in
  restricted execution with a `CustomCommandOrigin` and the arguments, and answers its
  `CustomCommandResult`. A callback that throws fails the command with the error's message, after
  the content log has it. A reload takes the commands out and registers the new ones.
- **Components.** Once every lifecycle has had its chance to register, the runtime binds a
  `ScriptComponentSink` through `ScriptWorld.bindComponents`. The world names, for each hook, the
  components the block or item names, each with the parameters its pack JSON gives it, and the
  sink runs the hook of every registered component that has it, in that order, with an event of
  the class the pack's own `@minecraft/server` version gives the hook and a
  `CustomComponentParameters`. `beforeOnPlayerPlace` runs at once, in restricted execution, and its
  `cancel` refuses the placement. Every other hook waits for the script flush, where BDS ran it.
  A block that names a component in `minecraft:custom_components` gets no parameters and no
  `onBreak`, as on BDS.

### HTTP requests and server configuration

`@minecraft/server-net` and `@minecraft/server-admin` are beta modules, so a pack that declares
either needs the Beta APIs experiment and a `permissions.json` that allows the module: BDS's
shipped `config/default/permissions.json` lists `@minecraft/server-admin` and leaves
`@minecraft/server-net` out. The `scripting.net` and `scripting.admin` families of the parity suite
record each rule below on the pinned BDS.

- **Requests.** `HttpRequest` and `HttpHeader` keep what a script sets. A request's `headers` is
  one list per request, filled again with new `HttpHeader`s on each read, so a list read earlier
  grows with `addHeader`. `http.get` and `http.request` hand the request to the world's
  `ScriptHttpChannel` (`ScriptWorld.http`) and return a promise. A URI whose scheme is not `http`
  or `https` rejects with `MalformedUriError` and reaches no network, and `cancelAll` rejects every
  request the pack has in flight with a plain `Error` of its reason.
- **Responses are inputs.** The network runs off the tick. Its result enters the world through the
  input step, which records it, and settles the request in the next script flush, before its
  promise jobs run ([ADR 0021](https://jsprismarine.dev/adr/0021-the-script-watchdog-counts-steps.md)). A replay
  admits the recorded results in the same ticks, so it settles the same promises the same way
  without the network. A failure rejects with `InternalHttpRequestError` and the code BDS's HTTP
  client gives it, such as 111 for a refused connection or `E_FAIL` for a timeout.
- **Variables and secrets.** `variables` and `secrets` read the pack's `variables.json` and
  `secrets.json`. `variables.get` returns a copy, its object keys in byte order. `secrets.get`
  returns a new `SecretString` each time, which a script cannot read; only a request header sends
  its text. A secret that is not a string is dropped with BDS's warning.
- **Transfers.** `transferPlayer` takes a player and either a hostname with a port or a NetherNet
  id, and hands it to `ScriptWorld.transferPlayer`.

### Debug shapes

`@minecraft/debug-utilities` is a beta module that BDS's shipped `permissions.json` allows. Its
shapes and `debugDrawer` have behavior; the `scripting.debug` family of the parity suite records
each rule below on the pinned BDS.

- **Shapes keep what a script sets.** Each class starts with BDS's defaults. A float property keeps
  what a 32-bit float keeps, so `scale = 1.1` reads back `1.100000023841858`, and an integer
  property drops its fraction. A `DimensionLocation` sets the shape's `dimension`, and a
  `RawMessage` text reads back inside `rawtext`.
- **The drawer.** `addShape`, `removeShape`, `removeAll` and a shape's `remove` decide which shapes
  the pack draws. At the end of each script flush the drawer hands `ScriptWorld.drawDebugShapes`
  the shapes that are new or changed and the ones that went, so a world sends a shape again only
  when the script changed it. A dimension given to `addShape` draws the shape there without
  becoming its `dimension`, as on BDS. A reload removes every shape the old runtime drew.
- **Time left counts in ticks.** The drawer's step takes 0.05 seconds off each drawn shape's
  `timeLeft`, and drops the shape once it reaches 0. A shape taken out loses that tick's time too.
  BDS takes off the frame's elapsed time instead, which depends on its load, so the scenario
  records which way each count moves rather than its values.
- **Not implemented.** `collectRuntimeStats` and `collectPluginStats` would read the engine's
  memory, which differs from BDS's and from one build to the next, and the diagnostics classes
  send stats to a client JSPrismarine does not have. They throw `NotImplementedError`.
  `disableWatchdogTimingWarnings` does nothing, as the watchdog counts steps and never warns about
  time.

`@minecraft/diagnostics` and `@minecraft/server-graphics` are served with no behavior, and BDS's
shipped `permissions.json` allows neither.

## Building it

In a checkout, `pnpm install` runs the install script too, and downloads the published build while
the native sources match the manifest. After a change to them, build the library for this machine:

```bash
pnpm --filter @jsprismarine/script-host run build:native
```

The build needs a C compiler, `tar` that reads `.tar.xz`, and `git`. The compiler is `cc` on Linux
and macOS and MinGW-w64's `gcc` on Windows, unless `CC` names another. Bellard's QuickJS includes
`<sys/time.h>` and uses pthreads, so MSVC cannot build it. The script downloads the QuickJS release
that `native/sources.json` pins into `node_modules/.cache/jsprismarine/script-host`, checks its
SHA-256, applies the patches in `native/patches/`, and compiles QuickJS with `native/src/engine.c`
into one shared library that exports only the `jsh_` interface. It writes the library to
`prebuilds/<platform>/` with a `build.json` that records its digest, and the binding accepts that
digest as well as the published one.

The native sources' hash, from `src/nativeHash.ts`, names a set of builds. The Script host workflow
builds every platform in CI, on Debian 12 for a glibc floor of 2.36 and on Alpine for musl, loads
each build, fails one that needs a library a bare machine lacks, runs this package's tests against
the builds, and installs the packed package from an npm project. When a push to `master` changes
the native sources, it attaches the builds to a GitHub release named for the hash and opens a pull
request that points the manifest at them. Until that merges, every CI job that installs the
repository builds its own library, or restores the one built for the same sources from the cache.

## The QuickJS patch

The patch adds these functions to QuickJS. Nothing in QuickJS behaves differently until the C layer
calls one:

- `JS_DisableFunctionFromString`, which makes the four `Function` constructors throw instead of
  compiling a string.
- `JS_GetStackOverflowCount`, which counts the stack overflows a runtime throws, caught or not.
- `JS_ResetInterruptCounter`, which restarts the count of polls until the next interrupt handler
  call, so each call from the host counts its steps from zero.
- `JS_DisableNewRegExpSyntax`, which makes the regular expression compiler refuse the `v` flag,
  modifier groups and a group name used twice, as releases before them did.
- `JS_AddLegacyMembers`, which defines `Object.__getClass` and `String.prototype.__quote` as
  earlier releases defined them.
- `JS_ExecutePendingJobOf`, which runs the first pending promise job of one context and leaves the
  jobs of the others queued.

`native/patches/quickjs-debugger.patch` ports the debugger hooks of koush's QuickJS fork
(`koush/quickjs`, `quickjs-debugger.c` and its `quickjs.c` changes), which the VS Code extension's
protocol was written against. As koush's does, the interpreter keeps a second dispatch table whose
entries call the debugger before each instruction. A function uses it only when a line hook is
set as it starts, so with no debugger attached every instruction runs the usual table and does
no extra work. The patch adds:

- `JS_SetDebugHooks`, which sets a line hook and a throw hook. The line hook runs before the first
  instruction of each line, when a loop jumps back, and when a call returns to a line partway
  through. The throw hook runs once for each thrown value, before any handler.
- `JS_GetDebugStackDepth` and `JS_GetDebugFrame`, the stack with each frame's function, file,
  line and column.
- `JS_GetDebugLocals` and `JS_GetDebugClosure`, a frame's variables.
- `JS_DebugEvaluate`, which compiles source as a direct `eval` inside a frame with all of the
  frame's variables in scope. A variable no closure captures has no reference in its frame, so
  the evaluation borrows the variable's slot and leaves any closure it made with a copy.
- `JS_GetDebugClassName`, an object's class name without running script.

`native/patches/quickjs-backtrace-oom.patch` fixes a use-after-free in QuickJS. When a script
runs out of memory, the interpreter adds the stack to the error it throws, and the string for the
stack can be the allocation that fails. That failure throws a new error, which frees the one the
stack was for, and the stack was then written to freed memory. The patch keeps a reference to the
error until its stack is set, and leaves the stack `null` when its string cannot be made. The
memory limit is hit at a different allocation on each C library, and Windows's was this one.

## Modules
