Skip to content

@bendyline/molen-kernel ​

Molen headless deterministic simulation kernel (no DOM, no three.js).

ts
import { /* … */ } from '@bendyline/molen-kernel';

Classes ​

KernelHost ​

Wires a World + Scheduler to a message link (Worker, MessagePort, or test mock). Commands and control messages come in; keyframes/deltas/events/diag go out. Environment-agnostic: the actual Worker glue (self.onmessage) is a thin wrapper provided by the client/example.

Constructors ​

Constructor ​
ts
new KernelHost(
   world, 
   link, 
   opts?
): KernelHost;
Parameters ​
world ​

World

MessageLink

opts? ​

KernelHostOptions

Returns ​

KernelHost

Methods ​

dispose() ​
ts
dispose(): void;
Returns ​

void

pause() ​
ts
pause(): void;
Returns ​

void

start() ​
ts
start(): void;

Start or resume the scheduler. Initial state is announced by the constructor. Throws if a tick has faulted the world — a resume control message answers with a control-rejected diag rather than pretending to restart a dead simulation.

Returns ​

void

step() ​
ts
step(n?): void;

Manually advance n ticks (used while paused, e.g. by a debugger).

Parameters ​
n? ​

number

Returns ​

void


Scheduler ​

Drives a world at its fixed timestep using a setTimeout accumulator. The world itself is clock-free; all real-time concerns live here. One implementation serves Worker and Node (setTimeout exists in both). Tests inject a clock to avoid flaky real timers.

Constructors ​

Constructor ​
ts
new Scheduler(world, opts?): Scheduler;
Parameters ​
world ​

World

opts? ​

SchedulerOptions

Returns ​

Scheduler

Accessors ​

state ​
Get Signature ​
ts
get state(): "running" | "paused";
Returns ​

"running" | "paused"

Methods ​

pause() ​
ts
pause(): void;
Returns ​

void

setRate() ​
ts
setRate(rate): void;
Parameters ​
rate ​

number

Returns ​

void

start() ​
ts
start(): void;

Start or resume. Refuses a faulted world: a tick that threw leaves the world unable to step (World.step throws on every call after a fault), so silently "resuming" would spin a dead loop. Recovery is explicit — rebuild the world, or restore a keyframe with applyKeyframeTo, which clears the fault — and then call start() again.

Returns ​

void

step() ​
ts
step(n?): void;

Run n ticks synchronously (manual stepping while paused). A failing tick pauses the scheduler and reports through onError like a timer-driven one, then rethrows so the synchronous caller sees it too.

Parameters ​
n? ​

number

Returns ​

void


World ​

The ECS world: component-major storage, version-stamped query cache, deferred structural ops, and a fixed-timestep tick in four phases (commands → update → physics → late).

Snapshot/delta and command machinery attach via the internal accessors at the bottom; they live in sibling modules to keep this file focused on the ECS + tick.

Constructors ​

Constructor ​
ts
new World(opts?): World;
Parameters ​
opts? ​

WorldOptions

Returns ​

World

Properties ​

componentRegistry ​
ts
readonly componentRegistry: ComponentRegistry;
content ​
ts
readonly content: Readonly<ContentIdentity>;

Content this world was built from, by domain; empty when none was declared.

dt ​
ts
readonly dt: number;
tickRate ​
ts
readonly tickRate: number;

Accessors ​

faulted ​
Get Signature ​
ts
get faulted(): Error | undefined;

The error that killed a tick, or undefined for a healthy world. A faulted world refuses to step again: hosts and schedulers check this to report the failure and to refuse a resume until the world is rebuilt or restored from a keyframe (applyKeyframeTo clears it).

Returns ​

Error | undefined

tick ​
Get Signature ​
ts
get tick(): number;
Returns ​

number

Methods ​

addSystem() ​
ts
addSystem(system, opts?): void;
Parameters ​
system ​

System

opts? ​
name? ​

string

phase? ​

Phase

priority? ​

number

Returns ​

void

commandTypes() ​
ts
commandTypes(): string[];

Every declared command type (registration order).

Returns ​

string[]

declareCommand() ​
ts
declareCommand(type, opts?): void;

Declare a command type (optionally with a payload validator) without attaching a handler. Scenes declare their commands this way at build time; scripts and setup modules attach handlers with onCommand/registerCommand.

Parameters ​
type ​

string

opts? ​

DeclareCommandOptions

Returns ​

void

describeSystems() ​
ts
describeSystems(): SystemInfo[];
Returns ​

SystemInfo[]

destroy() ​
ts
destroy(id): void;
Parameters ​
id ​

string

Returns ​

void

emit() ​
ts
emit(type, payload): void;
Parameters ​
type ​

string

payload ​

JsonValue

Returns ​

void

exists() ​
ts
exists(id): boolean;
Parameters ​
id ​

string

Returns ​

boolean

get() ​
ts
get<T>(id, c): Readonly<T> | undefined;

Returns the stored object itself (frozen in dev). See the aliasing rule on WorldOptions.

Type Parameters ​
T ​

T extends JsonObject

Parameters ​
id ​

string

c ​

ComponentType&lt;T&gt;

Returns ​

Readonly&lt;T&gt; | undefined

has() ​
ts
has(id, c): boolean;
Parameters ​
id ​

string

c ​

ComponentType&lt;JsonObject&gt;

Returns ​

boolean

hasCommand() ​
ts
hasCommand(type): boolean;
Parameters ​
type ​

string

Returns ​

boolean

on() ​
ts
on(event, handler): Unsubscribe;
Parameters ​
event ​

string

handler ​

EventHandler

Returns ​

Unsubscribe

onCommand() ​
ts
onCommand(type, handler): Unsubscribe;

Attach a handler for a command type (declaring it if needed). Returns a remover.

Parameters ​
type ​

string

handler ​

CommandHandler&lt;World&gt;

Returns ​

Unsubscribe

patch() ​
ts
patch<T>(
   id, 
   c, 
   partial
): void;
Type Parameters ​
T ​

T extends JsonObject

Parameters ​
id ​

string

c ​

ComponentType&lt;T&gt;

partial ​

Partial&lt;T&gt;

Returns ​

void

query() ​
Call Signature ​
ts
query<A>(a): QueryResult<[A]>;
Type Parameters ​
A ​

A extends JsonObject

Parameters ​
a ​

ComponentType&lt;A&gt;

Returns ​

QueryResult&lt;[A]&gt;

Call Signature ​
ts
query<A, B>(a, b): QueryResult<[A, B]>;
Type Parameters ​
A ​

A extends JsonObject

B ​

B extends JsonObject

Parameters ​
a ​

ComponentType&lt;A&gt;

b ​

ComponentType&lt;B&gt;

Returns ​

QueryResult&lt;[A, B]&gt;

Call Signature ​
ts
query<A, B, C>(
   a, 
   b, 
   c
): QueryResult<[A, B, C]>;
Type Parameters ​
A ​

A extends JsonObject

B ​

B extends JsonObject

C ​

C extends JsonObject

Parameters ​
a ​

ComponentType&lt;A&gt;

b ​

ComponentType&lt;B&gt;

c ​

ComponentType&lt;C&gt;

Returns ​

QueryResult&lt;[A, B, C]&gt;

Call Signature ​
ts
query<A, B, C, D>(
   a, 
   b, 
   c, 
   d
): QueryResult<[A, B, C, D]>;
Type Parameters ​
A ​

A extends JsonObject

B ​

B extends JsonObject

C ​

C extends JsonObject

D ​

D extends JsonObject

Parameters ​
a ​

ComponentType&lt;A&gt;

b ​

ComponentType&lt;B&gt;

c ​

ComponentType&lt;C&gt;

d ​

ComponentType&lt;D&gt;

Returns ​

QueryResult&lt;[A, B, C, D]&gt;

registerCommand() ​
ts
registerCommand(
   type, 
   handler, 
   opts?
): void;

Register a handler (and optional payload validator) for a command type. A type may carry many handlers (setup module + scripts); they run in registration order.

Parameters ​
type ​

string

handler ​

CommandHandler&lt;World&gt;

opts? ​

Omit&lt;CommandTypeDef&lt;World&gt;, "handler"&gt;

Returns ​

void

registerSnapshotProvider() ​
ts
registerSnapshotProvider(
   name, 
   save, 
   load
): void;

Register an opaque snapshot provider (e.g. a physics plugin). save is captured into keyframe.plugins[name]; load restores from it. Lets plugins persist state the legible ECS mirror can't (solver warm-start, sleeping flags) for bit-exact resume.

Parameters ​
name ​

string

save ​

() => JsonValue

load ​

(v) => void

Returns ​

void

remove() ​
ts
remove(id, c): void;
Parameters ​
id ​

string

c ​

ComponentType&lt;JsonObject&gt;

Returns ​

void

removeSystem() ​
ts
removeSystem(name): boolean;

Remove a registered system by name (a capability's dispose path). A removal during a tick takes effect from the next tick (the running tick iterates a snapshot). Returns whether a system was removed.

Parameters ​
name ​

string

Returns ​

boolean

set() ​
ts
set<T>(
   id, 
   c, 
   data
): void;
Type Parameters ​
T ​

T extends JsonObject

Parameters ​
id ​

string

c ​

ComponentType&lt;T&gt;

data ​

T

Returns ​

void

spawn() ​
ts
spawn(components, opts?): string;

spawnRaw plus the two conveniences: component defaults (registered via defineComponent) deep-merged UNDER the authored data, and shape validation against the schema component registry (on by default in devFreeze worlds). Both apply per component PRESENT in the map — spawn never adds a component you did not ask for.

Parameters ​
components ​

ComponentMap

opts? ​
id? ​

string

validate? ​

boolean

Returns ​

string

spawnRaw() ​
ts
spawnRaw(components, id?): string;

spawn without the conveniences: no component defaults, no shape validation. The hot path — snapshot restore and bulk spawners use it — and the terse one, so it is what most tests and scripts reach for. Prefer spawn when the components come from data you did not author, and see it for what the conveniences are. If id is omitted, a runtime id ("e"+seq) is allocated.

Parameters ​
components ​

ComponentMap

id? ​

string

Returns ​

string

step() ​
ts
step(): void;

Advance exactly one tick, synchronously. Clock-free (no Date/performance access).

Returns ​

void

stepN() ​
ts
stepN(n): void;
Parameters ​
n ​

number

Returns ​

void

submitCommand() ​
ts
submitCommand(command): SubmitResult;

Validate and enqueue a command. Invalid commands never queue and surface a command-rejected event carrying (source, seq) and the formatted reason.

Parameters ​
command ​

Command

Returns ​

SubmitResult

unregisterSnapshotProvider() ​
ts
unregisterSnapshotProvider(name): boolean;

Remove a snapshot provider (a plugin's dispose path). Returns whether one was removed.

Parameters ​
name ​

string

Returns ​

boolean

Interfaces ​

ApplyKeyframeOptions ​

Properties ​

allowContentDrift? ​
ts
optional allowContentDrift?: boolean;

Load even when the keyframe recorded different content than the world was built from (default false: that is an error naming the domain and both hashes).


AtmosphereSample ​

Properties ​

densityKgM3 ​
ts
densityKgM3: number;
pressurePa ​
ts
pressurePa: number;
relativeHumidity ​
ts
relativeHumidity: number;
temperatureK ​
ts
temperatureK: number;
windVelocity ​
ts
windVelocity: [number, number, number];

AudioMusicPayload ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

crossfadeS? ​
ts
optional crossfadeS?: number;
playlist ​
ts
playlist: string[] | null;

AudioPlayOptions ​

Properties ​

bus? ​
ts
optional bus?: string;
entity? ​
ts
optional entity?: string;

Play at (and follow) this entity's transform.

gain? ​
ts
optional gain?: number;
loop? ​
ts
optional loop?: boolean;

Loop until stop(handle); default the sound's own loop flag.

pitch? ​
ts
optional pitch?: number;
position? ​
ts
optional position?: Vec3;

Play at a fixed world position. Omit both for a non-positional sound.


AudioPlayPayload ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

bus? ​
ts
optional bus?: string;
entity? ​
ts
optional entity?: string;
gain? ​
ts
optional gain?: number;
handle ​
ts
handle: string;
loop? ​
ts
optional loop?: boolean;
pitch? ​
ts
optional pitch?: number;
position? ​
ts
optional position?: Vec3;
sound ​
ts
sound: string;

AudioScriptApi ​

Methods ​

music() ​
ts
music(playlist, opts?): void;

Switch background music to a track or playlist; null stops it. Emits audio.music.

Parameters ​
playlist ​

string | string[] | null

opts? ​
crossfadeS? ​

number

Returns ​

void

play() ​
ts
play(sound, opts?): string;

Play a sound-bank id; returns a handle for stop. Emits audio.play.

Parameters ​
sound ​

string

opts? ​

AudioPlayOptions

Returns ​

string

stop() ​
ts
stop(target, fadeS?): void;

Stop by handle, or every voice matching an entity and/or sound. Emits audio.stop.

Parameters ​
target ​

| string | { entity?: string; sound?: string; }

fadeS? ​

number

Returns ​

void


AudioStopPayload ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

entity? ​
ts
optional entity?: string;
fadeS? ​
ts
optional fadeS?: number;
handle? ​
ts
optional handle?: string;
sound? ​
ts
optional sound?: string;

BuildWorldOptions ​

Extends ​

Extended by ​

Properties ​

capabilities? ​
ts
optional capabilities?: (world, manifest) => Record<string, object> | undefined[];

Capability hooks (figures, vehicles, …), run in order after terrain and before setup. Same contract as physics: each may return script-api extension namespaces.

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

content? ​
ts
optional content?: ContentIdentity;

Which content the world is built from (see ContentIdentity), e.g. a type library's hash. Recorded in keyframes and replays next to the state hash, never inside it.

defaults? ​
ts
optional defaults?: Readonly<Record<string, JsonObject>>;
Inherited from ​

SceneResolveOptions.defaults

devFreeze? ​
ts
optional devFreeze?: boolean;
gameplay? ​
ts
optional gameplay?: boolean;
Inherited from ​

SceneResolveOptions.gameplay

physics? ​
ts
optional physics?: (world, manifest) => Record<string, object> | undefined;

Physics plugin hook (e.g. rapier), run after the data-declared systems and before setup. May return script-api extension namespaces ({ physics: rapierScriptApi(handle) }).

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

registry? ​
ts
optional registry?: ComponentRegistry;
Inherited from ​

SceneResolveOptions.registry

scriptExtensions? ​
ts
optional scriptExtensions?: Record<string, object>;

Extra script-api namespaces merged with whatever the hooks return.

scripts? ​
ts
optional scripts?: boolean;

Install resolved type scripts followed by the manifest's scripts (default true).

terrain? ​
ts
optional terrain?: (world, manifest) => Record<string, object> | undefined;

Terrain ground field hook, run after physics and before setup. Same contract as physics: returns script-api extensions ({ terrain: terrainScriptApi(handle) }).

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

types? ​
ts
optional types?: ResolvedTypes;

Flattened registry types; required when the scene references type ids.

Inherited from ​

SceneResolveOptions.types

validateSpawn? ​
ts
optional validateSpawn?: boolean;

CommandTypeDef ​

Per-type declaration: an optional payload validator (runs after envelope validation).

Type Parameters ​

W ​

W

Properties ​

handler ​
ts
handler: CommandHandler<W>;
validatePayload? ​
ts
optional validatePayload?: (payload) => PayloadCheck;

Optional payload validator (a scene's declared JSON Schema, or hand-written).

Parameters ​
payload ​

JsonValue

Returns ​

PayloadCheck


ComponentType ​

A typed handle over a wire-string component name. Strings on the wire, types in code. defineComponent is metadata only — there is no class instantiation anywhere; components are pure JSON data (the shipped vocabulary is docs-src/schemas/components.md).

Type Parameters ​

T ​

T extends JsonObject

Properties ​

__type? ​
ts
readonly optional __type?: T;

Phantom marker for the component's value type; never present at runtime.

defaults? ​
ts
readonly optional defaults?: () => T;
Returns ​

T

name ​
ts
readonly name: string;

DeclareCommandOptions ​

Properties ​

validatePayload? ​
ts
optional validatePayload?: (payload) => PayloadCheck;
Parameters ​
payload ​

JsonValue

Returns ​

PayloadCheck


DMath ​

Properties ​

PI ​
ts
readonly PI: number;
TAU ​
ts
readonly TAU: number;

Methods ​

abs() ​
ts
abs(x): number;
Parameters ​
x ​

number

Returns ​

number

acos() ​
ts
acos(x): number;
Parameters ​
x ​

number

Returns ​

number

asin() ​
ts
asin(x): number;
Parameters ​
x ​

number

Returns ​

number

atan() ​
ts
atan(x): number;
Parameters ​
x ​

number

Returns ​

number

atan2() ​
ts
atan2(y, x): number;
Parameters ​
y ​

number

x ​

number

Returns ​

number

cbrt() ​
ts
cbrt(x): number;
Parameters ​
x ​

number

Returns ​

number

ceil() ​
ts
ceil(x): number;
Parameters ​
x ​

number

Returns ​

number

clamp() ​
ts
clamp(
   x, 
   lo, 
   hi
): number;
Parameters ​
x ​

number

lo ​

number

hi ​

number

Returns ​

number

cos() ​
ts
cos(x): number;
Parameters ​
x ​

number

Returns ​

number

exp() ​
ts
exp(x): number;
Parameters ​
x ​

number

Returns ​

number

floor() ​
ts
floor(x): number;
Parameters ​
x ​

number

Returns ​

number

frac() ​
ts
frac(x): number;

Fractional part in [0, 1): x - floor(x).

Parameters ​
x ​

number

Returns ​

number

hypot() ​
ts
hypot(
   x, 
   y, 
   z?
): number;
Parameters ​
x ​

number

y ​

number

z? ​

number

Returns ​

number

lerp() ​
ts
lerp(
   a, 
   b, 
   t
): number;

a + (b - a) * t; t is not clamped.

Parameters ​
a ​

number

b ​

number

t ​

number

Returns ​

number

log() ​
ts
log(x): number;
Parameters ​
x ​

number

Returns ​

number

log10() ​
ts
log10(x): number;
Parameters ​
x ​

number

Returns ​

number

log2() ​
ts
log2(x): number;
Parameters ​
x ​

number

Returns ​

number

max() ​
ts
max(a, b): number;
Parameters ​
a ​

number

b ​

number

Returns ​

number

min() ​
ts
min(a, b): number;
Parameters ​
a ​

number

b ​

number

Returns ​

number

pow() ​
ts
pow(x, y): number;
Parameters ​
x ​

number

y ​

number

Returns ​

number

round() ​
ts
round(x): number;
Parameters ​
x ​

number

Returns ​

number

sign() ​
ts
sign(x): number;
Parameters ​
x ​

number

Returns ​

number

sin() ​
ts
sin(x): number;
Parameters ​
x ​

number

Returns ​

number

smoothstep() ​
ts
smoothstep(x): number;

Hermite smoothstep of x clamped to [0, 1].

Parameters ​
x ​

number

Returns ​

number

sqrt() ​
ts
sqrt(x): number;
Parameters ​
x ​

number

Returns ​

number

tan() ​
ts
tan(x): number;
Parameters ​
x ​

number

Returns ​

number

wrapAngle() ​
ts
wrapAngle(a): number;

Wrap an angle (radians) into (-PI, PI].

Parameters ​
a ​

number

Returns ​

number


Experience ​

Properties ​

kind ​
ts
readonly kind: "molen-experience";
setup ​
ts
readonly setup: WorldSetup;

ExperienceDef ​

Properties ​

commands? ​
ts
optional commands?: Record<string, 
  | CommandHandler<World>
| CommandTypeDef<World>>;

Command type -> handler (or handler + payload validator).

setup? ​
ts
optional setup?: WorldSetup;

Imperative escape hatch; runs after commands/systems are registered.

systems? ​
ts
optional systems?: object[];
fn ​
ts
fn: System;
name? ​
ts
optional name?: string;
phase? ​
ts
optional phase?: Phase;

FsmData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

state ​
ts
state: string;
transitions ​
ts
transitions: FsmTransition[];

FsmTransition ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

event ​
ts
event: string;
from ​
ts
from: string;
to ​
ts
to: string;

GameplayOptions ​

Properties ​

fsm? ​
ts
optional fsm?: boolean;
hierarchy? ​
ts
optional hierarchy?: boolean;
lifetime? ​
ts
optional lifetime?: boolean;
timers? ​
ts
optional timers?: boolean;
tweens? ​
ts
optional tweens?: boolean;

HardenScriptsOptions ​

Taming options for hardenScripts: the slice of SES's lockdown() options a kernel host has reason to choose. Anything omitted keeps SES's own default.

Properties ​

errorTaming? ​
ts
optional errorTaming?: "safe" | "unsafe" | "unsafe-debug";

'safe' (SES's default) takes the error.stack accessor away from the whole process, host code included; 'unsafe' keeps stacks readable, which is usually what you want while debugging. Script failures carry the kernel's script "x" tick handler at tick n: … message either way — stacks only affect what the host can log around it.

overrideTaming? ​
ts
optional overrideTaming?: "moderate" | "min" | "severe";

Override-by-assignment mitigation. 'severe' (our default) applies it to every property, the most forgiving setting for ordinary JS that assigns to an inherited property; SES's own default 'moderate' covers the well-known cases and starts faster. A compatibility knob, not a safety one.

stackFiltering? ​
ts
optional stackFiltering?: "concise" | "omit-frames" | "shorten-paths" | "verbose";

How much of a stack tamed error reports keep.


InstallScriptingOptions ​

Properties ​

extensions? ​
ts
optional extensions?: Record<string, object>;

Extra namespaces merged onto molen (deep-frozen for SES hygiene) — how capability packages reach a script without kernel coupling, e.g. { physics: rapierScriptApi(handle) }.

manifest? ​
ts
optional manifest?: SceneManifest;

Manifest enabling molen.spawn(prefabName, components?).

types? ​
ts
optional types?: ResolvedTypes;
validate? ​
ts
optional validate?: boolean;

Validate component shapes on spawn/set against the registry (default true).


JsonObject ​

Extended by ​

Indexable ​

ts
[key: string]: JsonValue | undefined

KernelHostOptions ​

Properties ​

clock? ​
ts
optional clock?: SchedulerClock;
keyframeInterval? ​
ts
optional keyframeInterval?: number;

Ticks between full keyframes (default from the scene's keyframeInterval, else 60).

rate? ​
ts
optional rate?: number;
startPaused? ​
ts
optional startPaused?: boolean;

Start paused; the client sends a resume control message to begin. Default false.


KernelWorker ​

Properties ​

host ​
ts
host: KernelHost;
world ​
ts
world: World;

LifetimeData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

ticksLeft ​
ts
ticksLeft: number;

LoadedProject ​

Properties ​

scene ​
ts
scene: SceneManifest;
types? ​
ts
optional types?: ResolvedTypes;

Present only when types documents were given; spreads straight into buildWorld.


LoadedScript ​

Properties ​

checkpoint? ​
ts
optional checkpoint?: "state";
config? ​
ts
optional config?: JsonObject;
id ​
ts
id: string;
source ​
ts
source: string;

LoadProjectOptions ​

Properties ​

scene ​
ts
scene: unknown;

The scene document as imported JSON. Validated as molen/scene@3.

scripts? ​
ts
optional scripts?: Readonly<Record<string, string>>;

Raw script sources, as a bundler's eager raw glob hands them over: module path to source text. Keys are matched to each script's path by suffix, so the glob's own prefix (../scenes/, ../, wherever the module sits) does not have to be stripped by hand.

types? ​
ts
optional types?: unknown;

Entity type registry documents as imported JSON, one or several. Omit when the scene declares no type refs.


ParentData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

id ​
ts
id: string;
onParentDestroyed? ​
ts
optional onParentDestroyed?: "destroy" | "detach";

QueryResult ​

Extends ​

  • Iterable&lt;[EntityId, ...T]&gt;

Type Parameters ​

T ​

T extends JsonObject[]

Methods ​

count() ​
ts
count(): number;
Returns ​

number

first() ​
ts
first(): [string, ...T[]] | undefined;
Returns ​

[string, ...T[]] | undefined

ids() ​
ts
ids(): readonly string[];
Returns ​

readonly string[]

without() ​
ts
without(...exclude): QueryResult<T>;

The same query, excluding entities that carry ANY of the given components.

Parameters ​
exclude ​

...ComponentType&lt;JsonObject&gt;[]

Returns ​

QueryResult&lt;T&gt;


Rng ​

Methods ​

int() ​
ts
int(n): number;

Next integer in [0, n) for integer n > 0.

Parameters ​
n ​

number

Returns ​

number

next() ​
ts
next(): number;

Next float in [0, 1).

Returns ​

number

range() ​
ts
range(lo, hi): number;

Float in [lo, hi).

Parameters ​
lo ​

number

hi ​

number

Returns ​

number

save() ​
ts
save(): RngState;

Capture state for snapshots.

Returns ​

RngState


SceneResolveOptions ​

Extends ​

  • SceneResolveOptions

Extended by ​

Properties ​

defaults? ​
ts
optional defaults?: Readonly<Record<string, JsonObject>>;
gameplay? ​
ts
optional gameplay?: boolean;
registry? ​
ts
optional registry?: ComponentRegistry;
types? ​
ts
optional types?: ResolvedTypes;

Flattened registry types; required when the scene references type ids.

Inherited from ​
ts
SceneResolveOptions.types

SchedulerClock ​

Methods ​

clearTimer() ​
ts
clearTimer(h): void;
Parameters ​
h ​

number

Returns ​

void

now() ​
ts
now(): number;
Returns ​

number

setTimer() ​
ts
setTimer(cb, ms): number;
Parameters ​
cb ​

() => void

ms ​

number

Returns ​

number


SchedulerOptions ​

Properties ​

clock? ​
ts
optional clock?: SchedulerClock;

Injectable clock for deterministic tests; defaults to Date.now + setTimeout.

maxCatchUpTicks? ​
ts
optional maxCatchUpTicks?: number;

Max ticks to catch up per wake before dropping debt (spiral-of-death guard).

onError? ​
ts
optional onError?: (error, tick) => void;

Called when a tick (or its onTick callback) throws. The scheduler has already paused; the world is faulted and start() will refuse until it is restored. tick is the tick the world was on when it failed.

Parameters ​
error ​

Error

tick ​

number

Returns ​

void

onOverrun? ​
ts
optional onOverrun?: (droppedTicks) => void;

Called when the catch-up cap is hit and ticks are dropped.

Parameters ​
droppedTicks ​

number

Returns ​

void

onTick? ​
ts
optional onTick?: (tick) => void;

Called once per advanced tick (after world.step()).

Parameters ​
tick ​

number

Returns ​

void

rate? ​
ts
optional rate?: number;

Playback rate multiplier; 1 = realtime. The sim tick rate is the world's tickRate.


ScriptAPI ​

The agent-facing verb set (string component names; scripts are text).

Properties ​

audio ​
ts
readonly audio: AudioScriptApi;

Sound: play(sound, { entity | position, gain, pitch, bus, loop }) → handle, stop(handle | { entity, sound }, fadeS?), music(playlist | null). Each emits an audio.* event the client plays; nothing enters the state hash. See guide/audio.md.

dt ​
ts
readonly dt: number;
math ​
ts
readonly math: DMath;
state ​
ts
readonly state: Readonly<JsonObject>;

Immutable script-owned JSON state, captured in checkpoints and preserved on reload.

tick ​
ts
readonly tick: number;

Methods ​

after() ​
ts
after(
   ticks, 
   event, 
   payload?
): string;

Emit event after ticks ticks (snapshot-safe world timer). Returns the timer id.

Parameters ​
ticks ​

number

event ​

string

payload? ​

JsonValue

Returns ​

string

cancelTimer() ​
ts
cancelTimer(timerId, entity?): void;
Parameters ​
timerId ​

string

entity? ​

string

Returns ​

void

cancelTween() ​
ts
cancelTween(entity, tweenId?): void;
Parameters ​
entity ​

string

tweenId? ​

string

Returns ​

void

destroy() ​
ts
destroy(id): void;
Parameters ​
id ​

string

Returns ​

void

emit() ​
ts
emit(type, payload): void;
Parameters ​
type ​

string

payload ​

JsonValue

Returns ​

void

every() ​
ts
every(
   ticks, 
   event, 
   payload?
): string;

Emit event every ticks ticks. Returns the timer id.

Parameters ​
ticks ​

number

event ​

string

payload? ​

JsonValue

Returns ​

string

exists() ​
ts
exists(id): boolean;
Parameters ​
id ​

string

Returns ​

boolean

get() ​
ts
get(id, component): JsonObject | undefined;
Parameters ​
id ​

string

component ​

string

Returns ​

JsonObject | undefined

has() ​
ts
has(id, component): boolean;
Parameters ​
id ​

string

component ​

string

Returns ​

boolean

on() ​
ts
on(event, handler): Unsubscribe;
Parameters ​
event ​

string

handler ​

(payload, ctx) => void

Returns ​

Unsubscribe

onCommand() ​
ts
onCommand(type, handler): Unsubscribe;

Handle a command type (player input, agent actions). The scene declares the type (and its payload schema) under commands; the queue rejects undeclared types and bad payloads before any handler runs. Handlers run in the commands phase, before every system.

Parameters ​
type ​

string

handler ​

(payload, ctx, command) => void

Returns ​

Unsubscribe

overlapCircle() ​
ts
overlapCircle(
   center, 
   radius, 
   mask?
): string[];
Parameters ​
center ​

Vec3

radius ​

number

mask? ​

number

Returns ​

string[]

parent() ​
ts
parent(id, parentId): void;

Parent an entity (keeps its current world pose); the hierarchy system takes over.

Parameters ​
id ​

string

parentId ​

string

Returns ​

void

patch() ​
ts
patch(
   id, 
   component, 
   partial
): void;
Parameters ​
id ​

string

component ​

string

partial ​

JsonObject

Returns ​

void

patchState() ​
ts
patchState(partial): void;
Parameters ​
partial ​

JsonObject

Returns ​

void

query() ​
ts
query(...components): ScriptQuery;

Entities having all named components. The result is iterable (yields [id, ...componentData] tuples) and also exposes .ids(), .count(), .first(), .without(...names).

Parameters ​
components ​

...string[]

Returns ​

ScriptQuery

raycast() ​
ts
raycast(
   origin, 
   dir, 
   maxDist, 
   mask?
): RayHit | null;
Parameters ​
origin ​

Vec3

dir ​

Vec3

maxDist ​

number

mask? ​

number

Returns ​

RayHit | null

remove() ​
ts
remove(id, component): void;
Parameters ​
id ​

string

component ​

string

Returns ​

void

rng() ​
ts
rng(): number;
Returns ​

number

set() ​
ts
set(
   id, 
   component, 
   data
): void;
Parameters ​
id ​

string

component ​

string

data ​

JsonObject

Returns ​

void

setState() ​
ts
setState(data): void;
Parameters ​
data ​

JsonObject

Returns ​

void

spawn() ​
Call Signature ​
ts
spawn(components, id?): string;

Spawn from a component map.

Parameters ​
components ​

Record&lt;string, JsonObject&gt;

id? ​

string

Returns ​

string

Call Signature ​
ts
spawn(
   prefab, 
   components?, 
   id?
): string;

Spawn from a manifest prefab by name, with optional components layered on top.

Parameters ​
prefab ​

string

components? ​

Record&lt;string, JsonObject&gt;

id? ​

string

Returns ​

string

spawnType() ​
ts
spawnType(
   type, 
   components?, 
   id?
): string;

Spawn a project-registry type with optional component overrides.

Parameters ​
type ​

string

components? ​

Record&lt;string, JsonObject&gt;

id? ​

string

Returns ​

string

tween() ​
ts
tween(entity, spec): void;

Start a data-driven tween on an entity (component + path + to + ticks [+ easing/loop]).

Parameters ​
entity ​

string

spec ​

TweenEntry

Returns ​

void

unparent() ​
ts
unparent(id): void;
Parameters ​
id ​

string

Returns ​

void


ScriptHost ​

Properties ​

count ​
ts
readonly count: number;

Number of registered scripts.

Methods ​

reload() ​
ts
reload(id, source): void;

Re-evaluate a script's source in a fresh Compartment (world state survives).

Parameters ​
id ​

string

source ​

string

Returns ​

void


ScriptQuery ​

The string-named query result scripts get (adds string-based .without()).

Extends ​

  • Iterable&lt;[EntityId, ...JsonObject[]]&gt;

Methods ​

count() ​
ts
count(): number;
Returns ​

number

first() ​
ts
first(): [string, ...JsonObject[]] | undefined;
Returns ​

[string, ...JsonObject[]] | undefined

ids() ​
ts
ids(): readonly string[];
Returns ​

readonly string[]

without() ​
ts
without(...components): ScriptQuery;

The same query, excluding entities carrying ANY of the named components.

Parameters ​
components ​

...string[]

Returns ​

ScriptQuery


StartKernelWorkerOptions ​

Extends ​

Properties ​

capabilities? ​
ts
optional capabilities?: (world, manifest) => Record<string, object> | undefined[];

Capability hooks (figures, vehicles, …), run in order after terrain and before setup. Same contract as physics: each may return script-api extension namespaces.

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

Inherited from ​

BuildWorldOptions.capabilities

content? ​
ts
optional content?: ContentIdentity;

Which content the world is built from (see ContentIdentity), e.g. a type library's hash. Recorded in keyframes and replays next to the state hash, never inside it.

Inherited from ​

BuildWorldOptions.content

defaults? ​
ts
optional defaults?: Readonly<Record<string, JsonObject>>;
Inherited from ​

BuildWorldOptions.defaults

devFreeze? ​
ts
optional devFreeze?: boolean;
Inherited from ​

BuildWorldOptions.devFreeze

gameplay? ​
ts
optional gameplay?: boolean;
Inherited from ​

BuildWorldOptions.gameplay

host? ​
ts
optional host?: KernelHostOptions;

Host options. keyframeInterval defaults to the scene's own.

ts
optional link?: MessageLink;

Where to speak. Defaults to this worker's own global scope.

physics? ​
ts
optional physics?: (world, manifest) => Record<string, object> | undefined;

Physics plugin hook (e.g. rapier), run after the data-declared systems and before setup. May return script-api extension namespaces ({ physics: rapierScriptApi(handle) }).

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

Inherited from ​

BuildWorldOptions.physics

registry? ​
ts
optional registry?: ComponentRegistry;
Inherited from ​

BuildWorldOptions.registry

scene ​
ts
scene: SceneManifest;

The manifest, scripts already inlined — loadProject returns one.

scriptExtensions? ​
ts
optional scriptExtensions?: Record<string, object>;

Extra script-api namespaces merged with whatever the hooks return.

Inherited from ​

BuildWorldOptions.scriptExtensions

scripts? ​
ts
optional scripts?: boolean;

Install resolved type scripts followed by the manifest's scripts (default true).

Inherited from ​

BuildWorldOptions.scripts

setup? ​
ts
optional setup?: WorldSetup;
terrain? ​
ts
optional terrain?: (world, manifest) => Record<string, object> | undefined;

Terrain ground field hook, run after physics and before setup. Same contract as physics: returns script-api extensions ({ terrain: terrainScriptApi(handle) }).

Parameters ​
world ​

World

manifest ​

SceneManifest

Returns ​

Record&lt;string, object&gt; | undefined

Inherited from ​

BuildWorldOptions.terrain

types? ​
ts
optional types?: ResolvedTypes;

Flattened registry types; required when the scene references type ids.

Inherited from ​

BuildWorldOptions.types

validateSpawn? ​
ts
optional validateSpawn?: boolean;
Inherited from ​

BuildWorldOptions.validateSpawn


SubmitResult ​

Properties ​

accepted ​
ts
accepted: boolean;
reason? ​
ts
optional reason?: string;

Set when rejected: human/agent-facing reason.

tickExecuted? ​
ts
optional tickExecuted?: number;

Set when accepted: the tick the command will actually execute on.


SystemInfo ​

Properties ​

name ​
ts
name: string;
order ​
ts
order: number;
phase ​
ts
phase: Phase;

TickContext ​

Properties ​

dt ​
ts
dt: number;
rng ​
ts
rng: Rng;
tick ​
ts
tick: number;

TimerData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

timers ​
ts
timers: TimerEntry[];

TimerEntry ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

event ​
ts
event: string;
id ​
ts
id: string;
payload? ​
ts
optional payload?: JsonValue;
repeatEvery? ​
ts
optional repeatEvery?: number;
ticksLeft ​
ts
ticksLeft: number;

TimerSpec ​

Properties ​

event ​
ts
event: string;
id? ​
ts
optional id?: string;
payload? ​
ts
optional payload?: JsonValue;
repeatEvery? ​
ts
optional repeatEvery?: number;
ticks ​
ts
ticks: number;

TransformData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

pos ​
ts
pos: [number, number, number];
rot ​
ts
rot: [number, number, number, number];
scale? ​
ts
optional scale?: [number, number, number];

TransformLike ​

Properties ​

pos ​
ts
pos: Vec3;
rot? ​
ts
optional rot?: Quat;
scale? ​
ts
optional scale?: Vec3;

TweenData ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

tweens ​
ts
tweens: TweenEntry[];

TweenEntry ​

Extends ​

Indexable ​

ts
[key: string]: JsonValue | undefined

Properties ​

component ​
ts
component: string;
easing? ​
ts
optional easing?: Easing;
elapsed? ​
ts
optional elapsed?: number;

Kernel-owned progress (snapshot-safe).

emitOnComplete? ​
ts
optional emitOnComplete?: string;
from? ​
ts
optional from?: number | number[];
id? ​
ts
optional id?: string;
loop? ​
ts
optional loop?: "none" | "loop" | "pingpong";
path ​
ts
path: string;

Select-style value path within the component, e.g. "pos", "pos[1]", "primitive.size".

ticks ​
ts
ticks: number;
to ​
ts
to: number | number[];

TypeLibrary ​

Properties ​

hash ​
ts
readonly hash: string;

Hash over every resolved type (components and scripts); the same for any document order.

types ​
ts
readonly types: ResolvedTypes;

The resolved registry; pass it as types to buildWorld.

Methods ​

component() ​
ts
component<T>(id, name): T;

One resolved component of a type, as a fresh copy; throws when the type lacks it.

Type Parameters ​
T ​

T

Parameters ​
id ​

string

name ​

string

Returns ​

T

components() ​
ts
components(id): ComponentMap;

A type's resolved components (inherited ones included), as a fresh copy.

Parameters ​
id ​

string

Returns ​

ComponentMap

has() ​
ts
has(id): boolean;
Parameters ​
id ​

string

Returns ​

boolean

ids() ​
ts
ids(): string[];

Every type id, in document order.

Returns ​

string[]

idsWith() ​
ts
idsWith(name): string[];

Ids of the types that have a component, in document order.

Parameters ​
name ​

string

Returns ​

string[]


TypeLibraryOptions ​

Properties ​

label? ​
ts
optional label?: string;

Names the content in errors, e.g. "molen.entities@0.0.1".

scripts? ​
ts
optional scripts?: Readonly<Record<string, string>>;

Script sources for types whose scripts use path refs, as a bundler's raw glob hands them over (matched by path suffix). Types without scripts, or with inline code, need none.


WorldOptions ​

Properties ​

content? ​
ts
optional content?: ContentIdentity;

Which content the world is built from (see ContentIdentity). Recorded in keyframes next to the state hash, never in it; loading a keyframe with different content fails by name.

defaults? ​
ts
optional defaults?: Readonly<Record<string, JsonObject>>;

World-local default values override package defaults for the named components.

devFreeze? ​
ts
optional devFreeze?: boolean;

Dev mode deep-freezes component data ONCE when it enters the store (freeze-on-write), so reads hand back the stored object and accidental mutation throws. Default true.

Aliasing rule (both modes): get() and query rows return the live stored object, never a copy. Never mutate what you read — in dev worlds it throws; with devFreeze: false it silently corrupts state and deltas. set/patch/spawn always install a NEW object, so a reference you hold goes stale after the next write, never corrupted.

lateCommands? ​
ts
optional lateCommands?: LateCommandPolicy;

Late-command policy (command.tick <= currentTick). Default 'rewrite'.

registry? ​
ts
optional registry?: ComponentRegistry;

Isolated component vocabulary; defaults to a copy of package registrations.

seed? ​
ts
optional seed?: string | number;
tickRate? ​
ts
optional tickRate?: number;

Hz; dt = 1/tickRate. Immutable for the world's lifetime.

validateSpawn? ​
ts
optional validateSpawn?: boolean;

Validate component shapes in spawn() against the schema registry. Default = devFreeze.

Type Aliases ​

CommandHandler ​

ts
type CommandHandler<W> = (world, command, ctx) => void;

Type Parameters ​

W ​

W

Parameters ​

world ​

W

command ​

Command

ctx ​

TickContext

Returns ​

void


Easing ​

ts
type Easing = 
  | "linear"
  | "quadIn"
  | "quadOut"
  | "quadInOut"
  | "cubicIn"
  | "cubicOut"
  | "cubicInOut";

EventHandler ​

ts
type EventHandler = (event, ctx) => void;

Parameters ​

event ​

EngineEvent

ctx ​

TickContext

Returns ​

void


JsonPrimitive ​

ts
type JsonPrimitive = string | number | boolean | null;

JsonValue ​

ts
type JsonValue = 
  | JsonPrimitive
  | JsonValue[]
  | JsonObject;

LateCommandPolicy ​

ts
type LateCommandPolicy = "rewrite" | "reject";

PayloadCheck ​

ts
type PayloadCheck = 
  | {
  ok: true;
}
  | {
  message: string;
  ok: false;
};

Result of a payload validator: ok, or a formatted, agent-facing reason.


Phase ​

ts
type Phase = "commands" | "update" | "physics" | "late";

Quat ​

ts
type Quat = [number, number, number, number];

ResolvedTypes ​

ts
type ResolvedTypes = ReadonlyMap<string, ResolvedEntityType>;

Pre-flattened project type registry.


System ​

ts
type System = (world, ctx) => void;

Parameters ​

world ​

World

ctx ​

TickContext

Returns ​

void


TimerHandle ​

ts
type TimerHandle = ReturnType<typeof setTimeout>;

Unsubscribe ​

ts
type Unsubscribe = () => void;

Returns ​

void


Vec3 ​

ts
type Vec3 = [number, number, number];

WorldSetup ​

ts
type WorldSetup = (world, manifest) => void;

Convenience for tooling: a manifest plus a code setup step (systems + command handlers).

Parameters ​

world ​

World

manifest ​

SceneManifest

Returns ​

void

Variables ​

AUDIO_MUSIC ​

ts
const AUDIO_MUSIC: "audio.music";

Event emitted by molen.audio.music.


AUDIO_PLAY ​

ts
const AUDIO_PLAY: "audio.play";

Event emitted by molen.audio.play.


AUDIO_STOP ​

ts
const AUDIO_STOP: "audio.stop";

Event emitted by molen.audio.stop.


AudioEnvironment ​

ts
const AudioEnvironment: ComponentType<AudioEnvironmentData>;

AudioSource ​

ts
const AudioSource: ComponentType<AudioSourceData>;

AudioZone ​

ts
const AudioZone: ComponentType<AudioZoneData>;

CONTENT_KEY ​

ts
const CONTENT_KEY: "$content" = "$content";

Keyframes record content identity under this reserved plugins key, beside $format.


dmath ​

ts
const dmath: DMath;

ENGINE_VERSION ​

ts
const ENGINE_VERSION: "0.0.4" = "0.0.4";

The kernel package's published version. Informational metadata only: it rides along in a keyframe so a save file says which build wrote it, and it is NOT compared on load and NOT hashed. Keep it in step with packages/kernel/package.json (a unit test pins the two together).


Fsm ​

ts
const Fsm: ComponentType<FsmData>;

Lifetime ​

ts
const Lifetime: ComponentType<LifetimeData>;

LocalTransform ​

ts
const LocalTransform: ComponentType<TransformData>;

Parent ​

ts
const Parent: ComponentType<ParentData>;

STATE_FORMAT ​

ts
const STATE_FORMAT: 1 = 1;

The state-format generation: what actually has to match for a keyframe to be loadable and for two state hashes to be comparable. Bump it ONLY when simulation semantics or the snapshot layout change — never for a release, a docs edit, or a client-only change. Every release on the fixed version line used to invalidate every save file and every recorded *.replay.json because the package version was the gate; this constant is the gate now.


STATE_FORMAT_KEY ​

ts
const STATE_FORMAT_KEY: "$format" = "$format";

Keyframes record their state format under this reserved key in plugins (the one extensible field of molen/keyframe@1; $scripts is the same kind of reserved name). A keyframe written before the key existed is read as format 1, the layout in use when it was introduced.


Timer ​

ts
const Timer: ComponentType<TimerData>;

Transform ​

ts
const Transform: ComponentType<TransformData>;

Tween ​

ts
const Tween: ComponentType<TweenData>;

Weather ​

ts
const Weather: ComponentType<WeatherData>;

Functions ​

applyDelta() ​

ts
function applyDelta(store, delta): Record<EntityId, ComponentMap>;

Apply a delta to a passive entity-major store (the client mirror / replay scrubber). Mutates and returns the store. Shared by client interpolation and tests.

Parameters ​

store ​

Record&lt;EntityId, ComponentMap&gt;

delta ​

Delta

Returns ​

Record&lt;EntityId, ComponentMap&gt;


applyKeyframeTo() ​

ts
function applyKeyframeTo(
   world, 
   keyframe, 
   options?
): void;

Load a keyframe's state into an existing world in place (replacing entities, RNG, tick, and counter), keeping its registered systems/commands. The replay scrubber uses this to seek. Acceptance is gated on the STATE_FORMAT generation, never on the engine version, and on the content both sides recorded.

Parameters ​

world ​

World

keyframe ​

Keyframe

options? ​

ApplyKeyframeOptions

Returns ​

void


approach() ​

ts
function approach(
   value, 
   target, 
   amount
): number;

Move value toward target by at most amount (amount ≥ 0).

Parameters ​

value ​

number

target ​

number

amount ​

number

Returns ​

number


audioEnvironmentOf() ​

ts
function audioEnvironmentOf(world): Readonly<AudioEnvironmentData> | undefined;

First audioEnvironment entity in world order (the singleton), like weatherOf.

Parameters ​

world ​

World

Returns ​

Readonly&lt;AudioEnvironmentData&gt; | undefined


audioScriptApi() ​

ts
function audioScriptApi(world): AudioScriptApi;

The molen.audio namespace: thin wrappers that emit audio.play|stop|music events. Handles are ${sound}@${tick}#${n} (n counts calls within the tick), so they are deterministic.

Parameters ​

world ​

World

Returns ​

AudioScriptApi


buildWorld() ​

ts
function buildWorld(
   manifest, 
   setup?, 
   opts?
): World;

The one way every host builds a world from a scene — tooling ops, example workers, tests:

createWorldFromScene (gameplay → kinematics/character → commands → entities) → opts.physics?() → opts.terrain?() → opts.capabilities → setup?() → resolved type scripts → the manifest's scripts.

Scripts install last so they see every declared command and every capability extension. Type and manifest scripts must already be inline (code); resolve path refs first with inlineScriptSources (browser) or the tooling scene loader (Node).

Parameters ​

manifest ​

SceneManifest

setup? ​

WorldSetup

opts? ​

BuildWorldOptions

Returns ​

World


cancelTimer() ​

ts
function cancelTimer(
   world, 
   entity, 
   timerId
): void;

Parameters ​

world ​

World

entity ​

string | null

timerId ​

string

Returns ​

void


cancelTween() ​

ts
function cancelTween(
   world, 
   entity, 
   tweenId?
): void;

Parameters ​

world ​

World

entity ​

string

tweenId? ​

string

Returns ​

void


canonicalBytes() ​

ts
function canonicalBytes(value): Uint8Array;

Canonical byte serialization of a JSON value (sorted keys, IEEE-754 number bits).

Parameters ​

value ​

JsonValue

Returns ​

Uint8Array


cloneJson() ​

ts
function cloneJson<T>(value): T;

Structured deep clone of pure-JSON data. Used so stored components never alias caller data.

Type Parameters ​

T ​

T extends JsonValue

Parameters ​

value ​

T

Returns ​

T


componentDefaults() ​

ts
function componentDefaults(name): (() => JsonObject) | undefined;

The registered defaults factory for a component name (from any defineComponent call).

Parameters ​

name ​

string

Returns ​

(() => JsonObject) | undefined


componentHandle() ​

ts
function componentHandle(name): ComponentType<JsonObject>;

A memoized bare handle for a wire-string component name (no defaults). The string-based surfaces (scripts, tweens, data-driven systems) use this so they never allocate a handle per call.

Parameters ​

name ​

string

Returns ​

ComponentType&lt;JsonObject&gt;


composeTransforms() ​

ts
function composeTransforms(parent, local): TransformLike;

world = parent ∘ local (scale is component-wise; no shear).

Parameters ​

parent ​

TransformLike

local ​

TransformLike

Returns ​

TransformLike


contentDrift() ​

ts
function contentDrift(recorded, loaded): string[];

Differences between recorded and loaded content, one message per domain present in both with a different hash. Domains only one side has are not compared: a replay recorded before a domain existed, or a host that loads extra content, is not a mismatch.

Parameters ​

recorded ​

ContentIdentity

loaded ​

ContentIdentity

Returns ​

string[]


createRng() ​

ts
function createRng(seed): Rng;

Build an RNG from a world seed (string or number).

Parameters ​

seed ​

string | number

Returns ​

Rng


createTypeLibrary() ​

ts
function createTypeLibrary(docs, options?): TypeLibrary;

Build a type library from molen/types@1 documents already in memory.

Parameters ​

docs ​

unknown

options? ​

TypeLibraryOptions

Returns ​

TypeLibrary


createWorldFromScene() ​

ts
function createWorldFromScene(manifest, opts?): World;

Build a World from a validated scene manifest: applies tickRate/seed/lateCommands, installs the data-declared systems (gameplay, kinematics + character when physics asks for them), declares the scene's commands (with their payload validators) and custom components, and instantiates entities (type/prefab/components) in manifest order, preserving authored ids.

Code setup (systems, command handlers) and the manifest's own scripts are NOT installed here; buildWorld layers those on top in the documented order.

Parameters ​

manifest ​

SceneManifest

opts? ​

object & SceneResolveOptions

Returns ​

World


deepFreeze() ​

ts
function deepFreeze<T>(value): T;

Deep-freeze pure-JSON data (dev mode) so in-place mutation throws instead of corrupting deltas.

Type Parameters ​

T ​

T extends JsonValue

Parameters ​

value ​

T

Returns ​

T


defineComponent() ​

ts
function defineComponent<T>(name, opts?): ComponentType<T>;

Type Parameters ​

T ​

T extends JsonObject

Parameters ​

name ​

string

opts? ​
defaults? ​

() => T

Returns ​

ComponentType&lt;T&gt;


defineExperience() ​

ts
function defineExperience(def): Experience;

Define an experience: commands + systems + an optional imperative setup, composed into one WorldSetup. buildWorld(manifest, experience.setup) — or hand the whole object to tooling, whose setup loader accepts either form.

Parameters ​

def ​

ExperienceDef

Returns ​

Experience


hardenScripts() ​

ts
function hardenScripts(options?): boolean;

Turn script evaluation into an actual isolation boundary by running SES lockdown() once for this process. Returns true if this call performed the lockdown, false if the realm was already hardened (calling it repeatedly is safe).

Without it, scripts are deterministic but not contained: they share the realm's mutable intrinsics and can reach the host global. After it, intrinsics are frozen and Function.prototype.constructor no longer builds a function in the host realm, so the usual escape fails.

Call it at host startup, before building a world, and only in a process whose job is running the kernel — a Worker or a dedicated Node host. lockdown() is process-global and irreversible: do not call it in a host that also runs bundlers, image or asset tooling, or a browser-automation stack, because frozen intrinsics break libraries that patch prototypes at runtime. The molen CLI and MCP server deliberately do not call it.

Determinism does not depend on this: the tamed Math/Date/Intl endowments already give that. Hardening only changes what a hostile script can reach.

Parameters ​

options? ​

HardenScriptsOptions

Returns ​

boolean


hashBytes() ​

ts
function hashBytes(data): string;

SHA-256 of raw bytes, prefixed "sha256:".

Parameters ​

data ​

Uint8Array

Returns ​

string


hashJson() ​

ts
function hashJson(value): string;

Stable SHA-256 of a JSON value, prefixed "sha256:".

Parameters ​

value ​

JsonValue

Returns ​

string


identityQuat() ​

ts
function identityQuat(): Quat;

A fresh identity quaternion [0, 0, 0, 1].

Returns ​

Quat


inlineScriptSources() ​

ts
function inlineScriptSources(manifest, sources): SceneManifest;

Replace every path script ref with inline code from sources (keyed by the exact path string). Pure; returns a shallow copy of the manifest. Browsers use this with a bundler's raw imports; the Node tooling loader reads the files itself.

Parameters ​

manifest ​

SceneManifest

sources ​

Record&lt;string, string&gt;

Returns ​

SceneManifest


installFsm() ​

ts
function installFsm(world): void;

Parameters ​

world ​

World

Returns ​

void


installGameplay() ​

ts
function installGameplay(world, opts?): void;

Install the gameplay systems (all on by default). createWorldFromScene calls this.

Parameters ​

world ​

World

opts? ​

GameplayOptions

Returns ​

void


installHierarchy() ​

ts
function installHierarchy(world): void;

Parameters ​

world ​

World

Returns ​

void


installLifetime() ​

ts
function installLifetime(world): void;

Parameters ​

world ​

World

Returns ​

void


installSceneScripts() ​

ts
function installSceneScripts(
   world, 
   manifest, 
   opts?
): ScriptHost;

Install the scripts declared in a scene manifest's scripts field as scene data — no setup module required. Maps the wire field code to the host's source and threads the manifest so scripts can molen.spawn(prefabName, …). Returns a no-op host when the manifest has no scripts. Scripts still carrying an unresolved path (a file ref) throw — the kernel is fs-free; run the manifest through the tooling scene loader (which inlines path into code) first.

Parameters ​

world ​

World

manifest ​

SceneManifest

opts? ​
extensions? ​

Record&lt;string, object&gt;

types? ​

ResolvedTypes

validate? ​

boolean

Returns ​

ScriptHost


installScripting() ​

ts
function installScripting(
   world, 
   scripts, 
   opts?
): ScriptHost;

Install scripting on a world: evaluate each script in a Compartment, run tick handlers in a single update-phase system (registration order), and route world events to script handlers.

Scripts may author logic two ways: at the top level using the injected molen/config globals, or by exporting a setup(molen, config) function (defined as a top-level function setup in its Compartment). A script that registers no molen.on handlers is warned about — that is the classic silent no-op (a typo'd verb leaves the script doing nothing).

Parameters ​

world ​

World

scripts ​

LoadedScript[]

opts? ​

InstallScriptingOptions

Returns ​

ScriptHost


installTimers() ​

ts
function installTimers(world): void;

Parameters ​

world ​

World

Returns ​

void


installTweens() ​

ts
function installTweens(world): void;

Parameters ​

world ​

World

Returns ​

void


inverseTransformPoint() ​

ts
function inverseTransformPoint(t, p): Vec3;

A world point into the local frame of a transform (the inverse of transformPoint).

Parameters ​

t ​

TransformLike

p ​

Vec3

Returns ​

Vec3


isExperience() ​

ts
function isExperience(value): value is Experience;

Is a value an Experience (vs a bare WorldSetup function)?

Parameters ​

value ​

unknown

Returns ​

value is Experience


keyframeContent() ​

ts
function keyframeContent(keyframe): ContentIdentity | undefined;

The identity a keyframe recorded, or undefined for one written without content.

Parameters ​

keyframe ​

Keyframe

Returns ​

ContentIdentity | undefined


keyframeStateFormat() ​

ts
function keyframeStateFormat(keyframe): number;

The state format a keyframe was written in. Keyframes from before the format key existed carry the layout it was introduced at (1), so they keep loading.

Parameters ​

keyframe ​

Keyframe

Returns ​

number


loadProject() ​

ts
function loadProject(options): LoadedProject;

Validate a project's documents and hand back what a host needs: the scene manifest with its scripts inlined, and the resolved type registry. Throws with the validator's formatted error — the same text molen validate prints — so a bad document fails at load with a pinpointed message rather than somewhere inside the first tick.

Parameters ​

options ​

LoadProjectOptions

Returns ​

LoadedProject


lookRotation() ​

ts
function lookRotation(forward, up?): Quat;

The rotation whose +Z axis points along forward with +Y as close to up as possible. Returns identity for a zero-length forward or a forward parallel to up.

Parameters ​

forward ​

Vec3

up? ​

Vec3

Returns ​

Quat


patchJson() ​

ts
function patchJson<T>(base, partial): T;

Shallow-merge a partial patch into a clone of base (whole-component semantics at top level). The result is a fresh null-prototype object, like every other stored component.

Type Parameters ​

T ​

T extends JsonObject

Parameters ​

base ​

T

partial ​

Partial&lt;T&gt;

Returns ​

T


quatConjugate() ​

ts
function quatConjugate(q): Quat;

The inverse of a unit quaternion.

Parameters ​

q ​

Quat

Returns ​

Quat


quatDot() ​

ts
function quatDot(a, b): number;

Parameters ​

a ​

Quat

b ​

Quat

Returns ​

number


quatFromAxisAngle() ​

ts
function quatFromAxisAngle(axis, angle): Quat;

Rotation of angle radians about a unit axis.

Parameters ​

axis ​

Vec3

angle ​

number

Returns ​

Quat


quatFromEuler() ​

ts
function quatFromEuler(
   pitch, 
   yaw, 
   roll
): Quat;

Intrinsic Y·X·Z Euler angles (yaw about +Y, then pitch about the rotated +X, then roll about the rotated +Z) — the natural order for characters and cameras.

Parameters ​

pitch ​

number

yaw ​

number

roll ​

number

Returns ​

Quat


quatFromTo() ​

ts
function quatFromTo(a, b): Quat;

The shortest-arc rotation taking direction a to direction b (inputs need not be unit length). Identity for zero-length inputs; a half-turn about a perpendicular axis for opposite inputs.

Parameters ​

a ​

Vec3

b ​

Vec3

Returns ​

Quat


quatFromYaw() ​

ts
function quatFromYaw(yaw): Quat;

Rotation of yaw radians about +Y (forward +Z turns toward +X for positive yaw).

Parameters ​

yaw ​

number

Returns ​

Quat


quatMul() ​

ts
function quatMul(a, b): Quat;

Parameters ​

a ​

Quat

b ​

Quat

Returns ​

Quat


quatNormalize() ​

ts
function quatNormalize(q): Quat;

Parameters ​

q ​

Quat

Returns ​

Quat


quatRotateVec3() ​

ts
function quatRotateVec3(q, v): Vec3;

Parameters ​

q ​

Quat

v ​

Vec3

Returns ​

Vec3


quatSlerp() ​

ts
function quatSlerp(
   a, 
   b, 
   t
): Quat;

Spherical linear interpolation along the shortest arc; t is clamped to [0, 1]. Falls back to normalized linear interpolation when the inputs are nearly parallel.

Parameters ​

a ​

Quat

b ​

Quat

t ​

number

Returns ​

Quat


resolveEntityComponents() ​

ts
function resolveEntityComponents(
   manifest, 
   entity, 
   opts?
): ComponentMap;

Resolve a scene entity's final components (type <- prefab <- components).

Parameters ​

manifest ​

SceneManifest

entity ​
components? ​

ComponentMap

prefab? ​

string

type? ​

string

opts? ​

SceneResolveOptions

Returns ​

ComponentMap


resolvePrefab() ​

ts
function resolvePrefab(
   manifest, 
   name, 
   opts?, 
   seen?
): ComponentMap;

Resolve a prefab's components: registry type <- extends chain <- own components.

Parameters ​

manifest ​

SceneManifest

name ​

string

opts? ​

SceneResolveOptions

seen? ​

string[]

Returns ​

ComponentMap


restoreRng() ​

ts
function restoreRng(world, state): void;

Restore RNG into a world (used by snapshot load).

Parameters ​

world ​

World

state ​

RngState

Returns ​

void


rngFromState() ​

ts
function rngFromState(state): Rng;

Restore an RNG from a snapshotted state.

Parameters ​

state ​

RngState

Returns ​

Rng


sampleAtmosphere() ​

ts
function sampleAtmosphere(
   data, 
   altitude?, 
   gravity?
): AtmosphereSample;

Ideal-gas density and a simple isothermal hydrostatic pressure profile. Temperature, wind and humidity are uniform; no forecast, moist-air correction or automatic rain/snow switch. Altitude is absolute world Y in meters. Gravity and gas constant allow authored worlds.

Parameters ​

data ​

WeatherData

altitude? ​

number

gravity? ​

number

Returns ​

AtmosphereSample


scheduleTimer() ​

ts
function scheduleTimer(
   world, 
   entity, 
   spec
): string;

Schedule a timer on an entity (null -> the kernel-owned $timers singleton). Returns its id.

Parameters ​

world ​

World

entity ​

string | null

spec ​

TimerSpec

Returns ​

string


scriptsHardened() ​

ts
function scriptsHardened(): boolean;

Whether this realm's intrinsics are frozen — by hardenScripts or by a host that called SES lockdown() itself.

Returns ​

boolean


seedToInt() ​

ts
function seedToInt(seed): number;

Hash an arbitrary string/number seed into a 32-bit integer (FNV-1a for strings).

Parameters ​

seed ​

string | number

Returns ​

number


setParent() ​

ts
function setParent(
   world, 
   id, 
   parentId
): void;

Set a parent, initializing localTransform so the child keeps its current world pose.

Parameters ​

world ​

World

id ​

string

parentId ​

string

Returns ​

void


spawnFromData() ​

ts
function spawnFromData<T>(
   world, 
   data, 
   template, 
   opts?
): string[];

Bind a data array to entities (the visualization building block): spawn one entity per item via a template. With idPrefix, entities get stable ids (prefix0, prefix1, …) so later systems can update them by index.

Type Parameters ​

T ​

T

Parameters ​

world ​

World

data ​

readonly T[]

template ​

(item, index) => ComponentMap

opts? ​
idPrefix? ​

string

Returns ​

string[]


startKernelWorker() ​

ts
function startKernelWorker(options): KernelWorker;

Build the world and serve it over the worker's message port: the whole body of a kernel worker entry. Returns both, so a host that wants to step manually or dispose still can.

keyframeInterval comes from the scene unless overridden, which is what makes a page's first frame arrive promptly instead of after a full keyframe period.

Parameters ​

options ​

StartKernelWorkerOptions

Returns ​

KernelWorker


startTween() ​

ts
function startTween(
   world, 
   entity, 
   spec
): void;

Start a tween on an entity (appends to its tween component).

Parameters ​

world ​

World

entity ​

string

spec ​

TweenEntry

Returns ​

void


stateHash() ​

ts
function stateHash(world): string;

Hash of serialized continuation state, including query order, commands, and plugin blobs. Equality assumes identical systems, script sources, and snapshot-safe host configuration. Mutable host/script closure state is outside this contract.

Parameters ​

world ​

World

Returns ​

string


takeDelta() ​

ts
function takeDelta(world, baseTick): Delta;

Produce a delta capturing changes since the last takeDelta/keyframe boundary, then reset dirty tracking. Whole-component replacement granularity (docs-src/schemas/delta.md).

Parameters ​

world ​

World

baseTick ​

number

Returns ​

Delta


takeKeyframe() ​

ts
function takeKeyframe(world): Keyframe;

Produce a complete keyframe of the world's current state (also the save-file format). A keyframe is a complete baseline, so it resets delta dirty-tracking: the next takeDelta reports only changes that happen after this keyframe.

Parameters ​

world ​

World

Returns ​

Keyframe


transformPoint() ​

ts
function transformPoint(t, p): Vec3;

A local point through a transform: scale, rotate, then translate.

Parameters ​

t ​

TransformLike

p ​

Vec3

Returns ​

Vec3


unparent() ​

ts
function unparent(world, id): void;

Parameters ​

world ​

World

id ​

string

Returns ​

void


weatherOf() ​

ts
function weatherOf(world): Readonly<WeatherData> | undefined;

First weather entity in world order; absence preserves a consumer's existing atmosphere.

Parameters ​

world ​

World

Returns ​

Readonly&lt;WeatherData&gt; | undefined


worldFromKeyframe() ​

ts
function worldFromKeyframe(keyframe, opts?): World;

Reconstruct a world from a keyframe. Restores entities, RNG, tick, and entity counter. Without opts.content, the world takes the content identity the keyframe recorded.

Parameters ​

keyframe ​

Keyframe

opts? ​

WorldOptions & ApplyKeyframeOptions

Returns ​

World


yawOf() ​

ts
function yawOf(q): number;

Yaw (radians, about +Y) of the +Z forward direction of q. Zero when forward is +Z.

Parameters ​

q ​

Quat

Returns ​

number

37 guides · 36 schema formats · 41 API entry points · 10 samples. API, CLI and schema pages are generated from the shipped build.