import { execFile, spawn } from "node:child_process"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { expect, it } from "vitest"; // Vitest resolves CommonJS packages differently than Node's ESM loader, so only the // real production bundle shows whether externals like ssh2 import correctly. const serverDir = path.resolve(__dirname, ".."); async function freePort() { const probe = createServer(); await new Promise(resolve => probe.listen(0, "127.0.0.1", resolve)); const { port } = probe.address() as { port: number }; await new Promise(resolve => probe.close(resolve)); return port; } it("starts the production bundle with Node and answers the health check", async () => { const outdir = await mkdtemp(path.join(serverDir, ".bundle-test-")); const work = await mkdtemp(path.join(tmpdir(), "shellbook-bundle-")); try { const { scripts } = JSON.parse(await readFile(path.join(serverDir, "package.json"), "utf8")) as { scripts: { build: string } }; const args = scripts.build.split(" ").slice(1).map(arg => arg.startsWith("--outdir=") ? `--outdir=${outdir}` : arg); await promisify(execFile)(path.join(serverDir, "node_modules", ".bin", "esbuild"), args, { cwd: serverDir, shell: process.platform === "win32" }); const port = await freePort(); const child = spawn(process.execPath, [path.join(outdir, "main.js")], { cwd: serverDir, env: { ...process.env, SHELLBOOK_HOST: "127.0.0.1", SHELLBOOK_PORT: String(port), SHELLBOOK_WORKSPACE: path.join(work, "workspace"), SHELLBOOK_DATA_DIR: path.join(work, "data"), SHELLBOOK_SSH_KEY: path.join(work, "data", "id_ed25519") }, stdio: ["ignore", "ignore", "pipe"], }); let stderr = ""; child.stderr.on("data", chunk => { stderr += chunk; }); const exited = new Promise(resolve => child.on("exit", resolve)); try { const healthy = await Promise.race([ (async () => { for (let attempt = 0; attempt < 100; attempt++) { try { if ((await fetch(`http://127.0.0.1:${port}/api/health`)).ok) return true; } catch { /* not listening yet */ } await new Promise(r => setTimeout(r, 100)); } return false; })(), exited.then(code => { throw new Error(`Server exited with ${code}: ${stderr}`); }), ]); expect(healthy).toBe(true); } finally { child.kill(); await exited; } } finally { await rm(outdir, { recursive: true, force: true }); await rm(work, { recursive: true, force: true }); } }, 60_000);