import { spawnSync } from "node:child_process"; import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; let compiled: string | undefined; /** A real Windows executable: execFile/spawn intentionally cannot run .cmd shims. */ export function writeWindowsExecutable( directory: string, name: string, stdout: string, delayMs = 0, ): string { if (!compiled) { const root = mkdtempSync(join(tmpdir(), "pi-ext-windows-executable-")); const output = join(root, "fake-cli.exe"); const compiler = join( process.env["SystemRoot"] ?? "C:\\Windows", "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe", ); const result = spawnSync( compiler, [ "/nologo", "/target:exe", `/out:${output}`, fileURLToPath(new URL("../fixtures/fake-cli.cs", import.meta.url)), ], { encoding: "utf8", timeout: 15_000, windowsHide: true }, ); if (result.error || result.status !== 0) { rmSync(root, { recursive: true, force: true }); throw new Error( `Windows executable fixture compilation failed: ${result.error?.message ?? result.stderr ?? result.stdout}`, ); } compiled = output; process.once("exit", () => { rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100, }); }); } const output = join(directory, `${name}.exe`); copyFileSync(compiled, output); writeFileSync( `${output}.response`, `${delayMs}\n${Buffer.from(stdout).toString("base64")}\n`, ); return output; }