@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
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The dependency determinism scan behind `ritmo-devtools scan <entry>` (Node
3
+ * only): every file the simulation entry imports, `node_modules` included,
4
+ * checked with the oxlint rules `ritmo/use-ops-for-math`,
5
+ * `ritmo/use-clock-for-time`, and `ritmo/use-random-for-randomness`.
6
+ *
7
+ * The import closure comes from rolldown: a real bundler resolves exactly
8
+ * what a game's build resolves (package `exports`, `browser` fields, CJS and
9
+ * ESM, TypeScript with type-only imports erased), and its module graph
10
+ * (`this.getModuleIds()`) lists every loaded file, including ones tree-shaking
11
+ * would drop. Rolldown is what Vite 8 builds with, so a game with Vite 8 needs
12
+ * nothing new: it is found as Vite's own dependency when the game does not
13
+ * install it directly. esbuild (through tsx) was the alternative, but Vite 8
14
+ * no longer depends on it, so fewer games would have it.
15
+ *
16
+ * The files are checked by spawning the game's own `oxlint` with
17
+ * `@typeonce/oxlint-plugin-ritmo` (both are in every game's setup) and a
18
+ * generated config that turns on only those three rules. Running the rules
19
+ * themselves, not a scanner that mirrors them, keeps one definition of what is
20
+ * flagged: the scan reports exactly what the lint would report if the
21
+ * dependency were the game's code, and what `oxlint --fix` fixes after the
22
+ * dependency is vendored.
23
+ *
24
+ * Each tool is looked up from the entry's directory first, then from devtools
25
+ * (`oxlint` and `rolldown` are optional peer dependencies).
26
+ *
27
+ * @internal
28
+ */
29
+ import { spawnSync } from "node:child_process"
30
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
31
+ import { tmpdir } from "node:os"
32
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path"
33
+ import { fileURLToPath, pathToFileURL } from "node:url"
34
+
35
+ import * as Result from "@typeonce/ritmo/Result"
36
+
37
+ /** The rules the scan runs: the determinism rules a dependency can break. */
38
+ export const rules = ["ritmo/use-ops-for-math", "ritmo/use-clock-for-time", "ritmo/use-random-for-randomness"] as const
39
+
40
+ export type Rule = (typeof rules)[number]
41
+
42
+ /** One report of a rule, at a 1-based line and column (UTF-16) in a file relative to the working directory. */
43
+ export interface Finding {
44
+ readonly file: string
45
+ readonly line: number
46
+ readonly column: number
47
+ readonly rule: Rule
48
+ /** The flagged source (`Math.sin`, `x ** 3`, `Date.now`), shortened to one line. */
49
+ readonly snippet: string
50
+ }
51
+
52
+ /** Findings of the files that belong to one package (nearest `package.json` with a `name`). */
53
+ export interface PackageReport {
54
+ readonly name: string
55
+ readonly files: number
56
+ readonly findings: ReadonlyArray<Finding>
57
+ }
58
+
59
+ /** The scan result; `packages` starts with the entry's own package, then the rest by name. */
60
+ export interface Report {
61
+ readonly entry: string
62
+ readonly files: number
63
+ readonly packages: ReadonlyArray<PackageReport>
64
+ }
65
+
66
+ export type ScanError =
67
+ | { readonly _tag: "EntryUnreadable"; readonly message: string }
68
+ | { readonly _tag: "ToolMissing"; readonly tool: string; readonly install: string }
69
+ | { readonly _tag: "ResolveFailed"; readonly message: string }
70
+ | { readonly _tag: "LintFailed"; readonly message: string }
71
+
72
+ const sourceFile = /\.(?:[cm]?[jt]s|[jt]sx)$/
73
+ const chunkSize = 400
74
+ const unnamed = "(no package)"
75
+
76
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
77
+ typeof value === "object" && value !== null && !Array.isArray(value)
78
+
79
+ const readJson = (path: string): unknown => {
80
+ try {
81
+ return JSON.parse(readFileSync(path, "utf8"))
82
+ } catch {
83
+ return undefined
84
+ }
85
+ }
86
+
87
+ /** The real directory of the installed package `name`, looked up through `node_modules` from `from` upward. */
88
+ const findPackage = (name: string, from: string): string | undefined => {
89
+ for (let directory = from; ; directory = dirname(directory)) {
90
+ const candidate = join(directory, "node_modules", name)
91
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate)
92
+ if (dirname(directory) === directory) return undefined
93
+ }
94
+ }
95
+
96
+ const exportTarget = (value: unknown): string | undefined => {
97
+ if (typeof value === "string") return value
98
+ if (Array.isArray(value)) return exportTarget(value[0])
99
+ if (!isRecord(value)) return undefined
100
+ for (const [condition, target] of Object.entries(value)) {
101
+ if (condition === "import" || condition === "node" || condition === "default") {
102
+ const found = exportTarget(target)
103
+ if (found !== undefined) return found
104
+ }
105
+ }
106
+ return undefined
107
+ }
108
+
109
+ /** The file the package's main entry imports (`exports["."]` with `import`/`node`/`default`, then `module`, `main`). */
110
+ const packageEntry = (directory: string): string => {
111
+ const manifest = readJson(join(directory, "package.json"))
112
+ const record = isRecord(manifest) ? manifest : {}
113
+ const exports = record["exports"]
114
+ const main = isRecord(exports) && "." in exports ? exports["."] : exports
115
+ const target = exportTarget(main)
116
+ ?? (typeof record["module"] === "string" ? record["module"] : undefined)
117
+ ?? (typeof record["main"] === "string" ? record["main"] : "index.js")
118
+ return join(directory, target)
119
+ }
120
+
121
+ const devtoolsDirectory = dirname(fileURLToPath(import.meta.url))
122
+
123
+ const locate = (name: string, from: string): string | undefined =>
124
+ findPackage(name, from) ?? findPackage(name, devtoolsDirectory)
125
+
126
+ interface Bundle {
127
+ readonly generate: (options: object) => Promise<unknown>
128
+ readonly close: () => Promise<void>
129
+ }
130
+ type Rolldown = (options: object) => Promise<Bundle>
131
+
132
+ /** Rolldown, installed directly or as Vite 8's dependency. */
133
+ const loadRolldown = async (from: string): Promise<Rolldown | undefined> => {
134
+ const vite = locate("vite", from)
135
+ const directory = locate("rolldown", from) ?? (vite === undefined ? undefined : findPackage("rolldown", vite))
136
+ if (directory === undefined) return undefined
137
+ const loaded: unknown = await import(pathToFileURL(packageEntry(directory)).href)
138
+ const rolldown = isRecord(loaded) ? loaded["rolldown"] : undefined
139
+ // The module is untyped here (an optional peer); only its shape was checked.
140
+ return typeof rolldown === "function" ? rolldown as Rolldown : undefined
141
+ }
142
+
143
+ /** Every source file the entry imports, itself included, as real absolute paths. */
144
+ const closure = async (rolldown: Rolldown, entry: string): Promise<ReadonlyArray<string>> => {
145
+ let ids: ReadonlyArray<string> = []
146
+ const bundle = await rolldown({
147
+ input: entry,
148
+ cwd: dirname(entry),
149
+ // The build that ships to players; Node builtins stay external.
150
+ platform: "browser",
151
+ treeshake: false,
152
+ logLevel: "silent",
153
+ plugins: [{
154
+ name: "ritmo-devtools-scan",
155
+ buildEnd(this: { getModuleIds: () => Iterable<string> }) {
156
+ ids = [...this.getModuleIds()]
157
+ }
158
+ }]
159
+ })
160
+ try {
161
+ await bundle.generate({})
162
+ } finally {
163
+ await bundle.close()
164
+ }
165
+ return [...new Set(ids.filter((id) => isAbsolute(id) && sourceFile.test(id) && existsSync(id)).map((id) => realpathSync(id)))].sort()
166
+ }
167
+
168
+ interface Diagnostic {
169
+ readonly file: string
170
+ readonly rule: Rule
171
+ readonly offset: number
172
+ readonly length: number
173
+ }
174
+
175
+ const parseDiagnostics = (stdout: string): ReadonlyArray<Diagnostic> | undefined => {
176
+ let parsed: unknown
177
+ try {
178
+ parsed = JSON.parse(stdout)
179
+ } catch {
180
+ return undefined
181
+ }
182
+ if (!isRecord(parsed) || !Array.isArray(parsed["diagnostics"])) return undefined
183
+ const out: Array<Diagnostic> = []
184
+ for (const diagnostic of parsed["diagnostics"]) {
185
+ if (!isRecord(diagnostic) || typeof diagnostic["code"] !== "string" || typeof diagnostic["filename"] !== "string") continue
186
+ const rule = diagnostic["code"].replace(/^ritmo\((.*)\)$/, "ritmo/$1")
187
+ const label = Array.isArray(diagnostic["labels"]) ? diagnostic["labels"][0] : undefined
188
+ const span = isRecord(label) && isRecord(label["span"]) ? label["span"] : undefined
189
+ if (!(rules as ReadonlyArray<string>).includes(rule) || span === undefined) continue
190
+ if (typeof span["offset"] !== "number" || typeof span["length"] !== "number") continue
191
+ out.push({ file: diagnostic["filename"], rule: rule as Rule, offset: span["offset"], length: span["length"] })
192
+ }
193
+ return out
194
+ }
195
+
196
+ const lint = (oxlint: string, plugin: string, files: ReadonlyArray<string>): Result.Result<ReadonlyArray<Diagnostic>, ScanError> => {
197
+ const directory = mkdtempSync(join(tmpdir(), "ritmo-scan-"))
198
+ try {
199
+ const config = join(directory, "oxlintrc.json")
200
+ writeFileSync(config, JSON.stringify({
201
+ jsPlugins: [plugin],
202
+ categories: { correctness: "off" },
203
+ rules: Object.fromEntries(rules.map((rule) => [rule, "error"])),
204
+ ignorePatterns: []
205
+ }))
206
+ const diagnostics: Array<Diagnostic> = []
207
+ for (let start = 0; start < files.length; start += chunkSize) {
208
+ const run = spawnSync(
209
+ process.execPath,
210
+ [oxlint, "-c", config, "--format", "json", "--no-ignore", "--disable-nested-config", ...files.slice(start, start + chunkSize)],
211
+ { encoding: "utf8", maxBuffer: 1024 * 1024 * 1024 }
212
+ )
213
+ const parsed = parseDiagnostics(run.stdout ?? "")
214
+ if (parsed === undefined) {
215
+ return Result.failure({ _tag: "LintFailed", message: (run.stderr || run.stdout || run.error?.message || "no output").trim() })
216
+ }
217
+ diagnostics.push(...parsed)
218
+ }
219
+ return Result.success(diagnostics)
220
+ } finally {
221
+ rmSync(directory, { recursive: true, force: true })
222
+ }
223
+ }
224
+
225
+ const shorten = (text: string): string => {
226
+ const line = text.replace(/\s+/g, " ").trim()
227
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line
228
+ }
229
+
230
+ /** Line, column (UTF-16), and snippet of each byte span (oxlint reports UTF-8 offsets), walking the file once. */
231
+ const locateSpans = (path: string, cwd: string, found: ReadonlyArray<Diagnostic>): ReadonlyArray<Finding> => {
232
+ const bytes = readFileSync(path)
233
+ const file = relative(cwd, path)
234
+ const sorted = [...found].sort((a, b) => a.offset - b.offset)
235
+ const out: Array<Finding> = []
236
+ let cursor = 0
237
+ let line = 1
238
+ let column = 1
239
+ for (const diagnostic of sorted) {
240
+ const end = Math.min(diagnostic.offset, bytes.length)
241
+ let lineStart = cursor
242
+ for (let index = cursor; index < end; index++) {
243
+ if (bytes[index] === 0x0a) {
244
+ line++
245
+ column = 1
246
+ lineStart = index + 1
247
+ }
248
+ }
249
+ column += bytes.subarray(lineStart, end).toString("utf8").length
250
+ cursor = end
251
+ out.push({
252
+ file,
253
+ line,
254
+ column,
255
+ rule: diagnostic.rule,
256
+ snippet: shorten(bytes.subarray(diagnostic.offset, diagnostic.offset + diagnostic.length).toString("utf8"))
257
+ })
258
+ }
259
+ return out
260
+ }
261
+
262
+ /** The `name` of the nearest `package.json` above `file` that has one. */
263
+ const packageOf = (cache: Map<string, string | undefined>, file: string): string | undefined => {
264
+ const visited: Array<string> = []
265
+ let name: string | undefined
266
+ for (let directory = dirname(file); ; directory = dirname(directory)) {
267
+ if (cache.has(directory)) {
268
+ name = cache.get(directory)
269
+ break
270
+ }
271
+ visited.push(directory)
272
+ const manifest = readJson(join(directory, "package.json"))
273
+ if (isRecord(manifest) && typeof manifest["name"] === "string" && manifest["name"] !== "") {
274
+ name = manifest["name"]
275
+ break
276
+ }
277
+ if (dirname(directory) === directory) break
278
+ }
279
+ for (const directory of visited) cache.set(directory, name)
280
+ return name
281
+ }
282
+
283
+ /** Scans the import closure of `entry`; paths in the report are relative to `cwd`. */
284
+ export const run = async (entry: string, cwd: string): Promise<Result.Result<Report, ScanError>> => {
285
+ const absolute = resolve(cwd, entry)
286
+ try {
287
+ if (!statSync(absolute).isFile()) return Result.failure({ _tag: "EntryUnreadable", message: `${entry} is not a file` })
288
+ readFileSync(absolute)
289
+ } catch (error) {
290
+ return Result.failure({ _tag: "EntryUnreadable", message: `${entry} could not be read: ${error instanceof Error ? error.message : String(error)}` })
291
+ }
292
+ const from = dirname(realpathSync(absolute))
293
+ const rolldown = await loadRolldown(from)
294
+ if (rolldown === undefined) {
295
+ return Result.failure({ _tag: "ToolMissing", tool: "rolldown (or vite 8, which includes it)", install: "npm install --save-dev rolldown" })
296
+ }
297
+ const oxlint = locate("oxlint", from)
298
+ const plugin = locate("@typeonce/oxlint-plugin-ritmo", from)
299
+ if (oxlint === undefined || plugin === undefined) {
300
+ return Result.failure({ _tag: "ToolMissing", tool: "oxlint with @typeonce/oxlint-plugin-ritmo", install: "npm install --save-dev oxlint @typeonce/oxlint-plugin-ritmo" })
301
+ }
302
+ const manifest = readJson(join(oxlint, "package.json"))
303
+ const bin = isRecord(manifest) ? manifest["bin"] : undefined
304
+ const oxlintBin = join(oxlint, typeof bin === "string" ? bin : isRecord(bin) && typeof bin["oxlint"] === "string" ? bin["oxlint"] : "bin/oxlint")
305
+
306
+ let files: ReadonlyArray<string>
307
+ try {
308
+ files = await closure(rolldown, realpathSync(absolute))
309
+ } catch (error) {
310
+ return Result.failure({ _tag: "ResolveFailed", message: error instanceof Error ? error.message : String(error) })
311
+ }
312
+ const diagnostics = lint(oxlintBin, packageEntry(plugin), files)
313
+ if (!diagnostics.ok) return diagnostics
314
+
315
+ const base = realpathSync(cwd)
316
+ const byFile = new Map<string, Array<Diagnostic>>()
317
+ for (const diagnostic of diagnostics.value) {
318
+ const path = realpathSync(diagnostic.file)
319
+ byFile.set(path, [...(byFile.get(path) ?? []), diagnostic])
320
+ }
321
+ const cache = new Map<string, string | undefined>()
322
+ const own = packageOf(cache, realpathSync(absolute)) ?? unnamed
323
+ const groups = new Map<string, { files: number; findings: Array<Finding> }>([[own, { files: 0, findings: [] }]])
324
+ for (const file of files) {
325
+ const name = packageOf(cache, file) ?? unnamed
326
+ const group = groups.get(name) ?? { files: 0, findings: [] }
327
+ group.files++
328
+ group.findings.push(...locateSpans(file, base, byFile.get(file) ?? []))
329
+ groups.set(name, group)
330
+ }
331
+ const packages = [...groups]
332
+ .sort(([a], [b]) => a === own ? -1 : b === own ? 1 : a.localeCompare(b))
333
+ .map(([name, group]) => ({ name, files: group.files, findings: group.findings }))
334
+ return Result.success({ entry: relative(base, realpathSync(absolute)), files: files.length, packages })
335
+ }
336
+
337
+ const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? "" : "s"}`
338
+
339
+ /** The text report: findings grouped by package, a summary line, and what to do next. */
340
+ export const format = (report: Report): string => {
341
+ const flagged = report.packages.filter((entry) => entry.findings.length > 0)
342
+ const total = flagged.reduce((sum, entry) => sum + entry.findings.length, 0)
343
+ const lines: Array<string> = []
344
+ for (const entry of flagged) {
345
+ lines.push(`${entry.name} (${plural(entry.findings.length, "finding")})`)
346
+ for (const finding of entry.findings) {
347
+ lines.push(` ${finding.file}:${finding.line}:${finding.column} ${finding.rule} ${finding.snippet}`)
348
+ }
349
+ lines.push("")
350
+ }
351
+ lines.push(`scanned ${plural(report.files, "file")} in ${plural(report.packages.length, "package")} imported by ${report.entry}: ${plural(total, "finding")} in ${plural(flagged.length, "package")}`)
352
+ lines.push(total > 0
353
+ ? "These are hints: code the simulation never calls is fine. For a dependency the simulation calls, vendor it into your source and run `oxlint --fix` with these rules on, or replace it; then confirm with Verify.acrossEngines (`ritmo-devtools verify`) or Netcode.syncTest."
354
+ : "No dependency uses the Math functions, clock, or randomness these rules flag; confirm the whole run with Verify.acrossEngines (`ritmo-devtools verify`) or Netcode.syncTest.")
355
+ return lines.join("\n")
356
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The network half of `Fuzz.run`: one simulation of every seat as its own
3
+ * peer, each a fresh runtime from the game's factory, joined by a seeded
4
+ * `MemoryNetworkLink` on one test clock and driven by `Netcode.rollback`
5
+ * sessions. Deterministic for a timeline and a network seed, so shrinking
6
+ * can run it again.
7
+ */
8
+ import { HostClock } from "@typeonce/ritmo"
9
+ import type * as Clock from "@typeonce/ritmo/Clock"
10
+ import type * as Descriptor from "@typeonce/ritmo/Descriptor"
11
+ import type { Source } from "@typeonce/ritmo/Schedule"
12
+ import { MemoryNetworkLink, Netcode } from "@typeonce/ritmo-netcode"
13
+
14
+ import type { Invariant } from "../Invariant.ts"
15
+ import type * as Replay from "../Replay.ts"
16
+
17
+ /** What one networked simulation came to: as `Fuzz`'s single-runtime outcome, without a replay. */
18
+ export type NetworkOutcome<Violation> =
19
+ | { readonly kind: "passed" }
20
+ | { readonly kind: "violated"; readonly violation: Violation; readonly frame: number }
21
+ | { readonly kind: "invalid"; readonly message: string }
22
+
23
+ export interface NetworkPlan {
24
+ /** The seats' service, codec, count, and idle input. */
25
+ readonly name: string
26
+ readonly codec: Descriptor.Codec<any, any>
27
+ readonly count: number
28
+ readonly idle: unknown
29
+ /** The game's factory, and the schedules it is fuzzed with. */
30
+ readonly make: (playback: Replay.Playback) => { readonly runtime: unknown; readonly schedules: Readonly<Record<string, unknown>> }
31
+ readonly schedule: string
32
+ readonly setup: string | undefined
33
+ readonly invariants: ReadonlyArray<Invariant>
34
+ readonly step: Clock.Step
35
+ readonly seed: number
36
+ readonly latencyMS: number
37
+ readonly jitterMS: number
38
+ readonly loss: number
39
+ readonly settle: number
40
+ readonly inputDelay: number | undefined
41
+ readonly maxRollback: number | undefined
42
+ readonly checksumEvery: number | undefined
43
+ }
44
+
45
+ /** What the sessions call on a runtime the factory made. `Fuzz.run`'s signature checked the real types. */
46
+ interface Peer {
47
+ readonly tryTick: (schedule: unknown) => { readonly ok: boolean; readonly error?: unknown }
48
+ readonly inspect: (inspector: unknown) => unknown
49
+ }
50
+
51
+ export type NetworkViolation =
52
+ | { readonly _tag: "SessionFailed"; readonly seat: number; readonly error: Netcode.SessionError<unknown> }
53
+ | { readonly _tag: "InvariantViolated"; readonly invariant: string; readonly message: string }
54
+ | { readonly _tag: "Defect"; readonly invariant: string | undefined; readonly error: unknown }
55
+
56
+ /** Plays `timeline` (per frame, the seats input's value: every seat's local input) on one peer per seat, then `settle` idle frames. */
57
+ export const play = (plan: NetworkPlan, timeline: ReadonlyArray<ReadonlyArray<unknown>>): NetworkOutcome<NetworkViolation> => {
58
+ const hostClock = HostClock.test()
59
+ const links = MemoryNetworkLink.make({ peers: plan.count, hostClock, seed: plan.seed, latencyMS: plan.latencyMS, jitterMS: plan.jitterMS, loss: plan.loss })
60
+ if (!links.ok) return { kind: "invalid", message: `network.${links.error.field} is out of range: ${links.error.value}` }
61
+ const peers: Array<{ readonly runtime: Peer; readonly session: Netcode.Session<unknown, unknown> }> = []
62
+ for (let seat = 0; seat < plan.count; seat++) {
63
+ const seats = Netcode.seats(plan.codec, { count: plan.count, idle: plan.idle })
64
+ if (!seats.ok) return { kind: "invalid", message: `the seats' idle input: ${seats.error.reason}` }
65
+ const unknown: Array<string> = []
66
+ const playback: Replay.Playback = {
67
+ source: <const SourceName extends string, Value extends Source<unknown>>(descriptor: Descriptor.Descriptor<"service", SourceName, Value>): Source<Replay.SourceData<Value>> => {
68
+ if (descriptor.name !== plan.name) unknown.push(descriptor.name)
69
+ // `Fuzz.seats` checked that this service is a `Netcode.Source` of the seats' input.
70
+ return seats.value.source as unknown as Source<Replay.SourceData<Value>>
71
+ },
72
+ constant: () => undefined
73
+ }
74
+ const target = plan.make(playback)
75
+ if (unknown.length > 0) return { kind: "invalid", message: `make asked playback.source for ${unknown.join(", ")}: over a network the simulation reads its input from the seats alone` }
76
+ const runtime = target.runtime as Peer
77
+ const schedule = target.schedules[plan.schedule]
78
+ if (schedule === undefined) return { kind: "invalid", message: `make returned no schedule ${plan.schedule}` }
79
+ // Only seat 0 sets up: every peer starts from its save.
80
+ if (seat === 0 && plan.setup !== undefined) {
81
+ const setup = target.schedules[plan.setup]
82
+ if (setup === undefined) return { kind: "invalid", message: `make returned no schedule ${plan.setup}` }
83
+ const ticked = runtime.tryTick(setup)
84
+ if (!ticked.ok) return { kind: "invalid", message: `setup failed with every input neutral: ${JSON.stringify(ticked.error)}` }
85
+ }
86
+ // `Fuzz.run`'s signature checked that the schedule rewinds and the runtime saves, as `Netcode.rollback` does.
87
+ const session = (Netcode.rollback as unknown as (runtime: unknown, options: unknown) => ReturnType<typeof Netcode.rollback>)(runtime, {
88
+ simulate: schedule,
89
+ seats: seats.value,
90
+ seat,
91
+ links: [links.value[seat]!],
92
+ hostClock,
93
+ step: plan.step,
94
+ keepSnapshots: true,
95
+ ...(plan.inputDelay === undefined ? {} : { inputDelay: plan.inputDelay }),
96
+ ...(plan.maxRollback === undefined ? {} : { maxRollback: plan.maxRollback }),
97
+ ...(plan.checksumEvery === undefined ? {} : { checksumEvery: plan.checksumEvery })
98
+ })
99
+ if (!session.ok) return { kind: "invalid", message: `network.${session.error.field}: ${session.error.reason}` }
100
+ peers.push({ runtime, session: session.value as Netcode.Session<unknown, unknown> })
101
+ }
102
+
103
+ const stepMS = plan.step.dt * 1000
104
+ const frames = timeline.length + plan.settle
105
+ for (let frame = 0; frame < frames; frame++) {
106
+ const values = timeline[frame]?.[0] as ReadonlyArray<unknown> | undefined
107
+ for (const [seat, { session }] of peers.entries()) {
108
+ let advanced: ReturnType<typeof session.advance>
109
+ try {
110
+ advanced = session.advance(values === undefined ? plan.idle : values[seat])
111
+ } catch (error) {
112
+ return { kind: "violated", violation: { _tag: "Defect", invariant: undefined, error }, frame: frame + 1 }
113
+ }
114
+ if (!advanced.ok) return { kind: "violated", violation: { _tag: "SessionFailed", seat, error: advanced.error }, frame: frame + 1 }
115
+ }
116
+ for (const { runtime } of peers) {
117
+ for (const invariant of plan.invariants) {
118
+ let message: unknown
119
+ try {
120
+ message = runtime.inspect(invariant.inspector)
121
+ } catch (error) {
122
+ return { kind: "violated", violation: { _tag: "Defect", invariant: invariant.name, error }, frame: frame + 1 }
123
+ }
124
+ if (typeof message === "string") return { kind: "violated", violation: { _tag: "InvariantViolated", invariant: invariant.name, message }, frame: frame + 1 }
125
+ }
126
+ }
127
+ hostClock.adjust(stepMS)
128
+ }
129
+ return { kind: "passed" }
130
+ }
@@ -1,4 +1,5 @@
1
- /** Value checks shared by sessions and the monitor. */
1
+ /** Value checks used by sessions. */
2
+ import type * as Debug from "@typeonce/ritmo/Debug"
2
3
 
3
4
  /**
4
5
  * The path of the first NaN or infinite number inside a value (`""` for the
@@ -15,3 +16,21 @@ export const nonFinitePath = (value: unknown, depth = 6, seen: Set<object> = new
15
16
  }
16
17
  return undefined
17
18
  }
19
+
20
+ /** The declared ranges (`meta` with `range`) of one descriptor's fields. */
21
+ export type FieldRanges = ReadonlyArray<readonly [field: string, min: number, max: number]>
22
+
23
+ const rangesBy = (entries: ReadonlyArray<{ readonly name: string; readonly meta: Debug.ComponentDescription["meta"] }>): ReadonlyMap<string, FieldRanges> => {
24
+ const ranges = new Map<string, FieldRanges>()
25
+ for (const { name, meta } of entries) {
26
+ const fields = Object.entries(meta).flatMap(([field, entry]) => entry.range === undefined ? [] : [[field, entry.range[0], entry.range[1]] as const])
27
+ if (fields.length > 0) ranges.set(name, fields)
28
+ }
29
+ return ranges
30
+ }
31
+
32
+ /** Every declared field range, by component and by resource name; descriptors without one are left out. */
33
+ export const rangesOf = (description: Debug.Description): {
34
+ readonly component: ReadonlyMap<string, FieldRanges>
35
+ readonly resource: ReadonlyMap<string, FieldRanges>
36
+ } => ({ component: rangesBy(description.components), resource: rangesBy(description.resources) })
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The page side of `PlaywrightEngine`: loaded in a browser by the Vite dev
3
+ * server it starts, it imports the game's entry and runs `Verify.trace` and
4
+ * `Verify.snapshotAt` there with the entry's `replayTarget`. What it returns
5
+ * crosses to Node as JSON, so it returns plain results and never throws a
6
+ * value Node cannot read.
7
+ */
8
+ import * as Result from "@typeonce/ritmo/Result"
9
+ import type * as Snapshot from "@typeonce/ritmo/Snapshot"
10
+
11
+ import type * as Replay from "../Replay.ts"
12
+ import * as Verify from "../Verify.ts"
13
+
14
+ /** What the page exposes to `PlaywrightEngine`. */
15
+ export interface Runner {
16
+ readonly trace: (file: Replay.ReplayFile) => Result.Result<Verify.Hashes, string>
17
+ readonly snapshotAt: (file: Replay.ReplayFile, tick: number) => Result.Result<Snapshot.WorldSnapshot, string>
18
+ }
19
+
20
+ const describe = (error: unknown): string => error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : JSON.stringify(error)
21
+
22
+ /** Imports the entry at `url` (a dev server path) and checks it exports `replayTarget`. */
23
+ export const start = async (url: string): Promise<Result.Result<Runner, string>> => {
24
+ let loaded: unknown
25
+ try {
26
+ loaded = await import(/* @vite-ignore */ url)
27
+ } catch (error) {
28
+ return Result.failure(`the entry did not load in the browser: ${describe(error)}`)
29
+ }
30
+ const make: unknown = typeof loaded === "object" && loaded !== null ? Reflect.get(loaded, "replayTarget") : undefined
31
+ if (typeof make !== "function") return Result.failure("the entry must export replayTarget: (playback) => { runtime, schedules, hostClock } (see the Verify module)")
32
+ // The CLI checked the same entry in Node, where its type is checked too.
33
+ const target = make as (playback: Replay.Playback) => Replay.Target<any, any>
34
+ const guard = <A>(run: () => Result.Result<A, unknown>): Result.Result<A, string> => {
35
+ try {
36
+ const result = run()
37
+ return result.ok ? result : Result.failure(`the replay did not open: ${JSON.stringify(result.error)}`)
38
+ } catch (error) {
39
+ return Result.failure(`the game threw: ${describe(error)}`)
40
+ }
41
+ }
42
+ return Result.success({
43
+ trace: (file) => guard(() => Verify.trace(target, file)),
44
+ snapshotAt: (file, tick) => guard(() => Verify.snapshotAt(target, file, tick))
45
+ })
46
+ }
@@ -3,4 +3,4 @@
3
3
  * `package.json` by `scripts/sync-version.ts` (run by \`pnpm version-packages\`)
4
4
  * and checked by a test.
5
5
  */
6
- export const libraryVersion = "0.14.0"
6
+ export const libraryVersion = "0.15.0"
package/dist/Monitor.d.ts DELETED
@@ -1,101 +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
- import { Collector, recentSchedule, recentSystem } from "./internal/monitor.ts";
37
- /**
38
- * The numbers behind the panel, without DOM: pass `collector.observe` to
39
- * `debug.observe`, call `sample(now)` periodically, read `history`, `alerts`,
40
- * spawn kinds, and the selected entity's changes. Use it for a custom UI or in
41
- * tests.
42
- */
43
- export { Collector, recentSchedule, recentSystem };
44
- export type { Alert, CollectorOptions, EntityLine, Sample, ScheduleWindow, SpawnKind, SystemWindow } from "./internal/monitor.ts";
45
- /** What the monitor needs from a runtime: its debug handle. */
46
- export interface Target<S extends Schema.Any, Root> {
47
- readonly debug: Debug.Handle<S, Root>;
48
- }
49
- /** What `attach` shows, where, and how the panel is opened. */
50
- export interface Options<S extends Schema.Any, Root> {
51
- /**
52
- * The schedules the game ticks, by name. They name the schedules in the
53
- * panel and make up the system map. Name the schedule objects actually
54
- * passed to `tick`: nested schedules are flattened into them.
55
- */
56
- readonly schedules: Readonly<Record<string, ExecutableScheduleDefinition<S, any, Root, any, any, AnyScheduleOrder>>>;
57
- /**
58
- * The page the panel lives in, passed explicitly (`window`): its
59
- * `document`, timers, animation frames, keyboard events, and
60
- * `performance` clock. The monitor reads no globals.
61
- */
62
- readonly host: Window;
63
- /** Where the panel is added. Defaults to `host.document.body`. */
64
- readonly mount?: HTMLElement;
65
- /** `KeyboardEvent.code` that toggles the panel. Defaults to `Backslash`. */
66
- readonly key?: string;
67
- /** Opens the panel right away. */
68
- readonly open?: boolean;
69
- /** The entity under a pointer event, for "Pick on screen". */
70
- readonly pick?: (event: PointerEvent) => number | undefined;
71
- /** An entity's position in client (viewport) pixels, to mark the selected entity. */
72
- readonly locate?: (entity: number) => {
73
- readonly x: number;
74
- readonly y: number;
75
- } | undefined;
76
- /** Milliseconds between panel refreshes. Defaults to 250. */
77
- readonly refreshMs?: number;
78
- /**
79
- * A replay recorder (`Replay.recorder`): adds a "Save replay" button that
80
- * saves the last seconds of play with the reason "Save replay button".
81
- */
82
- readonly replay?: {
83
- readonly save: (reason: string) => unknown;
84
- };
85
- }
86
- /** An attached monitor panel, from `attach`. */
87
- export interface Monitor {
88
- readonly open: () => void;
89
- readonly close: () => void;
90
- readonly toggle: () => void;
91
- /** Selects an entity in the Entity tab (`undefined` clears it). */
92
- readonly select: (entity: number | undefined) => void;
93
- /** Removes the panel and stops observing. */
94
- readonly detach: () => void;
95
- }
96
- /**
97
- * Adds the monitor to the page. The panel starts closed unless `open` is set;
98
- * toggle it with the key (`Backslash` by default) or the corner button.
99
- */
100
- export declare const attach: <S extends Schema.Any, Root>(runtime: Target<S, Root>, options: Options<S, Root>) => Monitor;
101
- //# sourceMappingURL=Monitor.d.ts.map