Scripting in DES
Use event-driven scripts to add custom material-flow behaviour that can continue from a saved run.
The examples on this page carry an AGPL header because they ship with the open-source core. A script you write yourself is part of your model. If you deliver realvirtual to others under AGPL and a script takes over code from the core or is tightly interwoven with it, the recipients must be able to get it under AGPL as well; see Licence.
Where a script lives
Section titled “Where a script lives”A DES script is a WebComponent on a node of the model. It is stored in the GLB next to the node’s other data, so it travels with the model. A script that observes the whole model, like a KPI counter, can sit on an empty node of its own.
- In the Editor, use Edit Script on the component in the Inspector, or open the Script Editor (component scripts) from the side toolbar and pick the node in its node selector.
- Scripts in a model only run after Enable scripting (or a link with
?scripts). Until then the editor is read-only and shows that scripting is disabled. - The chip in the title bar shows DES-safe when the component sets DesSafe and continuous when it does not; see Code checks.

The PalletYard demo carries this script as a teaching example: ShippingMonitor counts shipments that come later than twice the target takt and publishes the result as Late shipments. Logic that belongs to one project rather than to the model, such as a panel or a link to an external system, is project code instead; see Scripting for the three places code can live.
Which events reach a script
Section titled “Which events reach a script”In DES, a script does nothing between events. The simulation calls it when something happens that concerns it, the script changes its state and schedules what comes next, and the simulation moves on to the next event.
setup(self) runs once when the script is bound for a run. It returns the handlers; everything else happens in them.
| Event | Handler | Use it to |
|---|---|---|
A timer scheduled with self.in(delay, hook), self.at(time, hook) or self.every(interval, hook) is due | des.on(hook, mu, data) | Run a step after a delay, repeat a cycle, end a processing time |
| An upstream station offers a part | des.canAccept(mu, port), then des.onAccept(mu, port) | Make the node a station of its own: refuse parts while busy, start processing |
| A blocked output can take a part again | des.onDownstreamReady(port) | Pass on a part that was waiting |
| A part reaches a sink | callback of self.sink(name).on(cb), registered in setup | Count shipments, measure gaps, feed a KPI |
| Another script sends a message | onMessage(topic, data, fromPath) | Coordinate several scripts, for example a cell controller |
| The simulation is reset | onReset() | Clean up; pending timers are already cleared |
A node becomes a material-flow station as soon as its script declares canAccept, onAccept or onDownstreamReady. Timers appear in the Event Queue as Script.Hook. Frame hooks such as continuous.fixedUpdate only run while the simulation is animated and must not change the model in DES; see Timers.
A repeating timer
Section titled “A repeating timer”function setup(self) { const st = self.persist({ cycles: 0 }); self.every(60, 'cycle'); // every simulated minute return { des: { on(hook) { if (hook !== 'cycle') return; st.cycles++; self.statValue('Cycles', st.cycles); } }, };}A station with a processing time
Section titled “A station with a processing time”function setup(self) { const st = self.persist({ busy: false }); return { des: { canAccept() { return !st.busy; }, onAccept(mu) { st.busy = true; self.in(self.prop.ProcessTime ?? 30, 'done', mu); return true; }, on(hook, mu) { if (hook !== 'done') return; const out = self.freeOutputs(mu)[0]; if (out) { self.transfer(mu, out); st.busy = false; } }, onDownstreamReady(port) { const mu = self.mus[0]; if (mu) { self.transfer(mu, port); st.busy = false; } }, }, };}ProcessTime is a field on the same WebComponent; every primitive field there appears as self.prop.
Counting at a sink
Section titled “Counting at a sink”The ShippingMonitor shown above subscribes to both shipping sinks in setup and publishes two values. They appear in the Scripts tab of the Statistics window, and + Add KPI in the Experiments window offers them as KPIs.

Keeping state across a restore
Section titled “Keeping state across a restore”Scripts keep working across a restore if every value that changes during the run is stored in one object declared with self.persist.
// SPDX-License-Identifier: AGPL-3.0-only// Snapshot contract: keep all runtime state in one JSON-only self.persist object.// No module-scope let/var. The SDK restores the timer and RNG; do not re-arm// timers in onRestore (that would duplicate the pending tick).function setup(self) { const st = self.persist({ counter: 0, history: [], timerId: 0 }); st.timerId = self.every(1, 'beat'); return { des: { on(hook) { if (hook !== 'beat') return; st.counter++; st.history.push([self.now, Math.round(self.random() * 1000000)]); if (st.history.length > 4) st.history.shift(); } }, state() { return st; }, };}The example counts a simulated-second heartbeat and keeps its last four random draws.
Persistent state
Section titled “Persistent state”- Call
self.persistonce, duringsetup, and keep the returned object. A restore refills this same object. - It holds plain JSON data only: finite numbers, strings, booleans,
null, arrays and plain objects. NoNaN,Infinity,-0,Map,Set, functions, shared references or circular references. self.propis read-only configuration. Changes to it are not saved.
Timers
Section titled “Timers”Use self.in, self.at and self.every. Pending timers are part of the snapshot and fire at the same times after a restore, so do not start them again after a restore: that would run every tick twice. self.every returns an id; keep it in the persist object if you need to cancel the timer later. setTimeout, setInterval, Date and Math.random do not exist in scripts, and timers that count down in fixedUpdate do not work in event-based DES.
Code checks
Section titled “Code checks”When you save a script, and when DES binds it, the script is checked for state that would be lost. Findings read des-script-undeclared-state: line N: …; use self.persist(...). Without DesSafe they are warnings: the script runs on the DES clock, but a snapshot of the run is refused until its state is declared. When the component sets DesSafe, they are errors and DES does not run the script.
- changing variables declared outside the handlers (
let count = 0, arrays, objects,Map,Setat the top of the script or insetup) - classes declared at the top of the script or in
setup - writing to a variable of an outer function, to a global, or to properties of captured objects
- handlers created by a function call (
on: makeHandler()) instead of written out insetup - calling a helper function during
setupto build state
Constants, SDK handles such as self.drive(...), self, and scratch variables inside a handler are fine.
Converting an existing script
Section titled “Converting an existing script”// Before: state in a closure variable is lost on restorelet count = 0;function setup(self) { return { des: { on() { count++; } } };}
// After: state in self.persistfunction setup(self) { const st = self.persist({ count: 0 }); return { des: { on() { st.count++; } } };}Move every changing value into the persist object, write handlers out in place, and look up SDK handles inside the handler instead of storing them. The older onSnapshot and onRestore hooks still work, but they do not exempt a script from the check.
Random numbers and hooks
Section titled “Random numbers and hooks”Use self.random() for seeded random draws. With RNG v2, each script seed is derived from the run’s master seed, its component ID and the purpose script, so the same model and seed reproduce the sequence on each run. In v1 the default script seed comes from its component path, rather than the master seed. Draws during setup, and scripts created after a run starts, use their initial path seed (or an explicit SDK seed) until the next reset or run start.
des.on(hook, mu, data) receives scheduled hooks; the example handles beat. Its state() function returns the persistent object. The SDK also saves its own state-machine state, random position and timer IDs. onSnapshot and onRestore are a synchronous legacy facade; they do not make hidden closure state safe or replace self.persist.
Snapshot limits
Section titled “Snapshot limits”A restore refills the existing persistent object and restores pending timers. Script KPI state-time statistics are not saved. Callbacks registered after setup are not saved; register them during setup.
Larger logic: TypeScript project code
Section titled “Larger logic: TypeScript project code”A model script runs in a sandbox: a QuickJS interpreter compiled to WebAssembly, with no access to the DOM, the network or the wall clock, and with a limit of 5 ms per call. That keeps a model from an unknown source safe and makes every script part of the DES snapshot and seed contract. For short component logic this costs nothing you would notice. For logic that computes a lot per event, such as a dispatcher that searches orders, routes or storage places, the sandbox is the slower path.
The other path is project code: TypeScript modules in the project’s plugins/ folder, bound to a document in project.json and loaded as native code. See Scripting for how it is bound and loaded.
See Scripting for the SDK and editor, and Saving and restoring a run for model checks and snapshot limits.