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/LICENSE +21 -0
- package/README.md +174 -3
- package/container/Containerfile +12 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +115 -0
- package/dist/commands.d.ts +17 -0
- package/dist/commands.js +304 -0
- package/dist/deploy.d.ts +53 -0
- package/dist/deploy.js +336 -0
- package/dist/game.d.ts +47 -0
- package/dist/game.js +110 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/list-worker.d.ts +1 -0
- package/dist/list-worker.js +6 -0
- package/dist/nbt.d.ts +32 -0
- package/dist/nbt.js +112 -0
- package/dist/outcome.d.ts +31 -0
- package/dist/outcome.js +21 -0
- package/dist/parallel.d.ts +96 -0
- package/dist/parallel.js +190 -0
- package/dist/podman.d.ts +40 -0
- package/dist/podman.js +201 -0
- package/dist/preflight.d.ts +30 -0
- package/dist/preflight.js +71 -0
- package/dist/project.d.ts +43 -0
- package/dist/project.js +204 -0
- package/dist/registrations.d.ts +38 -0
- package/dist/registrations.js +194 -0
- package/dist/report.d.ts +87 -0
- package/dist/report.js +243 -0
- package/dist/server.d.ts +45 -0
- package/dist/server.js +161 -0
- package/dist/shared.d.ts +23 -0
- package/dist/shared.js +19 -0
- package/dist/world.d.ts +10 -0
- package/dist/world.js +30 -0
- package/package.json +47 -6
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { copyFile, cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { build } from 'esbuild';
|
|
6
|
+
import { enableBetaApis, plotStructure } from './nbt.js';
|
|
7
|
+
import { isFile, readPackHeader, readScriptEntry } from './project.js';
|
|
8
|
+
import { GAME_MODULES } from './registrations.js';
|
|
9
|
+
import { CONTINUATION, NAMED_TAG, TEST_ID } from './report.js';
|
|
10
|
+
import { BedrockServer } from './server.js';
|
|
11
|
+
import { PLOT_SIZE, PLOT_STRUCTURE, TEST_TAG } from './shared.js';
|
|
12
|
+
export const LEVEL_NAME = 'gametest';
|
|
13
|
+
/** Off the default 19132. The container has no network, so the port only matters inside it. */
|
|
14
|
+
const PORT = 19140;
|
|
15
|
+
const SERVER_PROPERTIES = {
|
|
16
|
+
'server-name': 'devrock-gametests',
|
|
17
|
+
'level-name': LEVEL_NAME,
|
|
18
|
+
'server-port': PORT,
|
|
19
|
+
'server-portv6': PORT + 1,
|
|
20
|
+
// Local only, and no player may join. server-ip only takes effect with the nethernet transport.
|
|
21
|
+
transport: 'nethernet',
|
|
22
|
+
'server-ip': '127.0.0.1',
|
|
23
|
+
'enable-lan-visibility': false,
|
|
24
|
+
'allow-player-joining': false,
|
|
25
|
+
// With no network, online mode waits a minute for Minecraft services and then stops the server. BDS accepts
|
|
26
|
+
// online-mode=false only with the allow list off.
|
|
27
|
+
'allow-list': false,
|
|
28
|
+
'online-mode': false,
|
|
29
|
+
'max-players': 1,
|
|
30
|
+
gamemode: 'creative',
|
|
31
|
+
// Peaceful removes monsters as soon as they spawn.
|
|
32
|
+
difficulty: 'easy',
|
|
33
|
+
// /gametest is a cheat command.
|
|
34
|
+
'allow-cheats': true,
|
|
35
|
+
'player-idle-timeout': 0,
|
|
36
|
+
// The runner reads pack loading errors from the console.
|
|
37
|
+
'content-log-console-output-enabled': true,
|
|
38
|
+
'content-log-file-enabled': true,
|
|
39
|
+
// A hung script should fail its test, not shut the server down before it can report.
|
|
40
|
+
'script-watchdog-enable-shutdown': false,
|
|
41
|
+
};
|
|
42
|
+
/** The modules the server lets packs use, which are all the ones stock BDS allows. */
|
|
43
|
+
const ALLOWED_MODULES = GAME_MODULES;
|
|
44
|
+
export function serverProperties() {
|
|
45
|
+
const lines = Object.entries(SERVER_PROPERTIES).map(([key, value]) => `${key}=${value}`);
|
|
46
|
+
return ['# Written by devrock-gametests for each run.', ...lines, ''].join('\n');
|
|
47
|
+
}
|
|
48
|
+
/** Where the template world's level.dat lives. It exists only once it is complete. */
|
|
49
|
+
export const templateLevelDat = (project) => path.join(project.workDir, 'template', project.serverVersion, 'level.dat');
|
|
50
|
+
/** Holds one run folder per container. */
|
|
51
|
+
export const runRoot = (project) => path.join(project.workDir, 'run');
|
|
52
|
+
/** The run folder of container `index`, which counts from 1. */
|
|
53
|
+
export const runDir = (project, index) => path.join(runRoot(project), String(index));
|
|
54
|
+
export const timestamp = () => new Date().toISOString().replace(/[:.]/g, '-');
|
|
55
|
+
export const logFile = (project, kind, stamp = timestamp()) => path.join(project.workDir, 'logs', `${kind}-${stamp}.log`);
|
|
56
|
+
/** Empties `dir` and writes the server.properties and config a server container mounts, with an empty world. */
|
|
57
|
+
async function writeServerDir(dir) {
|
|
58
|
+
await rm(dir, { recursive: true, force: true });
|
|
59
|
+
const configDir = path.join(dir, 'config', 'default');
|
|
60
|
+
const worldDir = path.join(dir, 'worlds', LEVEL_NAME);
|
|
61
|
+
await mkdir(configDir, { recursive: true });
|
|
62
|
+
await mkdir(worldDir, { recursive: true });
|
|
63
|
+
await writeFile(path.join(dir, 'server.properties'), serverProperties());
|
|
64
|
+
await writeFile(path.join(configDir, 'permissions.json'), `${JSON.stringify({ allowed_modules: ALLOWED_MODULES }, null, 2)}\n`);
|
|
65
|
+
return worldDir;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Makes the version's template world unless it exists, and returns its level.dat. Experiments only switch on in a
|
|
69
|
+
* world that already exists, so a first boot generates the world, and level.dat gets Beta APIs after it stops.
|
|
70
|
+
*/
|
|
71
|
+
export async function ensureTemplateWorld(project, image, log) {
|
|
72
|
+
const levelDat = templateLevelDat(project);
|
|
73
|
+
if (existsSync(levelDat))
|
|
74
|
+
return levelDat;
|
|
75
|
+
log('Generating the template world. This happens once per server version.');
|
|
76
|
+
const scratch = path.join(project.workDir, 'template', `${project.serverVersion}.partial`);
|
|
77
|
+
const worldDir = await writeServerDir(scratch);
|
|
78
|
+
const server = new BedrockServer({ image, serverDir: scratch, logFile: logFile(project, 'template') });
|
|
79
|
+
try {
|
|
80
|
+
await server.waitForReady();
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
await server.stop();
|
|
84
|
+
}
|
|
85
|
+
await enableBetaApis(path.join(worldDir, 'level.dat'));
|
|
86
|
+
await mkdir(path.dirname(levelDat), { recursive: true });
|
|
87
|
+
await copyFile(path.join(worldDir, 'level.dat'), `${levelDat}.partial`);
|
|
88
|
+
await rename(`${levelDat}.partial`, levelDat);
|
|
89
|
+
await rm(scratch, { recursive: true, force: true });
|
|
90
|
+
log('Enabled Beta APIs in the template world');
|
|
91
|
+
return levelDat;
|
|
92
|
+
}
|
|
93
|
+
/** Runs the project's build command, which builds the add-on into its packs. */
|
|
94
|
+
export function buildAddOn(project) {
|
|
95
|
+
const [command, ...args] = project.build;
|
|
96
|
+
const result = spawnSync(command, args, { cwd: project.root, stdio: 'inherit', windowsHide: true });
|
|
97
|
+
if (result.error || result.status !== 0) {
|
|
98
|
+
const reason = result.error?.message ?? `exit code ${result.status}`;
|
|
99
|
+
throw new Error(`The build command ${JSON.stringify(project.build)} failed (${reason}).`);
|
|
100
|
+
}
|
|
101
|
+
const entry = readScriptEntry(project.behaviorPack, project.root);
|
|
102
|
+
if (entry !== undefined && !isFile(path.join(project.behaviorPack, entry))) {
|
|
103
|
+
const manifest = path.relative(project.root, path.join(project.behaviorPack, 'manifest.json'));
|
|
104
|
+
throw new Error(`${manifest} names the script entry ${entry}, which the build didn't make.`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Rebuilds the run folder `dir` from nothing: server.properties, config, and a world with the template's level.dat,
|
|
109
|
+
* the built add-on packs and the test pack, whose test runtime follows `share`. Returns `dir`.
|
|
110
|
+
*/
|
|
111
|
+
export async function buildRunFolder(project, levelDat, dir, share) {
|
|
112
|
+
const worldDir = await writeServerDir(dir);
|
|
113
|
+
await copyFile(levelDat, path.join(worldDir, 'level.dat'));
|
|
114
|
+
const testPack = path.join(worldDir, 'behavior_packs', project.testPackFolder);
|
|
115
|
+
await buildTestPack(project, testPack, share);
|
|
116
|
+
const behaviorPack = path.join(worldDir, 'behavior_packs', path.basename(project.behaviorPack));
|
|
117
|
+
const resourcePack = path.join(worldDir, 'resource_packs', path.basename(project.resourcePack));
|
|
118
|
+
// A pack folder may be a link, such as a Windows junction to a build output. The world gets its contents.
|
|
119
|
+
await cp(project.behaviorPack, behaviorPack, { recursive: true, dereference: true });
|
|
120
|
+
await cp(project.resourcePack, resourcePack, { recursive: true, dereference: true });
|
|
121
|
+
await patchConsole(behaviorPack);
|
|
122
|
+
await writePackList(path.join(worldDir, 'world_behavior_packs.json'), [behaviorPack, testPack]);
|
|
123
|
+
await writePackList(path.join(worldDir, 'world_resource_packs.json'), [resourcePack]);
|
|
124
|
+
return dir;
|
|
125
|
+
}
|
|
126
|
+
/** The tag a test outside a container's share runs under instead of TEST_TAG, so that container's runset skips it. */
|
|
127
|
+
export const ELSEWHERE_TAG = `${TEST_TAG}_elsewhere`;
|
|
128
|
+
/** What a container's test pack prints, as a script INFO line, for each test it keeps the run tag on. */
|
|
129
|
+
const RUNS_NOTICE = 'devrock-gametests runs ';
|
|
130
|
+
/** What a full run's test pack prints, as a script INFO line, for each test it leaves to another container. */
|
|
131
|
+
const SKIPS_NOTICE = 'devrock-gametests skips ';
|
|
132
|
+
const noticed = (notice, transcript) => {
|
|
133
|
+
const notices = new RegExp(String.raw `^\[[^\]]+ INFO\] \[Scripting\] ${notice}(${TEST_ID})$`, 'gm');
|
|
134
|
+
return [...new Set([...transcript.matchAll(notices)].map((match) => match[1]))];
|
|
135
|
+
};
|
|
136
|
+
/** The tests a container's test pack kept the run tag on, so its `runset` runs them, from its transcript. */
|
|
137
|
+
export const testsRun = (transcript) => noticed(RUNS_NOTICE, transcript);
|
|
138
|
+
/** The tests a full run's test pack registered but left to another container, from its transcript. */
|
|
139
|
+
export const testsSkipped = (transcript) => noticed(SKIPS_NOTICE, transcript);
|
|
140
|
+
/** What a test pack prints, as a script INFO line, for each test that registers, tagged or not. */
|
|
141
|
+
const REGISTERS_NOTICE = 'devrock-gametests registers ';
|
|
142
|
+
/** Every test a container's test pack registered, tagged or not, from its transcript. */
|
|
143
|
+
export const testsRegistered = (transcript) => noticed(REGISTERS_NOTICE, transcript);
|
|
144
|
+
/**
|
|
145
|
+
* What a test pack prints, as a script INFO line, each time a test changes how many passes it needs, before the
|
|
146
|
+
* number. The last one counts.
|
|
147
|
+
*/
|
|
148
|
+
const REQUIRES_NOTICE = 'devrock-gametests requires ';
|
|
149
|
+
/**
|
|
150
|
+
* How many passes each test that called `requiredSuccessfulAttempts` or `rotateTest` needs, from a container's
|
|
151
|
+
* transcript. A rotated test needs its passes in each of its 4 rotations.
|
|
152
|
+
*/
|
|
153
|
+
export function testsRequired(transcript) {
|
|
154
|
+
const notices = new RegExp(String.raw `^\[[^\]]+ INFO\] \[Scripting\] ${REQUIRES_NOTICE}(\d+) pass(?:es)? of (${TEST_ID})$`, 'gm');
|
|
155
|
+
// Every test needs a pass, so a test set to need none can't pass without a verdict.
|
|
156
|
+
return new Map([...transcript.matchAll(notices)].map((match) => [match[2], Math.max(1, Number(match[1]))]));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Makes each line after a line break in a console or print message start with CONTINUATION, so the runner reads it
|
|
160
|
+
* as part of that message. The game prints each argument as `String(argument)`, so the patch does that first. Plain
|
|
161
|
+
* JavaScript, run before any other script in the pack.
|
|
162
|
+
*/
|
|
163
|
+
const CONSOLE_PATCH = `{
|
|
164
|
+
const continued = ${JSON.stringify(`\n${CONTINUATION}`)};
|
|
165
|
+
const lineBreaks = /\\r\\n|[\\n\\r\\u2028\\u2029]/g;
|
|
166
|
+
const marked = (args) =>
|
|
167
|
+
args.map((arg) => {
|
|
168
|
+
try {
|
|
169
|
+
return String(arg).replace(lineBreaks, continued);
|
|
170
|
+
} catch {
|
|
171
|
+
return arg;
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
for (const level of ['log', 'info', 'warn', 'error', 'debug']) {
|
|
175
|
+
const original = console[level];
|
|
176
|
+
if (typeof original === 'function') console[level] = (...args) => original.apply(console, marked(args));
|
|
177
|
+
}
|
|
178
|
+
if (typeof globalThis.print === 'function') {
|
|
179
|
+
const original = globalThis.print;
|
|
180
|
+
globalThis.print = (...args) => original(...marked(args));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
`;
|
|
184
|
+
/**
|
|
185
|
+
* Patches the console of the pack copy in `packDir` before its own scripts run: writes the patch next to the script
|
|
186
|
+
* entry its manifest names, under a file name the pack doesn't use, and imports it first. A pack with no script module
|
|
187
|
+
* is left alone.
|
|
188
|
+
*/
|
|
189
|
+
async function patchConsole(packDir) {
|
|
190
|
+
const entry = readScriptEntry(packDir);
|
|
191
|
+
if (entry === undefined)
|
|
192
|
+
return;
|
|
193
|
+
const entryFile = path.join(packDir, entry);
|
|
194
|
+
const fileName = (n) => `devrock_gametests_console${n === 0 ? '' : `_${n}`}.js`;
|
|
195
|
+
let n = 0;
|
|
196
|
+
while (existsSync(path.join(path.dirname(entryFile), fileName(n))))
|
|
197
|
+
n++;
|
|
198
|
+
await writeFile(path.join(path.dirname(entryFile), fileName(n)), CONSOLE_PATCH);
|
|
199
|
+
await writeFile(entryFile, `import './${fileName(n)}';\n${await readFile(entryFile, 'utf8')}`);
|
|
200
|
+
}
|
|
201
|
+
const GAMETEST = '@minecraft/server-gametest';
|
|
202
|
+
const RUNTIME_NAMESPACE = 'devrock-gametests-runtime';
|
|
203
|
+
/**
|
|
204
|
+
* Routes the bundle's imports of the GameTest module through a module that re-exports it, and that warns when an id
|
|
205
|
+
* is registered twice, because GameTest runs only one of them. That warning fails the run.
|
|
206
|
+
*
|
|
207
|
+
* With a `split` share, a test that tags itself TEST_TAG keeps it only in the container that runs its batch, and gets
|
|
208
|
+
* ELSEWHERE_TAG in every other one. It decides at the `tag()` call, because the engine ignores a tag added after the
|
|
209
|
+
* code that registers the test returns, such as a `system.beforeEvents.startup` callback. So a test must set its
|
|
210
|
+
* batch before its tag, and gets a warning if it doesn't. Each container says which tests it runs and which it
|
|
211
|
+
* skips, which is how the runner knows what each one runs and checks that they agree.
|
|
212
|
+
*
|
|
213
|
+
* With a `named` share, each named test gets NAMED_TAG as it registers, and the container says it runs it.
|
|
214
|
+
*
|
|
215
|
+
* The tests' source stays as it is.
|
|
216
|
+
*/
|
|
217
|
+
function testRuntime(share) {
|
|
218
|
+
const source = `
|
|
219
|
+
import * as gametest from '${GAMETEST}';
|
|
220
|
+
export * from '${GAMETEST}';
|
|
221
|
+
// Parsed from JSON, not written as an object literal, so a batch named __proto__ stays a batch.
|
|
222
|
+
const SHARE = JSON.parse(${JSON.stringify(JSON.stringify(share ?? null))});
|
|
223
|
+
const RUN_TAG = ${JSON.stringify(TEST_TAG)};
|
|
224
|
+
// Tags the runner gives tests itself. A test that gives itself one would run where it shouldn't.
|
|
225
|
+
const RESERVED_TAGS = ${JSON.stringify([NAMED_TAG, ELSEWHERE_TAG])};
|
|
226
|
+
const NAMED = SHARE?.kind === 'named' ? new Set(SHARE.ids.map((id) => id.toLowerCase())) : new Set();
|
|
227
|
+
// The first spelling of each id, by its lower case, because the engine matches ids in any letter case.
|
|
228
|
+
const registered = new Map();
|
|
229
|
+
function owner(batch) {
|
|
230
|
+
return Object.prototype.hasOwnProperty.call(SHARE.owners, batch) ? SHARE.owners[batch] : 1;
|
|
231
|
+
}
|
|
232
|
+
function track(className, testName, builder) {
|
|
233
|
+
const id = className + ':' + testName;
|
|
234
|
+
const first = registered.get(id.toLowerCase());
|
|
235
|
+
if (first !== undefined) {
|
|
236
|
+
const also = first === id ? '' : \` also as \${first},\`;
|
|
237
|
+
console.warn(\`devrock-gametests: \${id} is registered more than once,\${also} and GameTest runs only one of them. Give each test its own name.\`);
|
|
238
|
+
// The engine keeps the first, so naming this one too would leave the runner waiting for a verdict it can't get.
|
|
239
|
+
return builder;
|
|
240
|
+
}
|
|
241
|
+
registered.set(id.toLowerCase(), id);
|
|
242
|
+
// So a run can tell tests that never tagged themselves from no tests at all, even ones the listing can't see.
|
|
243
|
+
if (SHARE !== null) console.info(${JSON.stringify(REGISTERS_NOTICE)} + id);
|
|
244
|
+
if (SHARE?.kind === 'named' && NAMED.has(id.toLowerCase())) {
|
|
245
|
+
console.info(${JSON.stringify(RUNS_NOTICE)} + id);
|
|
246
|
+
builder.tag(${JSON.stringify(NAMED_TAG)});
|
|
247
|
+
}
|
|
248
|
+
const split = SHARE?.kind === 'split';
|
|
249
|
+
let batch = '';
|
|
250
|
+
let decided = false;
|
|
251
|
+
let attempts = 1;
|
|
252
|
+
let rotations = 1;
|
|
253
|
+
// Calls the builder's own methods on the builder itself, because the game's objects reject any other \`this\`.
|
|
254
|
+
const proxy = new Proxy(builder, {
|
|
255
|
+
get(target, key) {
|
|
256
|
+
const value = target[key];
|
|
257
|
+
if (typeof value !== 'function') return value;
|
|
258
|
+
return (...args) => {
|
|
259
|
+
if (key === 'tag' && RESERVED_TAGS.includes(args[0])) {
|
|
260
|
+
console.warn(\`devrock-gametests: \${id} uses the tag \${args[0]}, which devrock-gametests keeps for itself, so the test doesn't get it.\`);
|
|
261
|
+
return proxy;
|
|
262
|
+
}
|
|
263
|
+
if (split && key === 'tag' && args[0] === RUN_TAG) {
|
|
264
|
+
if (decided) return proxy;
|
|
265
|
+
decided = true;
|
|
266
|
+
const here = owner(batch) === SHARE.container;
|
|
267
|
+
console.info((here ? ${JSON.stringify(RUNS_NOTICE)} : ${JSON.stringify(SKIPS_NOTICE)}) + id);
|
|
268
|
+
value.apply(target, [here ? RUN_TAG : ${JSON.stringify(ELSEWHERE_TAG)}]);
|
|
269
|
+
return proxy;
|
|
270
|
+
}
|
|
271
|
+
if (key === 'batch') {
|
|
272
|
+
if (split && decided) {
|
|
273
|
+
console.warn(\`devrock-gametests: \${id} sets its batch after its tag, so the run can't keep it with its batch. Call batch() before tag().\`);
|
|
274
|
+
}
|
|
275
|
+
if (/[\\r\\n\\u2028\\u2029]/.test(String(args[0]))) {
|
|
276
|
+
console.warn(\`devrock-gametests: \${id} has a line break in its batch name, which the runner can't read back from the console. Use a name on one line.\`);
|
|
277
|
+
}
|
|
278
|
+
batch = args[0];
|
|
279
|
+
}
|
|
280
|
+
const result = value.apply(target, args);
|
|
281
|
+
// Without this the runner can't tell a test that needs another pass from one that is done. Each attempt
|
|
282
|
+
// of a rotated test prints a pass for each of its 4 rotations.
|
|
283
|
+
if (SHARE !== null && (key === 'requiredSuccessfulAttempts' || key === 'rotateTest')) {
|
|
284
|
+
if (key === 'requiredSuccessfulAttempts') attempts = Number(args[0]);
|
|
285
|
+
else rotations = args[0] ? 4 : 1;
|
|
286
|
+
const passes = attempts * rotations;
|
|
287
|
+
console.info(${JSON.stringify(REQUIRES_NOTICE)} + passes + (passes === 1 ? ' pass of ' : ' passes of ') + id);
|
|
288
|
+
}
|
|
289
|
+
return result === target ? proxy : result;
|
|
290
|
+
};
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
return proxy;
|
|
294
|
+
}
|
|
295
|
+
export const register = (className, testName, fn) => track(className, testName, gametest.register(className, testName, fn));
|
|
296
|
+
export const registerAsync = (className, testName, fn) =>
|
|
297
|
+
track(className, testName, gametest.registerAsync(className, testName, fn));
|
|
298
|
+
`;
|
|
299
|
+
return {
|
|
300
|
+
name: 'devrock-gametests-runtime',
|
|
301
|
+
setup(build) {
|
|
302
|
+
build.onResolve({ filter: /^@minecraft\/server-gametest$/ }, ({ namespace }) => namespace === RUNTIME_NAMESPACE
|
|
303
|
+
? { path: GAMETEST, external: true }
|
|
304
|
+
: { path: GAMETEST, namespace: RUNTIME_NAMESPACE });
|
|
305
|
+
build.onLoad({ filter: /.*/, namespace: RUNTIME_NAMESPACE }, () => ({ contents: source, loader: 'js' }));
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
async function buildTestPack(project, dir, share) {
|
|
310
|
+
await cp(project.testPack, dir, { recursive: true, dereference: true });
|
|
311
|
+
await build({
|
|
312
|
+
entryPoints: [project.entry],
|
|
313
|
+
outfile: path.join(dir, 'scripts', 'main.js'),
|
|
314
|
+
bundle: true,
|
|
315
|
+
format: 'esm',
|
|
316
|
+
platform: 'node',
|
|
317
|
+
logLevel: 'warning',
|
|
318
|
+
external: ALLOWED_MODULES,
|
|
319
|
+
plugins: [testRuntime(share)],
|
|
320
|
+
define: { ...project.define },
|
|
321
|
+
// The patch runs before any bundled module. It also keeps the bundle from being empty, which BDS refuses.
|
|
322
|
+
banner: { js: `// ${project.namespace} GameTests\n${CONSOLE_PATCH}` },
|
|
323
|
+
});
|
|
324
|
+
const [namespace, name] = PLOT_STRUCTURE.split(':');
|
|
325
|
+
const structureFile = path.join(dir, 'structures', namespace, `${name}.mcstructure`);
|
|
326
|
+
await mkdir(path.dirname(structureFile), { recursive: true });
|
|
327
|
+
await writeFile(structureFile, plotStructure(PLOT_SIZE));
|
|
328
|
+
}
|
|
329
|
+
/** Lists packs by manifest header uuid, which is what BDS matches on. */
|
|
330
|
+
async function writePackList(file, packDirs) {
|
|
331
|
+
const references = packDirs.map((packDir) => {
|
|
332
|
+
const { uuid, version } = readPackHeader(packDir);
|
|
333
|
+
return { pack_id: uuid, version };
|
|
334
|
+
});
|
|
335
|
+
await writeFile(file, `${JSON.stringify(references, null, 2)}\n`);
|
|
336
|
+
}
|
package/dist/game.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Imported by GameTests as `devrock-gametests/game`. It bundles into the test pack, which provides
|
|
3
|
+
* `@minecraft/server-gametest`, so the runner under Node imports `shared.ts` instead.
|
|
4
|
+
*/
|
|
5
|
+
import type { Dimension, Vector3 } from '@minecraft/server';
|
|
6
|
+
import { type RegistrationBuilder, type Test } from '@minecraft/server-gametest';
|
|
7
|
+
export { PLOT_SIZE, PLOT_STRUCTURE, TEST_AREA_END, TEST_TAG } from './shared.js';
|
|
8
|
+
/** Waits a tick at a time until `predicate` holds. Returns false if it still doesn't once `maxTicks` have passed. */
|
|
9
|
+
export declare function waitUntil(test: Test, predicate: () => boolean, maxTicks: number): Promise<boolean>;
|
|
10
|
+
/**
|
|
11
|
+
* Calls `add` until it adds its ticking area, freeing one finished test's area in `testDimension` before each
|
|
12
|
+
* retry. Bedrock caps ticking areas at 10, and GameTest holds one per started test until the run ends. Throws once
|
|
13
|
+
* it has freed MAX_FREED_INSTANCE_AREAS and `add` still fails.
|
|
14
|
+
*/
|
|
15
|
+
export declare function addTickingArea(testDimension: Dimension, name: string, add: () => boolean): void;
|
|
16
|
+
/**
|
|
17
|
+
* A ticking area of a far-area test's own, outside the runner's test area. With no players online, removing its
|
|
18
|
+
* ticking area is the only way to unload a chunk.
|
|
19
|
+
*/
|
|
20
|
+
export declare class FarArea {
|
|
21
|
+
private readonly test;
|
|
22
|
+
/** The middle of the area's floor, on the first air block above a flat world's grass. */
|
|
23
|
+
readonly location: Vector3;
|
|
24
|
+
private readonly command;
|
|
25
|
+
/** One block in each chunk column the area covers. */
|
|
26
|
+
private readonly chunks;
|
|
27
|
+
/** Taken at the start: a finished test can no longer reach its dimension. */
|
|
28
|
+
private readonly dimension;
|
|
29
|
+
/** The ticking area's name, which only the commands below use. */
|
|
30
|
+
private readonly name;
|
|
31
|
+
constructor(test: Test, name: string, x: number, radius: number);
|
|
32
|
+
/**
|
|
33
|
+
* Adds the ticking area and waits until every chunk in it loads. Chunks load one by one, and a mob can't find a
|
|
34
|
+
* path through one that hasn't loaded yet.
|
|
35
|
+
*/
|
|
36
|
+
load(): Promise<void>;
|
|
37
|
+
/** Removes the ticking area, which unloads its chunks. */
|
|
38
|
+
unload(): void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Registers a test that unloads and reloads chunks, in a batch of its own, with a FarArea centred on (`areaX`,
|
|
42
|
+
* `areaX`). A far area left loaded would count against the ticking-area cap for the rest of the run, so the area
|
|
43
|
+
* is removed when the test ends. Throws if the area would overlap the runner's test area.
|
|
44
|
+
*/
|
|
45
|
+
export declare function registerFarAreaTest(testClassName: string, testName: string, areaX: number, testFunction: (test: Test, area: FarArea) => Promise<void>,
|
|
46
|
+
/** Half the width of the ticking area. */
|
|
47
|
+
radius?: number): RegistrationBuilder;
|
package/dist/game.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { registerAsync } from '@minecraft/server-gametest';
|
|
2
|
+
import { PLOT_STRUCTURE, TEST_AREA_END, TEST_TAG } from './shared.js';
|
|
3
|
+
export { PLOT_SIZE, PLOT_STRUCTURE, TEST_AREA_END, TEST_TAG } from './shared.js';
|
|
4
|
+
/**
|
|
5
|
+
* GameTest numbers one ticking area per test it has started, as `gametestinstance_<structure>(<n>)`, so this must
|
|
6
|
+
* exceed the number of tests in a run.
|
|
7
|
+
*/
|
|
8
|
+
const MAX_FREED_INSTANCE_AREAS = 512;
|
|
9
|
+
/** Waits a tick at a time until `predicate` holds. Returns false if it still doesn't once `maxTicks` have passed. */
|
|
10
|
+
export async function waitUntil(test, predicate, maxTicks) {
|
|
11
|
+
for (let tick = 0; tick < maxTicks; tick++) {
|
|
12
|
+
if (predicate())
|
|
13
|
+
return true;
|
|
14
|
+
await test.idle(1);
|
|
15
|
+
}
|
|
16
|
+
return predicate();
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Calls `add` until it adds its ticking area, freeing one finished test's area in `testDimension` before each
|
|
20
|
+
* retry. Bedrock caps ticking areas at 10, and GameTest holds one per started test until the run ends. Throws once
|
|
21
|
+
* it has freed MAX_FREED_INSTANCE_AREAS and `add` still fails.
|
|
22
|
+
*/
|
|
23
|
+
export function addTickingArea(testDimension, name, add) {
|
|
24
|
+
let freed = 0;
|
|
25
|
+
while (!add()) {
|
|
26
|
+
if (freed === MAX_FREED_INSTANCE_AREAS) {
|
|
27
|
+
throw new Error(`ticking area ${name} was rejected after freeing ${freed} finished test areas`);
|
|
28
|
+
}
|
|
29
|
+
testDimension.runCommand(`tickingarea remove "gametestinstance_${PLOT_STRUCTURE}(${freed})"`);
|
|
30
|
+
freed++;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** How many far areas this script has made, so each gets a ticking area of its own, even a rotation of one test. */
|
|
34
|
+
let areasMade = 0;
|
|
35
|
+
/**
|
|
36
|
+
* `text` as a ticking-area name the command parser takes: letters, digits and underscores stay, and any other
|
|
37
|
+
* character becomes its code between hyphens, so different names stay different.
|
|
38
|
+
*/
|
|
39
|
+
const commandName = (text) => text.replace(/[^A-Za-z0-9_]/gu, (character) => `-${character.codePointAt(0)?.toString(16)}-`);
|
|
40
|
+
/**
|
|
41
|
+
* A ticking area of a far-area test's own, outside the runner's test area. With no players online, removing its
|
|
42
|
+
* ticking area is the only way to unload a chunk.
|
|
43
|
+
*/
|
|
44
|
+
export class FarArea {
|
|
45
|
+
test;
|
|
46
|
+
/** The middle of the area's floor, on the first air block above a flat world's grass. */
|
|
47
|
+
location;
|
|
48
|
+
command;
|
|
49
|
+
/** One block in each chunk column the area covers. */
|
|
50
|
+
chunks = [];
|
|
51
|
+
/** Taken at the start: a finished test can no longer reach its dimension. */
|
|
52
|
+
dimension;
|
|
53
|
+
/** The ticking area's name, which only the commands below use. */
|
|
54
|
+
name;
|
|
55
|
+
constructor(test, name, x, radius) {
|
|
56
|
+
this.test = test;
|
|
57
|
+
this.location = { x: x + 0.5, y: -60, z: x + 0.5 };
|
|
58
|
+
this.dimension = test.getDimension();
|
|
59
|
+
areasMade++;
|
|
60
|
+
this.name = `${commandName(name)}_${areasMade}`;
|
|
61
|
+
this.command = `tickingarea add ${x - radius} -64 ${x - radius} ${x + radius} 0 ${x + radius} ${this.name} true`;
|
|
62
|
+
const first = Math.floor((x - radius) / 16);
|
|
63
|
+
const last = Math.floor((x + radius) / 16);
|
|
64
|
+
for (let cx = first; cx <= last; cx++) {
|
|
65
|
+
for (let cz = first; cz <= last; cz++)
|
|
66
|
+
this.chunks.push({ x: cx * 16, y: -60, z: cz * 16 });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Adds the ticking area and waits until every chunk in it loads. Chunks load one by one, and a mob can't find a
|
|
71
|
+
* path through one that hasn't loaded yet.
|
|
72
|
+
*/
|
|
73
|
+
async load() {
|
|
74
|
+
const { dimension } = this;
|
|
75
|
+
addTickingArea(dimension, this.name, () => dimension.runCommand(this.command).successCount > 0);
|
|
76
|
+
const loaded = await waitUntil(this.test, () => this.chunks.every((at) => dimension.getBlock(at) !== undefined), 400);
|
|
77
|
+
if (!loaded)
|
|
78
|
+
throw new Error(`ticking area ${this.name} was added but never loaded`);
|
|
79
|
+
}
|
|
80
|
+
/** Removes the ticking area, which unloads its chunks. */
|
|
81
|
+
unload() {
|
|
82
|
+
this.dimension.runCommand(`tickingarea remove ${this.name}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Registers a test that unloads and reloads chunks, in a batch of its own, with a FarArea centred on (`areaX`,
|
|
87
|
+
* `areaX`). A far area left loaded would count against the ticking-area cap for the rest of the run, so the area
|
|
88
|
+
* is removed when the test ends. Throws if the area would overlap the runner's test area.
|
|
89
|
+
*/
|
|
90
|
+
export function registerFarAreaTest(testClassName, testName, areaX, testFunction,
|
|
91
|
+
/** Half the width of the ticking area. */
|
|
92
|
+
radius = 8) {
|
|
93
|
+
if (areaX - radius <= TEST_AREA_END) {
|
|
94
|
+
throw new Error(`${testClassName}:${testName}: a far area must start beyond x=${TEST_AREA_END}, the test area`);
|
|
95
|
+
}
|
|
96
|
+
// The class name's length keeps two ids that join to the same text, such as a_b:c and a:b_c, apart.
|
|
97
|
+
const name = `${TEST_TAG}_far_${testClassName.length}_${testClassName}_${testName}`;
|
|
98
|
+
return registerAsync(testClassName, testName, async (test) => {
|
|
99
|
+
const area = new FarArea(test, name, areaX, radius);
|
|
100
|
+
try {
|
|
101
|
+
await testFunction(test, area);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
area.unload();
|
|
105
|
+
}
|
|
106
|
+
})
|
|
107
|
+
.structureName(PLOT_STRUCTURE)
|
|
108
|
+
.batch(name)
|
|
109
|
+
.tag(TEST_TAG);
|
|
110
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { enableBetaApis, plotStructure, readStructure, type Structure, type StructureBlock } from './nbt.js';
|
|
2
|
+
export { type BlockedReason, type Host, nodeHost, type Preflight, preflight, type RunResult } from './preflight.js';
|
|
3
|
+
export { type ListOptions, listGameTests, type Registration } from './registrations.js';
|
|
4
|
+
export { type ContentLogLine, isComplete, parseReport, stoppedCleanly, type TestReport, type Tie, tieLabel, type Verdict, verdicts, } from './report.js';
|
|
5
|
+
export { PLOT_SIZE, PLOT_STRUCTURE, TEST_AREA_END, TEST_TAG } from './shared.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { enableBetaApis, plotStructure, readStructure } from './nbt.js';
|
|
2
|
+
export { nodeHost, preflight } from './preflight.js';
|
|
3
|
+
export { listGameTests } from './registrations.js';
|
|
4
|
+
export { isComplete, parseReport, stoppedCleanly, tieLabel, verdicts, } from './report.js';
|
|
5
|
+
export { PLOT_SIZE, PLOT_STRUCTURE, TEST_AREA_END, TEST_TAG } from './shared.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Lists GameTests in a worker thread for `listGameTestsInWorker`, which can stop it if the entries never finish loading.
|
|
2
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
3
|
+
import { listGameTests } from './registrations.js';
|
|
4
|
+
const { entries, options } = workerData;
|
|
5
|
+
// Not a top-level await: if an entry never finishes loading, Node would warn about this file instead of the entry.
|
|
6
|
+
listGameTests(entries, options).then((registrations) => parentPort?.postMessage({ registrations }), (error) => parentPort?.postMessage({ error: error.message }));
|
package/dist/nbt.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns on Beta APIs and the flat generator in a world BDS has already generated.
|
|
3
|
+
*
|
|
4
|
+
* server.properties has no key for experiments. They only live in level.dat, which starts with an
|
|
5
|
+
* 8-byte header: a uint32 storage version, then a uint32 body length. Little-endian NBT follows.
|
|
6
|
+
*/
|
|
7
|
+
export declare function enableBetaApis(levelDat: string): Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* Builds the room every GameTest runs in, a stone floor with air above it. Every test starts from
|
|
10
|
+
* the same blocks, whatever was there before. The runner generates it instead of committing it, so
|
|
11
|
+
* the repo holds no binary test assets.
|
|
12
|
+
*/
|
|
13
|
+
export declare function plotStructure(size: {
|
|
14
|
+
x: number;
|
|
15
|
+
y: number;
|
|
16
|
+
z: number;
|
|
17
|
+
}): Buffer;
|
|
18
|
+
export interface StructureBlock {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly states: Readonly<Record<string, unknown>>;
|
|
21
|
+
}
|
|
22
|
+
export interface Structure {
|
|
23
|
+
readonly size: {
|
|
24
|
+
x: number;
|
|
25
|
+
y: number;
|
|
26
|
+
z: number;
|
|
27
|
+
};
|
|
28
|
+
/** The block at a position, or undefined for a structure void or a position outside the structure. */
|
|
29
|
+
blockAt(x: number, y: number, z: number): StructureBlock | undefined;
|
|
30
|
+
}
|
|
31
|
+
/** Reads a `.mcstructure` file's size and blocks. */
|
|
32
|
+
export declare function readStructure(file: string): Promise<Structure>;
|
package/dist/nbt.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import nbt from 'prismarine-nbt';
|
|
3
|
+
/** The "Beta APIs" toggle. BDS reports it as `gtst` in its boot log. */
|
|
4
|
+
const BETA_APIS_KEY = 'gametest';
|
|
5
|
+
/** `Generator` 2 is a flat world with grass at y=-61, so every test plot sits on the same ground. */
|
|
6
|
+
const FLAT_GENERATOR = 2;
|
|
7
|
+
/** Block palette version the game writes as of 1.26.30. */
|
|
8
|
+
const BLOCK_VERSION = 18168865;
|
|
9
|
+
/**
|
|
10
|
+
* Turns on Beta APIs and the flat generator in a world BDS has already generated.
|
|
11
|
+
*
|
|
12
|
+
* server.properties has no key for experiments. They only live in level.dat, which starts with an
|
|
13
|
+
* 8-byte header: a uint32 storage version, then a uint32 body length. Little-endian NBT follows.
|
|
14
|
+
*/
|
|
15
|
+
export async function enableBetaApis(levelDat) {
|
|
16
|
+
const file = await readFile(levelDat);
|
|
17
|
+
const storageVersion = file.readUInt32LE(0);
|
|
18
|
+
const body = file.subarray(8);
|
|
19
|
+
if (file.readUInt32LE(4) !== body.length) {
|
|
20
|
+
throw new Error(`${levelDat} has a header the runner doesn't recognise, so the runner left it untouched.`);
|
|
21
|
+
}
|
|
22
|
+
const { parsed: root } = await nbt.parse(body, 'little');
|
|
23
|
+
const existing = root.value.experiments;
|
|
24
|
+
const experiments = existing?.type === 'compound' ? existing : compound({});
|
|
25
|
+
experiments.value[BETA_APIS_KEY] = nbt.byte(1);
|
|
26
|
+
experiments.value.experiments_ever_used = nbt.byte(1);
|
|
27
|
+
experiments.value.saved_with_toggled_experiments = nbt.byte(1);
|
|
28
|
+
root.value.experiments = experiments;
|
|
29
|
+
root.value.Generator = nbt.int(FLAT_GENERATOR);
|
|
30
|
+
const newBody = nbt.writeUncompressed(root, 'little');
|
|
31
|
+
const header = Buffer.alloc(8);
|
|
32
|
+
header.writeUInt32LE(storageVersion, 0);
|
|
33
|
+
header.writeUInt32LE(newBody.length, 4);
|
|
34
|
+
await writeFile(levelDat, Buffer.concat([header, newBody]));
|
|
35
|
+
}
|
|
36
|
+
const compound = (value) => ({ type: 'compound', value });
|
|
37
|
+
const intList = (values) => ({ type: 'list', value: { type: 'int', value: values } });
|
|
38
|
+
const paletteBlock = (name) => ({
|
|
39
|
+
name: nbt.string(name),
|
|
40
|
+
states: compound({}),
|
|
41
|
+
version: nbt.int(BLOCK_VERSION),
|
|
42
|
+
});
|
|
43
|
+
/**
|
|
44
|
+
* Builds the room every GameTest runs in, a stone floor with air above it. Every test starts from
|
|
45
|
+
* the same blocks, whatever was there before. The runner generates it instead of committing it, so
|
|
46
|
+
* the repo holds no binary test assets.
|
|
47
|
+
*/
|
|
48
|
+
export function plotStructure(size) {
|
|
49
|
+
const AIR = 0;
|
|
50
|
+
const STONE = 1;
|
|
51
|
+
const primary = [];
|
|
52
|
+
// .mcstructure block order is x, then y, then z, with z changing fastest.
|
|
53
|
+
for (let x = 0; x < size.x; x++) {
|
|
54
|
+
for (let y = 0; y < size.y; y++) {
|
|
55
|
+
for (let z = 0; z < size.z; z++) {
|
|
56
|
+
primary.push(y === 0 ? STONE : AIR);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// The secondary layer holds waterlogging, and -1 there means "no block".
|
|
61
|
+
const secondary = primary.map(() => -1);
|
|
62
|
+
const structure = {
|
|
63
|
+
type: 'compound',
|
|
64
|
+
name: '',
|
|
65
|
+
value: {
|
|
66
|
+
format_version: nbt.int(1),
|
|
67
|
+
size: intList([size.x, size.y, size.z]),
|
|
68
|
+
structure_world_origin: intList([0, 0, 0]),
|
|
69
|
+
structure: compound({
|
|
70
|
+
block_indices: {
|
|
71
|
+
type: 'list',
|
|
72
|
+
value: {
|
|
73
|
+
type: 'list',
|
|
74
|
+
value: [
|
|
75
|
+
{ type: 'int', value: primary },
|
|
76
|
+
{ type: 'int', value: secondary },
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
entities: { type: 'list', value: { type: 'compound', value: [] } },
|
|
81
|
+
palette: compound({
|
|
82
|
+
default: compound({
|
|
83
|
+
block_palette: {
|
|
84
|
+
type: 'list',
|
|
85
|
+
value: { type: 'compound', value: [paletteBlock('minecraft:air'), paletteBlock('minecraft:stone')] },
|
|
86
|
+
},
|
|
87
|
+
block_position_data: compound({}),
|
|
88
|
+
}),
|
|
89
|
+
}),
|
|
90
|
+
}),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
return nbt.writeUncompressed(structure, 'little');
|
|
94
|
+
}
|
|
95
|
+
/** Reads a `.mcstructure` file's size and blocks. */
|
|
96
|
+
export async function readStructure(file) {
|
|
97
|
+
const { parsed } = await nbt.parse(await readFile(file), 'little');
|
|
98
|
+
const value = nbt.simplify(parsed);
|
|
99
|
+
const [x, y, z] = value.size;
|
|
100
|
+
const palette = value.structure.palette.default.block_palette;
|
|
101
|
+
const indices = value.structure.block_indices[0];
|
|
102
|
+
return {
|
|
103
|
+
size: { x, y, z },
|
|
104
|
+
blockAt(bx, by, bz) {
|
|
105
|
+
const inside = (at, size) => Number.isInteger(at) && at >= 0 && at < size;
|
|
106
|
+
if (!inside(bx, x) || !inside(by, y) || !inside(bz, z))
|
|
107
|
+
return undefined;
|
|
108
|
+
const index = indices[(bx * y + by) * z + bz];
|
|
109
|
+
return index === undefined || index < 0 ? undefined : palette[index];
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|