import { execFile, spawn } from 'node:child_process'; import { join } from 'node:path'; import { promisify } from 'node:util'; import { GAME_FILES } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import offlineGameArguments from '@shared/offline-game-arguments.json'; import type { GameExit } from '@shared/schemas/launch.ts'; const execute = promisify(execFile); export async function gameProcessRunning(signal: AbortSignal): Promise { if (process.platform !== 'win32') return false; const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }); return /^"aces\.exe",/im.test(games.stdout); } export async function runGameProcess( copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void, ): Promise { if (await gameProcessRunning(signal)) throw new AppError('launch_game_running'); signal.throwIfAborted(); const child = spawn(join(copyPath, GAME_FILES.executable), [...offlineGameArguments, ...additionalArguments], { cwd: copyPath, shell: false, stdio: 'ignore', }); const stop = (): void => { child.kill(); }; try { return await new Promise((resolve, reject) => { child.once('spawn', () => { if (signal.aborted) stop(); else onStart(); }); child.once('error', (error) => { console.error('[game] process error:', error); reject(new AppError('launch_game_failed')); }); child.once('close', (code, reason) => { const logFolder = join(copyPath, '.game_logs'); if (code !== 0 && !signal.aborted) { console.warn('[game] process exited:', code ?? reason, logFolder); } resolve({ code, signal: reason, logFolder }); }); signal.addEventListener('abort', stop, { once: true }); }); } finally { signal.removeEventListener('abort', stop); } }