@typeonce/ritmo-devtools 0.14.0 → 0.15.0

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +296 -55
  3. package/dist/Desync.d.ts +17 -3
  4. package/dist/Desync.d.ts.map +1 -1
  5. package/dist/Desync.js +17 -15
  6. package/dist/Desync.js.map +1 -1
  7. package/dist/Determinism.d.ts +17 -6
  8. package/dist/Determinism.d.ts.map +1 -1
  9. package/dist/Determinism.js +11 -3
  10. package/dist/Determinism.js.map +1 -1
  11. package/dist/Format.d.ts +43 -8
  12. package/dist/Format.d.ts.map +1 -1
  13. package/dist/Format.js +63 -31
  14. package/dist/Format.js.map +1 -1
  15. package/dist/Fuzz.d.ts +268 -0
  16. package/dist/Fuzz.d.ts.map +1 -0
  17. package/dist/Fuzz.js +355 -0
  18. package/dist/Fuzz.js.map +1 -0
  19. package/dist/Invariant.d.ts +6 -2
  20. package/dist/Invariant.d.ts.map +1 -1
  21. package/dist/Invariant.js.map +1 -1
  22. package/dist/PlaywrightEngine.d.ts +29 -0
  23. package/dist/PlaywrightEngine.d.ts.map +1 -0
  24. package/dist/PlaywrightEngine.js +193 -0
  25. package/dist/PlaywrightEngine.js.map +1 -0
  26. package/dist/Replay.d.ts +40 -22
  27. package/dist/Replay.d.ts.map +1 -1
  28. package/dist/Replay.js +20 -27
  29. package/dist/Replay.js.map +1 -1
  30. package/dist/Session.d.ts +214 -17
  31. package/dist/Session.d.ts.map +1 -1
  32. package/dist/Session.js +563 -57
  33. package/dist/Session.js.map +1 -1
  34. package/dist/Verify.d.ts +147 -0
  35. package/dist/Verify.d.ts.map +1 -0
  36. package/dist/Verify.js +151 -0
  37. package/dist/Verify.js.map +1 -0
  38. package/dist/cli.js +136 -8
  39. package/dist/cli.js.map +1 -1
  40. package/dist/index.d.ts +3 -2
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +3 -2
  43. package/dist/index.js.map +1 -1
  44. package/dist/internal/dependencyScan.d.ts +44 -0
  45. package/dist/internal/dependencyScan.d.ts.map +1 -0
  46. package/dist/internal/dependencyScan.js +313 -0
  47. package/dist/internal/dependencyScan.js.map +1 -0
  48. package/dist/internal/fuzzNetwork.d.ts +56 -0
  49. package/dist/internal/fuzzNetwork.d.ts.map +1 -0
  50. package/dist/internal/fuzzNetwork.js +96 -0
  51. package/dist/internal/fuzzNetwork.js.map +1 -0
  52. package/dist/internal/values.d.ts +9 -1
  53. package/dist/internal/values.d.ts.map +1 -1
  54. package/dist/internal/values.js +11 -1
  55. package/dist/internal/values.js.map +1 -1
  56. package/dist/internal/verifyRunner.d.ts +19 -0
  57. package/dist/internal/verifyRunner.d.ts.map +1 -0
  58. package/dist/internal/verifyRunner.js +47 -0
  59. package/dist/internal/verifyRunner.js.map +1 -0
  60. package/dist/internal/version.d.ts +1 -1
  61. package/dist/internal/version.js +1 -1
  62. package/package.json +28 -3
  63. package/src/Desync.ts +34 -17
  64. package/src/Determinism.ts +46 -11
  65. package/src/Format.ts +99 -34
  66. package/src/Fuzz.ts +544 -0
  67. package/src/Invariant.ts +6 -2
  68. package/src/PlaywrightEngine.ts +229 -0
  69. package/src/Replay.ts +87 -43
  70. package/src/Session.ts +806 -72
  71. package/src/Verify.ts +273 -0
  72. package/src/cli.ts +131 -8
  73. package/src/index.ts +3 -2
  74. package/src/internal/dependencyScan.ts +356 -0
  75. package/src/internal/fuzzNetwork.ts +130 -0
  76. package/src/internal/values.ts +20 -1
  77. package/src/internal/verifyRunner.ts +46 -0
  78. package/src/internal/version.ts +1 -1
  79. package/dist/Monitor.d.ts +0 -101
  80. package/dist/Monitor.d.ts.map +0 -1
  81. package/dist/Monitor.js +0 -602
  82. package/dist/Monitor.js.map +0 -1
  83. package/dist/internal/monitor.d.ts +0 -126
  84. package/dist/internal/monitor.d.ts.map +0 -1
  85. package/dist/internal/monitor.js +0 -279
  86. package/dist/internal/monitor.js.map +0 -1
  87. package/src/Monitor.ts +0 -713
  88. package/src/internal/monitor.ts +0 -370
package/src/Monitor.ts DELETED
@@ -1,713 +0,0 @@
1
- /**
2
- * A live monitor panel for a running game in the browser: how the game is
3
- * built and what it is doing, without reading its code.
4
- *
5
- * - **Overview**: time per schedule tick, the busiest systems, entity counts
6
- * over the last seconds, state machines, and alerts (failed systems, NaN or
7
- * infinite numbers written, messages discarded by skipped systems).
8
- * - **Systems**: every schedule as its systems in order, grouped by run
9
- * conditions, with what each reads, writes, emits, and spawns. A dot shows
10
- * whether a system is working, idle, or skipped. Hover a name to light up
11
- * the systems that write it (orange) and read it (blue).
12
- * - **Entity**: pick an entity on screen (or by id) to follow its components
13
- * live and the changes systems make to it.
14
- *
15
- * The monitor observes the runtime only while it is open, so a closed monitor
16
- * costs nothing. While open it reduces trace events to counts and shows its
17
- * own cost per tick. It needs a runtime made with `debug: { hostClock }`, and the page passed as `host`.
18
- *
19
- * @module Monitor
20
- * @docGroup devtools
21
- *
22
- * @example
23
- * ```ts
24
- * const monitor = Monitor.attach(runtime, {
25
- * host: window,
26
- * schedules: { fixedUpdate: step, frame },
27
- * pick: (event) => entityUnderPointer(event),
28
- * locate: (entity) => screenPositionOf(entity)
29
- * })
30
- * // Toggle with the backslash key or the corner button.
31
- * ```
32
- */
33
- import type * as Debug from "@typeonce/ritmo/Debug"
34
- import type { AnyScheduleOrder, ExecutableScheduleDefinition } from "@typeonce/ritmo/Schedule"
35
- import type { Schema } from "@typeonce/ritmo/Schema"
36
-
37
- import * as Format from "./Format.ts"
38
- import { Collector, recentSchedule, recentSystem } from "./internal/monitor.ts"
39
- import type { Sample, SystemWindow } from "./internal/monitor.ts"
40
-
41
- /**
42
- * The numbers behind the panel, without DOM: pass `collector.observe` to
43
- * `debug.observe`, call `sample(now)` periodically, read `history`, `alerts`,
44
- * spawn kinds, and the selected entity's changes. Use it for a custom UI or in
45
- * tests.
46
- */
47
- export { Collector, recentSchedule, recentSystem }
48
- export type { Alert, CollectorOptions, EntityLine, Sample, ScheduleWindow, SpawnKind, SystemWindow } from "./internal/monitor.ts"
49
-
50
- /** What the monitor needs from a runtime: its debug handle. */
51
- export interface Target<S extends Schema.Any, Root> {
52
- readonly debug: Debug.Handle<S, Root>
53
- }
54
-
55
- /** What `attach` shows, where, and how the panel is opened. */
56
- export interface Options<S extends Schema.Any, Root> {
57
- /**
58
- * The schedules the game ticks, by name. They name the schedules in the
59
- * panel and make up the system map. Name the schedule objects actually
60
- * passed to `tick`: nested schedules are flattened into them.
61
- */
62
- readonly schedules: Readonly<Record<string, ExecutableScheduleDefinition<S, any, Root, any, any, AnyScheduleOrder>>>
63
- /**
64
- * The page the panel lives in, passed explicitly (`window`): its
65
- * `document`, timers, animation frames, keyboard events, and
66
- * `performance` clock. The monitor reads no globals.
67
- */
68
- readonly host: Window
69
- /** Where the panel is added. Defaults to `host.document.body`. */
70
- readonly mount?: HTMLElement
71
- /** `KeyboardEvent.code` that toggles the panel. Defaults to `Backslash`. */
72
- readonly key?: string
73
- /** Opens the panel right away. */
74
- readonly open?: boolean
75
- /** The entity under a pointer event, for "Pick on screen". */
76
- readonly pick?: (event: PointerEvent) => number | undefined
77
- /** An entity's position in client (viewport) pixels, to mark the selected entity. */
78
- readonly locate?: (entity: number) => { readonly x: number; readonly y: number } | undefined
79
- /** Milliseconds between panel refreshes. Defaults to 250. */
80
- readonly refreshMs?: number
81
- /**
82
- * A replay recorder (`Replay.recorder`): adds a "Save replay" button that
83
- * saves the last seconds of play with the reason "Save replay button".
84
- */
85
- readonly replay?: { readonly save: (reason: string) => unknown }
86
- }
87
-
88
- /** An attached monitor panel, from `attach`. */
89
- export interface Monitor {
90
- readonly open: () => void
91
- readonly close: () => void
92
- readonly toggle: () => void
93
- /** Selects an entity in the Entity tab (`undefined` clears it). */
94
- readonly select: (entity: number | undefined) => void
95
- /** Removes the panel and stops observing. */
96
- readonly detach: () => void
97
- }
98
-
99
- type Tab = "overview" | "systems" | "entity"
100
-
101
- /** Samples used for "recent" numbers (about two seconds at the default refresh). */
102
- const RECENT = 8
103
-
104
- const escape = (text: string): string =>
105
- text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
106
-
107
- const number = (value: number, digits = 2): string =>
108
- !Number.isFinite(value) ? String(value) : value >= 100 ? value.toFixed(0) : value.toFixed(digits)
109
-
110
- /** The most common `prefix/` among names, stripped for display. */
111
- const commonPrefix = (names: ReadonlyArray<string>): string => {
112
- const counts = new Map<string, number>()
113
- for (const name of names) {
114
- const slash = name.indexOf("/")
115
- if (slash > 0) counts.set(name.slice(0, slash + 1), (counts.get(name.slice(0, slash + 1)) ?? 0) + 1)
116
- }
117
- let best = ""
118
- let bestCount = 0
119
- for (const [prefix, count] of counts) {
120
- if (count > bestCount) {
121
- best = prefix
122
- bestCount = count
123
- }
124
- }
125
- return bestCount >= names.length / 2 ? best : ""
126
- }
127
-
128
- const sparkline = (values: ReadonlyArray<number>, width = 96, height = 18): string => {
129
- if (values.length < 2) return `<svg class="btm-spark" width="${width}" height="${height}"></svg>`
130
- const max = Math.max(...values)
131
- const min = Math.min(...values)
132
- const span = max - min || 1
133
- const points = values.map((value, index) =>
134
- `${((index / (values.length - 1)) * width).toFixed(1)},${(height - 2 - ((value - min) / span) * (height - 4)).toFixed(1)}`)
135
- return `<svg class="btm-spark" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><polyline points="${points.join(" ")}"/></svg>`
136
- }
137
-
138
- type Status = "failed" | "active" | "idle" | "skipped" | "stopped"
139
-
140
- const statusOf = (window: SystemWindow): Status =>
141
- window.failures > 0 ? "failed"
142
- : window.runs > 0 && window.writes + window.events + window.commands + window.spawns + window.despawns > 0 ? "active"
143
- : window.runs > 0 ? "idle"
144
- : window.skips > 0 ? "skipped"
145
- : "stopped"
146
-
147
- const statusText: Record<Status, string> = {
148
- failed: "failed recently",
149
- active: "running and changing things",
150
- idle: "running, changing nothing right now",
151
- skipped: "skipped by its run condition",
152
- stopped: "not running (other schedule, or never scheduled now)"
153
- }
154
-
155
- /** Reads and writes of one system, by kind, for the map's chips and highlighting. */
156
- interface Access {
157
- readonly reads: ReadonlyArray<string>
158
- readonly writes: ReadonlyArray<string>
159
- readonly resourceReads: ReadonlyArray<string>
160
- readonly resourceWrites: ReadonlyArray<string>
161
- readonly eventReads: ReadonlyArray<string>
162
- readonly eventWrites: ReadonlyArray<string>
163
- readonly machineReads: ReadonlyArray<string>
164
- readonly machineWrites: ReadonlyArray<string>
165
- }
166
-
167
- const accessOf = (system: Debug.SystemDescription): Access => {
168
- const unique = (values: ReadonlyArray<string>) => [...new Set(values)]
169
- const writes = unique(system.queries.flatMap((query) => query.writes))
170
- return {
171
- reads: unique(system.queries.flatMap((query) => [...query.reads, ...query.optional, ...query.added, ...query.changed, ...query.anyOf.flatMap((members) => [...members.added, ...members.changed])])).filter((name) => !writes.includes(name)),
172
- writes,
173
- resourceReads: system.resources.reads.filter((name) => !system.resources.writes.includes(name)),
174
- resourceWrites: system.resources.writes,
175
- eventReads: system.events.reads,
176
- eventWrites: system.events.writes,
177
- machineReads: system.machines.reads.filter((name) => !system.machines.next.includes(name)),
178
- machineWrites: [...system.machines.next, ...system.machines.updates]
179
- }
180
- }
181
-
182
- const STYLE = `
183
- .btm { font: 12px/1.35 "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace; color: #e6edf3; }
184
- .btm-toggle { position: fixed; left: 12px; bottom: 12px; z-index: 2147483000; font: inherit; font-size: 11px; color: #9da7b3; background: rgba(13,17,23,.85); border: 1px solid #30363d; border-radius: 12px; padding: 3px 10px; cursor: pointer; }
185
- .btm-toggle:hover { color: #e6edf3; border-color: #4ecdc4; }
186
- .btm-panel { position: fixed; top: 12px; left: 12px; bottom: 44px; width: 440px; z-index: 2147483000; display: flex; flex-direction: column; background: rgba(13,17,23,.95); border: 1px solid #30363d; border-radius: 8px; box-shadow: 0 8px 30px rgba(0,0,0,.5); }
187
- .btm-panel[hidden] { display: none; }
188
- .btm-head { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #30363d; }
189
- .btm-title { color: #4ecdc4; font-weight: 700; margin-right: 6px; }
190
- .btm-tab { font: inherit; color: #9da7b3; background: none; border: 1px solid transparent; border-radius: 4px; padding: 2px 8px; cursor: pointer; }
191
- .btm-tab.is-on { color: #e6edf3; border-color: #30363d; background: #21262d; }
192
- .btm-close { margin-left: auto; font: inherit; color: #9da7b3; background: none; border: none; cursor: pointer; font-size: 14px; }
193
- .btm-status { padding: 4px 10px; color: #7d8590; font-size: 11px; border-bottom: 1px solid #21262d; }
194
- .btm-controls { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; padding: 6px 10px; border-bottom: 1px solid #21262d; }
195
- .btm-controls[hidden] { display: none; }
196
- .btm-controls button, .btm-controls input, .btm-controls select { font: inherit; color: inherit; background: #0d1117; border: 1px solid #30363d; border-radius: 4px; padding: 2px 6px; }
197
- .btm-controls button { background: #21262d; cursor: pointer; }
198
- .btm-controls button.is-on { border-color: #4ecdc4; color: #4ecdc4; }
199
- .btm-controls input { width: 64px; }
200
- .btm-body { overflow: auto; padding: 6px 10px 12px; flex: 1; }
201
- .btm h3 { margin: 10px 0 4px; font-size: 11px; font-weight: 600; color: #7d8590; text-transform: uppercase; letter-spacing: .06em; }
202
- .btm-hint { color: #7d8590; font-size: 11px; margin: 2px 0 6px; }
203
- .btm-row { display: grid; grid-template-columns: 1fr auto auto; gap: 8px; align-items: center; padding: 1px 0; }
204
- .btm-row.is-wide { grid-template-columns: 1fr 64px 60px 100px; }
205
- .btm-num { text-align: right; color: #c9d1d9; font-variant-numeric: tabular-nums; }
206
- .btm-dim { color: #7d8590; }
207
- .btm-bar { height: 6px; background: #4ecdc4; border-radius: 3px; min-width: 1px; }
208
- .btm-barbox { width: 100px; background: #161b22; border-radius: 3px; }
209
- .btm-spark polyline { fill: none; stroke: #4ecdc4; stroke-width: 1.3; }
210
- .btm-alert { padding: 3px 6px; margin: 2px 0; border-left: 2px solid #ff7b72; background: rgba(255,123,114,.08); }
211
- .btm-alert.is-info { border-left-color: #d29922; background: rgba(210,153,34,.08); }
212
- .btm-group { margin: 6px 0; border: 1px solid #21262d; border-radius: 6px; }
213
- .btm-group-head { padding: 3px 8px; color: #d2a8ff; font-size: 11px; border-bottom: 1px solid #21262d; }
214
- .btm-marker { padding: 2px 8px; color: #7d8590; font-size: 11px; border-top: 1px dashed #30363d; }
215
- .btm-sys { padding: 4px 8px; border-top: 1px solid #161b22; cursor: pointer; transition: opacity .15s; }
216
- .btm-sys:first-child { border-top: none; }
217
- .btm-sys-line { display: flex; align-items: center; gap: 6px; }
218
- .btm-dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: #30363d; }
219
- .is-active > .btm-sys-line .btm-dot { background: #3fb950; box-shadow: 0 0 6px #3fb950; }
220
- .is-idle > .btm-sys-line .btm-dot { background: #2f6f3a; }
221
- .is-skipped > .btm-sys-line .btm-dot { background: transparent; border: 1px dashed #7d8590; box-sizing: border-box; }
222
- .is-failed > .btm-sys-line .btm-dot { background: #ff7b72; box-shadow: 0 0 6px #ff7b72; }
223
- .btm-name { flex: 1; }
224
- .btm-sys .btm-ms { color: #7d8590; font-size: 11px; }
225
- .btm-chips { display: flex; flex-wrap: wrap; gap: 3px; margin: 3px 0 0 14px; }
226
- .btm-chip { font-size: 10.5px; padding: 0 5px; border-radius: 3px; border: 1px solid; cursor: default; white-space: nowrap; }
227
- .btm-chip.is-read { color: #79c0ff; border-color: rgba(121,192,255,.35); }
228
- .btm-chip.is-write { color: #ffa657; border-color: rgba(255,166,87,.45); }
229
- .btm-chip.is-event { color: #d2a8ff; border-color: rgba(210,168,255,.4); }
230
- .btm-chip.is-spawn { color: #3fb950; border-color: rgba(63,185,80,.4); }
231
- .btm-chip.is-resource { font-style: italic; }
232
- .btm-chip.is-machine { font-weight: 700; }
233
- .btm-chip.is-lit { background: rgba(255,255,255,.12); }
234
- .btm-map.has-focus .btm-sys { opacity: .28; }
235
- .btm-map.has-focus .btm-sys.is-writer, .btm-map.has-focus .btm-sys.is-reader { opacity: 1; }
236
- .btm-sys.is-writer { box-shadow: inset 3px 0 #ffa657; }
237
- .btm-sys.is-reader { box-shadow: inset 3px 0 #79c0ff; }
238
- .btm-details { margin: 4px 0 2px 14px; color: #9da7b3; font-size: 11px; }
239
- .btm-legend { display: flex; flex-wrap: wrap; gap: 4px 10px; color: #7d8590; font-size: 11px; margin-bottom: 4px; }
240
- .btm-kv { display: grid; grid-template-columns: 150px 1fr; gap: 2px 8px; }
241
- .btm-kv > span:nth-child(odd) { color: #79c0ff; overflow: hidden; text-overflow: ellipsis; }
242
- .btm-kv > span:nth-child(even) { word-break: break-all; }
243
- .btm-flash { animation: btm-flash .6s ease-out; }
244
- @keyframes btm-flash { from { background: rgba(247,201,72,.35); } to { background: transparent; } }
245
- .btm-line { color: #9da7b3; font-size: 11px; padding: 1px 0; }
246
- .btm-ids { display: flex; flex-wrap: wrap; gap: 3px; }
247
- .btm-ids button { font: inherit; font-size: 11px; color: #79c0ff; background: #161b22; border: 1px solid #30363d; border-radius: 3px; padding: 0 5px; cursor: pointer; }
248
- .btm-marker-ring { position: fixed; z-index: 2147482999; width: 40px; height: 40px; margin: -20px 0 0 -20px; border: 2px solid #f7c948; border-radius: 50%; pointer-events: none; box-shadow: 0 0 12px rgba(247,201,72,.7); }
249
- .btm-marker-ring[hidden] { display: none; }
250
- .btm-picking, .btm-picking * { cursor: crosshair !important; }
251
- `
252
-
253
- /**
254
- * Adds the monitor to the page. The panel starts closed unless `open` is set;
255
- * toggle it with the key (`Backslash` by default) or the corner button.
256
- */
257
- export const attach = <S extends Schema.Any, Root>(runtime: Target<S, Root>, options: Options<S, Root>): Monitor => {
258
- const debug = runtime.debug
259
- debug.nameSchedules(options.schedules)
260
- const host = options.host
261
- const mount = options.mount ?? host.document.body
262
- const key = options.key ?? "Backslash"
263
- const refreshMs = options.refreshMs ?? 250
264
-
265
- if (host.document.getElementById("btm-style") === null) {
266
- const style = host.document.createElement("style")
267
- style.id = "btm-style"
268
- style.textContent = STYLE
269
- host.document.head.append(style)
270
- }
271
-
272
- const root = host.document.createElement("div")
273
- root.className = "btm"
274
- root.innerHTML = `
275
- <button class="btm-toggle" type="button" title="Toggle the Ritmo monitor">◉ monitor</button>
276
- <section class="btm-panel" hidden>
277
- <div class="btm-head">
278
- <span class="btm-title">Ritmo</span>
279
- <button class="btm-tab" data-tab="overview" type="button">Overview</button>
280
- <button class="btm-tab" data-tab="systems" type="button">Systems</button>
281
- <button class="btm-tab" data-tab="entity" type="button">Entity</button>
282
- ${options.replay === undefined ? "" : `<button class="btm-save-replay" type="button" title="Save the last seconds of play as a replay">Save replay</button>`}
283
- <button class="btm-close" type="button" title="Close">×</button>
284
- </div>
285
- <div class="btm-status"></div>
286
- <div class="btm-controls" hidden>
287
- <button class="btm-pick" type="button">Pick on screen</button>
288
- <input class="btm-id" type="number" min="1" placeholder="id" />
289
- <select class="btm-browse"><option value="">browse by component…</option></select>
290
- <button class="btm-clear" type="button">Clear</button>
291
- </div>
292
- <div class="btm-body"></div>
293
- </section>
294
- <div class="btm-marker-ring" hidden></div>`
295
- mount.append(root)
296
-
297
- const query = <E extends Element>(selector: string): E => root.querySelector<E>(selector)!
298
- const toggleButton = query<HTMLButtonElement>(".btm-toggle")
299
- const panel = query<HTMLElement>(".btm-panel")
300
- const status = query<HTMLElement>(".btm-status")
301
- const controls = query<HTMLElement>(".btm-controls")
302
- const body = query<HTMLElement>(".btm-body")
303
- const pickButton = query<HTMLButtonElement>(".btm-pick")
304
- const idInput = query<HTMLInputElement>(".btm-id")
305
- const browse = query<HTMLSelectElement>(".btm-browse")
306
- const ring = query<HTMLElement>(".btm-marker-ring")
307
- toggleButton.textContent = `◉ monitor (${key.replace(/^Key|^Digit/, "")})`
308
- if (options.pick === undefined) pickButton.disabled = true
309
-
310
- let tab: Tab = "overview"
311
- let collector: Collector | undefined
312
- let stopObserving: (() => void) | undefined
313
- let timer: number | undefined
314
- let openedAt = 0
315
- let description: Debug.Description | undefined
316
- /** How many systems read each component, to name what systems spawn. */
317
- let readers = new Map<string, number>()
318
- let prefix = ""
319
- let focus: string | undefined
320
- const expanded = new Set<string>()
321
- let selected: number | undefined
322
- let browsed: { readonly component: string; readonly ids: ReadonlyArray<number> } | undefined
323
- let previousValues = new Map<string, string>()
324
- let picking = false
325
- let renderMs = 0
326
-
327
- const short = (name: string) => (prefix !== "" && name.startsWith(prefix) ? name.slice(prefix.length) : name)
328
-
329
- // ── Overview ───────────────────────────────────────────────────────────
330
-
331
- const renderOverview = (history: ReadonlyArray<Sample>): string => {
332
- const parts: Array<string> = []
333
- const scheduleNames = Object.keys(options.schedules)
334
- parts.push("<h3>Schedules</h3>", `<div class="btm-hint">Time per tick of each schedule over the last ~2s, including tracing overhead (tracing runs only while this panel is open). The line shows the last ${history.length} samples.</div>`)
335
- parts.push(`<div class="btm-row is-wide btm-dim"><span>schedule</span><span class="btm-num">ticks/s</span><span class="btm-num">ms/tick</span><span></span></div>`)
336
- for (const name of scheduleNames) {
337
- const recent = recentSchedule(history, name, RECENT)
338
- const series = history.map((sample) => {
339
- const window = sample.schedules.get(name)
340
- return window === undefined || window.ticks === 0 ? 0 : window.ms / window.ticks
341
- })
342
- parts.push(`<div class="btm-row is-wide"><span>${escape(name)}</span><span class="btm-num">${recent.seconds === 0 ? "–" : number(recent.ticks / recent.seconds, 0)}</span><span class="btm-num" title="max ${number(recent.maxMs, 3)}ms">${recent.ticks === 0 ? "–" : number(recent.ms / recent.ticks, 3)}</span>${sparkline(series)}</div>`)
343
- }
344
-
345
- const names = new Set<string>()
346
- for (const sample of history.slice(-RECENT)) for (const name of sample.systems.keys()) names.add(name)
347
- const busiest = [...names]
348
- .map((name) => ({ name, recent: recentSystem(history, name, RECENT) }))
349
- .filter((entry) => entry.recent.runs > 0)
350
- .sort((left, right) => right.recent.ms - left.recent.ms)
351
- .slice(0, 8)
352
- const top = busiest[0]?.recent.ms ?? 0
353
- parts.push("<h3>Busiest systems</h3>", `<div class="btm-hint">Share of time over the last ~2s, and average ms per run.</div>`)
354
- for (const { name, recent } of busiest) {
355
- parts.push(`<div class="btm-row"><span title="${escape(name)}">${escape(short(name))}</span><span class="btm-barbox"><div class="btm-bar" style="width:${top === 0 ? 0 : (recent.ms / top) * 100}%"></div></span><span class="btm-num">${number(recent.ms / recent.runs, 3)}</span></div>`)
356
- }
357
-
358
- const latest = history[history.length - 1]
359
- if (latest !== undefined) {
360
- parts.push(`<h3>Population</h3>`, `<div class="btm-hint">Live entities, and entities per component. A line that only goes up is a leak.</div>`)
361
- parts.push(`<div class="btm-row"><span><b>entities</b></span><span class="btm-num">${latest.population.entities}</span>${sparkline(history.map((sample) => sample.population.entities))}</div>`)
362
- const components = Object.keys(latest.population.components)
363
- .filter((component) => history.some((sample) => (sample.population.components[component] ?? 0) > 0))
364
- .sort((left, right) => (latest.population.components[right] ?? 0) - (latest.population.components[left] ?? 0))
365
- for (const component of components) {
366
- parts.push(`<div class="btm-row"><span title="${escape(component)}">${escape(short(component))}</span><span class="btm-num">${latest.population.components[component] ?? 0}</span>${sparkline(history.map((sample) => sample.population.components[component] ?? 0))}</div>`)
367
- }
368
- }
369
-
370
- const machines = Object.entries(debug.dump({ limit: 0 }).machines)
371
- if (machines.length > 0) {
372
- parts.push("<h3>State machines</h3>")
373
- for (const [name, machine] of machines) {
374
- const pending = machine.pending === undefined ? "" : ` <span class="btm-dim">→ ${escape(Format.state(machine.pending))} (queued)</span>`
375
- parts.push(`<div class="btm-row"><span>${escape(short(name))}</span><span class="btm-num">${escape(Format.state(machine.current))}${pending}</span><span></span></div>`)
376
- }
377
- }
378
-
379
- parts.push("<h3>Alerts</h3>")
380
- const alerts = [...(collector?.alerts.values() ?? [])]
381
- if (alerts.length === 0) parts.push(`<div class="btm-dim">None since the monitor opened.</div>`)
382
- for (const alert of alerts) {
383
- parts.push(`<div class="btm-alert${alert.code === "discarded-messages" ? " is-info" : ""}">${escape(alert.message)} <span class="btm-dim">×${alert.count}, f${alert.firstFrame}–f${alert.lastFrame}</span></div>`)
384
- }
385
- return parts.join("")
386
- }
387
-
388
- // ── Systems map ────────────────────────────────────────────────────────
389
-
390
- const chip = (kind: string, subject: string, text: string, title: string) =>
391
- `<span class="btm-chip ${kind}${focus === subject ? " is-lit" : ""}" data-subject="${escape(subject)}" title="${escape(title)}">${escape(text)}</span>`
392
-
393
- const renderSystem = (system: Debug.SystemDescription, history: ReadonlyArray<Sample>, conditionReads: ReadonlyArray<string>): string => {
394
- const access = accessOf(system)
395
- const recent = recentSystem(history, system.name, 2)
396
- const longer = recentSystem(history, system.name, RECENT)
397
- const state = statusOf(recent)
398
- const writesFocus = focus !== undefined && [...access.writes, ...access.resourceWrites, ...access.eventWrites, ...access.machineWrites].includes(focus)
399
- const readsFocus = focus !== undefined && [...access.reads, ...access.resourceReads, ...access.eventReads, ...access.machineReads].includes(focus)
400
- // Name spawned entities by their most specific component: fewest live entities, then most readers.
401
- const counts = history[history.length - 1]?.population.components ?? {}
402
- const spawns = collector?.spawnNames(system.name, (left, right) =>
403
- (counts[left] ?? 0) - (counts[right] ?? 0) || (readers.get(right) ?? 0) - (readers.get(left) ?? 0)) ?? []
404
- const hidden = new Set(conditionReads)
405
- // What the system does first (writes, events, spawns), then what it reads.
406
- const chips = [
407
- ...access.writes.map((name) => chip("is-write", name, short(name), `writes component ${name}`)),
408
- ...access.resourceWrites.map((name) => chip("is-write is-resource", name, short(name), `writes resource ${name}`)),
409
- ...access.machineWrites.map((name) => chip("is-write is-machine", name, `→${short(name)}`, `queues the next state of ${name}`)),
410
- ...access.eventWrites.map((name) => chip("is-event", name, `${short(name)}→`, `emits event ${name}`)),
411
- ...(spawns.length === 0 ? [] : [chip("is-spawn", `spawn:${system.name}`, `+${spawns.map(short).join(", +")}`, "spawns entities (learned while running; details on click)")]),
412
- ...access.eventReads.map((name) => chip("is-event", name, `←${short(name)}`, `reads event ${name}`)),
413
- ...access.reads.map((name) => chip("is-read", name, short(name), `reads component ${name}`)),
414
- ...access.resourceReads.filter((name) => !hidden.has(name)).map((name) => chip("is-read is-resource", name, short(name), `reads resource ${name}`)),
415
- ...access.machineReads.filter((name) => !hidden.has(name)).map((name) => chip("is-read is-machine", name, short(name), `reads state machine ${name}`))
416
- ]
417
- const details: Array<string> = []
418
- if (expanded.has(system.name)) {
419
- const perSecond = (value: number) => number(value / Math.max(longer.seconds, 1e-6), 1)
420
- details.push(`<div class="btm-details">`)
421
- details.push(`<div>${statusText[state]}</div>`)
422
- details.push(`<div>${perSecond(longer.runs)} runs/s · ${longer.runs === 0 ? "–" : number(longer.ms / longer.runs, 3)} ms/run · max ${number(longer.maxMs, 3)} ms</div>`)
423
- if (longer.runs > 0) {
424
- details.push(`<div>per run: ${number(longer.writes / longer.runs, 1)} writes · ${number(longer.events / longer.runs, 1)} events · ${number(longer.commands / longer.runs, 1)} commands</div>`)
425
- }
426
- if (longer.spawns + longer.despawns > 0) details.push(`<div>${perSecond(longer.spawns)} spawns/s · ${perSecond(longer.despawns)} despawns/s</div>`)
427
- if (longer.skips > 0) details.push(`<div>${perSecond(longer.skips)} skips/s — ${escape(collector?.skippedBy.get(system.name) ?? "")}</div>`)
428
- for (const kind of collector?.spawnsOf(system.name) ?? []) {
429
- details.push(`<div>spawned ×${kind.count}: ${escape(kind.components.map(short).join(", "))}</div>`)
430
- }
431
- const error = collector?.lastError.get(system.name)
432
- if (error !== undefined) details.push(`<div style="color:#ff7b72">last error: ${escape(error)}</div>`)
433
- if (system.when.length > 0) details.push(`<div>runs when: ${escape(system.when.join(", "))}</div>`)
434
- if (system.pauseWhen.length > 0) details.push(`<div>pauses when: ${escape(system.pauseWhen.join(", "))}</div>`)
435
- if (system.local) details.push(`<div class="btm-dim">holds local state</div>`)
436
- details.push(`<div class="btm-dim">at ${escape(system.placements.join(", "))}</div>`)
437
- details.push(`</div>`)
438
- }
439
- const classes = ["btm-sys", `is-${state}`, writesFocus ? "is-writer" : "", readsFocus && !writesFocus ? "is-reader" : ""].filter(Boolean).join(" ")
440
- return `<div class="${classes}" data-system="${escape(system.name)}" title="${escape(statusText[state])}">
441
- <div class="btm-sys-line"><span class="btm-dot"></span><span class="btm-name">${escape(short(system.name))}</span><span class="btm-ms">${recent.runs === 0 ? "" : `${number(recent.ms / recent.runs, 3)}ms`}</span></div>
442
- <div class="btm-chips">${chips.join("")}</div>${details.join("")}
443
- </div>`
444
- }
445
-
446
- const renderSystems = (history: ReadonlyArray<Sample>): string => {
447
- if (description === undefined) return ""
448
- const byName = new Map(description.systems.map((system) => [system.name, system]))
449
- const parts: Array<string> = [
450
- `<div class="btm-legend"><span>● working</span><span style="color:#2f6f3a">● idle</span><span>◌ skipped</span><span style="color:#79c0ff">reads</span><span style="color:#ffa657">writes</span><span style="color:#d2a8ff">events</span><span style="color:#3fb950">spawns</span><span><i>italic</i> resource</span><span><b>bold</b> state</span></div>`,
451
- `<div class="btm-hint">Systems run top to bottom. Hover a name to see who writes it (orange edge) and who reads it (blue edge). Click a system for details.</div>`
452
- ]
453
- parts.push(`<div class="btm-map${focus === undefined ? "" : " has-focus"}">`)
454
- const runnable = new Set(Object.keys(options.schedules))
455
- const ordered = [...description.schedules].sort((left, right) => Number(runnable.has(right.name)) - Number(runnable.has(left.name)))
456
- for (const schedule of ordered) {
457
- parts.push(`<h3>${escape(schedule.name)}</h3>`)
458
- // Consecutive steps with the same run conditions form a group.
459
- const groups: Array<{ when: string; steps: Array<Debug.StepDescription> }> = []
460
- for (const step of schedule.steps) {
461
- const when = step.kind === "system" ? (byName.get(step.system)?.when.join(", ") ?? "") : undefined
462
- const last = groups[groups.length - 1]
463
- if (last !== undefined && (when === undefined || last.when === when)) last.steps.push(step)
464
- else groups.push({ when: when ?? "", steps: [step] })
465
- }
466
- for (const group of groups) {
467
- const members = group.steps.flatMap((step) => (step.kind === "system" ? [byName.get(step.system)!] : []))
468
- // Resources and machines every member reads come from the group's
469
- // conditions (a check's reads count as the gated system's reads).
470
- const conditionReads = !group.when.includes("check(") || members.length === 0
471
- ? []
472
- : [...members[0]!.resources.reads, ...members[0]!.machines.reads].filter((name) =>
473
- members.every((member) => member.resources.reads.includes(name) || member.machines.reads.includes(name)))
474
- const head = group.when === ""
475
- ? ""
476
- : `<div class="btm-group-head">when ${escape(group.when)}${conditionReads.length === 0 ? "" : ` <span class="btm-dim">· the condition reads ${escape(conditionReads.map(short).join(", "))}</span>`}</div>`
477
- const items = group.steps.map((step) => {
478
- if (step.kind === "system") return renderSystem(byName.get(step.system)!, history, conditionReads)
479
- const label = step.kind === "applyDeferred" ? "apply commands" : `apply state transitions${step.schedules.length > 0 ? ` (runs ${step.schedules.length} transition schedules)` : ""}`
480
- return `<div class="btm-marker">⟂ ${escape(label)}</div>`
481
- })
482
- parts.push(`<div class="btm-group">${head}${items.join("")}</div>`)
483
- }
484
- }
485
- parts.push("</div>")
486
- return parts.join("")
487
- }
488
-
489
- // ── Entity ─────────────────────────────────────────────────────────────
490
-
491
- const renderEntity = (): string => {
492
- const parts: Array<string> = []
493
- if (browsed !== undefined) {
494
- parts.push(`<h3>Entities with ${escape(short(browsed.component))} (${browsed.ids.length})</h3><div class="btm-ids">`)
495
- for (const id of browsed.ids.slice(0, 80)) parts.push(`<button type="button" data-entity="${id}">e${id}</button>`)
496
- parts.push(browsed.ids.length > 80 ? `<span class="btm-dim">…+${browsed.ids.length - 80}</span>` : "", "</div>")
497
- }
498
- if (selected === undefined) {
499
- parts.push(`<div class="btm-hint" style="margin-top:8px">${options.pick === undefined ? "Enter an entity id" : "Pick an entity on screen, enter an id,"} or browse by component.</div>`)
500
- return parts.join("")
501
- }
502
- const dumped = debug.dump({ entities: [selected] }).entities[0]
503
- parts.push(`<h3 style="text-transform:none">e${selected}</h3>`)
504
- if (dumped === undefined) {
505
- parts.push(`<div class="btm-dim">Not alive (despawned).</div>`)
506
- } else {
507
- const values = new Map<string, string>()
508
- parts.push(`<div class="btm-kv">`)
509
- for (const [component, value] of Object.entries(dumped.components)) {
510
- const text = Format.value(value, { depth: 2, items: 6 })
511
- values.set(component, text)
512
- const changed = previousValues.has(component) && previousValues.get(component) !== text
513
- parts.push(`<span title="${escape(component)}">${escape(short(component))}</span><span${changed ? ` class="btm-flash"` : ""}>${escape(text)}</span>`)
514
- }
515
- for (const [relation, target] of Object.entries(dumped.relations)) {
516
- parts.push(`<span>${escape(short(relation))}</span><span>→ e${target}</span>`)
517
- }
518
- parts.push(`</div>`)
519
- previousValues = values
520
- }
521
- parts.push(`<h3>Recent changes</h3>`)
522
- const lines = [...(collector?.entityLines ?? [])].reverse()
523
- if (lines.length === 0) parts.push(`<div class="btm-dim">No changes since it was selected.</div>`)
524
- for (const line of lines) {
525
- parts.push(`<div class="btm-line"><span class="btm-dim">f${line.frame}</span> ${escape(short(line.system))}: ${escape(line.text)}</div>`)
526
- }
527
- return parts.join("")
528
- }
529
-
530
- // ── Refresh ────────────────────────────────────────────────────────────
531
-
532
- const render = () => {
533
- if (collector === undefined) return
534
- const started = host.performance.now()
535
- const history = collector.history
536
- const latest = history.slice(-RECENT)
537
- const overhead = latest.reduce((total, sample) => total + sample.overheadMs, 0)
538
- const ticks = latest.reduce((total, sample) => total + [...sample.schedules.values()].reduce((sum, window) => sum + window.ticks, 0), 0)
539
- status.textContent = `observing for ${Math.round((host.performance.now() - openedAt) / 1000)}s · frame ${debug.frame()} · panel ${ticks === 0 ? "–" : number(overhead / ticks, 3)} ms/tick + ${number(renderMs, 1)} ms/refresh`
540
- status.title = "The panel's own work. Tracing (on only while the panel is open) also slows every system run a little, and the times shown include it: compare them with each other, not with a closed-monitor run."
541
- body.innerHTML = tab === "overview" ? renderOverview(history) : tab === "systems" ? renderSystems(history) : renderEntity()
542
- renderMs = host.performance.now() - started
543
- }
544
-
545
- const refresh = () => {
546
- if (collector === undefined) return
547
- collector.sample(host.performance.now())
548
- render()
549
- }
550
-
551
- const placeRing = () => {
552
- const at = selected === undefined || options.locate === undefined || panel.hidden ? undefined : options.locate(selected)
553
- ring.hidden = at === undefined
554
- if (at !== undefined) {
555
- ring.style.left = `${at.x}px`
556
- ring.style.top = `${at.y}px`
557
- }
558
- if (!panel.hidden) host.requestAnimationFrame(placeRing)
559
- }
560
-
561
- const setTab = (next: Tab) => {
562
- tab = next
563
- for (const button of root.querySelectorAll<HTMLButtonElement>(".btm-tab")) button.classList.toggle("is-on", button.dataset["tab"] === next)
564
- controls.hidden = next !== "entity"
565
- render()
566
- }
567
-
568
- const open = () => {
569
- if (!panel.hidden) return
570
- description = debug.describe()
571
- readers = new Map(description.access.components.map((entry) => [entry.name, entry.readers.length]))
572
- prefix = commonPrefix([...description.systems.map((system) => system.name), ...description.components.map((component) => component.name)])
573
- browse.replaceChildren(new Option("browse by component…", ""), ...description.components.map((component) => new Option(short(component.name), component.name)))
574
- collector = new Collector(() => debug.population(), () => host.performance.now())
575
- collector.select(selected)
576
- stopObserving = debug.observe(collector.observe)
577
- openedAt = host.performance.now()
578
- panel.hidden = false
579
- timer = host.setInterval(refresh, refreshMs)
580
- setTab(tab)
581
- host.requestAnimationFrame(placeRing)
582
- }
583
-
584
- const close = () => {
585
- if (panel.hidden) return
586
- panel.hidden = true
587
- ring.hidden = true
588
- stopObserving?.()
589
- stopObserving = undefined
590
- if (timer !== undefined) host.clearInterval(timer)
591
- timer = undefined
592
- collector = undefined
593
- setPicking(false)
594
- }
595
-
596
- const select = (entity: number | undefined) => {
597
- selected = entity
598
- previousValues = new Map()
599
- collector?.select(entity)
600
- idInput.value = entity === undefined ? "" : String(entity)
601
- render()
602
- }
603
-
604
- const onPick = (event: PointerEvent) => {
605
- if (event.target instanceof Node && root.contains(event.target)) return
606
- event.preventDefault()
607
- event.stopPropagation()
608
- event.stopImmediatePropagation()
609
- const entity = options.pick?.(event)
610
- setPicking(false)
611
- if (entity !== undefined) {
612
- if (tab !== "entity") setTab("entity")
613
- select(entity)
614
- }
615
- }
616
-
617
- function setPicking(on: boolean) {
618
- if (picking === on) return
619
- picking = on
620
- pickButton.classList.toggle("is-on", on)
621
- pickButton.textContent = on ? "Click an entity… (Esc)" : "Pick on screen"
622
- host.document.documentElement.classList.toggle("btm-picking", on)
623
- if (on) host.addEventListener("pointerdown", onPick, { capture: true })
624
- else host.removeEventListener("pointerdown", onPick, { capture: true })
625
- }
626
-
627
- // ── Events ─────────────────────────────────────────────────────────────
628
-
629
- const onKey = (event: KeyboardEvent) => {
630
- const target = event.target as HTMLElement | null
631
- if (target !== null && (target.tagName === "INPUT" || target.tagName === "SELECT" || target.tagName === "TEXTAREA")) return
632
- if (event.code === key) {
633
- if (panel.hidden) open()
634
- else close()
635
- } else if (event.code === "Escape" && picking) {
636
- setPicking(false)
637
- }
638
- }
639
- host.addEventListener("keydown", onKey)
640
- toggleButton.addEventListener("click", () => (panel.hidden ? open() : close()))
641
- query<HTMLButtonElement>(".btm-close").addEventListener("click", close)
642
- const replay = options.replay
643
- if (replay !== undefined) {
644
- const button = query<HTMLButtonElement>(".btm-save-replay")
645
- button.addEventListener("click", () => {
646
- replay.save("Save replay button")
647
- button.textContent = "Saved"
648
- host.setTimeout(() => { button.textContent = "Save replay" }, 1500)
649
- })
650
- }
651
- for (const button of root.querySelectorAll<HTMLButtonElement>(".btm-tab")) {
652
- button.addEventListener("click", () => setTab(button.dataset["tab"] as Tab))
653
- }
654
- pickButton.addEventListener("click", () => setPicking(!picking))
655
- idInput.addEventListener("keydown", (event) => event.stopPropagation())
656
- idInput.addEventListener("change", () => {
657
- const value = Number.parseInt(idInput.value, 10)
658
- select(Number.isFinite(value) && value > 0 ? value : undefined)
659
- })
660
- browse.addEventListener("change", () => {
661
- const component = browse.value
662
- browsed = component === ""
663
- ? undefined
664
- : { component, ids: debug.dump().entities.filter((entity) => component in entity.components).map((entity) => entity.id) }
665
- render()
666
- })
667
- query<HTMLButtonElement>(".btm-clear").addEventListener("click", () => {
668
- browsed = undefined
669
- browse.value = ""
670
- select(undefined)
671
- })
672
- body.addEventListener("click", (event) => {
673
- const target = event.target as HTMLElement
674
- const entity = target.closest<HTMLElement>("[data-entity]")
675
- if (entity !== null) {
676
- select(Number(entity.dataset["entity"]))
677
- return
678
- }
679
- const system = target.closest<HTMLElement>("[data-system]")
680
- if (system !== null && target.closest("[data-subject]") === null) {
681
- const name = system.dataset["system"]!
682
- if (expanded.has(name)) expanded.delete(name)
683
- else expanded.add(name)
684
- render()
685
- }
686
- })
687
- body.addEventListener("mouseover", (event) => {
688
- const subject = (event.target as HTMLElement).closest<HTMLElement>("[data-subject]")?.dataset["subject"]
689
- if (subject === focus || tab !== "systems") return
690
- focus = subject?.startsWith("spawn:") ? undefined : subject
691
- render()
692
- })
693
- body.addEventListener("mouseleave", () => {
694
- if (focus === undefined) return
695
- focus = undefined
696
- render()
697
- })
698
-
699
- setTab("overview")
700
- if (options.open === true) open()
701
-
702
- return {
703
- open,
704
- close,
705
- toggle: () => (panel.hidden ? open() : close()),
706
- select,
707
- detach: () => {
708
- close()
709
- host.removeEventListener("keydown", onKey)
710
- root.remove()
711
- }
712
- }
713
- }