roamwright 0.61.9 → 0.61.10

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.
@@ -0,0 +1,212 @@
1
+ // Generic published-layout IndexedDB terrain-bake persistence check built on a Roamwright page driver:
2
+ // switches served build fixtures on a single origin for a visitor with an existing IndexedDB store,
3
+ // verifying that unrelated publishes reuse cached terrain bakes while terrain-changing builds rewrite them.
4
+ //
5
+ // const { runBakePublishCheck } = require('roamwright/tools/bake-publish.cjs');
6
+ 'use strict';
7
+ const assert = require('node:assert/strict');
8
+ const { spawn } = require('node:child_process');
9
+ const { once } = require('node:events');
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { createInterface } = require('node:readline');
13
+
14
+ /**
15
+ * Resolves `scripts/serve.py` across an explicit override, the engine's own `scripts/serve.py`,
16
+ * and a remote runner's `../serve/serve.py` layout.
17
+ *
18
+ * @param {object} [options]
19
+ * @param {string} [options.serveScript] Explicit path to `serve.py`.
20
+ * @param {string} [options.callerDir] Directory of the invoking wrapper script.
21
+ * @returns {string}
22
+ */
23
+ function resolveServeScript({ serveScript = '', callerDir = '' } = {}) {
24
+ const candidates = [
25
+ serveScript,
26
+ path.resolve(__dirname, '../scripts/serve.py'),
27
+ callerDir ? path.resolve(callerDir, '../serve/serve.py') : '',
28
+ ].filter(Boolean);
29
+ const found = candidates.find(p => fs.existsSync(p));
30
+ if (!found) throw new Error('serve.py not found in: ' + candidates.join(', '));
31
+ return found;
32
+ }
33
+
34
+ /**
35
+ * Runs the multi-build IndexedDB terrain-bake persistence check against fixture directories.
36
+ *
37
+ * @param {object} driver Page driver from `createPageDriver`.
38
+ * @param {object} options
39
+ * @param {string[]} options.argv CLI arguments: `[root, rounds, oldA, oldB, newA, newB, newC]`.
40
+ * @param {string} [options.baseDir=process.cwd()] Directory used to resolve relative `root`.
41
+ * @param {string} [options.siteSubdir='world'] Subdirectory inside each fixture holding the published site.
42
+ * @param {string} [options.address=''] Relative route address to visit on each build.
43
+ * @param {string} options.expectedSpace Expected `window[debug].space.id` after loading `address`.
44
+ * @param {string} [options.dbName] IndexedDB database name (default: `<storagePrefix>-kept`).
45
+ * @param {string} [options.storeName='baked'] IndexedDB object store name for terrain bakes.
46
+ * @param {Record<string, string>} [options.prefs] Initial prefixed localStorage preferences verified to survive publishes.
47
+ * @param {string} [options.serveScript] Optional explicit path to `serve.py`.
48
+ * @returns {Promise<void>}
49
+ */
50
+ async function runBakePublishCheck(
51
+ driver,
52
+ {
53
+ argv,
54
+ baseDir = process.cwd(),
55
+ siteSubdir = 'world',
56
+ address = '',
57
+ expectedSpace,
58
+ dbName,
59
+ storeName = 'baked',
60
+ prefs = { quality: 'high', muted: '1' },
61
+ serveScript = '',
62
+ },
63
+ ) {
64
+ const { chromium, shell, GPU, debug, storagePrefix, printLog } = driver;
65
+ const [root, rounds, oldA, oldB, newA, newB, newC] = argv;
66
+ if (!root || !rounds || !oldA || !oldB || !newA || !newB || !newC) {
67
+ throw new Error('usage: bake-publish.cjs <fixture root> <rounds> <old-A> <old-B> <new-A> <new-B> <new-C>');
68
+ }
69
+ const databaseName = dbName || `${storagePrefix}-kept`;
70
+ const prefEntries = Object.entries(prefs);
71
+ const fixtures = path.resolve(baseDir, root);
72
+ const serverRoot = fs.mkdtempSync(path.join(fixtures, 'run-'));
73
+ const site = name => {
74
+ const target = path.join(fixtures, name, siteSubdir);
75
+ const build = JSON.parse(fs.readFileSync(path.join(target, 'version.json'))).build;
76
+ const link = path.join(serverRoot, siteSubdir);
77
+ fs.rmSync(link, { force: true });
78
+ fs.symlinkSync(target, link);
79
+ return build;
80
+ };
81
+ const serverScript = resolveServeScript({ serveScript, callerDir: baseDir });
82
+ const server = spawn(
83
+ 'python3',
84
+ [
85
+ '-u',
86
+ '-c',
87
+ "import runpy,sys; api=runpy.run_path(sys.argv[1]); server=api['Server'](('127.0.0.1',0),api['Handler']); print(server.server_port); server.serve_forever()",
88
+ serverScript,
89
+ ],
90
+ { cwd: serverRoot, stdio: ['ignore', 'pipe', 'ignore'] },
91
+ );
92
+ let browser;
93
+ try {
94
+ const [line] = await Promise.race([
95
+ once(createInterface({ input: server.stdout }), 'line'),
96
+ once(server, 'exit').then(([code]) => {
97
+ throw Error('Fixture server exited with code ' + code);
98
+ }),
99
+ ]);
100
+ const base = 'http://localhost:' + Number(line) + '/' + siteSubdir + '/';
101
+ browser = await chromium.launch({ executablePath: shell, ...GPU });
102
+ let referenceGrid;
103
+ for (let round = 0; round < Number(rounds); round++) {
104
+ for (const [a, b, c] of [
105
+ [oldA, oldB, null],
106
+ [newA, newB, newC],
107
+ ]) {
108
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 }, serviceWorkers: 'block' });
109
+ await ctx.addInitScript(
110
+ ({ prefix, items, store }) => {
111
+ if (location.protocol !== 'http:') return;
112
+ if (!sessionStorage.fixture) {
113
+ sessionStorage.fixture = '1';
114
+ for (const [k, v] of items) localStorage.setItem(prefix ? `${prefix}:${k}` : k, v);
115
+ }
116
+ window.gridReads = [];
117
+ window.gridWrites = [];
118
+ for (const [method, log] of [
119
+ ['get', window.gridReads],
120
+ ['put', window.gridWrites],
121
+ ]) {
122
+ const original = IDBObjectStore.prototype[method];
123
+ IDBObjectStore.prototype[method] = function (...args) {
124
+ if (this.name === store) log.push(args.at(-1));
125
+ return original.apply(this, args);
126
+ };
127
+ }
128
+ },
129
+ { prefix: storagePrefix, items: prefEntries, store: storeName },
130
+ );
131
+ const page = await ctx.newPage();
132
+ const faults = [];
133
+ page.on('pageerror', e => faults.push(e.message));
134
+ let visit = 0;
135
+ for (const [build, step, expected] of [
136
+ [a, 'cold', 'write'],
137
+ [a, 'return', 'read'],
138
+ [b, 'publish', c ? 'read' : 'write'],
139
+ [c, 'terrain', 'write'],
140
+ ]) {
141
+ if (!build) continue;
142
+ const hash = site(build);
143
+ await page.goto(base + address + '?test=' + round + '-' + ++visit, { waitUntil: 'domcontentloaded' });
144
+ await page.waitForFunction(d => window[d]?.state.mode === 'play', debug, { timeout: 120000 });
145
+ const result = await page.evaluate(
146
+ ({ d, prefix, keys }) => ({
147
+ ready: window[d].loadTimes.ready,
148
+ reads: window.gridReads,
149
+ writes: window.gridWrites,
150
+ build: document.querySelector('script[type=module][src]').src.match(/app-([0-9a-f]+)/)[1],
151
+ prefs: keys.map(k => localStorage.getItem(prefix ? `${prefix}:${k}` : k)),
152
+ space: window[d].space.id,
153
+ }),
154
+ { d: debug, prefix: storagePrefix, keys: prefEntries.map(([k]) => k) },
155
+ );
156
+ console.log('BAKE', round, build, step, JSON.stringify(result));
157
+ if (expectedSpace) assert.equal(result.space, expectedSpace);
158
+ assert.equal(result.build, hash);
159
+ assert.deepEqual(
160
+ result.prefs,
161
+ prefEntries.map(([, v]) => v),
162
+ );
163
+ assert.equal(result.reads.length, expected === 'read' ? 1 : 0);
164
+ assert.equal(result.writes.length, expected === 'write' ? 1 : 0);
165
+ if (round === 0) {
166
+ const key = result.reads[0] ?? result.writes[0];
167
+ const digests = await page.evaluate(
168
+ async ([dbId, store, recordKey]) => {
169
+ const request = indexedDB.open(dbId);
170
+ const db = await new Promise((resolve, reject) => {
171
+ request.onsuccess = () => resolve(request.result);
172
+ request.onerror = () => reject(request.error);
173
+ });
174
+ try {
175
+ const read = db.transaction(store).objectStore(store).get(recordKey);
176
+ const arrays = await new Promise((resolve, reject) => {
177
+ read.onsuccess = () => resolve(read.result);
178
+ read.onerror = () => reject(read.error);
179
+ });
180
+ return Promise.all(
181
+ arrays.map(async array => {
182
+ const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', array));
183
+ return Array.from(bytes, n => n.toString(16).padStart(2, '0')).join('');
184
+ }),
185
+ );
186
+ } finally {
187
+ db.close();
188
+ }
189
+ },
190
+ [databaseName, storeName, key],
191
+ );
192
+ referenceGrid ??= digests;
193
+ if (step === 'terrain') assert.notDeepEqual(digests, referenceGrid);
194
+ else assert.deepEqual(digests, referenceGrid);
195
+ console.log('verified', digests.length, 'array digests', build, step);
196
+ }
197
+ await printLog(page);
198
+ await page.evaluate(d => window[d].clearLog(), debug);
199
+ await page.goto('about:blank');
200
+ }
201
+ assert.deepEqual(faults, []);
202
+ await ctx.close();
203
+ }
204
+ }
205
+ } finally {
206
+ if (browser) await browser.close();
207
+ server.kill();
208
+ fs.rmSync(serverRoot, { recursive: true, force: true });
209
+ }
210
+ }
211
+
212
+ module.exports = { resolveServeScript, runBakePublishCheck };
@@ -0,0 +1,148 @@
1
+ // Generic published-build freshness and live-renewal checks built on a Roamwright page driver:
2
+ // - `runFreshnessCheck`: verifies a newer published `version.json` informs an active world once without reloading,
3
+ // while reloading immediately on the title screen.
4
+ // - `runRenewalCheck`: verifies a page that learns of a newer build renews in place at the visitor's position without
5
+ // triggering a second renewal loop.
6
+ //
7
+ // const { runFreshnessCheck, runRenewalCheck } = require('roamwright/tools/build-freshness.cjs');
8
+ 'use strict';
9
+
10
+ /**
11
+ * Tests build-freshness notifications in the active world and automatic reload on the title screen.
12
+ *
13
+ * @param {object} driver Page driver from `createPageDriver`.
14
+ * @param {object} [options]
15
+ * @param {string} [options.address=''] Relative route address to test in-world freshness.
16
+ * @param {string} [options.titleId='t-enter'] Title-screen wrapper element id.
17
+ * @param {string} [options.toastPattern='newer build'] Substring/regex pattern matched on the toast text.
18
+ * @returns {Promise<void>}
19
+ */
20
+ async function runFreshnessCheck(driver, { address = '', titleId = 't-enter', toastPattern = 'newer build' } = {}) {
21
+ const { chromium, shell, BASE, GPU, debug, applyStorage, closeBrowser } = driver;
22
+ const browser = await chromium.launch({ executablePath: shell, ...GPU });
23
+ try {
24
+ const ctx = await browser.newContext({ viewport: { width: 1200, height: 700 } });
25
+ await applyStorage(ctx, { muted: '1' });
26
+ const page = await ctx.newPage();
27
+ let loads = 0;
28
+ let out = false;
29
+ page.on('load', () => loads++);
30
+ page.on('pageerror', e => console.log('PAGE ERROR', e.message.slice(0, 300)));
31
+ await ctx.route('**/version.json*', route =>
32
+ out ? route.fulfill({ contentType: 'application/json', body: '{"build":"ffffffffff"}' }) : route.continue(),
33
+ );
34
+ const titled = () => page.waitForFunction(id => !document.getElementById(id)?.hidden, titleId, { timeout: 120000 });
35
+ const back = () => page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')));
36
+ const toast = () =>
37
+ page.evaluate(pattern => {
38
+ const re = new RegExp(pattern);
39
+ return (
40
+ [...document.querySelectorAll('body *')]
41
+ .filter(e => !e.children.length && re.test(e.textContent))
42
+ .map(e => e.textContent.trim())[0] || null
43
+ );
44
+ }, toastPattern);
45
+
46
+ await page.goto(BASE + address, { waitUntil: 'domcontentloaded' });
47
+ await page.waitForFunction(d => window[d]?.state?.mode === 'play', debug, { timeout: 180000 });
48
+ await page.waitForTimeout(3000);
49
+ const before = loads;
50
+ out = true;
51
+ await back();
52
+ await page.waitForTimeout(2500);
53
+ const line = await toast();
54
+ await page.waitForTimeout(6000);
55
+ await back();
56
+ await page.waitForTimeout(4000);
57
+ console.log(
58
+ 'in the world',
59
+ JSON.stringify({ reloads: loads - before, mode: await page.evaluate(d => window[d].state.mode, debug), told: line }),
60
+ );
61
+
62
+ out = false;
63
+ await page.goto(BASE, { waitUntil: 'domcontentloaded' });
64
+ await titled();
65
+ const atTitle = loads;
66
+ out = true;
67
+ await back();
68
+ await page.waitForTimeout(6000);
69
+ await titled();
70
+ console.log('on the title page', JSON.stringify({ reloads: loads - atTitle }));
71
+ } finally {
72
+ await closeBrowser(browser);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Tests that an open page encountering a new `version.json` build renews in place at the player's position and does not loop.
78
+ *
79
+ * @param {object} driver Page driver from `createPageDriver`.
80
+ * @param {object} [options]
81
+ * @param {string} [options.placeKey=''] Optional key on `window[debug].P` to anchor the test move before renewal.
82
+ * @param {number} [options.dx=60] East offset in metres applied before triggering renewal.
83
+ * @param {number} [options.dz=40] South offset in metres applied before triggering renewal.
84
+ * @param {number} [options.yaw=1.2] Facing angle in radians set before renewal.
85
+ * @param {string} [options.renewedKey] sessionStorage key holding the renewed build id (default: `<storagePrefix>:renewed`).
86
+ * @param {string} [options.busyClass='crossing-busy'] Body class present while renewal crossing is in progress.
87
+ * @returns {Promise<void>}
88
+ */
89
+ async function runRenewalCheck(driver, { placeKey = '', dx = 60, dz = 40, yaw = 1.2, renewedKey, busyClass = 'crossing-busy' } = {}) {
90
+ const { chromium, shell, BASE, GPU, debug, storagePrefix, enter } = driver;
91
+ const sessionKey = renewedKey || `${storagePrefix}:renewed`;
92
+ const browser = await chromium.launch({ executablePath: shell, ...GPU });
93
+ try {
94
+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });
95
+ page.on('pageerror', e => console.log('PAGE ERROR', e.message.slice(0, 300)));
96
+ await enter(page, BASE);
97
+ await page.waitForTimeout(3500);
98
+ const before = await page.evaluate(
99
+ ({ d, key, ox, oz, heading }) => {
100
+ const app = window[d];
101
+ const anchor = key && app.P?.[key] ? app.P[key] : app.player;
102
+ app.placePlayer(anchor.x + ox, anchor.z + oz, heading);
103
+ const real = window.fetch;
104
+ window.fetch = (u, o) =>
105
+ String(u).includes('version.json') ? Promise.resolve(new Response('{"build":"feedfacecafe"}')) : real(u, o);
106
+ document.dispatchEvent(new Event('visibilitychange'));
107
+ return {
108
+ x: Math.round(app.player.x),
109
+ z: Math.round(app.player.z),
110
+ script: document.querySelector('script[type=module]').src.split('/').slice(-2).join('/'),
111
+ };
112
+ },
113
+ { d: debug, key: placeKey, ox: dx, oz: dz, heading: yaw },
114
+ );
115
+ console.log('before', JSON.stringify(before));
116
+ await page.waitForTimeout(3000);
117
+ await page.waitForFunction(
118
+ ([d, busy]) => window[d] && window[d].state.mode === 'play' && !document.body.classList.contains(busy),
119
+ [debug, busyClass],
120
+ { timeout: 120000 },
121
+ );
122
+ await page.waitForTimeout(6000);
123
+ console.log(
124
+ 'after',
125
+ JSON.stringify(
126
+ await page.evaluate(
127
+ ([d, sKey]) => ({
128
+ x: Math.round(window[d].player.x),
129
+ z: Math.round(window[d].player.z),
130
+ mode: window[d].state.mode,
131
+ renewedFor: sessionStorage.getItem(sKey),
132
+ loads: performance.getEntriesByType('navigation')[0].type,
133
+ }),
134
+ [debug, sessionKey],
135
+ ),
136
+ ),
137
+ );
138
+ await page.waitForTimeout(8000);
139
+ console.log(
140
+ 'no second renewal',
141
+ JSON.stringify(await page.evaluate(d => ({ mode: window[d].state.mode, x: Math.round(window[d].player.x) }), debug)),
142
+ );
143
+ } finally {
144
+ await browser.close();
145
+ }
146
+ }
147
+
148
+ module.exports = { runFreshnessCheck, runRenewalCheck };
@@ -0,0 +1,61 @@
1
+ #!/bin/sh
2
+ # Generic photo-statistics look guard runner: dispatches a world's look-guard capture script through its runner,
3
+ # then compares the resulting look.yaml against the world's YAML baseline (or updates it with `keep`).
4
+ # Configured by LOOK_* environment variables passed by a world's thin wrapper script.
5
+ #
6
+ # sh look-guard.sh [keep | --strict | compare <reference-URL>] [--land=<id>] [--only=<substr>] [--lands-only | --scenes-only]
7
+ set -eu
8
+ NAME="${LOOK_NAME:-look-guard}"
9
+ TOOLS="${LOOK_TOOLS_DIR:?LOOK_TOOLS_DIR is required}"
10
+ ROOT="${LOOK_ROOT:?LOOK_ROOT is required}"
11
+ REPO="${LOOK_REPO:-$ROOT}"
12
+ SLOT="${LOOK_SLOT:-look-guard}"
13
+ PORT="${LOOK_PORT:-8798}"
14
+ OUT="${LOOK_OUT:?LOOK_OUT is required}"
15
+ RUNNER="${LOOK_RUNNER:-$TOOLS/runner.sh}"
16
+ PREFIX="${LOOK_RUNNER_PREFIX:-RUNNER}"
17
+ MEASURE_SCRIPT="${LOOK_MEASURE_SCRIPT:-look-guard.cjs}"
18
+ COMPARE_SCRIPT="${LOOK_COMPARE_SCRIPT:-$TOOLS/look-guard-compare.cjs}"
19
+ BASELINE="${LOOK_BASELINE:-$TOOLS/look-baseline.yaml}"
20
+
21
+ MODE=""
22
+ BASE2="${LOOK_BASE2:-}"
23
+ FILTERS=""
24
+
25
+ while [ "$#" -gt 0 ]; do
26
+ case "$1" in
27
+ keep | --strict)
28
+ MODE="$1"
29
+ shift
30
+ ;;
31
+ compare)
32
+ [ "$#" -ge 2 ] || {
33
+ echo "usage: $NAME.sh compare <reference-URL> [--land=<id>] [--only=<substr>]" >&2
34
+ exit 2
35
+ }
36
+ BASE2="$2"
37
+ shift 2
38
+ ;;
39
+ --land=* | --only=* | --lands-only | --scenes-only)
40
+ FILTERS="$FILTERS $1"
41
+ shift
42
+ ;;
43
+ *)
44
+ echo "usage: $NAME.sh [keep | --strict | compare <reference-URL>] [--land=<id>] [--only=<substr>] [--lands-only | --scenes-only]" >&2
45
+ exit 2
46
+ ;;
47
+ esac
48
+ done
49
+
50
+ COMMIT="$(git -C "$REPO" log -1 --format=%h)$([ -n "$(git -C "$REPO" status --porcelain src)" ] && echo '+uncommitted' || true)"
51
+
52
+ # shellcheck disable=SC2086
53
+ env \
54
+ "${PREFIX}_KIND=look" \
55
+ "${PREFIX}_SLOT=$SLOT" \
56
+ "${PREFIX}_PORT=$PORT" \
57
+ "${PREFIX}_REPO=$REPO" \
58
+ "${PREFIX}_BASE2=$BASE2" \
59
+ "$RUNNER" "$MEASURE_SCRIPT" "$COMMIT" $FILTERS
60
+
61
+ node "$COMPARE_SCRIPT" "$OUT/look.yaml" "$BASELINE" "$MODE"