import { execFile } from 'node:child_process'; import { readFile } from 'node:fs/promises'; import { createServer } from 'node:net'; import { isAbsolute, join, relative } from 'node:path'; import { promisify } from 'node:util'; import { BrowserWindow, shell } from 'electron'; import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { LaunchState } from '@shared/schemas/launch.ts'; import { getSettings } from '../config/settings-store.ts'; import { readInstallRecord } from '../install/install-record.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; import { buildCopy } from './build-copy.ts'; import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts'; const execute = promisify(execFile); interface LaunchJob { readonly stop: AbortController; readonly report: (state: LaunchState) => void; done: Promise; } let active: LaunchJob | null = null; let state: LaunchState = { phase: 'ready' }; export function getLaunchState(): LaunchState { return state; } export function startLaunch(report: LaunchJob['report']): LaunchState { if (active) throw new AppError('launch_busy'); const job = { stop: new AbortController(), report, done: Promise.resolve() }; active = job; update(job, { phase: 'checking' }); job.done = launch(job).catch((error: unknown) => { const port = state.port; const context = port === undefined ? {} : { port }; if (job.stop.signal.aborted) { update(job, { phase: 'ready' }); return; } console.error('[launch] launch failed:', error); const code = error instanceof AppError ? error.code : 'launch_lab_failed'; switch (code) { case 'launch_port_busy': update(job, { phase: 'port-busy', ...context }); break; case 'launch_server_exited': update(job, { phase: 'server-exited', ...context }); break; default: update(job, { phase: 'failed', error: code, ...context }); break; } }).finally(() => { active = null; }); return state; } export function stopLaunch(): Promise | null { const job = active; if (!job) return null; if (!job.stop.signal.aborted) { update(job, { ...state, phase: 'stopping' }); job.stop.abort(); } return job.done; } export async function openServerStatus(): Promise { if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited'); await shell.openExternal(labStatusUrl(state.port)); } function update(job: LaunchJob, next: LaunchState): void { state = next; job.report(next); } async function launch(job: LaunchJob): Promise { const signal = job.stop.signal; const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); if (!record) throw new AppError('launch_no_copy'); if (!settings.developerMode) throw new AppError('launch_lab_required'); if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam'); const currentVersion = await readVersion(record.copyPath, signal); if (!currentVersion || currentVersion !== record.gameVersion) { update(job, { phase: 'version-changed', actualVersion: currentVersion }); return; } const lab = await readInstalledLab(); const stockPath = settings.labStockPath ?? record.stockBackupPath; const dataPath = settings.labDataPath ?? record.dataPath; if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); } const relativeData = relative(stockPath, dataPath); if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) { throw new AppError('launch_copy_in_steam'); } update(job, { phase: 'checking', port: lab.port }); const [labVersion, stockVersion, games] = await Promise.all([ readVersion(lab.copyPath, signal), readVersion(stockPath, signal), execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }), ]); signal.throwIfAborted(); if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version'); if (/^"aces\.exe",/im.test(games.stdout)) throw new AppError('launch_game_running'); await checkPort(lab.port); signal.throwIfAborted(); update(job, { phase: 'building', port: lab.port }); await buildCopy({ kind: 'build', stockPath, copyPath: lab.copyPath, dataPath, port: lab.port, ...resourcePaths(), acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), }, signal, (filesWritten, filesTotal, file) => { if (!signal.aborted) update(job, { phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), }); }); await runLab(lab, stockPath, dataPath, signal, (phase) => { if (!signal.aborted) update(job, { phase, port: lab.port }); if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') { for (const window of BrowserWindow.getAllWindows()) window.minimize(); } }); update(job, { phase: 'ready' }); } async function readVersion(folder: string, signal: AbortSignal): Promise { try { return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal })); } catch (error) { signal.throwIfAborted(); console.warn('[launch] reading the game version failed:', folder, error); return null; } } async function checkPort(port: number): Promise { await new Promise((resolve, reject) => { const listener = createServer(); listener.once('error', (error: NodeJS.ErrnoException) => reject( error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error, )); listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve())); }); }