devrock-gametests 0.0.0-stage → 0.1.1

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/dist/report.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Reads GameTest results out of the BDS console. Mojang doesn't document these lines. These
3
+ * formats come from BDS 1.26.43:
4
+ *
5
+ * Running 16 tests with tag 'my_tag'...
6
+ * onTestStructureLoaded: my_class:my_test
7
+ * onTestPassed: my_class:my_test
8
+ * onTestFailed: my_class:my_test - GameTestError: expected ...
9
+ * No tests found for tag 'my_tag'
10
+ *
11
+ * The engine prints the verdicts as whole lines with no bracket, and the other two as INFO and ERROR lines with no
12
+ * category. A script's console message starts with a category, but BDS prints each line after a line break in it
13
+ * with no bracket. The runner's console patch starts each of those lines with CONTINUATION, so a script still can't
14
+ * print one of these.
15
+ *
16
+ * If a future version renames them, the run reports "no results" instead of passing.
17
+ */
18
+ import { TEST_TAG } from './shared.js';
19
+ /** One half of a test id: any characters but an ASCII space, a control character or a colon, as the engine prints it. */
20
+ const ID_PART = String.raw `[^\x00-\x20\x7f:]+`;
21
+ /** A test id as the engine prints it, `class:name`. */
22
+ export const TEST_ID = `${ID_PART}:${ID_PART}`;
23
+ /** The leading bracket of a line BDS prints, up to its level. */
24
+ const STAMP = String.raw `^\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d:\d+`;
25
+ const EXPECTED_RE = new RegExp(String.raw `${STAMP} INFO\] Running (\d+) tests? with tag '[^']*'\.\.\.$`);
26
+ const LOADED_RE = new RegExp(`^onTestStructureLoaded: (${TEST_ID})$`);
27
+ const PASSED_RE = new RegExp(`^onTestPassed: (${TEST_ID})$`);
28
+ const FAILED_RE = new RegExp(`^onTestFailed: (${TEST_ID}) - (.*)$`);
29
+ /** The tag a named run gives the tests it names, and runs with `runset`. */
30
+ export const NAMED_TAG = `${TEST_TAG}_named`;
31
+ const NO_TESTS_RE = new RegExp(String.raw `${STAMP} ERROR\] No tests found for tag '(?:${TEST_TAG}|${NAMED_TAG})'$`);
32
+ /** The engine's second line when `runset` finds no tests for its tag. */
33
+ const NO_TESTS_FAILED = "Failed to execute 'gametest' as [Null]";
34
+ /** The line GameTest prints as each batch starts. The batch name before the colon can be empty. */
35
+ export const BATCH_RE = /^Running test batch '(.*):\d+' \(\d+ tests\)\.\.\.$/;
36
+ /**
37
+ * What the runner's console patch puts at the start of each line after a line break in a script's console message.
38
+ * Such a line belongs to the message before it, which its level was read from.
39
+ */
40
+ export const CONTINUATION = ' | ';
41
+ /**
42
+ * A content log line looks like `[2026-09-08 00:58:10:916 ERROR] [Scripting] Error: boom ...`.
43
+ * Uncaught script errors and pack loading problems all arrive in this shape, under different
44
+ * categories. Loading problems include bad block, item or entity JSON, unknown components and
45
+ * broken references. A few engine notices have no category. The level is read only from the leading
46
+ * bracket, in any case, so a level word inside a message means nothing.
47
+ */
48
+ const CONTENT_LOG_RE = /^\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d:\d+ ([a-z]+)\](?: (?:\[([^\]]+)\] )?)?(.*?)\s*$/i;
49
+ /** Every line break node:readline splits the live console on, so a transcript parses into the lines BDS printed. */
50
+ const LINE_BREAK_RE = /\r\n|[\n\r\u2028\u2029]/;
51
+ /** The only levels that pass. The logs of every run on BDS 1.26.66.1, clean or not, hold only INFO, WARN and ERROR. */
52
+ const HARMLESS_LEVELS = new Set(['INFO']);
53
+ /** One SGR parameter that only sets or resets a colour. */
54
+ const COLOUR = String.raw `(?:0|3[0-79]|4[0-79]|9[0-7]|10[0-7]|[34]8;5;\d{1,3}|[34]8;2;\d{1,3};\d{1,3};\d{1,3})`;
55
+ /**
56
+ * Colour codes, the only terminal sequences removed. Any other sequence, such as one that moves the cursor,
57
+ * erases a line or hides text, keeps its escape and fails the line as a control character.
58
+ */
59
+ const COLOUR_RE = new RegExp(String.raw `\x1b\[(?:${COLOUR}(?:;${COLOUR})*)?m`, 'g');
60
+ /** Invisible format characters, which could split a level. */
61
+ const FORMAT_RE = /\p{Cf}/gu;
62
+ /**
63
+ * Control characters other than tab, left after colour codes are removed. A terminal acts on them, and
64
+ * node:readline doesn't split on all of them, so a line holding one can't be read as printed.
65
+ */
66
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the point.
67
+ const CONTROL_RE = /[\x00-\x08\x0a-\x1f\x7f-\x9f]/g;
68
+ /** Lines with no leading bracket that pass, byte for byte as BDS 1.26.66.1 prints them in clean runs. */
69
+ const PLAIN_LINES = new Set([
70
+ // BDS, around its startup banner and while it stops.
71
+ '',
72
+ // BDS, the top and bottom border of the startup banner.
73
+ '#####################################################',
74
+ // BDS, the padding lines of the startup banner.
75
+ '# #',
76
+ // BDS, at startup, because the server has no log file configured.
77
+ 'NO LOG FILE! - setting up server logging...',
78
+ // BDS, the last line of a clean stop.
79
+ 'Quit correctly',
80
+ // BDS, the startup banner when the world exists.
81
+ '# LOADING VANILLA WORLD #',
82
+ // BDS, the startup banner when setup creates the world.
83
+ '# CREATING VANILLA WORLD #',
84
+ // BDS, its reply to the runner's `tickingarea add`.
85
+ '1/10 ticking areas in use.',
86
+ ]);
87
+ /**
88
+ * The answer, byte for byte as BDS 1.26.66.1 prints it, to the chunk probe while the ticking area's chunks load. It
89
+ * passes only while the probe runs, so the same line at any other time still fails the run.
90
+ */
91
+ const PROBE_ANSWER_RE = /^\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d:\d+ ERROR\] Cannot access blocks outside of the world$/;
92
+ /** Lines with no leading bracket that pass because only their test id, batch name or test count varies. */
93
+ const GAMETEST_LINES = [
94
+ // GameTest, when a test's structure has loaded.
95
+ new RegExp(`^onTestStructureLoaded: ${TEST_ID}$`),
96
+ // GameTest, when a test passes. A failure isn't here, so it fails the content log as well as the test.
97
+ new RegExp(`^onTestPassed: ${TEST_ID}$`),
98
+ BATCH_RE,
99
+ ];
100
+ function tieOf(entry, ourContent) {
101
+ const name = ourContent.find((ours) => entry.includes(ours));
102
+ return name ? { kind: 'ours', name } : { kind: 'unattributed' };
103
+ }
104
+ export function tieLabel(tie) {
105
+ return tie.kind === 'ours' ? `ours: ${tie.name}` : 'unattributed, assumed ours';
106
+ }
107
+ /**
108
+ * The entry a line fails the run with, or null when it passes. Only a line whose leading bracket holds a
109
+ * harmless level passes, or a line with no bracket that is exactly a plain line, a runner echo or a
110
+ * GameTest line.
111
+ */
112
+ function failingEntry(raw, echoes) {
113
+ const line = raw.replace(COLOUR_RE, '').replace(FORMAT_RE, '').normalize('NFKC');
114
+ const shown = line.replace(CONTROL_RE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
115
+ if (shown !== line)
116
+ return shown.trim();
117
+ const match = CONTENT_LOG_RE.exec(line.trimStart());
118
+ if (match) {
119
+ const [, level, category, message] = match;
120
+ if (HARMLESS_LEVELS.has(level.toUpperCase()))
121
+ return null;
122
+ return category ? `[${category}] ${message}` : message;
123
+ }
124
+ const skipped = PLAIN_LINES.has(raw) || echoes.has(raw) || GAMETEST_LINES.some((shape) => shape.test(raw));
125
+ return skipped ? null : line;
126
+ }
127
+ /**
128
+ * `runOutput` is everything printed after the runset command. `fullOutput` also has startup, where
129
+ * pack load errors appear. `sent` is every command the runner sent, whose echoes pass. Every line that
130
+ * isn't at a harmless level or a known line with no bracket fails the run, except a line that continues a script's
131
+ * message. `probe` is where in `fullOutput` the chunk probe started and ended, each on a line start. Its answer passes
132
+ * only there.
133
+ */
134
+ export function parseReport(runOutput, fullOutput, ourContent, sent, probe = { start: 0, end: 0 }) {
135
+ const report = {
136
+ expected: null,
137
+ noTestsForTag: false,
138
+ loaded: [],
139
+ passed: [],
140
+ failed: new Map(),
141
+ finished: [],
142
+ batches: [],
143
+ contentErrors: [],
144
+ };
145
+ for (const line of runOutput.split(LINE_BREAK_RE)) {
146
+ const expected = EXPECTED_RE.exec(line);
147
+ const loaded = LOADED_RE.exec(line);
148
+ const passed = PASSED_RE.exec(line);
149
+ const failed = FAILED_RE.exec(line);
150
+ if (expected)
151
+ report.expected = Number(expected[1]);
152
+ if (loaded)
153
+ report.loaded.push(loaded[1]);
154
+ if (passed)
155
+ report.passed.push(passed[1]);
156
+ if (failed)
157
+ report.failed.set(failed[1], failed[2].trim());
158
+ const verdict = passed ?? failed;
159
+ if (verdict)
160
+ report.finished.push(verdict[1]);
161
+ const batch = BATCH_RE.exec(line);
162
+ if (batch)
163
+ report.batches.push(batch[1]);
164
+ if (NO_TESTS_RE.test(line))
165
+ report.noTestsForTag = true;
166
+ }
167
+ const echoes = new Set(sent.map((command) => `> ${command}`));
168
+ const probing = fullOutput.slice(probe.start, probe.end).split(LINE_BREAK_RE);
169
+ const lines = [
170
+ ...fullOutput.slice(0, probe.start).split(LINE_BREAK_RE),
171
+ ...probing.filter((line) => !PROBE_ANSWER_RE.test(line)),
172
+ ...fullOutput.slice(probe.end).split(LINE_BREAK_RE),
173
+ ];
174
+ const errors = new Map();
175
+ for (const line of lines) {
176
+ if (line.startsWith(CONTINUATION))
177
+ continue;
178
+ if (report.noTestsForTag && (NO_TESTS_RE.test(line) || line === NO_TESTS_FAILED))
179
+ continue;
180
+ const entry = failingEntry(line, echoes);
181
+ if (entry !== null)
182
+ errors.set(entry, { entry, tie: tieOf(entry, ourContent) });
183
+ }
184
+ report.contentErrors = [...errors.values()];
185
+ return report;
186
+ }
187
+ /** BDS prints this as its last line when it stops on its own, after everything it prints while shutting down. */
188
+ const QUIT_RE = /^Quit correctly$/m;
189
+ /** True if the transcript runs through a clean stop, so it holds every line the server printed. */
190
+ export function stoppedCleanly(transcript) {
191
+ return QUIT_RE.test(transcript);
192
+ }
193
+ const count = (ids, id) => ids.filter((other) => other === id).length;
194
+ /** True while a test has an attempt or rotation loaded that has no verdict yet. */
195
+ const isOpen = (report, id) => count(report.loaded, id) > count(report.finished, id);
196
+ const NO_REQUIRED = new Map();
197
+ /**
198
+ * True once each of `given` is done, no test has an attempt or rotation open, and there are as many verdicts as
199
+ * the engine announced tests, or once the engine said there was nothing to run. The engine announces each rotation
200
+ * as a test, and loads a test's next attempt just after the last one's verdict, so a caller should see this hold for
201
+ * a moment before it stops the server.
202
+ */
203
+ export function isComplete(report, given, required = NO_REQUIRED) {
204
+ if (report.noTestsForTag)
205
+ return true;
206
+ if (report.expected === null || report.finished.length < report.expected)
207
+ return false;
208
+ return isFinished(report, given, required);
209
+ }
210
+ /**
211
+ * True once each of `ids` failed an attempt or passed as many as it needs, and no test has an attempt or rotation
212
+ * open. A failure is final, because any failed attempt fails the test.
213
+ */
214
+ export function isFinished(report, ids, required = NO_REQUIRED) {
215
+ const done = (id) => report.failed.has(id) || count(report.passed, id) >= (required.get(id) ?? 1);
216
+ if (!ids.every(done))
217
+ return false;
218
+ return !report.loaded.some((id) => isOpen(report, id));
219
+ }
220
+ /**
221
+ * One verdict for each of `ids`, from all its attempts and rotations. A test passes only if it passed as many
222
+ * attempts as it needs, no attempt or rotation failed, and none was left open.
223
+ */
224
+ export function verdicts(report, ids, required = NO_REQUIRED) {
225
+ return ids.map((id) => {
226
+ const failure = report.failed.get(id);
227
+ if (failure !== undefined)
228
+ return { id, passed: false, error: failure };
229
+ if (isOpen(report, id)) {
230
+ return { id, passed: false, error: 'Started but never finished (timed out, or the server stopped).' };
231
+ }
232
+ const passes = count(report.passed, id);
233
+ const needed = required.get(id) ?? 1;
234
+ if (passes >= needed)
235
+ return { id, passed: true };
236
+ if (passes > 0) {
237
+ return { id, passed: false, error: `Passed ${passes} of the ${needed} passes it needs before the run ended.` };
238
+ }
239
+ return { id, passed: false, error: 'Never started.' };
240
+ });
241
+ }
242
+ /** The tests that reported a verdict or loaded, in the order they first did. */
243
+ export const testsSeen = (report) => [...new Set([...report.loaded, ...report.finished])];
@@ -0,0 +1,45 @@
1
+ import type { TimedLine } from './parallel.js';
2
+ export interface ServerOptions {
3
+ readonly image: string;
4
+ /** The folder with the server.properties, config and worlds the container mounts. */
5
+ readonly serverDir: string;
6
+ readonly logFile: string;
7
+ /** Prints every line the server prints. */
8
+ readonly echo?: boolean;
9
+ /** Printed before each echoed line, to tell servers apart. */
10
+ readonly label?: string;
11
+ }
12
+ /**
13
+ * One Bedrock Dedicated Server in its own Podman container. BDS reads console commands from stdin, one per line,
14
+ * and prints everything to stdout, including script console output and GameTest results.
15
+ */
16
+ export declare class BedrockServer {
17
+ private readonly child;
18
+ private readonly log;
19
+ private readonly listeners;
20
+ private readonly exited;
21
+ private readonly name;
22
+ private readonly echo;
23
+ private readonly label;
24
+ private hasExited;
25
+ private spawnError?;
26
+ /** Everything the server has printed so far, plus the commands sent to it. */
27
+ transcript: string;
28
+ readonly sent: string[];
29
+ /** Every line of the transcript with the time it arrived. */
30
+ readonly timeline: TimedLine[];
31
+ constructor({ image, serverDir, logFile, echo, label }: ServerOptions);
32
+ get running(): boolean;
33
+ private record;
34
+ send(command: string): void;
35
+ /** Resolves with the first line matching `pattern`. Rejects if the server exits or the timeout passes first. */
36
+ waitFor(pattern: RegExp, timeoutMs: number, what: string): Promise<string>;
37
+ /**
38
+ * Sends `command` and resolves with the first line after it that matches `pattern`. Rejects like `waitFor`, and
39
+ * at once if the server isn't running.
40
+ */
41
+ request(command: string, pattern: RegExp, timeoutMs: number, what: string): Promise<string>;
42
+ waitForReady(): Promise<string>;
43
+ /** Asks the server to save and stop, and removes its container if it hasn't exited within 30 seconds. */
44
+ stop(): Promise<void>;
45
+ }
package/dist/server.js ADDED
@@ -0,0 +1,161 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createWriteStream, mkdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { containerName, removeContainer, runArgs } from './podman.js';
6
+ /** The signals that end the runner, on which it removes its containers first. */
7
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK'];
8
+ /** The containers of the servers that haven't exited yet. */
9
+ const running = new Set();
10
+ /**
11
+ * Removes every running server's container when the runner exits or gets a signal. The container stops on its own
12
+ * once the podman client dies, but that takes a clean server stop. A run that ends any way Node sees removes it at
13
+ * once. SIGHUP is a closed terminal window, and SIGBREAK is Ctrl+Break on Windows. One set of handlers covers every
14
+ * server, so any number of them adds no listeners.
15
+ */
16
+ const removeAll = () => {
17
+ for (const name of running) {
18
+ if (!removeContainer(name)) {
19
+ console.error(`[devrock-gametests] Couldn't remove the container ${name}. Remove it with \`podman rm -f ${name}\`.`);
20
+ }
21
+ }
22
+ };
23
+ process.on('exit', removeAll);
24
+ for (const signal of SIGNALS) {
25
+ process.on(signal, () => {
26
+ removeAll();
27
+ process.exit(130);
28
+ });
29
+ }
30
+ /** `[2026-08-10 21:09:41:425 INFO] Server started.` */
31
+ const READY_RE = /\bServer started\./;
32
+ /**
33
+ * One Bedrock Dedicated Server in its own Podman container. BDS reads console commands from stdin, one per line,
34
+ * and prints everything to stdout, including script console output and GameTest results.
35
+ */
36
+ export class BedrockServer {
37
+ child;
38
+ log;
39
+ listeners = new Set();
40
+ exited;
41
+ name = containerName();
42
+ echo;
43
+ label;
44
+ hasExited = false;
45
+ spawnError;
46
+ /** Everything the server has printed so far, plus the commands sent to it. */
47
+ transcript = '';
48
+ sent = [];
49
+ /** Every line of the transcript with the time it arrived. */
50
+ timeline = [];
51
+ constructor({ image, serverDir, logFile, echo = false, label = '' }) {
52
+ this.echo = echo;
53
+ this.label = label;
54
+ mkdirSync(path.dirname(logFile), { recursive: true });
55
+ this.log = createWriteStream(logFile);
56
+ this.child = spawn('podman', runArgs(this.name, image, serverDir), { windowsHide: true });
57
+ createInterface({ input: this.child.stdout }).on('line', (line) => this.record(line));
58
+ // BDS prints everything, the content log too, on stdout, so stderr holds what Podman says itself, such as a
59
+ // warning about its setup. That isn't the content log, so it never fails a run, but the user should see it.
60
+ createInterface({ input: this.child.stderr }).on('line', (line) => {
61
+ this.log.write(`podman| ${line}\n`);
62
+ console.error(`[devrock-gametests] Podman${label ? ` (server ${label.trim()})` : ''}: ${line}`);
63
+ });
64
+ running.add(this.name);
65
+ // A write after the container is gone fails with EPIPE, which with no listener would crash the runner. `send`
66
+ // already refuses once the client has exited, and the close below ends the server.
67
+ this.child.stdin.on('error', () => { });
68
+ // `close` instead of `exit`, because `close` fires after the output streams flush their last lines.
69
+ this.exited = new Promise((resolve) => {
70
+ const done = () => {
71
+ this.hasExited = true;
72
+ // The client can end while its container lives on, for example when the attachment drops. Removing an
73
+ // already removed container does nothing, so this runs every time a client that started ends. A removal
74
+ // that fails keeps the container on the list, so the runner tries again, and says so, when it exits.
75
+ if (this.spawnError !== undefined || removeContainer(this.name))
76
+ running.delete(this.name);
77
+ this.log.end();
78
+ for (const listener of this.listeners)
79
+ listener('');
80
+ resolve();
81
+ };
82
+ this.child.once('close', done);
83
+ this.child.once('error', (error) => {
84
+ this.spawnError = error;
85
+ done();
86
+ });
87
+ });
88
+ }
89
+ get running() {
90
+ return !this.hasExited;
91
+ }
92
+ record(line) {
93
+ this.transcript += `${line}\n`;
94
+ this.timeline.push({ at: Date.now(), line });
95
+ this.log.write(`${line}\n`);
96
+ if (this.echo)
97
+ console.log(` ${this.label}| ${line}`);
98
+ for (const listener of this.listeners)
99
+ listener(line);
100
+ }
101
+ send(command) {
102
+ if (this.hasExited)
103
+ throw new Error(`Cannot send "${command}": the server is not running.`);
104
+ this.sent.push(command);
105
+ this.record(`> ${command}`);
106
+ this.child.stdin.write(`${command}\n`);
107
+ }
108
+ /** Resolves with the first line matching `pattern`. Rejects if the server exits or the timeout passes first. */
109
+ waitFor(pattern, timeoutMs, what) {
110
+ return new Promise((resolve, reject) => {
111
+ const finish = (settle) => {
112
+ clearTimeout(timer);
113
+ this.listeners.delete(onLine);
114
+ settle();
115
+ };
116
+ const onLine = (line) => {
117
+ if (this.hasExited) {
118
+ const reason = this.spawnError ? `could not start (${this.spawnError.message})` : 'exited';
119
+ finish(() => reject(new Error(`The server ${reason} while waiting for ${what}.`)));
120
+ }
121
+ else if (pattern.test(line)) {
122
+ finish(() => resolve(line));
123
+ }
124
+ };
125
+ const timer = setTimeout(() => finish(() => reject(new Error(`Timed out after ${timeoutMs / 1000}s waiting for ${what}.`))), timeoutMs);
126
+ this.listeners.add(onLine);
127
+ if (this.hasExited)
128
+ onLine('');
129
+ });
130
+ }
131
+ /**
132
+ * Sends `command` and resolves with the first line after it that matches `pattern`. Rejects like `waitFor`, and
133
+ * at once if the server isn't running.
134
+ */
135
+ async request(command, pattern, timeoutMs, what) {
136
+ const answer = this.waitFor(pattern, timeoutMs, what);
137
+ try {
138
+ this.send(command);
139
+ }
140
+ catch (error) {
141
+ answer.catch(() => { });
142
+ throw error;
143
+ }
144
+ return answer;
145
+ }
146
+ waitForReady() {
147
+ return this.waitFor(READY_RE, 180_000, 'the server to start');
148
+ }
149
+ /** Asks the server to save and stop, and removes its container if it hasn't exited within 30 seconds. */
150
+ async stop() {
151
+ if (this.hasExited)
152
+ return;
153
+ this.send('stop');
154
+ const timeout = new Promise((resolve) => setTimeout(() => resolve('timeout'), 30_000).unref());
155
+ if ((await Promise.race([this.exited, timeout])) === 'timeout') {
156
+ removeContainer(this.name);
157
+ this.child.kill();
158
+ await this.exited;
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The names and places the runner and the tests share, so the tag a test registers with, the structure the runner
3
+ * writes into the test pack, and the area the runner keeps loaded can't drift apart. It has no imports, so both the
4
+ * runner under Node and a test pack can load it.
5
+ */
6
+ /** Register every test with this tag. `devrock-gametests run` runs `/gametest runset <TEST_TAG>`. */
7
+ export declare const TEST_TAG = "devrock_gametests";
8
+ /**
9
+ * The room every test runs in, a stone floor with air above, which the runner writes into the test pack.
10
+ * Test coordinates are relative to the GameTest structure block, and (0, 1, 0) is the block above it, so put
11
+ * blocks and mobs at y=2 or higher to keep them clear of the floor.
12
+ */
13
+ export declare const PLOT_STRUCTURE = "devrock_gametests:plot";
14
+ export declare const PLOT_SIZE: {
15
+ readonly x: 7;
16
+ readonly y: 6;
17
+ readonly z: 7;
18
+ };
19
+ /**
20
+ * The runner keeps x and z from 0 to TEST_AREA_END loaded with a ticking area, 9x9 chunks, and lays out the test
21
+ * plots inside it. A world with no players only simulates inside ticking areas.
22
+ */
23
+ export declare const TEST_AREA_END = 143;
package/dist/shared.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The names and places the runner and the tests share, so the tag a test registers with, the structure the runner
3
+ * writes into the test pack, and the area the runner keeps loaded can't drift apart. It has no imports, so both the
4
+ * runner under Node and a test pack can load it.
5
+ */
6
+ /** Register every test with this tag. `devrock-gametests run` runs `/gametest runset <TEST_TAG>`. */
7
+ export const TEST_TAG = 'devrock_gametests';
8
+ /**
9
+ * The room every test runs in, a stone floor with air above, which the runner writes into the test pack.
10
+ * Test coordinates are relative to the GameTest structure block, and (0, 1, 0) is the block above it, so put
11
+ * blocks and mobs at y=2 or higher to keep them clear of the floor.
12
+ */
13
+ export const PLOT_STRUCTURE = 'devrock_gametests:plot';
14
+ export const PLOT_SIZE = { x: 7, y: 6, z: 7 };
15
+ /**
16
+ * The runner keeps x and z from 0 to TEST_AREA_END loaded with a ticking area, 9x9 chunks, and lays out the test
17
+ * plots inside it. A world with no players only simulates inside ticking areas.
18
+ */
19
+ export const TEST_AREA_END = 143;
@@ -0,0 +1,10 @@
1
+ import type { BedrockServer } from './server.js';
2
+ /** Readies a started server's world for tests: no natural mob spawns, and the test area keeps ticking. */
3
+ export declare function prepareWorld(server: BedrockServer, templateLevelDat: string): Promise<void>;
4
+ /**
5
+ * `tickingarea add` answers before the area's chunks load, and commands like `summon` fail in unloaded chunks.
6
+ * Chunks load as whole columns, so comparing the area's bottom layer with itself succeeds once all of them are in.
7
+ * Until then the probe answers `Cannot access blocks outside of the world` as an error, which the content-log check
8
+ * passes only up to where this returns.
9
+ */
10
+ export declare function waitForTickingArea(server: BedrockServer): Promise<void>;
package/dist/world.js ADDED
@@ -0,0 +1,30 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { TEST_AREA_END } from './shared.js';
3
+ /** A world with no players only simulates inside ticking areas. This one covers the test area. */
4
+ const TICKING_AREA = `0 -64 0 ${TEST_AREA_END} 320 ${TEST_AREA_END}`;
5
+ /** Readies a started server's world for tests: no natural mob spawns, and the test area keeps ticking. */
6
+ export async function prepareWorld(server, templateLevelDat) {
7
+ if (!/Experiment\(s\) active:.*\bgtst\b/.test(server.transcript)) {
8
+ throw new Error(`The server started without Beta APIs. Delete ${templateLevelDat} and run again.`);
9
+ }
10
+ server.send('gamerule domobspawning false');
11
+ await server.request(`tickingarea add ${TICKING_AREA} gametest true`, /Added ticking area/, 30_000, 'the ticking area');
12
+ }
13
+ /**
14
+ * `tickingarea add` answers before the area's chunks load, and commands like `summon` fail in unloaded chunks.
15
+ * Chunks load as whole columns, so comparing the area's bottom layer with itself succeeds once all of them are in.
16
+ * Until then the probe answers `Cannot access blocks outside of the world` as an error, which the content-log check
17
+ * passes only up to where this returns.
18
+ */
19
+ export async function waitForTickingArea(server) {
20
+ const [x1, y1, z1, x2, , z2] = TICKING_AREA.split(' ');
21
+ const probe = `testforblocks ${x1} ${y1} ${z1} ${x2} ${y1} ${z2} ${x1} ${y1} ${z1}`;
22
+ const deadline = Date.now() + 30_000;
23
+ while (Date.now() < deadline) {
24
+ const answer = await server.request(probe, /blocks compared|Cannot access blocks/, 10_000, 'the ticking area to load');
25
+ if (/blocks compared/.test(answer))
26
+ return;
27
+ await sleep(250);
28
+ }
29
+ throw new Error('Timed out after 30s waiting for the ticking area to load.');
30
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
- {
2
- "name": "devrock-gametests",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "devrock-gametests",
3
+ "version": "0.1.1",
4
+ "description": "Runs Minecraft Bedrock GameTests on a Bedrock Dedicated Server in a Podman container with no network.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "devrock-gametests": "./dist/cli.js"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./game": {
16
+ "types": "./dist/game.d.ts",
17
+ "default": "./dist/game.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "container"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22.15"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.build.json",
29
+ "prepare": "npm run build",
30
+ "test": "node --import tsx --test \"test/**/*.test.ts\"",
31
+ "typecheck": "tsc -p .",
32
+ "lint": "biome check src test",
33
+ "test:live": "npm run build && tsx test/live.ts"
34
+ },
35
+ "dependencies": {
36
+ "esbuild": "^0.28.2",
37
+ "prismarine-nbt": "^2.8.0"
38
+ },
39
+ "devDependencies": {
40
+ "@biomejs/biome": "^2.5.10",
41
+ "@minecraft/server": "^2.9.0",
42
+ "@minecraft/server-gametest": "1.0.0-beta.1.26.66-stable",
43
+ "@types/node": "^26.2.0",
44
+ "tsx": "^4.23.12",
45
+ "typescript": "^7.0.2"
46
+ }
47
+ }