import { spawn } from 'node:child_process'; import { chromium } from 'playwright'; const targetUrl = process.env.VERIFY_URL ?? 'http://localhost:5173/'; let serverProcess; let browser; try { serverProcess = await ensureLocalServer(targetUrl); browser = await chromium.launch({ headless: true }); const page = await browser.newPage({ viewport: { width: 1280, height: 720 } }); await page.goto(targetUrl, { waitUntil: 'networkidle' }); await page.evaluate(() => window.localStorage.clear()); await page.reload({ waitUntil: 'networkidle' }); await page.waitForSelector('canvas'); await page.waitForFunction(() => window.__HEROS_GAME__ !== undefined); await page.waitForFunction(() => window.__HEROS_DEBUG__ !== undefined); await page.waitForTimeout(500); const debugBeforeBattle = await page.evaluate(() => window.__HEROS_DEBUG__?.activeScenes() ?? []); if (!debugBeforeBattle.includes('TitleScene')) { throw new Error(`Expected TitleScene before starting. Active scenes: ${debugBeforeBattle.join(', ')}`); } await page.mouse.click(962, 240); await page.waitForTimeout(250); for (let i = 0; i < 20; i += 1) { const isBattleActive = await page.evaluate(() => { const activeScenes = window.__HEROS_GAME__?.scene.getScenes(true) ?? []; return activeScenes.some((scene) => scene.scene.key === 'BattleScene'); }); if (isBattleActive) { break; } await page.keyboard.press('Space'); await page.waitForTimeout(220); } await page.waitForFunction(() => { const activeScenes = window.__HEROS_GAME__?.scene.getScenes(true) ?? []; return activeScenes.some((scene) => scene.scene.key === 'BattleScene'); }); await page.keyboard.press('F9'); await page.waitForTimeout(100); await page.screenshot({ path: 'dist/verification-battle.png', fullPage: true }); const result = await page.evaluate(() => { const canvas = document.querySelector('canvas'); const activeScenes = window.__HEROS_DEBUG__?.activeScenes() ?? []; const battleState = window.__HEROS_DEBUG__?.battle(); return { activeScenes, battleState, canvasWidth: canvas?.width ?? 0, canvasHeight: canvas?.height ?? 0 }; }); if (result.canvasWidth !== 1280 || result.canvasHeight !== 720) { throw new Error(`Unexpected canvas size: ${result.canvasWidth}x${result.canvasHeight}`); } if (!result.activeScenes.includes('BattleScene')) { throw new Error(`BattleScene was not active. Active scenes: ${result.activeScenes.join(', ')}`); } if (!result.battleState || result.battleState.scene !== 'BattleScene') { throw new Error(`Debug battle state was not available: ${JSON.stringify(result.battleState)}`); } if (result.battleState.battleId !== 'first-battle-zhuo-commandery') { throw new Error(`Expected first battle scenario id: ${JSON.stringify(result.battleState)}`); } const actionTexturesLoaded = await page.evaluate(() => { const textures = window.__HEROS_GAME__?.textures; return [ 'unit-liu-bei-actions', 'unit-guan-yu-actions', 'unit-zhang-fei-actions', 'unit-rebel-actions', 'unit-rebel-archer-actions', 'unit-rebel-cavalry-actions', 'unit-rebel-leader-actions' ].every((key) => textures?.exists(key)); }); if (!actionTexturesLoaded) { throw new Error('Expected all unit action textures to be loaded.'); } await page.waitForTimeout(700); await page.mouse.click(260, 300, { button: 'right' }); await page.waitForTimeout(120); await page.mouse.click(182, 213); await page.waitForTimeout(120); await page.mouse.click(400, 213); await page.waitForTimeout(180); const battleSlotSave = await page.evaluate(() => { const raw = window.localStorage.getItem('heros-web:battle:first-battle-zhuo-commandery:slot-1'); return raw ? JSON.parse(raw) : undefined; }); if (!battleSlotSave || battleSlotSave.battleId !== 'first-battle-zhuo-commandery') { throw new Error(`Expected slot 1 battle save from save UI: ${JSON.stringify(battleSlotSave)}`); } await page.mouse.click(260, 300, { button: 'right' }); await page.waitForTimeout(120); await page.mouse.click(182, 247); await page.waitForTimeout(120); await page.mouse.click(400, 213); await page.waitForFunction(() => window.__HEROS_DEBUG__?.battle()?.scene === 'BattleScene'); const cameraBeforeScroll = result.battleState.camera; if ( !cameraBeforeScroll || cameraBeforeScroll.mapWidth <= cameraBeforeScroll.visibleColumns || cameraBeforeScroll.mapHeight <= cameraBeforeScroll.visibleRows ) { throw new Error(`Expected a scrollable battle map: ${JSON.stringify(cameraBeforeScroll)}`); } await page.mouse.move(872, 360); await page.waitForTimeout(520); const cameraAfterEdgeScroll = await page.evaluate(() => window.__HEROS_DEBUG__?.battle()?.camera); if (!cameraAfterEdgeScroll || cameraAfterEdgeScroll.x <= cameraBeforeScroll.x) { throw new Error(`Expected edge scrolling to move camera right: ${JSON.stringify({ cameraBeforeScroll, cameraAfterEdgeScroll })}`); } await page.mouse.click(1138, 553); await page.waitForTimeout(160); const cameraAfterMiniMapClick = await page.evaluate(() => window.__HEROS_DEBUG__?.battle()?.camera); if ( !cameraAfterMiniMapClick || cameraAfterMiniMapClick.x < cameraAfterMiniMapClick.mapWidth - cameraAfterMiniMapClick.visibleColumns || cameraAfterMiniMapClick.y !== 0 ) { throw new Error(`Expected minimap click to move camera to the northeast: ${JSON.stringify(cameraAfterMiniMapClick)}`); } const readyUnits = result.battleState.units.filter((unit) => !unit.acted); if (!readyUnits.some((unit) => unit.animating && unit.animationKey?.includes('-idle-'))) { throw new Error(`Expected ready units to loop idle frames: ${JSON.stringify(readyUnits)}`); } await page.keyboard.press('F9'); await page.waitForTimeout(100); await page.evaluate(() => window.__HEROS_DEBUG__?.forceBattleOutcome('victory')); await page.waitForFunction(() => { const state = window.__HEROS_DEBUG__?.battle(); return state?.battleOutcome === 'victory' && state?.phase === 'resolved' && state?.resultVisible === true; }); const victoryState = await page.evaluate(() => window.__HEROS_DEBUG__?.battle()); const livingEnemiesAfterVictory = victoryState.units.filter((unit) => unit.faction === 'enemy' && unit.hp > 0); if (livingEnemiesAfterVictory.length > 0) { throw new Error(`Expected no living enemies after forced victory: ${JSON.stringify(livingEnemiesAfterVictory)}`); } await page.screenshot({ path: 'dist/verification-battle-result-victory.png', fullPage: true }); await page.mouse.click(738, 642); await page.waitForFunction(() => { const activeScenes = window.__HEROS_DEBUG__?.activeScenes() ?? []; return activeScenes.includes('CampScene'); }); await page.screenshot({ path: 'dist/verification-camp.png', fullPage: true }); const campState = await page.evaluate(() => window.__HEROS_DEBUG__?.camp()); if (!campState || campState.scene !== 'CampScene' || campState.report?.rewardGold <= 0) { throw new Error(`Expected CampScene report after victory: ${JSON.stringify(campState)}`); } await page.mouse.click(830, 38); await page.waitForTimeout(120); await page.mouse.click(974, 482); await page.waitForTimeout(260); const campStateAfterDialogue = await page.evaluate(() => window.__HEROS_DEBUG__?.camp()); if (!campStateAfterDialogue.report?.completedCampDialogues?.length) { throw new Error(`Expected camp dialogue to award bond exp: ${JSON.stringify(campStateAfterDialogue)}`); } const campaignSaveAfterDialogue = await page.evaluate(() => { const raw = window.localStorage.getItem('heros-web:campaign-state'); return raw ? JSON.parse(raw) : undefined; }); if ( !campaignSaveAfterDialogue || campaignSaveAfterDialogue.step !== 'first-camp' || campaignSaveAfterDialogue.latestBattleId !== 'first-battle-zhuo-commandery' || !campaignSaveAfterDialogue.battleHistory?.['first-battle-zhuo-commandery'] || !campaignSaveAfterDialogue.completedCampDialogues?.length || Object.keys(campaignSaveAfterDialogue.inventory ?? {}).length === 0 ) { throw new Error(`Expected campaign save to persist camp progress: ${JSON.stringify(campaignSaveAfterDialogue)}`); } const campaignSlotAfterDialogue = await page.evaluate(() => { const raw = window.localStorage.getItem('heros-web:campaign-state:slot-1'); return raw ? JSON.parse(raw) : undefined; }); if (!campaignSlotAfterDialogue || campaignSlotAfterDialogue.latestBattleId !== 'first-battle-zhuo-commandery') { throw new Error(`Expected campaign slot 1 to persist progress: ${JSON.stringify(campaignSlotAfterDialogue)}`); } await page.evaluate(() => window.__HEROS_GAME__?.scene.start('TitleScene')); await page.waitForFunction(() => { const activeScenes = window.__HEROS_DEBUG__?.activeScenes() ?? []; return activeScenes.includes('TitleScene'); }); await page.mouse.click(962, 310); await page.waitForFunction(() => { const activeScenes = window.__HEROS_DEBUG__?.activeScenes() ?? []; return activeScenes.includes('CampScene'); }); await page.evaluate(() => window.__HEROS_DEBUG__?.goToBattle()); await page.waitForFunction(() => { const state = window.__HEROS_DEBUG__?.battle(); return state?.scene === 'BattleScene' && state?.battleOutcome === null && state?.phase === 'idle'; }); await page.evaluate(() => window.__HEROS_DEBUG__?.forceBattleOutcome('defeat')); await page.waitForFunction(() => { const state = window.__HEROS_DEBUG__?.battle(); return state?.battleOutcome === 'defeat' && state?.phase === 'resolved' && state?.resultVisible === true; }); const defeatState = await page.evaluate(() => window.__HEROS_DEBUG__?.battle()); const liuBei = defeatState.units.find((unit) => unit.id === 'liu-bei'); if (!liuBei || liuBei.hp > 0) { throw new Error(`Expected Liu Bei to be defeated after forced defeat: ${JSON.stringify(liuBei)}`); } console.log(`Verified title-to-battle flow, result states, and debug API at ${targetUrl}`); } finally { await browser?.close(); if (serverProcess && !serverProcess.killed) { serverProcess.kill(); } } async function ensureLocalServer(url) { if (await canReach(url)) { return undefined; } const parsed = new URL(url); const isLocal = ['localhost', '127.0.0.1', '0.0.0.0'].includes(parsed.hostname); if (!isLocal) { throw new Error(`No server responded at ${url}`); } const stderr = []; const child = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', parsed.port || '5173'], { cwd: process.cwd(), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] }); child.stderr.on('data', (chunk) => stderr.push(chunk.toString())); child.stdout.on('data', () => {}); for (let i = 0; i < 80; i += 1) { if (await canReach(url)) { return child; } await delay(250); } child.kill(); throw new Error(`Vite server did not start at ${url}\n${stderr.join('')}`); } async function canReach(url) { try { const response = await fetch(url, { signal: AbortSignal.timeout(1000) }); return response.ok; } catch { return false; } } function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }