Hazel reports · ^report(43) · Hazel as a JS library · started 2026-11-06, updated 2026-11-06 17:04 MST · work in progress · after ^report(39)

Scripting a JavaScript App in Hazel

Messed Up Dress Up, a game for kids written in plain JavaScript, lets its players rewrite some of the game's rules in Hazel while they play. It does that through hazeljs, Hazel packaged as a JavaScript library. This report explains how the game does it, and how a JavaScript developer could do the same in their own program: the pattern, the steps, a worked example in another domain, run in Node, and what it costs today. It is the first of two reports on using hazeljs from JavaScript: this one, in a whole app whose rules are Hazel; ^report(44), in an article, its Hazel listings in Hazel's own editor (the way this page shows its listings). Matthew asked for it on 2026-11-06, for his meeting with Cyrus on 2026-11-11 (^report(42), the agenda, item 5). The first readers in mind are a group in Cambridge who simulate Petri nets with JavaScript tools of their own, so the example is a Petri net. As of 2026-11-06, with hazeljs 0.0.4 from npm.

Outline#

  1. The pattern: what a JS app hands to Hazel, what it gets back, and why write a handler in Hazel at all.
  2. How Messed Up Dress Up does it: the game's pieces, from its Hazel types to acting out a rule's commands, each linked to its code.
  3. Doing the same in another app: the six steps as we took them for a Petri net app of our own, and where other kinds of Petri nets fit.
  4. A worked example: a Petri net: the net running on this page with its rules in Hazel's editor (try it), and what the same rules did in Node (the runs).
  5. What it costs: a call into Hazel, a build and a rebuild, against the same handler in JS.
  6. Limits today, and what tripped us: three things building a second app turned up, a bug in hazeljs among them.
  7. What next, and how this was put together.

The pattern#

Your app keeps its state and its screen, and Hazel only decides. On an event, the app calls a Hazel function with a typed view of its state and the event, and carries out the command the function returns, which is plain data (Figure 1).

Many JavaScript programs are organized around events: a click, a key, a timer, a message. In this pattern, some of those events are handed to a function written in Hazel. The JS side builds two values: one describing what happened (the event), and one describing what the handler may see (a view of the app's state). It calls the Hazel function with both, and gets back a value describing what to do (a command). Hazel never touches the page or the app's objects; its answer is data, and the app acts it out. We call a program built this way a Hazlet; Messed Up Dress Up is the first one (^report(39)).

Your app, with some of its handlers in Hazel (hazeljs)your JS appkeeps the state,draws, takes inputa view of the statea typed Hazel recordthe eventa Hazel constructoron_eventa Hazel function,type-checked as typeda commanddata your appacts outthe app performs the command; while the Hazel program is unfinished or has errors, your own JS handler answers instead
Figure 1. The pattern. The app hands Hazel a typed view of its state and an event, and acts out the command that comes back. While the Hazel program has errors or is unfinished, the app's own JS handler answers instead, so the app keeps working while its rules are being edited.

Why write a handler in Hazel at all? Three reasons, each of which the game uses:

How Messed Up Dress Up does it#

In the game's 📜 Scripting tab, the game's logic for five rooms is a Hazel program made of modules: 📚 Common, helpers every room can use, then one module per room. A red lever pulled in the castle's trap room is the event Pull(L). The game builds the room's view of its state, a Globals record (the levers, how the pits are wired, the game's random draws, and more), and calls TrapRoom.on_event. The rule answers a Cmd, a chain of commands such as Flip(L, SetPit(0, true, Done)): flip the lever, then open pit 0. The game carries out each command the way its own code would, with its animation.

The game's Scripting panel at full size: the game's view at the top left, and the trap room's rule in Hazel, a case on the event: a red lever pulled flips the pits wired to it, a blue lever pulled moves the boulders.
Figure 2. The trap room's rule in the game's Scripting panel, in Hazel's own editor, beside the game. From the game's Game Scripts Guide.

All of it is in one file of the game, js/25-scripting.js (read at the game's 0.0.491). The pieces, in the order an event meets them:

PieceWhat it doesIn the game's code
The vocabularyHazel types, declared before every module: Cmd (what a rule may do, each command with the rest after it, ending in Done), Event, Globals, and sums for the game's own words (a lever's side L or R, a wiring, a direction, a kind of room).SCRIPT_PREAMBLE
The modules📚 Common, then one per room; each is the text in one of the panel's editors. The tail of the program gives each room's on_event, held to the type a rule has.scriptTail
scriptSpec
Loading HazelThe library, from hazeljs on a CDN, loaded with a script tag the first time a script runs or the tab opens.hazelLoad
BuildingHazel.runProgram on the modules' texts, once per change of text (the texts are the cache key). It keeps the errors, holes and unfinished brackets, module by module, and each room's handler.scriptCompile
CallingOnly when the program is ready: otherwise the game's own JS handler answers the event, and Hazel's answer, run as far as its errors allow, goes in the event log beside it.scriptEventRun
The boundaryThe game's own state has text where the rules have sums (a lever's name "L"); a wrapper turns text into constructors on the way in, and back on the way out.scriptTyped
ActingWalks the command chain, each command by the room's own method; Say and Wait are the game's everywhere; a command the room does not know ends the walk, and is said.scriptRun
SCRIPT_ACTS
Errors, said plainlyHazel's messages are written for Hazel's developers; the game rewrites a type error as "this is wanted here, but this is that", by the game's own type names.scriptErrorText

The editor in the game is Hazel's own: its app, in a frame, showing each module in Hazel's tiles with its error marks, and posting each edit back to the game. That part is not in hazeljs; it comes from a branch build of Hazel (^report(39) has where each piece stands). Plain text boxes work too, and are where the game started.

Doing the same in another app: our Petri net example#

Six steps: declare the vocabulary as Hazel types; let users write modules against it; build the program with Hazel.runProgram; call the Hazel function only while the build is ok, and your own JS handler otherwise; carry out its commands; and show its errors by module.

To see what a second app takes, we did it ourselves, as another user of hazeljs would: we took the pattern out of the game and built a small app around a Petri net, in a repository of its own, matthewhammer/hazeljs-petri-example. It is now at version 0.0.7, and live at matthewhammer.org/hazeljs-petri-example: the rules in Hazel's editor on the left; the net, its buttons and its event log on the right; each error under the rule it is in; and full screen, with a divider between the columns. Its rules and its net are files (rules/*.hz, net.json), read both by its page and by a Node script, so the same rules run in both. This is what we did, in the order we did it; the code is cut from the files that ran. The next section runs the result on this page.

  1. We installed hazeljs. npm install hazeljs, then import Hazel from "hazeljs" in Node; in the page, <script src="https://cdn.jsdelivr.net/npm/hazeljs@0.0.4/hazel-lib.js">, which defines window.Hazel. We pinned the version: the package is a prototype, and its API may change in any release.

  2. We wrote the vocabulary first, as Hazel types in the program's preamble (rules/preamble.hz), which every module sees: what a rule is told (Net), what can happen (Event), and what a rule may answer (Cmd). The answer is a chain of commands, each with the rest after it, ending in Done, so the page can walk it in order, log it, and refuse a command it does not know.

    type Arc = (place = Int, weight = Int) in
    type Transition = (name = String, inputs = [Arc], outputs = [Arc]) in
    type Net = (marking = [Int], transitions = [Transition], draw = Float) in
    type Event = + Fire(Int) + Step in
    type Cmd = + Done + Take(Int, Int, Cmd) + Put(Int, Int, Cmd) + Say(String, Cmd) in

    Sum types go here, not inside a module: a type's constructors are in scope only where the type is. This is also where another group's nets would differ first: tokens that carry data, weights, a guard, a clock.

  3. We split the rules into modules, as the game does: helpers in Common, the handler in Rules, each a text (and a file). A module's text is its members, with no in; one module sees the ones before it, by name (Common.fire).

  4. We built the program with Hazel.runProgram, once per change of text. The tail is what the program gives back: here, the handler, held to its type.

    function build(rules) {
      const r = Hazel.runProgram(spec(rules));
      return { ok: r.ok, errors: r.errors.map(e => `${e.module ?? "the program"}: ${e.message.replace(/\s+/g, " ")}`),
               holes: r.holes, incomplete: r.incomplete, ms: r.ms, handler: r.ok ? r.value : null };
    }
  5. We kept our own JS handler, and call Hazel's only while the build is ok; ours answers while a rule has errors, holes or unfinished brackets. Hazel still runs a program around its errors, so the page can log what Hazel would have said, but where an error stopped it, the value is a printout ({hazel: "..."}), not something to act on.

    function jsHandler(net, ev) {
      const t = net.transitions[ev.tag === "Fire" ? ev.value : 0];
      const ok = t && t.inputs.every(a => net.marking[a.place] >= a.weight);
      if (!ok) return { tag: "Say", value: ["(js) cannot fire", { tag: "Done" }] };
      let k = { tag: "Done" };
      for (const a of [...t.outputs].reverse()) k = { tag: "Put", value: [a.place, a.weight, k] };
      for (const a of [...t.inputs].reverse()) k = { tag: "Take", value: [a.place, a.weight, k] };
      return { tag: "Say", value: ["(js) " + t.name, k] };
    }
    const handlerOf = b => b.ok ? b.handler : jsHandler;
  6. We acted out the commands, and showed the errors by module. Values cross the boundary as plain JS: a labeled tuple is an object, a list an array, a constructor {tag, value}, a function a JS function. The page keeps control: it refuses a command that would take a place below zero, and one it does not know.

    function perform(cmd, marking, log) {
      const m = marking.slice();
      for (let c = cmd; c && c.tag !== "Done"; ) {
        const [a, b, rest] = Array.isArray(c.value) ? c.value : [c.value];
        if (c.tag === "Take") { m[a] -= b; c = rest; }
        else if (c.tag === "Put") { m[a] += b; c = rest; }
        else if (c.tag === "Say") { log.push(a); c = b; }
        else throw new Error("a command this app does not know: " + c.tag);
      }
      return m;
    }

Three things tripped us along the way, none of them in the game's way of doing it; they are in What tripped us, after the limits.

For your own kind of Petri net. Most of what makes one group's nets differ from another's goes in three places: the vocabulary, the helpers, and the net's file. Coloured nets (tokens that carry data, which some groups call types): a place's tokens become a list of Hazel values of that place's type, and a transition's guard and output become Hazel functions, so Hazel's type checker checks the colours as they are written. Weights, inhibitor arcs, priorities, timing: a field in net.json, a case in Common, a word in the vocabulary. And which enabled transition fires is the rule's choice (Step), so a scheduling policy is a few lines of Hazel, swapped without touching the app. The repository's plan has what comes next for it, more nets among them, and a site of its own.

A worked example: a Petri net#

It carried over to a new domain on the first try. The firing rule is about 30 lines of Hazel in two modules, and it ran as written; in 2,000 random steps, the two processes were never both inside the shared section (the runs). The net runs on this page too, its rules in Hazel's own editor, every edit built by hazeljs from npm (try it).

The net is the classic small one for mutual exclusion: two processes, each idle or busy, and one lock. To become busy, a process takes the lock; to become idle again, it gives the lock back (Figure 3). The JavaScript app keeps the marking (the tokens in each place), and draws it. The rule decides what an event does: Fire(i) fires transition i if it can, and Step fires one of those that can, chosen by a random draw the app passes in.

Try it: this page is the app#

Below, this page plays the app. It loads hazeljs 0.0.4 from npm (through the jsDelivr CDN), keeps the net's marking, and draws it. The two modules of rules are in Hazel's own editor, one per module: Hazel's app in a frame, in the editable embed mode that Messed Up Dress Up uses. Every edit comes back to the page, which builds the program again with Hazel.runProgram. While the build is ok, Hazel's on_event answers each event. While it is not, the page's own JS handler answers, the status says why, and the log says who answered. Click a transition to fire it, or step at random.

Where an error shows. An error in a rule is outlined in Hazel's editor where it is, and its message appears under the listing it is in, with a ⚠️, and in the status beside the net, by module. (In Hazel's own app the message is in a bar at the bottom, which the editor in a frame does not have.) The first thing to try below makes one. A ¤ in the editor marks a gap, two pieces side by side with nothing joining them (0. 1, say): join them with an operator or a comma, or delete one.

idle1idle1busy1busy1transition enter1enter1transition leave1leave1idle2idle2busy2busy2transition enter2enter2transition leave2leave2locklock
Figure 3. The example's net, live. Circles are places, with their tokens; bars are transitions, grey when they cannot fire. enter1 takes a token from idle1 and one from lock, and puts one in busy1; leave1 does the reverse. Process 2 is the mirror image.

With JavaScript on, this net runs, and the rules below are Hazel editors.

🪵 event log

The vocabulary, the preamble every module sees. Each listing here is Hazel's editor: Ctrl+click a name (or F12 on it) to go to its definition, in whichever listing has it. The editors start with the text that ran in Node, and Reset the rules goes back to it.

type Arc = (place = Int, weight = Int) in
type Transition = (name = String, inputs = [Arc], outputs = [Arc]) in
type Net = (marking = [Int], transitions = [Transition], draw = Float) in
type Event = + Fire(Int) + Step in
type Cmd = + Done + Take(Int, Int, Cmd) + Put(Int, Int, Cmd) + Say(String, Cmd) in
Common helpers the rules use
# the i-th of a list of Ints, 0 past its end #
let nth = fun (xs, i) : ([Int], Int) ->
  case xs
  | [] => 0
  | x :: rest => if i == 0 then x else nth(rest, i - 1)
  end;
let len = fun xs : [Int] ->
  case xs | [] => 0 | _ :: rest => 1 + len(rest) end;
# the i-th transition, if there is one #
let pick = fun (ts, i) : ([Transition], Int) ->
  case ts
  | [] => None
  | t :: rest => if i == 0 then Some(t) else pick(rest, i - 1)
  end;
# every input place holds at least its arc's weight #
let has = fun (m, arcs) : ([Int], [Arc]) ->
  case arcs
  | [] => true
  | a :: rest => nth(m, a.place) >= a.weight && has(m, rest)
  end;
let enabled = fun (m, t) : ([Int], Transition) -> has(m, t.inputs);
# the indices of the transitions that can fire #
let ready = fun (m, ts, i) : ([Int], [Transition], Int) ->
  case ts
  | [] => []
  | t :: rest =>
    if enabled(m, t) then i :: ready(m, rest, i + 1)
    else ready(m, rest, i + 1)
  end;
# firing: take each input's tokens, then put each output's #
let takes = fun (arcs, k) : ([Arc], Cmd) ->
  case arcs
  | [] => k
  | a :: rest => Take(a.place, a.weight, takes(rest, k))
  end;
let puts = fun (arcs, k) : ([Arc], Cmd) ->
  case arcs
  | [] => k
  | a :: rest => Put(a.place, a.weight, puts(rest, k))
  end;
let fire = fun t : Transition ->
  Say(t.name, takes(t.inputs, puts(t.outputs, Done)))
Rules the handler, on_event
# Fire(i): fire transition i, if it can. #
# Step: fire one of those that can, chosen by the app's draw. #
let fire_at = fun (n, i) : (Net, Int) ->
  case Common.pick(n.transitions, i)
  | None => Say("there is no transition " ++ string_of_int(i), Done)
  | Some(t) =>
    if Common.enabled(n.marking, t) then Common.fire(t)
    else Say(t.name ++ " cannot fire now", Done)
  end;
let on_event = fun (n, e) : (Net, Event) ->
  case e
  | Fire(i) => fire_at(n, i)
  | Step =>
    let r = Common.ready(n.marking, n.transitions, 0) in
    let k = Common.len(r) in
    if k == 0 then Say("deadlock: nothing can fire", Done)
    else
      let j = int_of_float(n.draw *. float_of_int(k)) in
      fire_at(n, Common.nth(r, j))
  end

Things to try.

What the Node runs showed#

Four events by hand (the app's log, then the marking it keeps): the second shows the lock doing its job.

EventThe rule's answer, as the app logs itMarking after (idle1, busy1, idle2, busy2, lock)
Fire(0)enter1[0, 1, 1, 0, 0]
Fire(2)enter2 cannot fire now[0, 1, 1, 0, 0]
Fire(1)leave1[1, 0, 1, 0, 1]
Fire(2)enter2[1, 0, 0, 1, 0]

2,000 random steps, from a fixed stream of draws: fired enter1 485, leave1 485, enter2 515, leave2 515; the two processes were both busy in 0 of the 2,000 markings, and the net ended where it began. The same counts in all three runs.

A mistake in a rule. Change fire_at(n, i) to fire_at(n, "one"), and the build is not ok; Hazel reports, before anything runs, by module:

Rules: Error in term: "one" Nature of error: Expecting type Int but got inconsistent type String
Rules: Error in term: n, "one" Nature of error: Expecting type Net, Int but got inconsistent type Net, String

One mistake gives two messages here, the argument and the pair around it; an app may want to show the first. Meanwhile the app's own JS handler answered Fire(0), so the simulation kept going.

A rule still being written. Replace the Step case's answer with a hole, ?: no error, but holes: {Rules: 1}, and ok is false. That is the state of a rule in the middle of an edit, and the app can say exactly that, rather than "syntax error".

What it costs#

A call costs about 3.3 ms, against 0.7 µs for the same handler in JS: fast enough for each click, but not yet for a simulator's inner loop. Building the program takes 338 to 366 ms, and rebuilding after an edit 138 to 154 ms (Node, three runs).

Milliseconds, logarithmic scale (medians of three runs)1 µs10 µs0.1 ms1 ms10 ms100 ms1 sone frame at 60 fpsyour app's own JS handler, one callyour app's own JS handler, one call: 0.7 µs0.7 µsthe Hazel rule, one callthe Hazel rule, one call: 3.3 ms3.3 msrebuilding the program after an editrebuilding the program after an edit: 151 ms151 msthe first build of the programthe first build of the program: 340 ms340 ms
Figure 4. The example's costs in Node, medians of three runs (the dashed line is one frame of an animation at 60 frames a second). A call to the Hazel rule is a few milliseconds, thousands of times the same handler written in JS; building the program is a few hundred.
RunFirst buildHazel call, median (p90)Same, tail unannotatedJS handler call, medianRebuild: one module changed / unchanged
1366 ms3.45 ms (4.17)3.19 ms (3.79)0.7 µs154 / 148 ms
2340 ms3.33 ms (4.01)3.18 ms (3.96)0.7 µs151 / 148 ms
3338 ms3.23 ms (3.91)3.10 ms (3.76)0.7 µs145 / 138 ms

Making the calls themselves faster is the subject of an experiment on the same agenda: compiling Hazel functions to JavaScript (^report(42), item 2).

Limits today#

What tripped us#

Building the second app turned up three things the game's way of doing it never met, which is why a second app was worth building:

What next#

  1. Ask the group in Cambridge, through Cyrus, what their tools would want a Hazel rule to decide, and what their nets look like (sizes, colours, timing), before building more of the example.
  2. Measure where a call's 3 ms goes in this example: the boundary's conversions against the rule's own evaluation, and how both grow with the net's size.
  3. Once hazel-jit, the compiler of Hazel to JavaScript being designed for livelits' views (^report(42), item 2), can compile this rule: put the JS it makes beside the page's own handler, the JS a person would write, and compare the two, the code side by side and the time per call. How close does the compiled rule come to the hand-written one?
  4. A small helper in hazeljs for the pattern itself: give it the preamble, the modules and the handler's type, and get back a handler that falls back to yours while the rules are not ready.

How this was put together#