229 lines
10 KiB
TypeScript
229 lines
10 KiB
TypeScript
/**
|
|
* The garden in a BUILT app, on a real machine or device (tauri-platforms.md §5): it opens,
|
|
* she is watered, the app is closed and opened again, and she is still watered. Also measured
|
|
* on the way: the origin, that there is no service worker, what `persisted()` answers, that no
|
|
* request leaves the origin and no CSP violation is reported, and what *Save her to a file* does.
|
|
*
|
|
* tsx e2e/apps/check-garden.ts desktop [path-to-exe]
|
|
* tsx e2e/apps/check-garden.ts android [device-serial]
|
|
*
|
|
* Desktop: runs the release `.exe` with its WebView2 data in a fresh temporary folder (never the
|
|
* player's own) and its DevTools port on 127.0.0.1 only (CLAUDE.md §5.7), through WebView2's own
|
|
* environment variables. Those replace the app's `additionalBrowserArgs` for this run, so this
|
|
* check says nothing about WebView2's own traffic (G-T6).
|
|
* Android: the installed debug APK (`adb install -r`), driven through Playwright's Android support
|
|
* over adb; its data is cleared first with `pm clear` (it is the test app, not a player's).
|
|
* Every app it starts is stopped in `finally`.
|
|
*/
|
|
import { expect, _android as android, chromium, type Page } from '@playwright/test';
|
|
import { PRODUCT_NAME } from '@rosea/schema';
|
|
import { en } from '@rosea/ui/copy';
|
|
import { openRing, pastGardener } from '../garden.js';
|
|
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
|
|
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join, resolve } from 'node:path';
|
|
import { storedCare } from '../stored.js';
|
|
|
|
const PACKAGE_ID = 'cz.mareknovak.domi.rosea';
|
|
const report: Record<string, unknown> = {};
|
|
|
|
/** Requests that leave the game's origin, and CSP violations, from now on. */
|
|
function watch(page: Page): { outside: string[]; csp: string[]; errors: string[] } {
|
|
const seen = { outside: [] as string[], csp: [] as string[], errors: [] as string[] };
|
|
const origin = new URL(page.url()).origin;
|
|
page.on('request', (r) => {
|
|
const url = r.url();
|
|
if (!url.startsWith(origin + '/') && !url.startsWith('data:') && !url.startsWith('blob:')) seen.outside.push(url);
|
|
});
|
|
page.on('console', (m) => {
|
|
if (m.type() !== 'error') return;
|
|
if (/Content Security Policy/i.test(m.text())) seen.csp.push(m.text());
|
|
else seen.errors.push(m.text());
|
|
});
|
|
return seen;
|
|
}
|
|
|
|
async function garden(page: Page): Promise<void> {
|
|
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME, { timeout: 20_000 });
|
|
}
|
|
|
|
/** The first visit: the first gardener, skip the town (no town is the private choice), water her from the ring, wait for the write. */
|
|
async function firstVisit(page: Page): Promise<void> {
|
|
await garden(page);
|
|
const seen = watch(page);
|
|
await page.reload();
|
|
await garden(page);
|
|
report['origin'] = await page.evaluate(() => location.origin);
|
|
report['serviceWorkers'] = await page.evaluate(async () =>
|
|
'serviceWorker' in navigator ? (await navigator.serviceWorker.getRegistrations()).length : 'no API'
|
|
);
|
|
report['manifestLink'] = await page.evaluate(() => document.querySelector('link[rel="manifest"]') !== null);
|
|
report['cspMeta'] = await page.evaluate(() => document.querySelector('meta[http-equiv="Content-Security-Policy"]') !== null);
|
|
|
|
await pastGardener(page);
|
|
const skip = page.getByRole('button', { name: /^Not now/ });
|
|
if (await skip.isVisible().catch(() => false)) await skip.click();
|
|
|
|
await openRing(page);
|
|
const water = page.getByRole('button', { name: en.rose.water });
|
|
await expect(water).toBeVisible();
|
|
const box = await water.boundingBox();
|
|
if (!box) throw new Error('the Water button has no box');
|
|
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
|
await page.mouse.down();
|
|
await page.waitForTimeout(1500);
|
|
await page.mouse.up();
|
|
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
|
|
await storedCare(page, 1);
|
|
report['persistedAfterCare'] = await page.evaluate(async () => (navigator.storage?.persisted ? navigator.storage.persisted() : 'no API'));
|
|
report['firstVisit'] = { outside: seen.outside, csp: seen.csp, errors: seen.errors };
|
|
}
|
|
|
|
/** After the app was closed and opened again: she is still watered. */
|
|
async function secondVisit(page: Page): Promise<void> {
|
|
await garden(page);
|
|
// By keyboard: on the tablet a pointer click once waited 30 s for the button to stop moving
|
|
// while the garden animated (review). Enter is a real activation, as for a keyboard player.
|
|
const numbers = page.getByRole('button', { name: en.rose.numbers });
|
|
await numbers.focus();
|
|
await numbers.press('Enter');
|
|
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
|
|
await storedCare(page, 1);
|
|
report['afterRestart'] = 'still watered: 1 day of care, the care log kept';
|
|
}
|
|
|
|
/** What *Save her to a file* does here (G-T4): a download event, or nothing. */
|
|
async function trySave(page: Page): Promise<void> {
|
|
const title = page.getByRole('button', { name: en.rose.safe.title });
|
|
if (!(await title.isVisible().catch(() => false))) {
|
|
report['saveToFile'] = 'Keep her safe not visible';
|
|
return;
|
|
}
|
|
await title.click();
|
|
const save = page.getByRole('button', { name: en.rose.safe.save });
|
|
await expect(save).toBeVisible();
|
|
const download = page.waitForEvent('download', { timeout: 5_000 }).then(
|
|
async (d) => {
|
|
await d.cancel();
|
|
return `a download started: ${d.suggestedFilename()} (cancelled by the check)`;
|
|
},
|
|
() => 'nothing happened within 5 s'
|
|
);
|
|
await save.click();
|
|
report['saveToFile'] = await download;
|
|
}
|
|
|
|
async function desktop(exe: string): Promise<void> {
|
|
if (!existsSync(exe)) throw new Error(`no app at ${exe}; run pnpm tauri:build first`);
|
|
const data = mkdtempSync(join(tmpdir(), 'rosea-desktop-check-'));
|
|
const port = 9333;
|
|
const env = {
|
|
...process.env,
|
|
WEBVIEW2_USER_DATA_FOLDER: data,
|
|
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port} --remote-debugging-address=127.0.0.1`
|
|
};
|
|
const start = (): ChildProcess => spawn(exe, [], { env, stdio: 'ignore' });
|
|
const attach = async (): Promise<{ page: Page; close: () => Promise<void> }> => {
|
|
for (let i = 0; i < 60; i++) {
|
|
try {
|
|
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
|
|
for (let j = 0; j < 40; j++) {
|
|
const page = browser.contexts().flatMap((c) => c.pages())[0];
|
|
if (page) return { page, close: () => browser.close() };
|
|
await new Promise((r) => setTimeout(r, 250));
|
|
}
|
|
await browser.close();
|
|
} catch {
|
|
// Not listening yet: the app is still starting. Tried again below; a real failure ends in the throw.
|
|
}
|
|
await new Promise((r) => setTimeout(r, 500));
|
|
}
|
|
throw new Error('the app never opened a page on the debugging port');
|
|
};
|
|
let app: ChildProcess | undefined;
|
|
try {
|
|
app = start();
|
|
let session = await attach();
|
|
await firstVisit(session.page);
|
|
await session.close();
|
|
app.kill();
|
|
await new Promise((r) => setTimeout(r, 1500));
|
|
|
|
app = start();
|
|
session = await attach();
|
|
await secondVisit(session.page);
|
|
await trySave(session.page);
|
|
await session.close();
|
|
report['dataFolder'] = data;
|
|
} finally {
|
|
app?.kill();
|
|
await new Promise((r) => setTimeout(r, 1000));
|
|
rmSync(data, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 });
|
|
}
|
|
}
|
|
|
|
async function androidDevice(serial: string | undefined): Promise<void> {
|
|
// The USB link to a real tablet drops now and then ("device offline"); a dropped link is waited
|
|
// for and the command tried again, up to three times. A command that fails for another reason
|
|
// fails the check at once.
|
|
const adb = (...args: string[]): string => {
|
|
const target = serial ? ['-s', serial] : [];
|
|
for (let attempt = 1; ; attempt++) {
|
|
const r = spawnSync('adb', [...target, ...args], { encoding: 'utf8' });
|
|
if (r.status === 0) return r.stdout;
|
|
const dropped = /offline|closed|not found|no devices/i.test(r.stderr);
|
|
if (!dropped || attempt === 3) throw new Error(`adb ${args.join(' ')} failed: ${r.stderr}`);
|
|
spawnSync('adb', [...target, 'wait-for-device'], { timeout: 30_000 });
|
|
}
|
|
};
|
|
// Playwright's handle to the device dies with the link, so it is found again for each visit.
|
|
const open = async (): Promise<{ page: Page; close: () => Promise<void> }> => {
|
|
adb('wait-for-device');
|
|
const devices = await android.devices();
|
|
const device = serial ? devices.find((d) => d.serial() === serial) : devices[0];
|
|
if (!device) throw new Error('no Android device over adb');
|
|
report['device'] = `${device.model()} (${device.serial()})`;
|
|
adb('shell', 'monkey', '-p', PACKAGE_ID, '-c', 'android.intent.category.LAUNCHER', '1');
|
|
const webView = await device.webView({ pkg: PACKAGE_ID }, { timeout: 30_000 });
|
|
return { page: await webView.page(), close: () => device.close() };
|
|
};
|
|
const dump = adb('shell', 'dumpsys', 'package', PACKAGE_ID);
|
|
if (!dump.includes(`Package [${PACKAGE_ID}]`)) throw new Error(`${PACKAGE_ID} is not installed; adb install -r <apk>`);
|
|
report['internetPermission'] = /android\.permission\.INTERNET/.test(dump);
|
|
report['allowBackupFlag'] = /flags=\[[^\]]*ALLOW_BACKUP/.test(dump);
|
|
let session: { page: Page; close: () => Promise<void> } | undefined;
|
|
try {
|
|
adb('shell', 'pm', 'clear', PACKAGE_ID);
|
|
session = await open();
|
|
await firstVisit(session.page);
|
|
await session.close();
|
|
|
|
adb('shell', 'am', 'force-stop', PACKAGE_ID);
|
|
await new Promise((r) => setTimeout(r, 1500));
|
|
session = await open();
|
|
await secondVisit(session.page);
|
|
await trySave(session.page);
|
|
} finally {
|
|
adb('shell', 'am', 'force-stop', PACKAGE_ID);
|
|
await session?.close().catch((error: unknown) => console.error('check-garden: closing the device handle failed', error));
|
|
}
|
|
}
|
|
|
|
const [target, arg] = process.argv.slice(2);
|
|
try {
|
|
if (target === 'desktop') {
|
|
await desktop(resolve(arg ?? 'apps/rosea-tauri/src-tauri/target/release/rosea-shell.exe'));
|
|
} else if (target === 'android') {
|
|
await androidDevice(arg);
|
|
} else {
|
|
throw new Error('usage: check-garden.ts desktop [exe] | android [serial]');
|
|
}
|
|
console.log(JSON.stringify(report, null, 2));
|
|
console.log(`check-garden ${target}: PASSED`);
|
|
} catch (error) {
|
|
console.log(JSON.stringify(report, null, 2));
|
|
console.error(`check-garden ${target}: FAILED — ${(error as Error).message}`);
|
|
process.exitCode = 1;
|
|
}
|