@moku-labs/game 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **A 2D puzzle game engine where the game is a deterministic graph of business logic.**
4
4
 
5
- `@moku-labs/game` is a Layer-2 framework on [`@moku-labs/core`](https://github.com/moku-labs/core), written in TypeScript, with PixiJS v8 as a peer dependency. You write small nodes and edge tables. The engine runs them, commits state on the edges, saves at rest points and replays the same game without a screen. It is not a general-purpose engine and it ships no genre rules: no match-3, no merge, no physics. Today it is the logic half only. The screen arrives in V2.
5
+ `@moku-labs/game` is a Layer-2 framework on [`@moku-labs/core`](https://github.com/moku-labs/core), written in TypeScript, with PixiJS v8 as a peer dependency. You write small nodes and edge tables. The engine runs them, commits state on the edges, saves at rest points and replays the same game without a screen. It is not a general-purpose engine and it ships no genre rules: no match-3, no merge, no physics. V1 is the logic half; V2 adds the screen: an own small ECS, projections from committed state, a Pixi v8 renderer loaded lazily, gestures as data components, typed asset keys and scenes as declarations. V3 adds the interface: choreographies as data, strings as data, text from MSDF fonts, screens written in JSX and laid out by Yoga, and sound as an effect a node awaits. V4 adds two doors for the editor: sources that read a running game and dev-only commands that drive it. V5 adds cosmetic effects as data: particles and WGSL filters as components, a frame loop for sprites, and the render numbers that say what they cost; then the production pack of the art, icons that wrap with their words, a text field, and visual tests.
6
6
 
7
7
  <br/>
8
8
 
@@ -15,7 +15,7 @@
15
15
 
16
16
  <br/>
17
17
 
18
- [Why](#why-moku-labsgame) · [Status](#status) · [Install](#install) · [Quick start](#quick-start) · [How it works](#how-it-works) · [Plugins](#plugins) · [Events](#events) · [Configuration](#configuration) · [Development](#development) · [Requirements](#requirements) · [Docs](#docs)
18
+ [Why](#why-moku-labsgame) · [Status](#status) · [Install](#install) · [Quick start](#quick-start) · [How it works](#how-it-works) · [Plugins](#plugins) · [Interface in JSX](#interface-in-jsx) · [Doors for the editor](#doors-for-the-editor) · [Events](#events) · [Configuration](#configuration) · [Development](#development) · [Requirements](#requirements) · [Docs](#docs)
19
19
 
20
20
  ---
21
21
 
@@ -25,23 +25,23 @@
25
25
  - **State commits only on edges.** A node works on drafts. The runner commits them when the node returns an outcome. A node that throws changes nothing.
26
26
  - **Position is data.** Node path, input and state describe the whole game. That gives checkpoints, rollback, bookmarks, fast walk and repro runs.
27
27
  - **Input and world events are answers.** A rest node waits. A player answer comes through the gate, a world event comes through the inbox. Nothing else moves the graph.
28
- - **The screen is a projection, not the game.** Rendering reads committed state and never owns it. The projection arrives in V2. V1 plays whole games headless.
28
+ - **The screen is a projection, not the game.** Rendering reads committed state and never owns it. A projection is one pure `view(item)` function; the engine diffs the components and plays enter, exit, change and settle motions. The same game plays whole headless.
29
29
  - **Deterministic by construction.** Time is an input named `now`. Randomness is a persisted `rng` stream. Lint rule L3 refuses `Date.now` and `Math.random` in the logic set.
30
30
 
31
31
  ## Status
32
32
 
33
- Only V1 exists. Everything else in this table is a plan and may change.
33
+ V1, V2 and V3 are built. V4 has its engine side: the two doors described in [Doors for the editor](#doors-for-the-editor). The editor that uses them is a separate package. V5 is built: the `effects` plugin, the `Frames` component, the `components` prop of the JSX tags and the render numbers; the production pack of `assets` (`--pack`, a v2 manifest with WebP atlas pages); icons inside wrapped text; the `input` tag, a text field; and visual tests in `@moku-labs/game/testing`. Everything after that is a plan and may change.
34
34
 
35
35
  | Milestone | State | Scope | Exit criterion |
36
36
  |---|---|---|---|
37
37
  | V1 | built | `time`, `lifecycle`, `model`, `clock`, `flow`, the `@moku-labs/game/testing` entry | A fixture game is played to the end headless |
38
- | V2 | planned | `world`, `renderer`, `input`, `assets`, `scenes` | A board is visible and items move by drag |
39
- | V3 | planned | `anim`, `i18n`, `audio`, `text`, `ui` | Popup, HUD and buttons with sound |
40
- | V4 | planned | `/inspect` and `/control` entries | External tools can read and drive a game |
41
- | V5 | planned | `effects`, production mode of `assets`, visual test helpers | Not defined yet |
38
+ | V2 | built | `world`, `renderer`, `input`, `assets`, `scenes`, the `@moku-labs/game/assets` entry | A board is visible and items merge by drag; the same game still plays to the end headless |
39
+ | V3 | built | `anim`, `i18n`, `text`, `ui`, `audio`, the `@moku-labs/game/jsx-runtime` entry | Popup, HUD and buttons with sound; the same game still plays to the end headless |
40
+ | V4 | doors built | `/inspect` and `/control` entries | External tools can read and drive a game |
41
+ | V5 | built | `effects`, `Frames`, render passes and draw calls; the production pack of `assets`, icons in wrapped text, the `input` tag, visual tests in `/testing` | Not defined yet |
42
42
  | V6 | planned | `platform` | A template game runs on a phone |
43
43
 
44
- Rendering decision for V2: WebGPU is preferred, with Pixi's WebGL fallback.
44
+ Rendering: WebGPU is preferred, with Pixi's WebGL fallback and an honest "unsupported device" screen when neither exists.
45
45
 
46
46
  ## Install
47
47
 
@@ -53,7 +53,7 @@ bun add @moku-labs/game pixi.js
53
53
  > **Status: `0.0.0`, not published yet.** The package is not on npm. The command above is the intended install line. `pixi.js` `^8.0.0` is a peer dependency. No V1 code imports it.
54
54
 
55
55
  > [!IMPORTANT]
56
- > Bun only. ESM only. `"sideEffects": false`. There is no CJS build.
56
+ > Bun only. ESM only. `"sideEffects": false`. There is no CJS build. `yoga-layout` is a dependency the `ui` plugin loads lazily; nothing imports it before `onStart`.
57
57
 
58
58
  ## Quick start
59
59
 
@@ -149,6 +149,8 @@ export const createGame = (seed: "from-save" | number = "from-save") =>
149
149
  });
150
150
  ```
151
151
 
152
+ A hook that throws never stops the game. The engine writes it to the log as the error entry `"game: a hook failed"`; read it with `app.log.trace()`. A game can add its own `onError: (error, ctx) => …` to `createApp`; the kernel calls both.
153
+
152
154
  **5. Play it headless.** `createHeadless` returns a game object once the graph rests at its first
153
155
  rest node. Its `walk` method plays a route.
154
156
 
@@ -181,7 +183,7 @@ it("plays two rolls and a reset without a screen", async () => {
181
183
  In a live game the same answer comes from the screen: `app.flow.gate.answer({ intent: "roll" })`.
182
184
 
183
185
  > [!TIP]
184
- > Types reach a game through one namespace per plugin: `import type { Flow, Model, Clock, Lifecycle, Time } from "@moku-labs/game"`, then `Flow.RouteStep`, `Model.PlayerStateProvider`, `Time.Phase`.
186
+ > Types reach a game through one namespace per plugin: `import type { Flow, Model, Clock, Lifecycle, Time } from "@moku-labs/game"`, then `Flow.RouteStep`, `Model.PlayerStateProvider`, `Time.Phase`. The screen and interface plugins follow the same rule: `World`, `Renderer`, `Input`, `Assets`, `Scenes`, `Anim`, `I18n`, `TextTypes`, `Ui`, `Audio`. `Text` is the component, so its type namespace is `TextTypes`.
185
187
 
186
188
  > [!TIP]
187
189
  > A larger worked example lives in [`tests/integration/merge-game/`](./tests/integration/merge-game). It is a small game written on the public API only, with sub-flows, a slot, a feature and timers. It is an internal test fixture and is not published. Its scenario is [`tests/integration/template-merge.test.ts`](./tests/integration/template-merge.test.ts).
@@ -196,7 +198,7 @@ flowchart LR
196
198
  N --> E["Edge<br/>commit, journal, flow:edge"]
197
199
  E --> R
198
200
  E --> M["model<br/>committed state and save"]
199
- M --> S["Screen<br/>projection, V2"]
201
+ M --> S["Screen<br/>projection, JSX"]
200
202
  classDef u fill:#0b7285,stroke:#08525f,color:#fff;
201
203
  classDef m fill:#1864ab,stroke:#0d3d6e,color:#fff;
202
204
  class P,W,S u
@@ -223,7 +225,7 @@ flowchart LR
223
225
 
224
226
  ## Plugins
225
227
 
226
- Seven plugins are on every app today. `log` and `env` come from [`@moku-labs/common`](https://github.com/moku-labs/common) and sit on every plugin context as `ctx.log` and `ctx.env`.
228
+ Five logic plugins are on every app; the nine screen plugins are the list `screen` a game spreads in; `audio` and `effects` are opt-in, `[...screen, audioPlugin, effectsPlugin]`. `log` and `env` come from [`@moku-labs/common`](https://github.com/moku-labs/common) and sit on every plugin context as `ctx.log` and `ctx.env`.
227
229
 
228
230
  ### Built
229
231
 
@@ -233,7 +235,18 @@ Seven plugins are on every app today. `log` and `env` come from [`@moku-labs/com
233
235
  | [`lifecycle`](./src/plugins/lifecycle/README.md) | Standard | The stack of pause reasons. Pauses `time` by a direct call | `push(reason)`, `pop(reason)`, `reasons()`, `isPaused()` |
234
236
  | [`model`](./src/plugins/model/README.md) | Very Complex | The `session` tree and the save document `{ player, rng }`, transactions, rest-point rollback, rng streams | `store.load()`, `store.snapshot()`, `store.begin()`, `store.markRest()`, `store.markBarrier(txId)`, `store.rollback()`, `store.restore(input)`, `store.flush()`, `rng.peek(id)` |
235
237
  | [`clock`](./src/plugins/clock/README.md) | Standard | Trusted time as an input: monotonic `now()` and one `elapsed` signal at the next due moment | `now()`, `scheduleAt(moment)`, `onElapsed(listener)`, `poke()`, `dueAt()` |
236
- | [`flow`](./src/plugins/flow/README.md) | Very Complex | The graph: runner, gate, inbox, effects gateway, features registry | `run()`, `register(flow)`, `onEnter(stage, callback)`, `walk(route, options?)`, `bookmark()`, `restore(bookmark)`, `describe()`, `state()`, `history()`, `setMode(mode)`, `gate.answer(answer)`, `gate.pointer(active)`, `gate.state()`, `inbox.post(event)`, `fx.handle(kind, handler, options?)`, `fx.dispatch(descriptor)`, `features.register(name, description)`, `features.all()`, `features.contributions(slotName)` |
238
+ | [`flow`](./src/plugins/flow/README.md) | Very Complex | The graph: runner, gate, inbox, effects gateway, features registry | `run()`, `onEnter(stage, callback)`, `walk(route, options?)`, `bookmark()`, `restore(bookmark)`, `describe()`, `state()`, `history()`, `setMode(mode)`, `gate.answer(answer)`, `gate.pointer(active)`, `gate.state()`, `inbox.post(event)`, `fx.handle(kind, handler, options?)`, `fx.dispatch(descriptor)`, `features.register(name, description)`, `features.all()`, `features.contributions(slotName)` |
239
+ | [`world`](./src/plugins/world/README.md) | Very Complex | A zero-dependency ECS (`ecs`) and the projection from committed state to entities (`projection`): keyed reconcile of one `view(item)` function, retarget motions, a despawn queue, named layers | `ecs.spawn(owner, components)`, `ecs.query(...Components)`, `ecs.system(def)`, `ecs.set(entity, Component, patch)`, `ecs.changed(Component)`, `ecs.snapshot()`, `ecs.mode()`, `projection.mount(names, owner)`, `projection.setLayers(list)`, `projection.settle(entity)`, `projection.keyOf(entity)`, `projection.entityOf(projection, key)` |
240
+ | [`renderer`](./src/plugins/renderer/README.md) | Very Complex | The Pixi v8 host loaded lazily (`host`), one `sync` system that owns every display object, the reference viewport fitted to `referenceSide` and `referenceLong` (`viewport`), the frame numbers: render passes in every build, draw calls in a dev build | `host.ready()`, `host.kind()`, `host.canvas()`, `host.device()`, `sync.hitTest(x, y, accept)`, `sync.textures.provide(fn)`, `sync.filters.set(entity, slots)`, `sync.displayOf(entity)`, `viewport.toReference(x, y)`, `viewport.size()`, `stats()` |
241
+ | [`input`](./src/plugins/input/README.md) | Standard | Gestures as data components: `Tappable`, `Pressable`, `Draggable`, `DropTarget`, `Swipeable`; the drop target names the intent that reaches `flow.gate` | `tap(target)`, `press(target)`, `drag(from, to)`, `swipe(target, direction)` |
242
+ | [`assets`](./src/plugins/assets/README.md) | Complex | The manifest, five load tiers, graph-driven preload, a texture budget with LRU unload; typed keys from the `assets` entry | `load(bundle)`, `unload(bundle)`, `isLoaded(bundle)`, `texture(key)`, `usage()` |
243
+ | [`scenes`](./src/plugins/scenes/README.md) | Standard | A scene as a declaration: bundle, layers, projections, `music`. A node names its scene; the runner switches through `flow.onEnter` | `current()` |
244
+ | [`anim`](./src/plugins/anim/README.md) | Complex | The one tween core, installed into `world.projection` as the `TweenDriver`; timelines as frozen data built from typed slots; `defineMotion` sugar for the enter, exit and change hooks; the `Frames` component, a frame loop that walks a sprite's textures for its whole life | `play(animation, slots)`, `finishAll()`, `active()`, `onMark(fn)` |
245
+ | [`i18n`](./src/plugins/i18n/README.md) | Complex | Strings as data: `tr(key, params)` is a `Message`, ICU MessageFormat compiled to plain functions by `compileStrings` on the `assets` door, `Part[]` at run time, never a joined string | `locale()`, `setLocale(locale)`, `format(message, locale?)`, `plain(message)`, `has(key)`, `locales()` |
246
+ | [`text`](./src/plugins/text/README.md) | Complex | The `Text` component, `label()`, `defineTextStyles()`, the tags `<b> <i> <color=#hex> <icon=key>`, measurement from the font's advance table, BitmapText from the MSDF fonts of a bundle | `measure(content, style)`, `styles()` |
247
+ | [`ui`](./src/plugins/ui/README.md) | Very Complex | A screen is a projection whose `view` returns JSX; the tree is reconciled by identity into entities, laid out by one Yoga solve per change, `Box` is the rest pose; `defineComponent` with `local` and `outcomes`, `popup` as an effect, `defineStyle`, `defineTokens`; every tag takes `components`, extra component values such as a filter; the `input` tag is a text field whose text lives in `local` | `tree()`, `find(key)`, `lint()`, `fill(key, value)` |
248
+ | [`audio`](./src/plugins/audio/README.md) | Standard | Opt-in. Buses `master`, `music`, `sfx`; `sfx()` descriptors of `anim` and `music()` descriptors handled here; the scene's `music`; volumes read from the committed player through `volumes` | `setVolume(bus, value)`, `volume(bus)`, `mute(bus, on)`, `unlocked()` |
249
+ | [`effects`](./src/plugins/effects/README.md) | Complex | Opt-in. Particles: `defineEmitter` and the `Emitter` component, one Pixi `ParticleContainer` per instance stepped by the engine clock. Filters: `defineFilter` turns a WGSL fragment body into a flat component that `tween` drives; `Glow`, `Outline`, `Blur`, `ColorMatrix`, `Noise`, `Displacement`, `Alpha` ship built in. Budgets warn once per crossing; a dev build compiles each WGSL kind before its first instance. Headless it draws nothing | `stats()` |
237
250
 
238
251
  ```mermaid
239
252
  flowchart LR
@@ -243,13 +256,51 @@ flowchart LR
243
256
  F --> M["model"]
244
257
  F --> C["clock"]
245
258
  L --> T
259
+ W["world"] --> T
260
+ W --> M
261
+ W --> F
262
+ R["renderer"] --> T
263
+ R --> L
264
+ R --> W
265
+ I["input"] --> F
266
+ I --> W
267
+ I --> R
268
+ A["assets"] --> F
269
+ A --> R
270
+ S["scenes"] --> F
271
+ S --> W
272
+ S --> A
273
+ AN["anim"] --> F
274
+ AN --> W
275
+ AN --> R
276
+ N["i18n"] --> F
277
+ X["text"] --> W
278
+ X --> R
279
+ X --> A
280
+ X --> N
281
+ U["ui"] --> I
282
+ U --> AN
283
+ U --> X
284
+ AU["audio"] --> L
285
+ AU --> M
286
+ AU --> F
287
+ AU --> A
288
+ AU --> S
289
+ EF["effects"] --> F
290
+ EF --> W
291
+ EF --> R
292
+ EF --> A
246
293
  classDef u fill:#0b7285,stroke:#08525f,color:#fff;
247
294
  classDef m fill:#1864ab,stroke:#0d3d6e,color:#fff;
295
+ classDef s fill:#5c940d,stroke:#3d6208,color:#fff;
296
+ classDef v fill:#862e9c,stroke:#5f1f70,color:#fff;
248
297
  class G u
249
298
  class F,T,L,M,C m
299
+ class W,R,I,A,S s
300
+ class AN,N,X,U,AU,EF v
250
301
  ```
251
302
 
252
- An arrow means "depends on". `time`, `model` and `clock` depend on nothing. The plugins are registered in this order: `time`, `lifecycle`, `model`, `clock`, `flow`.
303
+ An arrow means "depends on"; for the V3 plugins the edges to `time` and the edges a nearer plugin already implies are left out for space, the plugin READMEs list them in full. `time`, `model` and `clock` depend on nothing. The logic plugins are registered in this order: `time`, `lifecycle`, `model`, `clock`, `flow`; the screen set `screen` follows as `world`, `renderer`, `input`, `assets`, `scenes`, `anim`, `i18n`, `text`, `ui`; a game that wants sound appends `audioPlugin`, and one that wants particles and filters appends `effectsPlugin`. A game without `effectsPlugin` carries none of its systems, filters or WGSL in its bundle. Without a document the screen plugins are inert: the same app starts in plain Bun, Yoga included.
253
304
 
254
305
  ### Planned
255
306
 
@@ -257,17 +308,6 @@ Not built. Names are reserved: `defineFeature` refuses them as feature names. Sc
257
308
 
258
309
  | Plugin | Milestone | Tier | Depends on | Will own |
259
310
  |---|---|---|---|---|
260
- | `world` | V2 | Very Complex | `time`, `model`, `flow` | ECS world and the projections of the model |
261
- | `renderer` | V2 | Very Complex | `time`, `lifecycle`, `world` | The Pixi host, sync and viewport. Pixi is loaded lazily |
262
- | `input` | V2 | Standard | `time`, `flow`, `world`, `renderer` | Pointer listeners on the canvas |
263
- | `assets` | V2 | Complex | `flow`, `renderer` | Manifest, tiers, preload, budget |
264
- | `scenes` | V2 | Standard | `flow`, `world`, `assets` | Scenes as data, switched through `flow.onEnter` |
265
- | `anim` | V3 | Complex | `flow`, `world` | Tweens and motion |
266
- | `i18n` | V3 | Standard | `flow`, `world`, `assets` | String tables per locale |
267
- | `text` | V3 | Complex | `world`, `renderer`, `assets`, `i18n` | Text rendering and the text field |
268
- | `ui` | V3 | Very Complex | `flow`, `world`, `renderer`, `anim`, `i18n`, `text` | JSX components, styles, layout |
269
- | `audio` | V3 | Standard | `lifecycle`, `flow`, `assets`, `scenes` | Audio context and unlock |
270
- | `effects` | V5 | Complex | `flow`, `world`, `renderer` | Particles, filters, frames |
271
311
  | `platform` | V6 | Standard | `lifecycle`, `flow` | The native provider: background, system dialogs |
272
312
 
273
313
  ### Root exports
@@ -276,18 +316,37 @@ Not built. Names are reserved: `defineFeature` refuses them as feature names. Sc
276
316
  |---|---|---|
277
317
  | `createApp` | function | Creates a game application |
278
318
  | `createPlugin` | function | Creates a game plugin bound to the engine's config and events |
279
- | `defineGame` | function | Returns `{ defineNode, defineFlow, defineFeature }` typed with the game's `player` and `session` |
280
- | `defineFeature` | function | Turns a feature description into a plugin |
319
+ | `defineGame` | function | Returns the authoring helpers typed with the game's `player`, `session`, `assets`, `bundles`, `strings`, `textStyles` and `emitters`: `defineNode`, `defineFlow`, `defineFeature`, `projection`, `sprite`, `Sprite`, `NineSlice`, `defineBundles`, `load`, `defineScene`, from V3 `tr`, `label`, `defineTextStyles`, `defineComponent`, `defineStyle`, `defineTokens`, `popup`, `defineAnimation`, `frames`, `sfx`, `play`, `music`, and from V5 `Frames`, `defineEmitter`, `Emitter`, `Displacement`: a texture key the game does not have or an effect id it did not declare does not compile |
320
+ | `defineFeature` | function | Turns a feature description into a plugin. V3 keys: `projections`, `animations`, `ui`, `strings`, `textStyles`. V5 keys: `emitters`, `filters` |
281
321
  | `type`, `exit`, `to`, `slot` | functions | Type tag of a payload, and the three graph helpers for edge targets and slots |
282
322
  | `schedule`, `guide`, `hint` | functions | Effect descriptors: next due moment, tutorial narrowing of the gate, cosmetic hint |
283
323
  | `SaveUnreadableError` | class | Thrown by `model.store.load()` when the save cannot be read |
284
- | `teardown` | object | `teardown.register(global, key, dispose)` and `teardown.run(global, key)` for plugins that own a resource |
285
- | `timePlugin`, `lifecyclePlugin`, `modelPlugin`, `clockPlugin`, `flowPlugin` | plugin instances | For `depends` and `ctx.require` in game plugins |
286
- | `Time`, `Lifecycle`, `Model`, `Clock`, `Flow` | type namespaces | All public types of one plugin |
324
+ | `component`, `tag`, `resource`, `mut`, `system`, `projection`, `Layer`, `Order`, `Exiting`, `Tree` | functions and components | The ECS vocabulary of `world` and the projection helper |
325
+ | `Transform`, `Sprite`, `NineSlice`, `Shape`, `Parent`, `Display`, `sprite` | components | The display components of `renderer` |
326
+ | `Tappable`, `Pressable`, `Draggable`, `DropTarget`, `Swipeable`, `Touchable`, `Held`, `Hovered`, `PointerOver`, `Pressed`, `Pointer` | components | Gestures as data, from `input`; `PointerOver` marks the view under an idle mouse or pen (the `hover` style state) |
327
+ | `defineBundles`, `load`, `defineScene` | functions | Bundle and scene declarations |
328
+ | `defineAnimation`, `sequence`, `parallel`, `stagger`, `tween`, `set`, `wait`, `mark`, `frames`, `sfx`, `haptic`, `use`, `spawn`, `spawned`, `play`, `external`, `defineMotion`, `Animation`, `Frames` | functions and components | Choreography as frozen data. `play(animation, slots)` is the effect a node awaits; `spawn` makes a temporary entity (flying coins, a toast sign) that the timeline despawns when it ends; `sfx` and `haptic` are descriptors `audio` and `platform` handle; `external` throws until Spine arrives. `Frames({ keys, fps, loop, playing })` walks a sprite through its textures for the entity's whole life, a spinning coin |
329
+ | `tr` | function | `tr(key, params?)` builds a frozen `Message`; no locale is read at the call site |
330
+ | `Text`, `label`, `defineTextStyles` | component and functions | Words on the screen and the text styles a feature registers |
331
+ | `defineComponent`, `popup`, `defineStyle`, `defineTokens`, `resolve`, `Box`, `LocalWrite` | functions and components | Interface components, the popup effect, the style vocabulary, the rect of an element |
332
+ | `music` | function | `music(key \| null, { fadeMs? })`, the awaited effect that switches the music track |
333
+ | `defineEmitter`, `Emitter`, `defineFilter`, `Glow`, `Outline`, `Blur`, `ColorMatrix`, `Noise`, `Displacement`, `Alpha` | functions and components | Effects as data, drawn by `effectsPlugin`. `defineEmitter(id, config)` describes a particle effect that a feature lists under `emitters`; `Emitter({ effect, active })` runs it on its entity. `defineFilter(id, { wgsl, uniforms, passes?, padding? })` returns a filter component type that a feature lists under `filters`; a filter on a ui element goes in its `components` prop |
334
+ | `timePlugin`, `lifecyclePlugin`, `modelPlugin`, `clockPlugin`, `flowPlugin`, `worldPlugin`, `rendererPlugin`, `inputPlugin`, `assetsPlugin`, `scenesPlugin`, `animPlugin`, `i18nPlugin`, `textPlugin`, `uiPlugin`, `audioPlugin`, `effectsPlugin` | plugin instances | For `depends` and `ctx.require` in game plugins; `screen` is the list of the nine screen plugins |
335
+ | `Time`, `Lifecycle`, `Model`, `Clock`, `Flow`, `World`, `Renderer`, `Input`, `Assets`, `Scenes`, `Anim`, `I18n`, `TextTypes`, `Ui`, `Audio`, `Effects` | type namespaces | All public types of one plugin |
336
+
337
+ ### Other entries
338
+
339
+ | Entry | Runs in | Exports |
340
+ |---|---|---|
341
+ | `@moku-labs/game/testing` | node and bun only | The headless helpers and the visual tests, see below. The visual runner reads and writes baseline files |
342
+ | `@moku-labs/game/assets` | node and bun only | `scanAssets`, `emitKeys`, `emitManifest`, `compileStrings`, `checkStrings`, `packAssets`, `runCli`. A game runs it as `bun run assets:keys`: it writes the manifest, the typed asset keys and, next to them, `generated/strings.ts` with one `strings.<locale>.ts` per locale; `--check` fails when any of them is out of date; `--pack <dir>` writes the production build: WebP atlas pages, content-hashed names and a v2 manifest |
343
+ | `@moku-labs/game/inspect` | anywhere, production included | `read`, `watch`, `defineSource`, the catalogue `sources` and the types `Source`, `InputSchema`, `InputOf`. See [Doors for the editor](#doors-for-the-editor) |
344
+ | `@moku-labs/game/control` | dev builds only | `run`, `defineCommand`, `controlRefused`, the catalogue `commands` and the types `Command`, `Ran`. See [Doors for the editor](#doors-for-the-editor) |
345
+ | `@moku-labs/game/jsx-runtime`, `@moku-labs/game/jsx-dev-runtime` | anywhere | `jsx`, `jsxs`, `jsxDEV`, `Fragment` and the `JSX` namespace that `"jsxImportSource": "@moku-labs/game"` resolves to. A game never imports them by hand |
287
346
 
288
347
  ### Testing entry
289
348
 
290
- `@moku-labs/game/testing` re-exports the headless helpers.
349
+ `@moku-labs/game/testing` re-exports the headless helpers and the visual tests.
291
350
 
292
351
  | Export | Signature | Purpose |
293
352
  |---|---|---|
@@ -297,9 +356,353 @@ Not built. Names are reserved: `defineFeature` refuses them as feature names. Sc
297
356
  | `fakeClock` | `(start = 0) => FakeClock` | A `ClockSource` with `advance(ms)` and `set(moment)` |
298
357
  | `memory` | `(fixture?: { state: SaveDoc; version: number }) => PlayerStateProvider & { calls: ProviderCall[] }` | In-memory save provider. It keeps what it was committed and records every call |
299
358
  | `saveOf` | `(player: Json, seed?: number) => SaveDoc` | Builds a save document for a fixture |
359
+ | `defineVisualTest` | `(name: string, test: { start: VisualStart; steps: readonly VisualStep[] }) => VisualTest` | A visual test as frozen data: where it starts and its steps |
360
+ | `runVisualTests` | `(setup: VisualSetup, tests: readonly VisualTest[], options?: VisualOptions) => Promise<VisualReport>` | Plays the tests and compares every checkpoint with its baseline files |
361
+ | `parseVisualArgv` | `(argv: readonly string[]) => { update?; pixels?; only?; dir? }` | Reads `--update`, `--no-pixels`, `--only <name>` and `--dir <path>` from a command line |
300
362
 
301
363
  A `HeadlessGame` has `walk(route)`, `answer(answer)`, `state()`, `history()` and `stop()`.
302
364
 
365
+ ### Visual tests
366
+
367
+ A visual test is data: where the game starts, then steps. A step is a `/control` command by its short name (`answer`, `tap`, `drag`, `key`, `fill`, `walk`, `restore`, `step`, `pause`, `resume`, `reducedMotion`) with that command's input, or a checkpoint.
368
+
369
+ ```ts
370
+ // tests/visual/reward-popup.visual.ts
371
+ export const rewardPopup = defineVisualTest("reward-popup", {
372
+ start: { player: fixtures.ready, checkpoint: "home" },
373
+ steps: [
374
+ { tap: { key: "play" } },
375
+ { answer: { intent: "deliver", payload: { orderId: "o1" } } },
376
+ { checkpoint: "open" },
377
+ { tap: { key: "claim" } },
378
+ { checkpoint: "claimed" }
379
+ ]
380
+ });
381
+
382
+ // tests/visual/run.ts, `bun tests/visual/run.ts --update`
383
+ const report = await runVisualTests({ app: () => createScreenGame().app, page: { url: "http://localhost:3000/" } }, [rewardPopup]);
384
+ process.exitCode = report.ok ? 0 : 1;
385
+ ```
386
+
387
+ A checkpoint settles the motions and saves three baseline files next to the test: `<dir>/<test>/<checkpoint>/state.json`, `describe.json` and `screen.webp`. A missing file is written; `--update` rewrites them; any other file is compared. The headless leg plays every test in plain Bun and compares `state.json` and `describe.json` exactly, so it runs in `bun run test`. The pixel leg plays the same steps on the dev page in Chrome with WebGPU, on a Mac only, and compares `screen.webp` with a tolerance; a pixel difference with the same state and describe is reported as a rendering regression. The page is the contract: a dev build that sets `globalThis.game` to the app and `globalThis.doors` to `{ read, watch, sources, run, commands }`. No CI job runs pixels.
388
+
389
+ #### Pixels
390
+
391
+ The pixel leg runs on a Mac only. `pixels` is on by default when the setup has a `page` and the platform is `darwin`, and off everywhere else. No CI job runs it: a Linux runner has no WebGPU worth trusting.
392
+
393
+ - **`playwright-core`** is an optional peer dependency. The leg loads it with a dynamic import, so a game that never runs pixels never installs it. Add it with `bun add -d playwright-core`. Without it the run stops with "The pixel leg needs playwright-core"; `--no-pixels` runs the headless leg alone.
394
+ - **The browser.** `page.browser` when the setup names one (`{ channel }` or `{ executablePath }`). Otherwise Playwright's own Chromium, whose version `playwright-core` pins, so a Chrome update never moves the baselines: install it with `bunx playwright-core install chromium`. Otherwise the system Google Chrome. Chrome starts with WebGPU on Metal; a page that draws with anything else fails the leg.
395
+ - **The page.** 390 CSS px wide at a device scale of 2, as tall as the game's inert frame: 520 for a 4:3 portrait game, so `screen.webp` is 780 × 1040.
396
+ - **Game time.** The leg drives the clock itself, so two runs draw the same pixels: a dash phase, a pulse or a particle reads the same time. It waits until the page has loaded what it asked for (no request for half a second), runs `pause`, then steps the game to 5 s of game time, the last frame shorter so it lands exactly. From there every frame of the restore, of every settle and of a checkpoint is a `step` of 1000/60 ms, the frame of the headless leg; the browser's own frames move no game time. The picture is the stage after the last stepped frame. A `resume` step hands the clock back to the browser.
397
+ - **The picture.** Lossless WebP: the page encodes it with `convertToBlob({ type: "image/webp", quality: 1 })`, which Chrome encodes without loss, so the baseline holds the captured pixels exactly.
398
+ - **`--update`** rewrites `state.json`, `describe.json` and `screen.webp` of every test it runs. A pixel difference writes `screen.actual.webp` and `screen.diff.webp` beside the baseline, red where a pixel differs. Git ignores both.
399
+ - **Tolerance.** A pixel differs when one of its channels moves by more than 24. A checkpoint differs when more than 0.1% of its pixels do. Both are `tolerance` in the options.
400
+
401
+ The fixture game keeps its visual tests in `tests/visual/`: one `*.visual.ts` per test, the list in `tests.ts`, the script in `run.ts` and the baselines next to them. The script imports the runner from `src/testing`, so a stale `dist/` never writes baselines. `bun run test` runs the headless leg through `tests/integration/visual-headless.test.ts`. Both legs run against the dev page:
402
+
403
+ ```sh
404
+ # terminal 1: the dev page of the fixture on a free port
405
+ cd tests/integration/merge-game && bun ./web/serve.ts --port 4173
406
+
407
+ # terminal 2: from the root of the repository
408
+ bun run fixture:visual --url http://localhost:4173/ # compare with the baselines
409
+ bun run fixture:visual --url http://localhost:4173/ --update # write the baselines again
410
+ bun run fixture:visual --only gift-popup --no-pixels # one test, headless only
411
+ ```
412
+
413
+ Without `--url` the page is `http://localhost:3000/`. The exit code is 1 when a checkpoint differs.
414
+
415
+ The test of the browser leg itself opens a real Chrome only on request: `MOKU_VISUAL_BROWSER=1 bunx vitest run tests/unit/visual/browser.test.ts`. It also proves the WebP is lossless: random opaque pixels come back byte for byte. Without the variable it skips with its reason, so `bun run test` opens no browser.
416
+
417
+ ## Interface in JSX
418
+
419
+ The interface is one more projection. A screen is a projection whose `view` returns JSX; `ui` reconciles the tree by identity into entities it owns and lays them out with one Yoga solve per change. There is no DOM and no React: the runtime builds plain description nodes, and `"jsxImportSource": "@moku-labs/game"` is the only setup.
420
+
421
+ ```jsonc
422
+ // tsconfig.json of the game
423
+ { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "@moku-labs/game" } }
424
+ ```
425
+
426
+ The tags are `screen`, `layer`, `row`, `column`, `stack`, `spacer`, `panel`, `image`, `icon`, `text`, `button`, `scroll` and `input`. A `button` either names an `intent` for the gate or writes `local` state of its nearest component, never both. An `input` is a text field: its text lives in the `local` field it names, every keystroke writes it, and Enter answers its `submit` intent with `{ [local]: value }`, the only thing the gate hears: `<input key="nameField" local="name" maxLength={16} submit="save" placeholder={tr("rename.hint")} />`. A `text` takes a string or a `Message` from `tr`; its size comes from a text style key, not from the layout style. Every tag takes `components`, a list of extra component values for the element's entity: `<button key="claim" intent="claim" components={[Glow({ strength: 2 })]} />` glows, and the glow covers the button and its label.
427
+
428
+ ```tsx
429
+ // features/hud/view.tsx — the HUD, a reward popup and the choreography they share
430
+ import type { Anim } from "@moku-labs/game";
431
+ import { Transform, mark, parallel, sequence, sfx, tween, type } from "@moku-labs/game";
432
+ import { defineAnimation, defineComponent, defineFeature, defineTextStyles, projection, tr } from "../../state";
433
+
434
+ export const hud = projection({
435
+ name: "hud",
436
+ layer: "ui",
437
+ from: player => ({ coins: player.coins }),
438
+ view: hud => (
439
+ <row key="bar" style={{ gap: 16, padding: { top: "safeArea.top", left: 24, right: 24 }, width: "100%", height: 120 }}>
440
+ <text key="coins" style="hud.digits" content={tr("hud.coins", { n: hud.coins })} />
441
+ <button key="settings" intent="openSettings" style={{ width: 96, height: 96 }}>
442
+ <icon name="hud.gear" />
443
+ </button>
444
+ </row>
445
+ )
446
+ });
447
+
448
+ export const RewardPopup = defineComponent("RewardPopup", {
449
+ outcomes: { claim: type<{ orderId: string }>() },
450
+ view: (props: { orderId: string; gold: number }) => (
451
+ <panel key="reward" style={{ nineSlice: "ui.panel", direction: "column", gap: 16, padding: 32, width: 600, height: 400, fit: "contain" }}>
452
+ <text key="title" content={tr("orders.complete")} />
453
+ <text key="gold" style="hud.digits" content={String(props.gold)} />
454
+ <button key="claim" intent="claim" payload={{ orderId: props.orderId }} style={{ width: 240, height: 88 }}>
455
+ <text content={tr("common.claim")} />
456
+ </button>
457
+ </panel>
458
+ )
459
+ });
460
+
461
+ export const popCoins = defineAnimation("hud.popCoins", {
462
+ slots: { coins: type<Anim.Target>() },
463
+ build: ({ coins }) =>
464
+ sequence(
465
+ tween(coins, Transform, { scale: 1.2 }, { ms: 120 }),
466
+ parallel(tween(coins, Transform, { scale: 1 }, { ms: 200, ease: "outCubic" }), sfx("hud.coins")),
467
+ mark("done")
468
+ )
469
+ });
470
+
471
+ export const hudFeature = defineFeature("hud", {
472
+ projections: [hud],
473
+ ui: [RewardPopup],
474
+ animations: [popCoins],
475
+ textStyles: defineTextStyles({ "hud.digits": { font: "ui.font-digits", size: 40, fill: 0xffe082, digits: true } }),
476
+ strings: { en: () => import("../../generated/strings.en") }
477
+ });
478
+ ```
479
+
480
+ A popup is an effect. The node awaits it, the gate opens for the outcomes of the component, and the promise resolves with the intent of the button the player pressed. The choreography is played the same way.
481
+
482
+ ```ts
483
+ // features/orders/deliver.ts
484
+ import { play, sfx, type } from "@moku-labs/game";
485
+ import { defineNode, popup } from "../../state";
486
+ import { popCoins, RewardPopup } from "../hud/view";
487
+
488
+ export const deliver = defineNode({
489
+ outcomes: { claimed: type<{ orderId: string }>() },
490
+ run: async ({ player, fx, out }) => {
491
+ fx(sfx("orders.complete"));
492
+ const answer = (await fx(popup(RewardPopup, { orderId: "o1", gold: 5 }))) as { intent: "claim"; payload: { orderId: string } };
493
+
494
+ player.coins += 5;
495
+ await fx(play(popCoins, { coins: { projection: "hud", key: "coins" } }));
496
+ return out.claimed({ orderId: answer.payload.orderId });
497
+ }
498
+ });
499
+ ```
500
+
501
+ Headless the same node runs to the end: `popup` resolves through the gate, `play` finishes at once in fast mode, and `sfx` without `audio` resolves `undefined`. The strings behind `tr` come from `features/*/strings/<locale>.json`; `bun run assets:keys` compiles them next to the asset keys, and `strings: Strings` in `defineGame` makes a wrong key or a missing parameter a compile error.
502
+
503
+ ```ts
504
+ // game.ts — sound is opt-in, the buses follow the committed player
505
+ createApp({
506
+ plugins: [...screen, audioPlugin, hudFeature],
507
+ pluginConfigs: {
508
+ renderer: { mount: "#game" },
509
+ audio: { volumes: player => (player as Player).settings.audio }
510
+ }
511
+ });
512
+ ```
513
+
514
+ `volumes` receives the committed player as `Json`, so the game names its own type once. `player.settings.audio` is `{ master?, music?, sfx? }`, committed by a settings node like any other state and applied on every `model:committed`.
515
+
516
+ > [!TIP]
517
+ > `app.ui.tree()` answers the live screen as plain data, `app.ui.find(key)` the entity of a keyed element, and `app.ui.lint()` the tap targets under `tapTargetPt`, the text that overflows in some locale and the absolute elements without a `reason`. The example app of the `ui` tests, [`src/plugins/ui/__tests__/app.tsx`](./src/plugins/ui/__tests__/app.tsx), is a whole HUD with a settings component, a scrolling list and a popup, run in plain Bun.
518
+
519
+ ## Doors for the editor
520
+
521
+ The editor, MCP tools and e2e scripts reach a running game through two subpaths. Neither is on the root.
522
+
523
+ | Subpath | Exports | In a production build |
524
+ |---|---|---|
525
+ | `@moku-labs/game/inspect` | `read`, `watch`, `defineSource`, the catalogue `sources`, the types `Source`, `InputSchema`, `InputOf` | Safe. Every source only reads. The door reaches no command module, so its bundle carries no command |
526
+ | `@moku-labs/game/control` | `run`, `defineCommand`, `controlRefused`, the catalogue `commands`, the types `Command`, `Ran` | Dev only. `run` throws unless the dev flag is `true`, and a `define` of `false` drops every command body |
527
+
528
+ A source or a command is data: an id, a title, an input schema and one function. `sources` and `commands` are frozen objects keyed by a short name, so an editor registers `Object.values(sources)` and `Object.values(commands)`. Each descriptor lives in the plugin that owns its data, in that plugin's `inspect.ts` or `control.ts`; the machinery lives in `flow`, see its [README](./src/plugins/flow/README.md#doors-for-the-editor).
529
+
530
+ The dice game of the [Quick start](#quick-start), driven through both doors:
531
+
532
+ ```ts
533
+ // dice.test.ts
534
+ import { commands, run } from "@moku-labs/game/control";
535
+ import { read, sources, watch } from "@moku-labs/game/inspect";
536
+ import { createHeadless } from "@moku-labs/game/testing";
537
+ import { it, vi } from "vitest";
538
+ import { createGame } from "./game";
539
+
540
+ it("rolls, bookmarks and restores through the doors", async () => {
541
+ vi.stubGlobal("__MOKU_GAME_DEV__", true);
542
+ const app = createGame(42);
543
+ const game = await createHeadless(app);
544
+
545
+ read(app, sources.position); // { path: "home", flow: "main", node: "home", waiting: ["roll", "reset"] }
546
+
547
+ const seen: string[] = [];
548
+ const stop = watch(app, sources.position, undefined, position => {
549
+ seen.push(position.path);
550
+ });
551
+ app.time.step(16);
552
+ seen; // ["home"]: a headless watch reads on the frames a test steps
553
+
554
+ const walked = await run(app, commands.walk, { route: [{ at: "home", intent: "roll" }] });
555
+ walked.value.path; // "home"
556
+ walked.state; // { path: "home", frame: 1, tainted: false }: a walk goes through the graph
557
+ read(app, sources.model).session; // { rolls: 1 }
558
+
559
+ const { value: mark } = await run(app, commands.bookmark);
560
+ await run(app, commands.restore, { bookmark: mark });
561
+ read(app, sources.tainted); // true: a restore replaces the state outside the graph
562
+ read(app, sources.cheats); // [{ id: "game.restore", input: { bookmark: { path: "home", ... } }, frame: 1 }]
563
+
564
+ stop();
565
+ await game.stop();
566
+ });
567
+ ```
568
+
569
+ - **Input.** A schema maps field names to `"string"`, `"number"`, `"boolean"` or `"json"`. A kind with a trailing `?` is optional. The input may be left out when every field is optional. The descriptor function gets it typed.
570
+ - **`read(app, source, input?)`** calls the source once and returns what it reads.
571
+ - **`watch(app, source, input, fn)`** reads on the first frame, in the `signals` phase, and again when the source's change key moved: `frame` every frame, `commit` when `model.store.snapshot()` is a new object, `edge` when `flow.state()` is. It returns the stop function. It runs on the frame loop, so a headless test steps frames with `app.time.step(16)`.
572
+ - **`run(app, command, input?)`** resolves `{ value, state }`. `value` is what the command returned. `state` is the envelope `{ path, frame, tainted }`, read after the command.
573
+ - **Screen sources need the screen.** `Source` and `Command` name the app they need. `read(app, sources.rect, { key: "play" })` on an app without `ui` and `renderer` is a compile error.
574
+
575
+ ### Base sources
576
+
577
+ From `@moku-labs/game/inspect`. `Changes` is when `watch` reads the source again.
578
+
579
+ | Key in `sources` | id | Input | Changes | Reads |
580
+ |---|---|---|---|---|
581
+ | `graph` | `game.graph` | none | edge | `flow.describe()`: flows, nodes with their flags and outcomes, edges, slots |
582
+ | `position` | `game.position` | none | edge | `{ path, flow, node, waiting }` from `flow.state()`. `waiting` lists the intents the gate waits for |
583
+ | `history` | `game.history` | `{ last: "number?" }` | edge | `flow.history()`, the edges since the last checkpoint: all of them, or the last `last` |
584
+ | `tainted` | `game.tainted` | none | frame | Whether a `cheat` or `raw` command ran on this app |
585
+ | `cheats` | `game.cheats` | none | frame | The journal of `cheat` and `raw` commands, `{ id, input, frame }`, oldest first, the last 500 |
586
+ | `model` | `game.model` | none | commit | `model.store.snapshot()`: the committed `{ player, session, rng }` |
587
+ | `entities` | `game.entities` | `{ owner: "string?", component: "string?" }` | frame | `world.ecs.snapshot().entities`: all, the ones whose owner has that name, the ones that carry that component, or both |
588
+ | `projections` | `game.projections` | none | commit | Projection name to key to entity, through `world.projection.keyOf` |
589
+ | `ui` | `game.ui` | none | frame | `ui.tree()`: the live screen as plain data |
590
+ | `rect` | `game.rect` | `{ key: "string" }` | frame | Where the element with that `key` is on the page, in CSS px; in reference units while the renderer is inert. `undefined` when it is not on screen |
591
+ | `render` | `game.render` | none | frame | `renderer.stats()`: `{ fps, frameMs, textures, textureMb, views, pooled, renderPasses }`, and `drawCalls` in a dev build. `renderPasses` is 1 for the frame plus, for every view with an enabled filter, 1 for its content and the passes of its filters |
592
+ | `effects` | `game.effects` | none | frame | `effects.stats()`: `{ particles, emitters, filters, renderPasses }`. Only in a game that composes `effectsPlugin` |
593
+ | `sounds` | `game.sounds` | `{ last: "number?" }` | frame | `audio.journal()`: all, or the last `last`. Empty unless `pluginConfigs.audio.journal` is above 0 |
594
+ | `assets` | `game.assets` | none | frame | `assets.usage()`: `{ textureMb, budgetMb, bundles }` |
595
+ | `log` | `game.log` | `{ level: "string?" }` | frame | `log.trace()`: every entry, or the entries at `level` and above. A level other than `debug`, `info`, `warn`, `error` throws |
596
+
597
+ ### Base commands
598
+
599
+ From `@moku-labs/game/control`. Every command runs in dev builds only and leaves a `moku:dev` debug entry in the log.
600
+
601
+ | Key in `commands` | id | Input | Effect | Does |
602
+ |---|---|---|---|---|
603
+ | `answer` | `game.answer` | `{ intent: "string", payload: "json?" }` | route | `flow.gate.answer({ intent, payload })`. Value: whether the gate took the answer |
604
+ | `tap` | `game.tap` | `{ key: "string?", target: "json?" }`, exactly one | route | `input.tap` on the ui element with that `key`, or on the view `target: { projection, key }`. Value: whether the gate took the answer |
605
+ | `drag` | `game.drag` | `{ from: "json", to: "json" }` | route | `input.drag(from, to)`, both `{ projection, key }`. Value: whether the gate took the answer |
606
+ | `key` | `game.key` | `{ key: "string", shift: "boolean?" }` | route | `input.pressKey(key, { shift })`. Value: whether a listener handled the key |
607
+ | `fill` | `game.fill` | `{ key: "string", value: "string" }` | route | `ui.fill(key, value)`: types into the `input` with that `key`, cut to its `maxLength`. Value: whether the field took the text |
608
+ | `walk` | `game.walk` | `{ route: "json" }` | route | `flow.walk(route)`. Value: the flow state after the walk |
609
+ | `bookmark` | `game.bookmark` | none | read | `flow.bookmark()`. Value: the bookmark, plain JSON |
610
+ | `restore` | `game.restore` | `{ bookmark: "json?", repro: "json?" }`, exactly one | raw | `flow.restore(bookmark)`, or a `/testing` repro: its state at its checkpoint, then `flow.walk(repro.route)`. Value: the flow state |
611
+ | `step` | `game.step` | `{ frames: "number", deltaMs: "number?" }` | cosmetic | `time.step(deltaMs)` `frames` times, also while paused. `deltaMs` is 1000/60 by default. Value: `time.snapshot()` |
612
+ | `pause` | `game.pause` | none | cosmetic | `lifecycle.push("devtools")`. Value: `lifecycle.isPaused()` |
613
+ | `resume` | `game.resume` | none | cosmetic | `lifecycle.pop("devtools")`. Value: `lifecycle.isPaused()`, still true while another reason holds |
614
+ | `capture` | `game.capture` | none | read | `renderer.capture()`: a PNG data URL of the canvas after the next drawn frame. `undefined` while the renderer is inert |
615
+ | `debug` | `game.debug` | `{ nineSlice: "boolean" }` | cosmetic | `renderer.sync.debug.nineSlice(on)`. Value: the debug switches |
616
+ | `reducedMotion` | `game.reducedMotion` | `{ on: "boolean" }` | cosmetic | `anim.setReducedMotion(on)`. Value: `anim.reducedMotion()` |
617
+
618
+ ### Effects, taint and the cheat journal
619
+
620
+ | Effect | Means |
621
+ |---|---|
622
+ | `read` | Takes something out of the game and changes nothing |
623
+ | `route` | Goes through the graph or the input, the way a player does. The session stays clean |
624
+ | `cosmetic` | Changes how the game runs or looks. The session stays clean |
625
+ | `cheat` | Changes the state outside the rules. Taints the session and is journaled |
626
+ | `raw` | Replaces the state outside the graph. Taints the session and is journaled |
627
+
628
+ `run` journals a `cheat` or `raw` command as `{ id, input, frame }` before it runs, so a failing one still counts. The session and the journal belong to one app object: two apps in one process never share them. Read them with `sources.tainted` and `sources.cheats` (`game.cheats`), and in `state.tainted` of every `run`. Of the base commands only `game.restore` is `raw`; none is `cheat`.
629
+
630
+ ### Turn the dev build on
631
+
632
+ `__MOKU_GAME_DEV__` is a global the engine reads and never sets. Only `true` turns the dev build on; undefined means production, and `run` throws `[game] Control commands run in dev builds only.` The package ships its declaration, `var __MOKU_GAME_DEV__: boolean | undefined`. A game never re-declares it.
633
+
634
+ **Preferred: a bundler `define`**, `true` in dev and `false` in production.
635
+
636
+ ```ts
637
+ // build.ts of the game
638
+ const production = Bun.argv.includes("--production");
639
+
640
+ await Bun.build({
641
+ entrypoints: ["web/main.ts"],
642
+ outdir: "dist",
643
+ minify: true,
644
+ define: { __MOKU_GAME_DEV__: production ? "false" : "true" }
645
+ });
646
+ ```
647
+
648
+ **Or set the global** in a module the dev entry imports before the engine. The fixture page does this in [`tests/integration/merge-game/web/dev.ts`](./tests/integration/merge-game/web/dev.ts):
649
+
650
+ ```ts
651
+ // web/dev.ts, the first import of web/main.ts
652
+ globalThis.__MOKU_GAME_DEV__ = true;
653
+ ```
654
+
655
+ A test sets it with `vi.stubGlobal("__MOKU_GAME_DEV__", true)`.
656
+
657
+ **What the `define` strips.** Every command body starts with the inline guard `if (typeof __MOKU_GAME_DEV__ === "undefined" || !__MOKU_GAME_DEV__) throw controlRefused();`. A `define` of `false` folds the condition, and the minifier drops the body behind it. [`tests/integration/doors-build.test.ts`](./tests/integration/doors-build.test.ts) proves it with a minified Bun build of each door: with `false` no command body of `/control` is left, with `true` every body is there, and an `/inspect` bundle carries no command id at all. The descriptors stay, so an editor can still list the commands. Without a `define` the bodies stay in the bundle, and `run` still refuses them while the flag is undefined.
658
+
659
+ ### A game's own sources and commands
660
+
661
+ `defineSource` and `defineCommand` take the same shape as the base catalogue. The id is camelCase words joined by dots, at least two (`dice.rolls`); any other id throws. Keep them in `.dev` modules that only the dev entry and the tests import, so a production bundle never reaches them. `defineCommand` adds no guard: a command writes the inline guard itself, because Bun does not inline a guard function across modules.
662
+
663
+ ```ts
664
+ // dice.dev.ts
665
+ import { controlRefused, defineCommand } from "@moku-labs/game/control";
666
+ import { defineSource } from "@moku-labs/game/inspect";
667
+ import type { createGame } from "./game";
668
+
669
+ export const rolls = defineSource({
670
+ id: "dice.rolls",
671
+ title: "Rolls",
672
+ input: {},
673
+ changes: "commit",
674
+ read: (app: ReturnType<typeof createGame>) => app.model.store.snapshot().session
675
+ });
676
+
677
+ export const rollTwice = defineCommand({
678
+ id: "dice.rollTwice",
679
+ title: "Roll twice",
680
+ input: {},
681
+ effect: "route",
682
+ run: app => {
683
+ if (typeof __MOKU_GAME_DEV__ === "undefined" || !__MOKU_GAME_DEV__) throw controlRefused();
684
+ return app.flow.walk([{ at: "home", intent: "roll" }, { at: "home", intent: "roll" }]);
685
+ }
686
+ });
687
+
688
+ export const giveCoins = defineCommand({
689
+ id: "dice.giveCoins",
690
+ title: "Give coins",
691
+ input: { coins: "number" },
692
+ effect: "cheat",
693
+ run: (app, { coins }) => {
694
+ if (typeof __MOKU_GAME_DEV__ === "undefined" || !__MOKU_GAME_DEV__) throw controlRefused();
695
+ return app.flow.restore({ ...app.flow.bookmark(), player: { coins, lastRoll: 0 } });
696
+ }
697
+ });
698
+
699
+ // On a fresh headless game, before any frame:
700
+ // (await run(app, rollTwice)).state; // { path: "home", frame: 0, tainted: false }
701
+ // read(app, rolls); // { rolls: 2 }
702
+ // (await run(app, giveCoins, { coins: 100 })).state.tainted; // true
703
+ // read(app, sources.cheats); // [{ id: "dice.giveCoins", input: { coins: 100 }, frame: 0 }]
704
+ ```
705
+
303
706
  ## Events
304
707
 
305
708
  Global events are empty: every event belongs to a plugin. `time` and `clock` emit nothing.
@@ -311,6 +714,15 @@ Global events are empty: every event belongs to a plugin. `time` and `clock` emi
311
714
  | `flow:edge` | `flow` | `{ flow: string; node: string; outcome: string; payload: Json; next: string; patches: { doc: Patch[]; session: Patch[] }; index: number; now: number }` | After the commit of an edge |
312
715
  | `flow:rest` | `flow` | `{ path: string; checkpoint: boolean }` | The graph entered a rest node |
313
716
  | `flow:error` | `flow` | `{ path: string; error: unknown; rolledBackTo: string; retry: boolean }` | A node failed and the graph rolled back |
717
+ | `world:reconciled` | `world` | counts per reconcile | Dev only, behind `reconciledEvent` |
718
+ | `renderer:device-lost` | `renderer` | `{ kind, reason }` | The GPU device or context was lost; `lifecycle` is pushed |
719
+ | `assets:bundle-loaded`, `assets:bundle-unloaded` | `assets` | `{ bundle, tier, mb, reason }` | A bundle entered or left memory |
720
+ | `scenes:changed` | `scenes` | `{ from, to, music }` | The scene switched on entering a node |
721
+ | `anim:mark` | `anim` | `{ animation, mark }` | A `mark` step was reached, or jumped by `finish()` |
722
+ | `anim:finished` | `anim` | `{ animation }` | A timeline ended or was finished. Never on `cancel()` |
723
+ | `i18n:locale-changed` | `i18n` | `{ locale }` | The module of the new locale is loaded; `text` re-resolves. Never at start |
724
+
725
+ `text`, `ui` and `audio` emit nothing.
314
726
 
315
727
  ```ts
316
728
  import { createPlugin, flowPlugin } from "@moku-labs/game";
@@ -330,13 +742,14 @@ export const edgeLog = createPlugin("edgeLog", {
330
742
  ### Global
331
743
 
332
744
  ```ts
333
- createApp({ config: { orientation: "landscape", referenceSide: 1080 } });
745
+ createApp({ config: { orientation: "landscape", referenceSide: 1080, referenceLong: 1920 } });
334
746
  ```
335
747
 
336
748
  | Key | Type | Default | Meaning |
337
749
  |---|---|---|---|
338
750
  | `orientation` | `"portrait" \| "landscape"` | `"portrait"` | Screen orientation the game is designed for |
339
751
  | `referenceSide` | `number` | `1080` | Short side of the reference resolution in pixels |
752
+ | `referenceLong` | `number` | `1920` | The long side, in reference units, the layout needs inside the safe area. The viewport scale is `min(short / referenceSide, safeLong / referenceLong)`, so a wide screen gives the layout more width instead of shrinking it |
340
753
 
341
754
  ### Per plugin
342
755
 
@@ -346,6 +759,8 @@ Set with `createApp({ pluginConfigs: { <plugin>: { ... } } })`.
346
759
  |---|---|---|---|---|
347
760
  | `time` | `maxFps` | `30 \| 60 \| 120` | `60` | Frame rate cap |
348
761
  | `time` | `maxDeltaMs` | `number` | `50` | Upper bound of one frame's delta in milliseconds |
762
+ | `time` | `idleFps` | `0 \| 30` | `30` | Frame rate cap of an idle screen. `0` turns the idle cap off. Any plugin lifts it with `wake()` |
763
+ | `time` | `idleAfterMs` | `number` | `2000` | Unscaled milliseconds without a `wake()` after which the loop drops to `idleFps` |
349
764
  | `lifecycle` | none | | | The plugin has no config |
350
765
  | `model` | `playerProvider` | `PlayerStateProvider \| undefined` | `undefined` | The save seam. `undefined` means an in-memory provider: the save lives as long as the app does |
351
766
  | `model` | `initialPlayer` | `Json` | `{}` | Player state of a new player. Deep-cloned |
@@ -359,13 +774,40 @@ Set with `createApp({ pluginConfigs: { <plugin>: { ... } } })`.
359
774
  | `flow` | `retries` | `number` | `1` | Retries of a failed transition before `safeNode` |
360
775
  | `flow` | `settleTimeoutMs` | `number` | `2000` | How long `onStop` waits for the active node to settle after abort |
361
776
  | `flow` | `journalLimit` | `number` | `500` | Journal entries kept between checkpoints |
777
+ | `world` | `settleMs` | `number` | `350` | Length of the default settle motion |
778
+ | `world` | `reconciledEvent` | `boolean` | `false` | Emit `world:reconciled` after every reconcile (dev tools) |
779
+ | `renderer` | `mount` | `string \| undefined` | `undefined` | Selector of the mount element. `undefined` keeps the renderer inert |
780
+ | `renderer` | `preference` | `"webgpu" \| "webgl"` | `"webgpu"` | Preferred backend; Pixi falls back to WebGL |
781
+ | `renderer` | `background`, `antialias`, `maxResolution`, `aspect`, `poolLimit`, `unsupportedMessage`, `loadPixi` | | see the plugin README | Host, viewport and pool settings; `loadPixi` is the lazy loader, a test passes a fake |
782
+ | `renderer` | `debug` | `{ nineSlice: boolean }` | `{ nineSlice: false }` | Outline every nine-slice from the start; `sync.debug.nineSlice(on)` switches it live |
783
+ | `input` | `tapSlopPx`, `longPressMs`, `dragStartPx`, `swipeMinPx`, `swipeMaxMs` | `number` | `12`, `450`, `8`, `48`, `300` | Gesture thresholds in reference px and ms |
784
+ | `input` | `cursor` | `{ control: string; idle: string }` | `{ control: "pointer", idle: "" }` | CSS cursor over a control and elsewhere |
785
+ | `assets` | `manifest` | `string \| Manifest \| undefined` | `undefined` | Manifest URL, or the parsed file in a test |
786
+ | `assets` | `textureBudgetMb` | `number` | `192` | Texture memory budget for the LRU unload |
787
+ | `assets` | `preloadDepth` | `number` | `2` | Graph edges walked for the preload at a rest node |
788
+ | `assets` | `baseUrl`, `io` | | `undefined` | The CDN seam and the fetch/decode/texture seam a test replaces |
789
+ | `anim` | `maxTracks` | `number` | `2000` | Dev guard: one warning each time the running track count rises past it. Durations live in the steps, never here |
790
+ | `i18n` | `locale` | `string` | `"en"` | The locale at start |
791
+ | `i18n` | `fallback` | `string` | `"en"` | The locale a missing key is read from before it is reported missing |
792
+ | `i18n` | `locales` | `Record<string, module \| loader>` | `{}` | Compiled modules outside features, per locale |
793
+ | `text` | `fonts` | `{ body, digits }` | `{ body: "ui.font-body", digits: "ui.font-digits" }` | The two boot fonts behind the built-in styles `body` and `digits` |
794
+ | `ui` | `tapTargetPt` | `number` | `44` | The smallest tap target `lint()` accepts |
795
+ | `ui` | `breakpoints` | `{ tall, wide }` | `{ tall: 2, wide: 1.5 }` | Aspect thresholds of the `when` style variants |
796
+ | `audio` | `buses` | `{ master, music, sfx }` | `{ master: 1, music: 0.6, sfx: 1 }` | Start gain of each bus, 0..1 |
797
+ | `audio` | `musicFadeMs` | `number` | `600` | Cross-fade of a music switch, in real milliseconds |
798
+ | `audio` | `volumes` | `(player) => Partial<Record<Bus, number>> \| undefined` | `undefined` | Reads the player's choice from the committed player on every `model:committed`. Absent: the buses stay at `buses` |
799
+ | `audio` | `context` | `() => AudioContext \| undefined` | `undefined` | The context factory, a test seam. Absent: `new AudioContext()` where the global exists |
800
+ | `effects` | `maxParticles` | `number` | `3000` | Live particles over every instance above which `effects:particle-budget` warns once per crossing |
801
+ | `effects` | `maxPasses` | `number` | `24` | Render passes per frame above which `effects:pass-budget` warns once per crossing |
802
+ | `effects` | `phone` | `boolean \| "auto"` | `"auto"` | Whether the device is a phone. `"auto"`: a coarse pointer and a short side of at most 820 CSS px, read once at start |
803
+ | `effects` | `blur` | `{ quality, phoneResolution }` | `{ quality: 2, phoneResolution: 0.5 }` | What a `Blur` with `quality: 0` and `resolution: 0` resolves to |
362
804
 
363
805
  ## Development
364
806
 
365
807
  ### Scripts
366
808
 
367
809
  ```sh
368
- bun run build # build with tsdown: dist/index.mjs and dist/testing.mjs
810
+ bun run build # build with tsdown: dist/index.mjs, testing.mjs, assets.mjs, inspect.mjs, control.mjs, jsx-runtime.mjs, jsx-dev-runtime.mjs
369
811
  bun run typecheck # tsc --noEmit
370
812
  bun run lint # biome check . && eslint .
371
813
  bun run lint:fix # biome check --write . && eslint --fix .
@@ -375,6 +817,8 @@ bun run test:unit # vitest project "unit"
375
817
  bun run test:integration # vitest project "integration"
376
818
  bun run test:coverage # both projects with coverage, 90% thresholds
377
819
  bun run validate # publint and attw with the esm-only profile
820
+ bun run fixture:pack # pack the fixture game into tests/integration/merge-game/dist/assets
821
+ bun run fixture:visual # the fixture's visual tests, both legs: --url <dev page>, --update, --only <name>, --no-pixels
378
822
  bun run release:setup # moku-release setup
379
823
  bun run release:doctor # moku-release doctor
380
824
  bun run release # moku-release
@@ -384,16 +828,17 @@ bun run release # moku-release
384
828
 
385
829
  | Path | Holds |
386
830
  |---|---|
387
- | `tests/unit/` | Framework-level unit tests: root index, setup, teardown registry |
831
+ | `tests/unit/` | Framework-level unit tests: root index, setup |
388
832
  | `tests/integration/` | Framework-level scenarios across plugins |
389
833
  | `tests/integration/merge-game/` | The fixture game, written on the public API only. Not published |
834
+ | `tests/visual/` | The visual tests of the fixture game and their baselines: `<test>/<checkpoint>/state.json`, `describe.json`, `screen.webp` |
390
835
  | `src/plugins/<name>/__tests__/unit/` | Unit tests of one plugin |
391
836
  | `src/plugins/<name>/__tests__/integration/` | Integration tests of one plugin |
392
837
  | `src/plugins/flow/__tests__/types/` | Type-level tests of the graph typing |
393
838
 
394
839
  Plugin tests never go into the root `tests/` folder. Coverage thresholds are 90% for lines, functions, branches and statements.
395
840
 
396
- ### Lint rules L1 to L6
841
+ ### Lint rules L1 to L9
397
842
 
398
843
  The project rules live in [`eslint.config.ts`](./eslint.config.ts).
399
844
 
@@ -403,14 +848,18 @@ The project rules live in [`eslint.config.ts`](./eslint.config.ts).
403
848
  | L2 | No static import of `pixi.js` or `yoga-layout`. They are loaded lazily with `import()` | `src/**` |
404
849
  | L3 | Determinism: no `Date.now`, `performance.now`, `new Date`, `Math.random`, `setTimeout`, `setInterval` | `model`, `flow`, `clock` except `clock/system.ts`, and the rules of the fixture game |
405
850
  | L4 | The rules of the fixture game import only their siblings | `tests/integration/merge-game/rules/` |
406
- | L5 | No module-scope state: no top-level `let`, no top-level `Map`, `Set`, `WeakMap`, `WeakSet`. The only registry is `src/teardown.ts` | `src/**` |
407
- | L6 | Plugin wiring files need no JSDoc on small inline arrows. Every other export needs JSDoc with description, params, returns and example | `src/plugins/*/index.ts` |
851
+ | L5 | No module-scope state: no top-level `let`, no top-level `Map`, `Set`, `WeakMap`, `WeakSet`. No allowlist | `src/**` |
852
+ | L6 | Plugin wiring files need no JSDoc on small inline arrows. Every function declaration and every exported type needs JSDoc with description, params and returns | `src/plugins/*/index.ts` |
853
+ | L7 | The public contract carries the docs: every member of a `…Api` type in `types.ts` has JSDoc and a scenario `@example` (when it is called, literal arguments, the result). A member another plugin calls is shown from that plugin's point of view; there is no private tier and no exemption. The implementation of an API method has no JSDoc. Elsewhere an example is allowed, never required | `src/plugins/**/types.ts` |
854
+ | L8 | No signature echo: an `@example` whose whole body is one call with bare identifiers is an error | `src/**` |
855
+ | L9 | The JSX runtime module is reached only through `src/jsx-runtime.ts` and `src/jsx-dev-runtime.ts`, and those two import nothing else | `src/**` outside `ui` |
408
856
 
409
857
  ## Requirements
410
858
 
411
859
  - **Node `>= 24`** and **Bun `>= 1.3.14`**. Use `bun` only, never npm, yarn or pnpm.
412
860
  - **TypeScript** in strict mode, with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`.
413
- - **`pixi.js` `^8.0.0`** as a peer dependency.
861
+ - **`pixi.js` `^8.0.0`** as a peer dependency. **`yoga-layout`** is a dependency, loaded lazily by `ui`. The string compiler on the `assets` door uses `@formatjs/icu-messageformat-parser`; no parser ships to the browser.
862
+ - **JSX**: `"jsx": "react-jsx"` and `"jsxImportSource": "@moku-labs/game"` in the game's `tsconfig.json`. Screens are `.tsx` files.
414
863
  - **[`@moku-labs/core`](https://github.com/moku-labs/core)** is the kernel: plugins, lifecycle, events. **[`@moku-labs/common`](https://github.com/moku-labs/common)** brings `log` and `env`.
415
864
 
416
865
  ## Docs
@@ -419,7 +868,13 @@ The project rules live in [`eslint.config.ts`](./eslint.config.ts).
419
868
  - [`lifecycle`](./src/plugins/lifecycle/README.md): pause reasons
420
869
  - [`model`](./src/plugins/model/README.md): store, rng, provider seam, migrations
421
870
  - [`clock`](./src/plugins/clock/README.md): `now`, `scheduleAt`, `fakeClock`
422
- - [`flow`](./src/plugins/flow/README.md): runner, gate, inbox, fx, features
871
+ - [`flow`](./src/plugins/flow/README.md): runner, gate, inbox, fx, features, the door machinery
872
+ - [`world`](./src/plugins/world/README.md), [`renderer`](./src/plugins/renderer/README.md), [`input`](./src/plugins/input/README.md), [`assets`](./src/plugins/assets/README.md), [`scenes`](./src/plugins/scenes/README.md): the screen
873
+ - [`anim`](./src/plugins/anim/README.md): tracks, timelines, `defineMotion`, the driver
874
+ - [`i18n`](./src/plugins/i18n/README.md): messages, parts, the compiler, supported ICU
875
+ - [`text`](./src/plugins/text/README.md): styles, tags, measurement, fonts
876
+ - [`ui`](./src/plugins/ui/README.md): the JSX runtime, components, styles, layout, popups
877
+ - [`audio`](./src/plugins/audio/README.md): buses, the unlock, pause, memory
423
878
  - [`llms.txt`](./llms.txt): overview for an LLM that writes a game on this engine
424
879
  - [Moku Core specification](https://github.com/moku-labs/core/tree/main/specification)
425
880