Repository navigation
Expand file tree
/
Copy pathrun.mjs
More file actions
2448 lines (2334 loc) · 151 KB
/
Copy pathrun.mjs
File metadata and controls
2448 lines (2334 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Browser tests: starts the real server on seeded data, drives headless
// Chrome through the Chrome DevTools Protocol, and clicks through every
// interactive part of the page - tabs, pins, modals, search, admin.
//
// No dependencies: Node's built-in WebSocket talks CDP directly.
//
// node server/tests/e2e/run.mjs (from the repo root)
//
// Needs Python with server/requirements.txt installed, Node 22+, and
// Chrome/Chromium (set CHROME=/path/to/binary if it isn't found).
import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
const SERVER_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const API_KEY = 'e2e-api-key-0123456789abcdef0123456789abcdef';
const TIMEOUT_MS = 12000;
const children = [];
const tempDirs = [];
process.on('exit', () => {
for (const child of children) child.kill('SIGKILL');
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
});
function freePort() {
return new Promise((resolve) => {
const srv = net.createServer();
srv.listen(0, '127.0.0.1', () => {
const { port } = srv.address();
srv.close(() => resolve(port));
});
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function findChrome() {
const candidates = [
process.env.CHROME,
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
'/usr/bin/google-chrome',
'/usr/bin/google-chrome-stable',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
];
const found = candidates.find((c) => c && fs.existsSync(c));
if (!found) throw new Error('No Chrome/Chromium found - set CHROME=/path/to/binary');
return found;
}
// ---------------------------------------------------------------- server
// Resolves to { base, setupCode }: the code from the setup link a server
// with no users prints at startup.
async function startServer(extraEnv = {}) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcm-e2e-data-'));
tempDirs.push(dataDir);
const port = await freePort();
const child = spawn(process.env.PYTHON || 'python3', ['app.py'], {
cwd: SERVER_DIR,
env: {
...process.env,
DATA_DIR: dataDir,
API_KEY,
SESSION_COOKIE_SECURE: '0',
// The live crafting tree calls a step stuck after this long unmoved.
CRAFT_STALL_SECONDS: '4',
PORT: String(port),
...extraEnv,
},
stdio: ['ignore', 'pipe', 'pipe'],
});
children.push(child);
let log = '';
child.stdout.on('data', (d) => { log += d; });
child.stderr.on('data', (d) => { log += d; });
const base = `http://127.0.0.1:${port}`;
for (let i = 0; i < 100; i++) {
try {
// "Serving on" follows the setup link on the same stream, so once
// it has been read, so has the link.
if ((await fetch(base + '/')).ok && log.includes('Serving on')) {
return { base, setupCode: (/\/#setup=(\S+)/.exec(log) || [])[1] };
}
} catch (e) { /* not up yet */ }
if (child.exitCode !== null) break;
await sleep(100);
}
throw new Error('server did not start:\n' + log);
}
// ---------------------------------------------------------------- fake GitHub
// The Game data page lists gtnh-data-* releases from GitHub's API and
// downloads their assets. This serves one small but real bundle (a 16px
// icon for Iron Ingot, and a 32px one standing in for its Faithful
// render, and marked as drawn past the item box like a halo; Neutronium
// Ingot's is in the lookup but not the zips, and it has a description
// and the rest of item_info.json),
// made with Python so its zips and checksums are exactly what the
// server expects. A second release, E2E_NEXT_VERSION, is the same bundle
// with other recipes (next/): the seeded Macerator pattern's recipe takes
// two Neutronium Ingots there, for the pattern check. Its item list has
// the GregTech items the seeded patterns use too, which the first one's
// lacks, so admins are told the game data looks older than the game.
const E2E_DATA_VERSION = '2.9.0-e2e';
const E2E_NEXT_VERSION = '2.9.1-e2e';
const MAKE_BUNDLE = `
import gzip, hashlib, json, os, struct, sys, zipfile, zlib
out = sys.argv[1]
def recipes(path, ingots):
data = {"format": 1, "items": ["gregtech:gt.metaitem.01:11028", "gregtech:gt.metaitem.01:2032",
"gregtech:gt.metaitem.01:2129", "minecraft:iron_ingot:0"],
"item_names": ["Neutronium Ingot", "Iron Dust", "Neutronium Dust", "Iron Ingot"],
"fluids": ["water"], "fluid_names": ["Water"],
"maps": {"gt.recipe.macerator": {"machines": [{"name": "Macerator", "key": None}],
"recipes": [{"i": [[0, ingots]], "o": [[1, 1]], "e": 30, "d": 100}]},
"gt.recipe.compressor": {"machines": [{"name": "Compressor", "key": None}],
"recipes": [{"i": [[2, 1]], "o": [[0, 1]], "e": 30, "d": 100}]}}}
with gzip.open(path, "wt") as f:
json.dump(data, f)
recipes(out + "/recipes.json.gz", 1)
os.makedirs(out + "/next", exist_ok=True)
recipes(out + "/next/recipes.json.gz", 2)
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
def png(size):
rows = b"".join(b"\\x00" + b"\\xcc\\x44\\x22\\xff" * size for _ in range(size))
return (b"\\x89PNG\\r\\n\\x1a\\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
for name, size in (("images.zip", 16), ("images-faithful32.zip", 32)):
with zipfile.ZipFile(out + "/" + name, "w") as zf:
zf.writestr("item/minecraft/iron_ingot~0.png", png(size))
open(out + "/icons_lookup.json", "w").write(json.dumps(
{"by_key": {"minecraft:iron_ingot:0": "item/minecraft/iron_ingot~0.png",
"gregtech:gt.metaitem.01:11028": "item/gregtech/gt.metaitem.01~11028.png"},
"fluids_by_key": {}, "by_label": {}, "bleed": {"item/minecraft/iron_ingot~0.png": 12}}))
open(out + "/item_catalog.txt", "w").write("minecraft:iron_ingot\\n")
open(out + "/next/item_catalog.txt", "w").write("gregtech:gt.metaitem.01\\nminecraft:iron_ingot\\n")
open(out + "/ore_dict.json", "w").write(json.dumps(
{"gemDiamond": ["minecraft:diamond:0", "IC2:itemPartIndustrialDiamond:0"],
"ingotNeutronium": ["gregtech:gt.metaitem.01:11028"]}))
nt = "gregtech:gt.metaitem.01:11028"
open(out + "/item_info.json", "w").write(json.dumps({
"tooltips": {"by_key": {nt: "\\u00a7eNt\\n\\u00a77Machine Type: Plasma Forge, \\u00a7bDTPF"}},
"shift_tooltips": {"by_key": {nt: "\\u00a77Structure: \\u00a7e33x24x33"}},
"rarity": {"by_key": {nt: "d"}},
"fluids": {"water": {"temperature": 295, "gaseous": False, "formula": "H\\u2082O"}},
"mods": {"gregtech": "GregTech", "minecraft": "Minecraft"}}))
for bundle in (out, out + "/next"):
files = {}
for name in ("images.zip", "images-faithful32.zip", "icons_lookup.json", "item_catalog.txt", "ore_dict.json",
"item_info.json", "recipes.json.gz"):
data = open((bundle if name in ("recipes.json.gz", "item_catalog.txt") else out) + "/" + name, "rb").read()
files[name] = {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
open(bundle + "/data.json", "w").write(
json.dumps({"format": 1, "files": files, "generated_at": "2026-09-25T00:00:00Z"}))
`;
const BUNDLE_FILES = [
'data.json', 'images.zip', 'images-faithful32.zip', 'icons_lookup.json', 'item_catalog.txt', 'ore_dict.json',
'item_info.json', 'recipes.json.gz',
];
// The files E2E_NEXT_VERSION has of its own; the rest are the same.
const NEXT_FILES = ['data.json', 'recipes.json.gz', 'item_catalog.txt'];
// What the server posted to its webhook (WEBHOOK_URLS points at the
// fake GitHub server's /webhook).
const webhookPosts = [];
async function startFakeGitHub() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcm-e2e-gamedata-'));
tempDirs.push(dir);
const made = spawnSync(process.env.PYTHON || 'python3', ['-c', MAKE_BUNDLE, dir], { encoding: 'utf8' });
if (made.status !== 0) throw new Error('making the game data bundle failed:\n' + made.stderr);
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const server = http.createServer((req, res) => {
if (req.url === '/webhook' && req.method === 'POST') {
let body = '';
req.on('data', (chunk) => { body += chunk; });
req.on('end', () => {
webhookPosts.push(JSON.parse(body));
res.statusCode = 204;
res.end();
});
return;
}
if (req.url.startsWith('/repos/e2e/scripts/tags')) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify([{ name: 'v1.1.0' }, { name: 'v1.2.0' }]));
return;
}
if (req.url.startsWith('/repos/')) {
res.setHeader('Content-Type', 'application/json');
const release = (version, publishedAt, assets, ids) => ({
tag_name: `gtnh-data-${version}`,
published_at: publishedAt,
assets: BUNDLE_FILES.map((name, index) => {
const own = assets === 'assets-next' && NEXT_FILES.includes(name);
return {
name,
id: ids + index,
size: fs.statSync(path.join(own ? path.join(dir, 'next') : dir, name)).size,
browser_download_url: `${base}/${assets}/${name}`,
};
}),
});
// Published before E2E_DATA_VERSION, so that one stays first.
res.end(JSON.stringify([
release(E2E_DATA_VERSION, '2026-09-25T00:00:00Z', 'assets', 1000),
release(E2E_NEXT_VERSION, '2026-09-20T00:00:00Z', 'assets-next', 2000),
]));
return;
}
const [, assets, name] = req.url.split('/');
if (!BUNDLE_FILES.includes(name) || !['assets', 'assets-next'].includes(assets)) {
res.statusCode = 404;
res.end();
return;
}
const own = assets === 'assets-next' && NEXT_FILES.includes(name);
res.end(fs.readFileSync(path.join(own ? path.join(dir, 'next') : dir, name)));
});
await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));
server.unref();
return base;
}
async function api(base, method, urlPath, body, headers = {}) {
const response = await fetch(base + urlPath, {
method,
headers: { 'Content-Type': 'application/json', ...headers },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = await response.json().catch(() => null);
if (!response.ok) throw new Error(`${method} ${urlPath} -> ${response.status} ${JSON.stringify(data)}`);
return { response, data };
}
const game = (base, urlPath, body) => api(base, 'POST', urlPath, body, { 'X-API-Key': API_KEY });
// The server measures progress against the first report of a job, so
// seed() sends a starting report (atStart) first: 3/5 ingots and 6/10 ore
// left afterwards is 40%.
function postCrafts(base, w01Busy, atStart = false) {
return game(base, '/api/crafts', {
source: 'me_controller',
jobs: [
w01Busy
? {
name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: atStart ? 5 : 3 }],
pending: [{ name: 'Iron Ore', size: atStart ? 10 : 6 }], stored: [],
}
: { name: 'W01', busy: false },
{ name: 'W02', busy: false },
],
});
}
async function seed(base) {
await postCrafts(base, true, true);
await postCrafts(base, true);
// Half an hour apart in all, so the Power tab has a trend to show.
const now = Date.now() / 1000;
for (const [ago, stored] of [[1800, 100000], [900, 200000], [0, 300000]]) {
await game(base, '/api/power', { stored, capacity: 1000000, avg_eu_in_5s: 50, avg_eu_out_5s: 20, timestamp: now - ago });
}
await scanNetwork(base);
await scanPatterns(base);
}
const SEEDED_ITEMS = [
{ mod: 'minecraft', internal: 'iron_ingot', damage: 0, name: 'Iron Ingot', size: 1234, isCraftable: true },
{ mod: 'gregtech', internal: 'gt.metaitem.01', damage: 11028, name: 'Neutronium Ingot', size: 5, isCraftable: false },
{ internal: 'water', kind: 'fluid', name: 'Water', size: 64000 },
];
async function scanNetwork(base) {
const { data: scan } = await game(base, '/api/network/scan/start', {});
// Copies: the server reads the items, and these are reused.
await game(base, '/api/network/scan/batch', { scan_token: scan.scan_token, items: SEEDED_ITEMS.map(it => ({ ...it })) });
await game(base, '/api/network/scan/finish', { scan_token: scan.scan_token, chunks_sent: 1, total_errors: 0 });
}
// ---------------------------------------------------------------- browser
// Iron Ingot from Iron Dust (in the later slot, so AE2 tries it first) or
// from Water, 20,000 a time; the dust from Neutronium Ingot, of which
// there are only 5; more Neutronium from Neutronium Dust, which there is
// none of - four levels, one more than the plan's first answer holds.
const pattern = (provider, slot, outputs, inputs) => ({
provider: { name: provider, x: slot, y: 64, z: 0, dim: 0 }, slot, crafting: false, outputs, inputs,
});
const IRON_INGOT = { kind: 'item', mod: 'minecraft', internal: 'iron_ingot', damage: 0, name: 'Iron Ingot', size: 1 };
const IRON_DUST = { kind: 'item', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 2032, name: 'Iron Dust', size: 1 };
const SEEDED_PATTERNS = [
pattern('Fluid Solidifier', 0, [IRON_INGOT], [{ kind: 'fluid', internal: 'water', name: 'Water', size: 20000 }]),
pattern('Furnace', 1, [IRON_INGOT], [IRON_DUST]),
pattern('Macerator', 2, [IRON_DUST],
[{ kind: 'item', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 11028, name: 'Neutronium Ingot', size: 1 }]),
pattern('Compressor', 3,
[{ kind: 'item', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 11028, name: 'Neutronium Ingot', size: 1 }],
[{ kind: 'item', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 2129, name: 'Neutronium Dust', size: 1 }]),
];
// A pattern's NBT holding only byte flags (substitute, beSubstitute),
// gzipped and hex-encoded, as network_browser.lua sends it.
function flagsTag(flags) {
const parts = [Buffer.from([0x0a, 0, 0])];
for (const [name, value] of Object.entries(flags)) {
const len = Buffer.alloc(2);
len.writeUInt16BE(name.length);
parts.push(Buffer.from([0x01]), len, Buffer.from(name), Buffer.from([value]));
}
parts.push(Buffer.from([0]));
return zlib.gzipSync(Buffer.concat(parts)).toString('hex');
}
async function scanPatterns(base) {
const { data: scan } = await game(base, '/api/network/patterns/start', {});
await game(base, '/api/network/patterns/batch', { scan_token: scan.scan_token, patterns: SEEDED_PATTERNS });
await game(base, '/api/network/patterns/finish', { scan_token: scan.scan_token, chunks_sent: 1, total_errors: 0 });
}
class Cdp {
constructor(wsUrl) {
this.ws = new WebSocket(wsUrl);
this.nextId = 1;
this.pending = new Map();
this.handlers = new Map();
this.ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.id && this.pending.has(msg.id)) {
const { resolve, reject } = this.pending.get(msg.id);
this.pending.delete(msg.id);
if (msg.error) reject(new Error(msg.error.message)); else resolve(msg.result);
} else if (msg.method && this.handlers.has(msg.method)) {
for (const fn of this.handlers.get(msg.method)) fn(msg.params);
}
};
this.opened = new Promise((resolve, reject) => {
this.ws.onopen = resolve;
this.ws.onerror = reject;
});
}
send(method, params = {}) {
const id = this.nextId++;
this.ws.send(JSON.stringify({ id, method, params }));
return new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
}
on(method, fn) {
if (!this.handlers.has(method)) this.handlers.set(method, []);
this.handlers.get(method).push(fn);
}
}
async function startBrowser() {
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'gcm-e2e-chrome-'));
tempDirs.push(profile);
const child = spawn(findChrome(), [
'--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run',
'--remote-debugging-port=0', `--user-data-dir=${profile}`,
'--window-size=1280,900', 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
children.push(child);
const wsUrl = await new Promise((resolve, reject) => {
let err = '';
child.stderr.on('data', (d) => {
err += d;
const m = err.match(/DevTools listening on (ws:\/\/\S+)/);
if (m) resolve(m[1]);
});
child.on('exit', () => reject(new Error('chrome exited:\n' + err)));
});
const port = new URL(wsUrl).port;
const target = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: 'PUT' })).json();
const cdp = new Cdp(target.webSocketDebuggerUrl);
await cdp.opened;
return cdp;
}
// ---------------------------------------------------------------- page helpers
function pageHelpers(cdp) {
const errors = [];
cdp.on('Runtime.exceptionThrown', (p) => {
const d = p.exceptionDetails;
errors.push(`uncaught: ${d.exception?.description || d.text}`);
});
cdp.on('Runtime.consoleAPICalled', (p) => {
if (p.type === 'error') errors.push(`console.error: ${p.args.map((a) => a.value ?? a.description).join(' ')}`);
});
cdp.on('Log.entryAdded', ({ entry }) => {
// Missing icons (no images.zip in the test data dir) are expected 404s.
if (entry.level === 'error' && entry.source !== 'network') errors.push(`${entry.source}: ${entry.text}`);
});
async function evaluate(expression) {
const result = await cdp.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) {
throw new Error(`${expression}\n -> ${result.exceptionDetails.exception?.description || result.exceptionDetails.text}`);
}
return result.result.value;
}
async function waitFor(description, expression) {
const deadline = Date.now() + TIMEOUT_MS;
let last;
while (Date.now() < deadline) {
try {
last = await evaluate(expression);
if (last) return last;
} catch (e) {
last = e.message;
}
await sleep(100);
}
throw new Error(`timed out waiting for: ${description}\n last value: ${JSON.stringify(last)}`);
}
return { errors, evaluate, waitFor };
}
// Selecting by visible text keeps these tests independent of how the
// markup wires its handlers, which is exactly what refactors change.
const PAGE_LIB = `
window.$ = (sel, root = document) => root.querySelector(sel);
window.$$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
window.byText = (sel, text, root = document) =>
$$(sel, root).find((el) => el.textContent.trim() === text);
window.visible = (el) => !!el && el.getClientRects().length > 0
&& getComputedStyle(el).visibility !== 'hidden';
window.card = (cpu) => $$('#root .card').find((c) => c.querySelector('.card-cpu')?.textContent === 'CPU ' + cpu);
window.typeInto = (sel, text) => {
const el = $(sel);
el.focus();
el.value = text;
el.dispatchEvent(new Event('input', { bubbles: true }));
};
window.pressKey = (key, sel) => (sel ? $(sel) : document.body)
.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
window.pressEnter = (sel) => pressKey('Enter', sel);
// Opens an item's history the way a user would: search, click the cell.
window.openItem = (name) => {
typeInto('#networkSearch', name);
const cells = $$('#networkList .network-cell');
if (cells.length !== 1) throw new Error('expected one cell for ' + name + ', got ' + cells.length);
cells[0].click();
};
window.confirm = () => true;
true;
`;
// ---------------------------------------------------------------- tests
async function main() {
const github = await startFakeGitHub();
const { base, setupCode } = await startServer({
GAMEDATA_API_URL: github, GAMEDATA_REPO: 'e2e/repo', SCRIPTS_REPO: 'e2e/scripts',
// As publish.yml would set it: computers older than this get a notice.
GCM_SCRIPTS_VERSION: 'v1.1.0',
});
// The first admin, made the way the setup dialog makes it; the dialog
// itself is tried on a server of its own, last.
const setup = await fetch(base + '/api/auth/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: setupCode, display_name: 'Administrator' }),
});
if (!setup.ok) throw new Error(`setup: ${setup.status} ${await setup.text()}`);
const adminToken = (await setup.json()).token;
await seed(base);
const cdp = await startBrowser();
const { errors, evaluate, waitFor } = pageHelpers(cdp);
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
await cdp.send('Page.enable');
await cdp.send('Page.navigate', { url: base + '/' });
await waitFor('page loaded', `document.readyState === 'complete'`);
await evaluate(PAGE_LIB);
const steps = [];
const step = (name, fn) => steps.push({ name, fn });
const click = (expr) => evaluate(`(${expr}).click(), true`);
// Real mouse input, for what el.click() skips: the press and release
// go through the browser's own hit testing and click targeting.
const mouse = (type, [x, y]) => cdp.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 });
const centerOf = (expr) => evaluate(`(() => { const r = (${expr}).getBoundingClientRect(); return [r.x + r.width / 2, r.y + r.height / 2]; })()`);
// A click on a modal's dimmed backdrop, in its top-left corner, clear
// of the dialog box.
const clickBackdrop = async () => {
await mouse('mousePressed', [5, 5]);
await mouse('mouseReleased', [5, 5]);
};
step('crafts tab renders the busy CPU', async () => {
await waitFor('W01 card', `card('W01')?.querySelector('.craft-title').textContent.includes('Iron Ingot')`);
await waitFor('W02 in idle group', `$('details.idle-group') && card('W02')`);
await waitFor('tab badge counts the busy one', `$('#tabBtnCrafts .tab-badge')?.textContent === '1'`);
});
step('a CPU without a Crafting Monitor: "Starting job…" at first, then a hint', async () => {
const crafts = (jobs) => game(base, '/api/crafts', { source: 'me_controller', jobs: [
{ name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: 3 }], pending: [{ name: 'Iron Ore', size: 6 }], stored: [] },
{ name: 'W02', busy: false },
...jobs,
] });
// M01 just started; M02 was already running when the server first saw
// it, so it's past the wait for an output.
await crafts([{ name: 'M01', busy: false }]);
await crafts([{ name: 'M01', busy: true, pending: [{ name: 'Iron Ore', size: 6 }] },
{ name: 'M02', busy: true, pending: [{ name: 'Iron Ore', size: 6 }] }]);
await waitFor('M01 starting', `card('M01')?.querySelector('.craft-title').textContent === 'Starting job…'
&& !card('M01').querySelector('.monitor-hint')`);
await waitFor('M02 hint', `card('M02')?.querySelector('.craft-title').textContent === 'Unknown output'
&& card('M02').querySelector('.monitor-hint a').href.endsWith('in-game.md#crafting-cpus')`);
await crafts([]);
await waitFor('gone', `!card('M01') && !card('M02')`);
});
step('a CPU nobody named is named after its size, with a (?) saying so', async () => {
const crafts = (jobs) => game(base, '/api/crafts', { source: 'me_controller', jobs: [
{ name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: 3 }], pending: [{ name: 'Iron Ore', size: 6 }], stored: [] },
{ name: 'W02', busy: false },
...jobs,
] });
// AE2 reports a CPU nobody named with an empty name.
await crafts([{ name: '', busy: false, storage: 1024 }, { name: '', busy: false, storage: 65536 }]);
await waitFor('each named after its size, with the mark', `card('64k #1')?.querySelector('.cpu-auto')?.title.includes('its size was added')
&& card('1k #1')?.querySelector('.cpu-auto')`);
// A link to the docs, as a phone has no hover for the title.
await waitFor('the mark links to the docs', `card('64k #1').querySelector('.cpu-auto').href.endsWith('in-game.md#crafting-cpus')
&& card('64k #1').querySelector('.cpu-auto').getAttribute('aria-label').includes('Wire Cutters')`);
// Beside the name, not in it, so a long name's ellipsis can't hide it.
await waitFor('the mark is shown in full', `(() => {
const mark = card('64k #1').querySelector('.card-top > .cpu-auto');
const r = mark?.getBoundingClientRect();
return r && r.width >= 13 && r.height >= 13;
})()`);
await waitFor('named CPUs have no mark', `card('W02') && !card('W02').querySelector('.cpu-auto')`);
await crafts([]);
await waitFor('gone', `!card('64k #1') && !card('1k #1')`);
});
step('crafts poll each second, and an unchanged report answers 304', async () => {
const polls = `performance.getEntriesByType('resource').filter((e) => new URL(e.name).pathname === '/api/crafts').length`;
const before = await evaluate(polls);
await sleep(2500);
const after = await evaluate(polls);
if (after - before < 2) throw new Error(`only ${after - before} crafts polls in 2.5s`);
const status = await evaluate(`(async () => {
const first = await fetch('/api/crafts', { cache: 'no-store' });
const again = await fetch('/api/crafts', { cache: 'no-store', headers: { 'If-None-Match': first.headers.get('ETag') } });
return again.status;
})()`);
if (status !== 304) throw new Error(`conditional crafts fetch: ${status}`);
});
step('allowed inline styles apply; the progress bar is sized', async () => {
// Every dialog starts hidden via style="display:none;" - which only
// works if the CSP's style hashes match index.html.
await waitFor('all dialogs hidden', `$$('.modal-overlay').length >= 5 && $$('.modal-overlay').every((m) => !visible(m))`);
await waitFor('progress 40%', `card('W01').querySelector('.progress-fill').style.width === '40%'`);
// Busy in the server's first report, so only a lower bound on its run time.
await waitFor('run time', `/running ≥\\d/.test(card('W01').querySelector('.progress-label').textContent)`);
});
step('Content-Security-Policy blocks injected script and style', async () => {
const before = errors.length;
await evaluate(`document.body.insertAdjacentHTML('beforeend',
'<img id="xssImg" src="/icons?path=missing.png" onerror="window.__xss = 1">'
+ '<div id="xssStyle" style="color: rgb(255, 0, 0)">x</div>'), true`);
await sleep(1000);
await waitFor('inline handler did not run', `window.__xss === undefined`);
await waitFor('inline style ignored', `getComputedStyle($('#xssStyle')).color !== 'rgb(255, 0, 0)'`);
await evaluate(`$('#xssImg').remove(), $('#xssStyle').remove(), true`);
const reported = errors.splice(before);
if (!reported.some((e) => /Content Security Policy/i.test(e))) {
throw new Error('expected a CSP violation report, got:\n ' + reported.join('\n '));
}
});
step('sign in with the admin token', async () => {
await evaluate(`typeInto('#accessTokenInput', ${JSON.stringify(adminToken)})`);
await click(`$('#authBtn')`);
await waitFor('admin menu available', `$('#settingsUser').textContent !== '' && !visible($('#authBtn'))`);
// Run from source: no version, and nothing to update to.
await waitFor('no version, no update dot', `$('#settingsVersion').textContent === '' && !visible($('#settingsUpdateDot'))`);
});
step('sign out, then sign in again with the Enter key', async () => {
await click(`$('#settingsBtn')`);
await waitFor('menu open', `visible($('#settingsMenu'))`);
await click(`byText('#settingsMenu button', 'Sign out')`);
await waitFor('signed out', `visible($('#authBtn')) && $('#settingsUser').textContent === ''`);
await evaluate(`typeInto('#accessTokenInput', ${JSON.stringify(adminToken)})`);
// A synthetic Enter keydown doesn't submit a form; requestSubmit() is
// what pressing Enter in the field does.
await evaluate(`$('#signInForm').requestSubmit(), true`);
await waitFor('signed in', `$('#settingsUser').textContent !== '' && $('#settingsUser').textContent.includes('Administrator')`);
});
step('notifications switch in the settings menu', async () => {
await click(`$('#settingsBtn')`);
await waitFor('menu open', `visible($('#settingsMenu'))`);
await waitFor('off before permission', `$('#notifToggle').getAttribute('aria-checked') === 'false'`);
await cdp.send('Browser.grantPermissions', { origin: base, permissions: ['notifications'] });
await click(`$('#notifToggle')`);
await waitFor('switched on', `$('#notifToggle').getAttribute('aria-checked') === 'true'`);
await waitFor('menu stays open', `visible($('#settingsMenu'))`);
await click(`$('#notifToggle')`);
await waitFor('switched off despite permission', `$('#notifToggle').getAttribute('aria-checked') === 'false'`);
await click(`$('#notifToggle')`);
await waitFor('back on', `$('#notifToggle').getAttribute('aria-checked') === 'true'`);
await waitFor('service worker registered', `navigator.serviceWorker.getRegistration('/').then(r => Boolean(r && r.active))`);
await evaluate(`pressKey('Escape'), true`);
await waitFor('menu closed', `!visible($('#settingsMenu'))`);
});
step('theme: light, dark or the system\'s, remembered across a reload', async () => {
const bg = `getComputedStyle(document.body).backgroundColor`;
await click(`$('#settingsBtn')`);
await waitFor('menu open', `visible($('#settingsMenu'))`);
await waitFor('auto by default', `!document.documentElement.dataset.theme
&& $('[data-theme-choice="auto"]').getAttribute('aria-checked') === 'true'`);
await click(`$('[data-theme-choice="dark"]')`);
await waitFor('dark', `document.documentElement.dataset.theme === 'dark' && ${bg} === 'rgb(15, 17, 21)'`);
await waitFor('menu stays open', `visible($('#settingsMenu'))`);
await click(`$('[data-theme-choice="light"]')`);
await waitFor('light', `document.documentElement.dataset.theme === 'light' && ${bg} === 'rgb(244, 245, 247)'
&& $('[data-theme-choice="light"]').getAttribute('aria-checked') === 'true'
&& $('[data-theme-choice="dark"]').getAttribute('aria-checked') === 'false'`);
await cdp.send('Page.reload');
await waitFor('reloaded', `document.readyState === 'complete' && !window.byText`);
await evaluate(PAGE_LIB);
await waitFor('still light', `document.documentElement.dataset.theme === 'light'
&& $('[data-theme-choice="light"]').getAttribute('aria-checked') === 'true'`);
await click(`$('#settingsBtn')`);
await click(`$('[data-theme-choice="auto"]')`);
await waitFor('back to auto', `!document.documentElement.dataset.theme
&& localStorage.getItem('gtnhCraftMonitor.theme') === null`);
await evaluate(`pressKey('Escape'), true`);
await waitFor('menu closed', `!visible($('#settingsMenu'))`);
});
step('admin: set a webhook on the page; one that isn\'t a web address is refused', async () => {
await click(`$('#settingsBtn')`);
await waitFor('menu open', `visible($('#settingsMenu'))`);
await click(`$('#webhooksBtn')`);
await waitFor('webhooks dialog', `visible($('#webhooksModal')) && $('#webhookUrls').value === ''
&& $('#webhookEventCrafts').checked && !$('#webhookEventStock').checked`);
await evaluate(`typeInto('#webhookUrls', 'file:///etc/passwd'), true`);
await click(`$('#webhooksSaveBtn')`);
await waitFor('refused', `visible($('#webhooksError')) && $('#webhooksError').textContent.includes('Not a web address')`);
await evaluate(`typeInto('#webhookUrls', ${JSON.stringify(`${github}/webhook\n`)}), true`);
await click(`$('#webhooksSaveBtn')`);
await waitFor('saved', `$('#toastContainer').textContent.includes('Webhooks saved.') && !visible($('#webhooksError'))
&& $('#webhookUrls').value === ${JSON.stringify(`${github}/webhook`)}`);
await evaluate(`pressKey('Escape'), true`);
await waitFor('closed', `!visible($('#webhooksModal'))`);
});
step('a CPU\'s live crafting tree: rebuilt from patterns, updated in place, stuck steps', async () => {
// J01 makes 10 Iron Ingots: the dust (crafting) from the Neutronium
// it pulled - so the Furnace's pattern, not the Fluid Solidifier AE2
// would try first.
const ironIngot = { name: 'Iron Ingot', mod: 'minecraft', internal: 'iron_ingot', damage: 0 };
const ironDust = { name: 'Iron Dust', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 2032 };
const neutronium = { name: 'Neutronium Ingot', mod: 'gregtech', internal: 'gt.metaitem.01', damage: 11028 };
const report = (dustLeft) => game(base, '/api/crafts', { source: 'me_controller', jobs: [
{ name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: 3 }], pending: [{ name: 'Iron Ore', size: 6 }], stored: [] },
{ name: 'W02', busy: false },
{ name: 'J01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
pending: [{ ...ironIngot, size: 10 }], active: [{ ...ironDust, size: dustLeft }],
stored: [{ ...neutronium, size: 10 }] },
] });
await report(10);
await waitFor('J01 card', `card('J01')?.querySelector('.ingredients-btn')`);
await click(`card('J01').querySelector('.ingredients-btn')`);
await click(`$('#ingredientsModal [data-view="tree"]')`);
await waitFor('tree', `$$('#ingredientsTree li.job-node').length === 3 && !visible($('#ingredientsGrid'))`);
await waitFor('rows', `(() => {
const [ingot, dust, raw] = $$('#ingredientsTree li.job-node');
const row = (li) => li.querySelector(':scope > .plan-row').textContent;
return row(ingot).includes('0 / 10') && row(ingot).includes('Furnace') && ingot.classList.contains('job-waiting')
&& row(dust).includes('Macerator')
&& row(dust).includes('0 / 10') && dust.classList.contains('job-active')
&& raw.classList.contains('job-storage') && raw.textContent.includes('from storage');
})()`);
await evaluate(`window.dustText = $$('#ingredientsTree li.job-node')[1].querySelector('.job-step-text'), true`);
// A new report: the numbers change in place, the row isn't redrawn.
await report(4);
await waitFor('updated in place', `window.dustText.textContent === '6 / 10' && window.dustText.isConnected
&& $$('#ingredientsTree .job-bar-fill')[1].style.width === '60%'`);
// Shutting and opening a step redraws the tree: the bar is drawn where
// it was, not replayed from 0.
await sleep(5000); // the update's own transition (4.5s) is over
await click(`$$('#ingredientsTree [data-action="job-tree-toggle"]')[0]`);
await click(`$$('#ingredientsTree [data-action="job-tree-toggle"]')[0]`);
const ratio = await evaluate(`(() => {
const fill = $$('#ingredientsTree .job-bar-fill')[1];
return parseFloat(getComputedStyle(fill).width) / parseFloat(getComputedStyle(fill.parentElement).width);
})()`);
if (Math.abs(ratio - 0.6) > 0.02) throw new Error(`bar replayed from 0 on redraw: at ${ratio} of its track, not 0.6`);
// Nothing back past CRAFT_STALL_SECONDS: stalled, shown as stuck,
// saying why and where the machine is, with a chip to jump to it.
await report(4);
await waitFor('stuck', `$$('#ingredientsTree li.job-node')[1].classList.contains('job-stuck')
&& !$('#ingredientsStuck').hidden && $('#ingredientsStuck').textContent.includes('Iron Dust')
&& $('#ingredientsStuck .plan-chip').title.startsWith('nothing back from its machine for')
&& $$('#ingredientsTree li.job-node')[1].querySelector(':scope > .plan-row .job-step-note').textContent
.match(/^nothing back from its machine for \\d+s · -?\\d+, -?\\d+, -?\\d+/)`);
const tint = await evaluate(`(() => {
const bg = (li) => getComputedStyle(li.querySelector(':scope > .plan-row')).backgroundColor;
const [root, stuck] = $$('#ingredientsTree li.job-node');
return { stuck: bg(stuck), other: bg(root) };
})()`);
if (tint.stuck === tint.other) throw new Error(`a stuck step's row isn't tinted: ${JSON.stringify(tint)}`);
await click(`$$('#ingredientsTree [data-action="job-tree-toggle"]')[0]`);
await waitFor('shut, saying what is under it', `$$('#ingredientsTree li.job-node').length === 1
&& $('#ingredientsTree .job-step-note .job-count-stuck')?.textContent === '1 stuck'`);
// The filter box works on the tree too: only the way to a match,
// opened even where it was shut, the match marked.
await evaluate(`typeInto('#ingredientsFilter', 'neutronium'), true`);
await waitFor('filtered tree', `(() => {
const rows = $$('#ingredientsTree li.job-node');
return rows.length === 3 && rows[2].classList.contains('filter-match')
&& !rows[0].classList.contains('filter-match');
})()`);
await evaluate(`typeInto('#ingredientsFilter', 'gold'), true`);
await waitFor('nothing matches', `$$('#ingredientsTree li.job-node').length === 1
&& $('#ingredientsTree').textContent.includes('Nothing in this job matches')`);
// A stuck chip clears the filter to show its step.
await click(`$('#ingredientsStuck .plan-chip')`);
await waitFor('jumped to it', `$('#ingredientsTree li[data-pos="0"] > .plan-row')?.classList.contains('plan-jump')
&& $('#ingredientsFilter').value === ''`);
await click(`$('#ingredientsModal [data-view="grid"]')`);
await waitFor('grid again', `visible($('#ingredientsGrid')) && $('#ingredientsTreeWrap').hidden`);
await evaluate(`pressKey('Escape'), true`);
await waitFor('closed', `!visible($('#ingredientsModal'))`);
await postCrafts(base, true);
});
step('ingredients modal; stays open across a refresh, Escape closes it', async () => {
await waitFor('ingredients button', `card('W01').querySelector('.ingredients-btn')`);
await click(`card('W01').querySelector('.ingredients-btn')`);
await waitFor('open with a cell per item', `visible($('#ingredientsModal')) && $$('#ingredientsGrid .ingredient-cell').length === 2`);
await waitFor('the page under it does not scroll', `getComputedStyle(document.documentElement).overflowY === 'hidden'`);
await waitFor('crafting cell first', `$('#ingredientsGrid .ingredient-cell').classList.contains('crafting')
&& $('#ingredientsGrid .ingredient-cell').textContent.includes('Crafting: 3')`);
await evaluate(`window.ingBar = $('#ingredientsProgress .progress-fill'), true`);
await sleep(3500); // the crafts tab re-renders every 3s
await waitFor('still open after re-render', `visible($('#ingredientsModal')) && $$('#ingredientsGrid .ingredient-cell').length === 2`);
await waitFor('the same progress bar', `window.ingBar && $('#ingredientsProgress .progress-fill') === window.ingBar`);
// The filter box keeps what it matches through the next refresh.
await evaluate(`typeInto('#ingredientsFilter', 'ore'), true`);
await waitFor('filtered to the ore', `$$('#ingredientsGrid .ingredient-cell').length === 1
&& $('#ingredientsGrid .ingredient-cell').dataset.name === 'Iron Ore'`);
await sleep(3500);
await waitFor('still filtered after re-render', `$$('#ingredientsGrid .ingredient-cell').length === 1`);
await evaluate(`typeInto('#ingredientsFilter', 'gold'), true`);
await waitFor('nothing matches', `!$('#ingredientsGrid .ingredient-cell')
&& $('#ingredientsGrid').textContent.includes('Nothing matches')`);
// Escape in the box clears it; the next one closes the dialog.
await evaluate(`pressKey('Escape', '#ingredientsFilter'), true`);
await waitFor('cleared, still open', `visible($('#ingredientsModal')) && $('#ingredientsFilter').value === ''
&& $$('#ingredientsGrid .ingredient-cell').length === 2`);
await evaluate(`pressKey('Escape'), true`);
await waitFor('closed', `!visible($('#ingredientsModal'))`);
await waitFor('the page scrolls again', `getComputedStyle(document.documentElement).overflowY !== 'hidden'`);
});
step('an ingredient opens its item over the dialog; Back closes one at a time', async () => {
// An ingredient with an item id, which is what makes it a link.
await game(base, '/api/crafts', { source: 'me_controller', jobs: [
{ name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: 3 }],
pending: [{ name: 'Iron Ore', mod: 'minecraft', internal: 'iron_ore', damage: 0, size: 6 }], stored: [] },
{ name: 'W02', busy: false },
] });
await waitFor('W01 card', `card('W01')?.querySelector('.ingredients-btn')`);
await click(`card('W01').querySelector('.ingredients-btn')`);
await waitFor('dialog open', `visible($('#ingredientsModal')) && $$('#ingredientsGrid .ingredient-cell').length === 2
&& $$('#ingredientsGrid .ingredient-cell').find(c => c.dataset.internal === 'iron_ore')`);
await click(`$$('#ingredientsGrid .ingredient-cell').find(c => c.dataset.name === 'Iron Ore')`);
await waitFor('item over the dialog, still on crafts', `visible($('#itemHistoryModal')) && $('#itemHistoryName').textContent === 'Iron Ore'
&& visible($('#ingredientsModal')) && visible($('#craftsTab')) && $('#tabBtnCrafts').classList.contains('active')
&& location.pathname.startsWith('/network/item/')`);
await evaluate(`history.back(), true`);
await waitFor('item closed, dialog still open', `!visible($('#itemHistoryModal')) && visible($('#ingredientsModal'))
&& visible($('#craftsTab')) && !location.pathname.startsWith('/network')`);
await evaluate(`history.back(), true`);
await waitFor('dialog closed, still on crafts', `!visible($('#ingredientsModal')) && visible($('#craftsTab'))`);
await evaluate(`history.forward(), true`);
await waitFor('forward reopens the dialog', `visible($('#ingredientsModal')) && $$('#ingredientsGrid .ingredient-cell').length === 2`);
await evaluate(`history.forward(), true`);
await waitFor('and the item over it', `visible($('#itemHistoryModal')) && visible($('#ingredientsModal')) && visible($('#craftsTab'))`);
// Closing by hand steps back too, so Back has nothing left to reopen.
await click(`$('#itemHistoryModal .history-close-btn')`);
await waitFor('item closed by its button', `!visible($('#itemHistoryModal')) && visible($('#ingredientsModal'))
&& !location.pathname.startsWith('/network')`);
await click(`$('#ingredientsModal [data-action="close-ingredients"]')`);
await waitFor('dialog closed by its button', `!visible($('#ingredientsModal')) && visible($('#craftsTab'))
&& (history.state === null || history.state.view !== 'ingredients')`);
await postCrafts(base, true);
});
step('dialogs by keyboard: focus goes in, Tab stays in, focus comes back; item links open with Enter', async () => {
// Real key presses, so focus moves the browser's own way.
const CODES = { Enter: 13, Escape: 27, Tab: 9 };
const key = async (k, shift) => {
const ev = { key: k, code: k, windowsVirtualKeyCode: CODES[k], modifiers: shift ? 8 : 0 };
// Enter's text is what makes a <button> click.
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', ...ev, ...(k === 'Enter' ? { text: '\r' } : {}) });
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...ev });
};
await game(base, '/api/crafts', { source: 'me_controller', jobs: [
{ name: 'W01', busy: true, final_output: 'Iron Ingot', final_output_mod: 'minecraft',
final_output_internal: 'iron_ingot', final_output_damage: 0,
active: [{ name: 'Iron Ingot', size: 3 }],
pending: [{ name: 'Iron Ore', mod: 'minecraft', internal: 'iron_ore', damage: 0, size: 6 }], stored: [] },
{ name: 'W02', busy: false },
] });
await waitFor('W01 card', `card('W01')?.querySelector('.ingredients-btn')`);
const box = `$('#ingredientsModal .modal-box')`;
await evaluate(`card('W01').querySelector('.ingredients-btn').focus(), true`);
await key('Enter');
await waitFor('open', `visible($('#ingredientsModal'))`);
await waitFor('a modal dialog', `${box}.getAttribute('role') === 'dialog' && ${box}.getAttribute('aria-modal') === 'true'`);
await waitFor('labelled by its title', `document.getElementById(${box}.getAttribute('aria-labelledby'))?.textContent.includes('Iron Ingot')`);
await waitFor('focus in it', `$('#ingredientsModal').contains(document.activeElement)`);
// Round the dialog more than once, both ways: never out of it.
for (const shift of [false, true]) {
for (let i = 0; i < 8; i++) {
await key('Tab', shift);
const inside = await evaluate(`$('#ingredientsModal').contains(document.activeElement) && document.activeElement !== ${box}`);
if (!inside) throw new Error(`Tab ${shift ? 'backwards ' : ''}left the dialog, at ${i}: ${await evaluate('document.activeElement.outerHTML.slice(0, 120)')}`);
}
}
// An ingredient is a button to the keyboard.
await evaluate(`$$('#ingredientsGrid .ingredient-cell').find(c => c.dataset.internal === 'iron_ore').focus(), true`);
await key('Enter');
await waitFor('item open over it, focus in the item', `visible($('#itemHistoryModal')) && $('#itemHistoryName').textContent === 'Iron Ore'
&& $('#itemHistoryModal').contains(document.activeElement)`);
await key('Escape');
await waitFor('item closed, focus back in the ingredients', `!visible($('#itemHistoryModal'))
&& $('#ingredientsModal').contains(document.activeElement)`);
await key('Escape');
await waitFor('closed, focus back on its button', `!visible($('#ingredientsModal'))
&& document.activeElement.matches('[data-action="open-ingredients"][data-cpu="W01"]')`);
// So is a card's item name.
await evaluate(`card('W01').querySelector('.item-history-link').focus(), true`);
await key('Enter');
await waitFor('its item open', `visible($('#itemHistoryModal')) && $('#itemHistoryName').textContent === 'Iron Ingot'`);
await key('Escape');
await waitFor('closed, focus back on the name', `!visible($('#itemHistoryModal'))
&& document.activeElement.matches('.item-history-link[data-internal="iron_ingot"]')`);
await postCrafts(base, true);
});
step('a redraw keeps icon <img>s, so animated ones carry on', async () => {
// Kept isn't enough: an <img> moved through another document (a
// template's content) restarts all the same. adoptedCallback counts
// those trips.
const kept = await evaluate(`(async () => {
const { updateHtml } = await import('/static/js/util.js');
customElements.define('adopt-count-img', class extends HTMLImageElement {
adoptedCallback() { window.__adopted++; }
}, { extends: 'img' });
// In the page: a custom element is only upgraded once connected.
const el = document.body.appendChild(document.createElement('div'));
const img = (cls, src) => '<img is="adopt-count-img" class="' + cls + '" src="/icons?path=' + src + '">';
const html = (cls) => img(cls, 'a.png') + img('', 'b.png') + img('', 'a.png') + '<span>x</span>';
updateHtml(el, html('one'));
const [a1, b, a2] = el.querySelectorAll('img');
window.__adopted = 0;
updateHtml(el, '<i>y</i>' + html('two'));
const now = el.querySelectorAll('img');
el.remove();
return now[0] === a1 && now[1] === b && now[2] === a2 && a1.className === 'two'
&& el.firstChild.tagName === 'I' && el.textContent === 'yx' && window.__adopted === 0;
})()`);
if (!kept) throw new Error('icon <img>s were not kept across updateHtml');
});
step('a redraw updates in place: items, icons, focus, selection and clicks survive it', async () => {
const result = await evaluate(`(async () => {
const { updateHtml } = await import('/static/js/util.js');
const el = document.body.appendChild(document.createElement('div'));
const img = (src) => '<img is="adopt-count-img" src="/icons?path=' + src + '">';
const item = (id, src, text) => '<div data-id="' + id + '">' + img(src) + '<span>' + text + '</span><button>b' + id + '</button></div>';
updateHtml(el, item('a', 'x.png', 'one') + item('b', 'y.png', 'two'));
const [a, b] = el.children;
const [ax, by] = el.querySelectorAll('img');
a.querySelector('span').style.width = '40%';
// Any src set on an <img> already in the page restarts its animation.
let srcChanges = 0;
const watch = new MutationObserver((rs) => { srcChanges += rs.filter(r => r.target.isConnected && r.oldValue !== null).length; });
watch.observe(el, { subtree: true, attributes: true, attributeFilter: ['src'], attributeOldValue: true });
window.__adopted = 0;
const fail = [];
// Reordered: the same items move, with their icons.
updateHtml(el, item('b', 'y.png', 'two') + item('a', 'x.png', 'one'));
if (el.children[0] !== b || el.children[1] !== a) fail.push('reorder replaced the items');
if (b.querySelector('img') !== by || a.querySelector('img') !== ax) fail.push('reorder replaced the icons');
// The icons swap items: each moves, none is given the other's src.
updateHtml(el, item('b', 'x.png', 'two') + item('a', 'y.png', 'one'));
if (b.querySelector('img') !== ax || a.querySelector('img') !== by) fail.push('swapped icons were not moved');
// Text changes in place; a style set through the DOM stays.
const span = a.querySelector('span');
updateHtml(el, item('b', 'x.png', 'two') + item('a', 'y.png', 'uno'));
if (a.querySelector('span') !== span || span.textContent !== 'uno') fail.push('text was not updated in place');
if (span.style.width !== '40%') fail.push('the style set through the DOM was dropped');
// Focus, and a selection in text that didn't change, carry on.
a.querySelector('button').focus();
getSelection().selectAllChildren(b.querySelector('span'));
updateHtml(el, item('b', 'x.png', 'two') + item('a', 'y.png', 'one'));
if (document.activeElement !== a.querySelector('button')) fail.push('focus was lost');
if (getSelection().toString() !== 'two') fail.push('the selection was lost');
getSelection().removeAllRanges();
// A new item's new icon is a new <img>; the others are untouched.
updateHtml(el, item('c', 'z.png', 'three') + item('b', 'x.png', 'two') + item('a', 'y.png', 'one'));
if (el.children[1] !== b || el.children[2] !== a || el.querySelectorAll('img').length !== 3) fail.push('a new item disturbed the others');
await new Promise(r => setTimeout(r, 0));
watch.disconnect();
if (srcChanges) fail.push(srcChanges + ' src change(s) on kept <img>s');
if (window.__adopted) fail.push(window.__adopted + ' <img>(s) moved through another document');
window.redrawTarget = el;
return fail.join('; ');
})()`);
if (result) throw new Error(result);
// Lists in sections, as the Crafts tab draws them.
const sections = await evaluate(`(async () => {
const { updateHtml: update } = await import('/static/js/util.js');
const el = document.body.appendChild(document.createElement('div'));
const img = (src) => '<img is="adopt-count-img" src="/icons?path=' + src + '">';
const card = (id, src) => '<div data-id="' + id + '">' + img(src) + '<button>' + id + '</button></div>';
const section = (id, cards) => '<section data-id="' + id + '"><div class="grid">' + cards.join('') + '</div></section>';
const byId = (id) => el.querySelector('[data-id="' + id + '"]');
const fail = [];
// Whatever was kept or moved, the result is exactly the new markup.
const updateHtml = (target, html) => {
update(target, html);
const t = document.createElement('template');
t.innerHTML = html;
if (target.innerHTML !== t.innerHTML) fail.push('the result differs from the markup: ' + html.slice(0, 80));
};
// Kept nodes taken out of the page and put back (a move) lose focus.
let moved = new Set();
const watch = new MutationObserver((rs) => { for (const r of rs) for (const n of r.removedNodes) moved.add(n); });
watch.observe(el, { subtree: true, childList: true });
const settle = async () => { await new Promise(r => setTimeout(r, 0)); const m = moved; moved = new Set(); return m; };
// c2 first: the old code gave a new card the first free <img>
// showing its icon, in page order - c2's.
updateHtml(el, section('active', [card('c2', 'x.png'), card('c1', 'x.png'), card('c3', 'y.png')]));
const [c1, c2, c3] = ['c1', 'c2', 'c3'].map(byId);
const [x2, x1, y3] = el.querySelectorAll('img');
const active = byId('active');
await settle();
window.__adopted = 0;
// c1 finishes: a Finished section appears above, with a card for the
// same item. The Active section and the cards in it stay put, c2
// keeps its own icon, and the finished card takes c1's.
updateHtml(el, section('finished', [card('done1', 'x.png')]) + section('active', [card('c2', 'x.png'), card('c3', 'y.png')]));
let m = await settle();
if (byId('active') !== active || byId('c2') !== c2 || byId('c3') !== c3) fail.push('a section appearing replaced the one after it');
if (m.has(active) || m.has(c2) || m.has(c3)) fail.push('a section appearing moved the one after it');
if (c2.querySelector('img') !== x2) fail.push("the finished card took the icon of a card that stayed");
if (byId('done1').querySelector('img') !== x1) fail.push("the finished card didn't take the finished CPU's icon");
// The first card of a list goes: none after it moves.
updateHtml(el, section('finished', [card('done1', 'x.png')]) + section('active', [card('c3', 'y.png')]));
m = await settle();
if (byId('c3') !== c3 || m.has(c3)) fail.push('removing the first card moved the next');
// c3 is pinned with its button focused: it moves to a new Pinned
// section, the same element, and keeps focus.
c3.querySelector('button').focus();
updateHtml(el, section('finished', [card('done1', 'x.png')]) + section('pinned', [card('c3', 'y.png')]));
if (byId('c3') !== c3 || c3.querySelector('img') !== y3) fail.push('a card moving section was rebuilt');
if (document.activeElement !== c3.querySelector('button')) fail.push('a card moving section lost focus');