// Small process helpers: run a command and collect its output (never throws), // run async work with limited concurrency, and open a visible console window. const { execFile, spawn } = require('child_process') const fs = require('fs') const path = require('path') const RUN_DIR = path.join(__dirname, '..', '.cache', 'run') function run(cmd, args, opts = {}) { return new Promise((resolve) => { execFile(cmd, args, { encoding: 'utf-8', timeout: opts.timeout ?? 5000, windowsHide: true, maxBuffer: 64 * 1024 * 1024, cwd: opts.cwd, env: opts.env, }, (err, stdout, stderr) => resolve({ ok: !err, code: err ? (typeof err.code === 'number' ? err.code : -1) : 0, stdout: stdout ?? '', stderr: stderr ?? '', })) }) } async function pool(items, size, fn) { const out = new Array(items.length) let next = 0 const workers = Array.from({ length: Math.min(size, items.length) }, async () => { while (next < items.length) { const i = next++ out[i] = await fn(items[i], i) } }) await Promise.all(workers) return out } // Paths end up quoted inside a .cmd file ("cd /d """), so they must not // contain quotes, % (variable expansion) or line breaks. function assertSafe(s) { if (/["%\r\n]/.test(s)) throw new Error(`unsupported character in: ${s}`) } // Opens a new, visible cmd window in `cwd` that runs `command` and stays open. // The command is written into a small .cmd file, so no shell quoting through // spawn is needed. `echo on` makes cmd print the command before it runs. // Commands may contain quotes (call "x.bat", py "main.py"); a line break is // refused, and % is doubled so file names with % stay literal – except for // the user's own start command (raw), where %VAR% may be meant. function openConsole(title, cwd, command, { raw = false } = {}) { assertSafe(cwd) if (/[\r\n]/.test(command)) throw new Error('Zeilenumbruch im Befehl') if (!raw) command = command.replace(/%/g, '%%') fs.mkdirSync(RUN_DIR, { recursive: true }) const slug = title.replace(/[^\w.-]+/g, '_').slice(0, 60) const file = path.join(RUN_DIR, `${slug}.cmd`) const safeTitle = title.replace(/[^\w .:-]+/g, ' ') fs.writeFileSync(file, [ '@echo off', `title ${safeTitle}`, `cd /d "${cwd}"`, 'echo on', command, '', ].join('\r\n')) spawn('cmd.exe', ['/c', `start "" cmd /k "${file}"`], { windowsVerbatimArguments: true, detached: true, stdio: 'ignore', }).unref() } // Starts a GUI program / opens a file with its default app, detached. // A start error (file gone, no permission) must not crash the server: without an // 'error' listener Node throws it as an uncaught exception. function openDetached(exe, args = [], cwd) { const child = spawn(exe, args, { detached: true, stdio: 'ignore', cwd }) child.on('error', (e) => console.error(`start failed: ${exe}: ${e.message}`)) child.unref() } module.exports = { run, pool, openConsole, openDetached, assertSafe }