import { type ChildProcess, spawn } from "node:child_process"; import { createServer, createConnection } from "node:net"; import path from "node:path"; import { createInterface } from "node:readline/promises"; import { fileURLToPath } from "node:url"; import open from "open"; import { type PonyProject, type WebPortConflictBehavior, pathExists, webPortSchema, } from "../core/index.js"; import { waitForChildExit } from "./child-process.js"; import { captureTerminalState, type ProcessSignalTarget } from "./terminal.js"; import { PONY_WEB_PROJECTS_ENV, serializeWebProjects, } from "../core/web-project-environment.js"; export const WEB_ENTRY_PATH = path.join("dist", "web", "server", "entry.mjs"); export const DEFAULT_WEB_HOST = "127.0.0.1"; export const MINIMUM_NODE_VERSION = { major: 22, minor: 0 } as const; const CLEAN_WEB_EXIT_SIGNALS = new Set(["SIGINT", "SIGTERM"]); const MAX_PORT_CONFLICT_SELECTIONS = 10; const SERVER_READINESS_STABILITY_MS = 50; export interface WebServerOptions { host?: string; open?: boolean; port?: string; } export interface ResolvedWebServerOptions { browserUrl: string; host: string; open: boolean; port: number; probeHost: string; } export interface WebServerRuntime { captureTerminalState(): () => void; pathExists(filePath: string): Promise; assertPortAvailable(host: string, port: number): Promise; findAvailablePort(host: string): Promise; isInteractive(): boolean; confirmPortChange( host: string, occupiedPort: number, availablePort: number, ): Promise; signalTarget: ProcessSignalTarget; spawnProcess( command: string, args: string[], options: { cwd: string; env: NodeJS.ProcessEnv; stdio: "inherit"; }, ): ChildProcess; waitForServer(child: ChildProcess, host: string, port: number): Promise; waitForExit(child: ChildProcess): Promise; openBrowser(url: string): Promise; } export class WebPortInUseError extends Error { readonly code = "EADDRINUSE"; constructor( readonly host: string, readonly port: number, ) { super(`Port ${port} is already in use on ${host}.`); this.name = "WebPortInUseError"; } } export function findPackageRoot(startUrl = import.meta.url): Promise { return findPackageRootFrom(path.dirname(fileURLToPath(startUrl))); } async function findPackageRootFrom(startPath: string): Promise { let current = startPath; while (true) { if (await pathExists(path.join(current, "package.json"))) { return current; } const parent = path.dirname(current); if (parent === current) { throw new Error("Could not locate Pony package root."); } current = parent; } } function resolveHost(host: string | undefined): string { const resolved = host?.trim() || DEFAULT_WEB_HOST; if (/\s/.test(resolved)) { throw new Error(`Invalid web host: ${resolved}`); } return resolved; } function probeHost(host: string): string { if (host === "0.0.0.0") { return "127.0.0.1"; } if (host === "::") { return "::1"; } return host; } function urlHost(host: string): string { const browserHost = probeHost(host); return browserHost.includes(":") ? `[${browserHost}]` : browserHost; } export function resolveWebServerOptions( configPort: number, options: WebServerOptions, env: NodeJS.ProcessEnv = process.env, ): ResolvedWebServerOptions { const port = webPortSchema.parse(options.port ?? env.PORT ?? configPort); const host = resolveHost(options.host ?? env.HOST); return { browserUrl: `http://${urlHost(host)}:${port}/`, host, open: options.open ?? true, port, probeHost: probeHost(host), }; } export function isLoopbackHost(host: string): boolean { return host === "127.0.0.1" || host === "::1" || host === "localhost"; } export function assertSupportedNodeVersion( version = process.versions.node, ): void { const [major = 0, minor = 0] = version.split(".").slice(0, 2).map(Number); if ( major < MINIMUM_NODE_VERSION.major || (major === MINIMUM_NODE_VERSION.major && minor < MINIMUM_NODE_VERSION.minor) ) { throw new Error( `Pony web requires Node.js ${MINIMUM_NODE_VERSION.major}.${MINIMUM_NODE_VERSION.minor} or newer; found ${version}.`, ); } } async function assertPortAvailable(host: string, port: number): Promise { await new Promise((resolve, reject) => { const server = createServer(); server.unref(); server.once("error", (error: NodeJS.ErrnoException) => { if (error.code === "EADDRINUSE") { reject(new WebPortInUseError(host, port)); return; } reject(error); }); server.listen(port, host, () => { server.close((error) => (error ? reject(error) : resolve())); }); }); } async function findAvailablePort(host: string): Promise { return new Promise((resolve, reject) => { const server = createServer(); server.unref(); server.once("error", reject); server.listen(0, host, () => { const address = server.address(); if (address === null || typeof address === "string") { server.close(() => reject(new Error(`Could not select an available port on ${host}.`)), ); return; } server.close((error) => (error ? reject(error) : resolve(address.port))); }); }); } async function canConnect(host: string, port: number): Promise { return new Promise((resolve) => { const socket = createConnection({ host, port }); const finish = (connected: boolean) => { socket.destroy(); resolve(connected); }; socket.setTimeout(250); socket.once("connect", () => finish(true)); socket.once("error", () => finish(false)); socket.once("timeout", () => finish(false)); }); } function childIsRunning(child: ChildProcess): boolean { return child.exitCode === null && child.signalCode === null; } async function assertChildIsRunning( child: ChildProcess, host: string, port: number, ): Promise { if (childIsRunning(child)) return; if (await canConnect(host, port)) { throw new WebPortInUseError(host, port); } throw new Error("Pony web server exited before it became ready."); } async function waitForServer( child: ChildProcess, host: string, port: number, timeoutMs = 10_000, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { await assertChildIsRunning(child, host, port); if (await canConnect(host, port)) { /** * A competing process can win the bind race and accept our probe before * the Pony child reports EADDRINUSE. Require a brief stable child period * so another service cannot be mistaken for a ready Pony server. */ await new Promise((resolve) => setTimeout(resolve, SERVER_READINESS_STABILITY_MS), ); await assertChildIsRunning(child, host, port); return; } await new Promise((resolve) => setTimeout(resolve, 50)); } child.kill("SIGTERM"); throw new Error( `Pony web server did not become ready within ${timeoutMs}ms.`, ); } const defaultWebServerRuntime: WebServerRuntime = { captureTerminalState: () => captureTerminalState(process.stdin, process.stdout), pathExists, assertPortAvailable, findAvailablePort, isInteractive: () => process.stdin.isTTY === true && process.stdout.isTTY === true, confirmPortChange: async (host, occupiedPort, availablePort) => { const prompt = createInterface({ input: process.stdin, output: process.stdout, }); try { const answer = await prompt.question( `Use available port ${availablePort} on ${host} instead of occupied port ${occupiedPort}? [y/N] `, ); return /^(?:y|yes)$/iu.test(answer.trim()); } finally { prompt.close(); } }, signalTarget: process, spawnProcess: (command, args, options) => spawn(command, args, options), waitForServer, waitForExit: (child) => waitForChildExit(child, "Pony web server", CLEAN_WEB_EXIT_SIGNALS), openBrowser: async (url) => { await open(url); }, }; interface WebServerExitResult { error: unknown | null; } /** * Keeps the local CLI alive until the server exits, even after interruption. * The calling shell must not regain the shared TTY while this child can still * write output or retain terminal modes. */ class WebServerSession { private readonly exitResult: Promise; private readonly interrupted: Promise; private readonly onSigint = () => this.forwardSignal("SIGINT"); private readonly onSigterm = () => this.forwardSignal("SIGTERM"); private receivedSignal: NodeJS.Signals | null = null; private resolveInterruption!: () => void; constructor( private readonly child: ChildProcess, private readonly runtime: WebServerRuntime, private readonly restoreTerminal: () => void, ) { this.exitResult = runtime.waitForExit(child).then( () => ({ error: null }), (error: unknown) => ({ error }), ); this.interrupted = new Promise((resolve) => { this.resolveInterruption = resolve; }); runtime.signalTarget.on("SIGINT", this.onSigint); runtime.signalTarget.on("SIGTERM", this.onSigterm); } async waitForReadiness(host: string, port: number): Promise { await Promise.race([ this.runtime.waitForServer(this.child, host, port), this.interrupted, ]); return this.receivedSignal === null; } async waitForExitError(): Promise { return (await this.exitResult).error; } interruptionStatus(): number | null { if (this.receivedSignal === "SIGINT") return 130; if (this.receivedSignal === "SIGTERM") return 143; return null; } async close(): Promise { this.runtime.signalTarget.off("SIGINT", this.onSigint); this.runtime.signalTarget.off("SIGTERM", this.onSigterm); try { this.stopChild(this.receivedSignal ?? "SIGTERM"); return (await this.exitResult).error; } catch (error) { return error; } finally { this.restoreTerminal(); } } private forwardSignal(signal: NodeJS.Signals): void { if (this.receivedSignal === null) this.receivedSignal = signal; this.resolveInterruption(); this.stopChild(signal); } private stopChild(signal: NodeJS.Signals): void { if (childIsRunning(this.child)) this.child.kill(signal); } } function spawnWebServerSession( entryPath: string, projects: readonly PonyProject[], resolved: ResolvedWebServerOptions, env: NodeJS.ProcessEnv, runtime: WebServerRuntime, ): WebServerSession { const restoreTerminal = runtime.captureTerminalState(); const primaryProject = projects[0]; if (!primaryProject) { restoreTerminal(); throw new Error("Pony web requires at least one selected project."); } try { /** * The executable belongs to the installed Pony package, while all mutable * state belongs to caller-selected repositories. The primary workspace * preserves the existing single-project environment contract, while the * explicit project list lets every request retain its owning repository. */ const child = runtime.spawnProcess(process.execPath, [entryPath], { cwd: primaryProject.root, env: { ...env, HOST: resolved.host, PONY_WORKSPACE_CWD: primaryProject.root, [PONY_WEB_PROJECTS_ENV]: serializeWebProjects(projects), PORT: String(resolved.port), }, stdio: "inherit", }); return new WebServerSession(child, runtime, restoreTerminal); } catch (error) { restoreTerminal(); throw error; } } async function openBrowser( runtime: WebServerRuntime, browserUrl: string, ): Promise { try { await runtime.openBrowser(browserUrl); } catch (error) { const message = error instanceof Error ? error.message : String(error); console.warn(`Could not open the browser: ${message}`); } } function resolvedOptionsWithPort( resolved: ResolvedWebServerOptions, port: number, ): ResolvedWebServerOptions { return { ...resolved, browserUrl: `http://${urlHost(resolved.host)}:${port}/`, port, }; } function isPortConflict(error: unknown): error is WebPortInUseError { return ( error instanceof WebPortInUseError || (typeof error === "object" && error !== null && "code" in error && error.code === "EADDRINUSE") ); } async function resolvePortConflict( conflict: WebPortInUseError, resolved: ResolvedWebServerOptions, behavior: WebPortConflictBehavior, selectionCount: number, runtime: WebServerRuntime, ): Promise { if (behavior === "fail") throw conflict; console.warn(conflict.message); // Bound repeated bind races so automatic unattended starts always terminate. if (selectionCount > MAX_PORT_CONFLICT_SELECTIONS) { throw new Error( `Pony could not secure an available port after ${MAX_PORT_CONFLICT_SELECTIONS} attempts. Choose another port with \`pony start --port \` or set web.port_conflict to fail.`, ); } const availablePort = await runtime.findAvailablePort(resolved.host); if (behavior === "prompt") { if (!runtime.isInteractive()) { throw new Error( "web.port_conflict is set to prompt, but no interactive terminal is available. Run Pony interactively or set web.port_conflict to auto or fail.", ); } const confirmed = await runtime.confirmPortChange( resolved.host, conflict.port, availablePort, ); if (!confirmed) { throw new Error( `Pony was not started because port ${conflict.port} remains selected. Choose another port or set web.port_conflict to auto.`, ); } } else { console.log(`Using available port ${availablePort} instead.`); } return resolvedOptionsWithPort(resolved, availablePort); } async function startWebServerAttempt( entryPath: string, projects: readonly PonyProject[], resolved: ResolvedWebServerOptions, env: NodeJS.ProcessEnv, runtime: WebServerRuntime, ): Promise { const session = spawnWebServerSession( entryPath, projects, resolved, env, runtime, ); let operationError: unknown = null; try { const ready = await session.waitForReadiness( resolved.probeHost, resolved.port, ); if (ready) { console.log(`Pony is available at ${resolved.browserUrl}`); if (resolved.open) await openBrowser(runtime, resolved.browserUrl); operationError = await session.waitForExitError(); } } catch (error) { operationError = error; } const cleanupError = await session.close(); const interruptionStatus = session.interruptionStatus(); if (interruptionStatus !== null) return interruptionStatus; if (operationError) throw operationError; if (cleanupError) throw cleanupError; return 0; } /** * Runtime dependencies are injectable so process, socket, and browser * lifecycle behavior can be verified without launching external resources. */ export async function startWebServer( packageRoot: string, selectedProjects: PonyProject | readonly PonyProject[], options: WebServerOptions, env: NodeJS.ProcessEnv = process.env, runtime: WebServerRuntime = defaultWebServerRuntime, ): Promise { assertSupportedNodeVersion(); const projects = Array.isArray(selectedProjects) ? selectedProjects : [selectedProjects]; const primaryProject = projects[0]; if (!primaryProject) { throw new Error("Pony web requires at least one selected project."); } const entryPath = path.join(packageRoot, WEB_ENTRY_PATH); if (!(await runtime.pathExists(entryPath))) { throw new Error( `Pony web build is missing at ${entryPath}. Reinstall Pony, or run \`npm run build\` in a linked Pony repository.`, ); } let resolved = resolveWebServerOptions( primaryProject.config.web.port, options, env, ); if (!isLoopbackHost(resolved.host)) { console.warn( `Warning: Pony is listening on ${resolved.host}. Put an authenticated reverse proxy in front of externally accessible servers.`, ); } let selectionCount = 0; const recoverFromPortConflict = async (error: unknown): Promise => { if (!isPortConflict(error)) throw error; selectionCount += 1; const conflict = error instanceof WebPortInUseError ? error : new WebPortInUseError(resolved.host, resolved.port); resolved = await resolvePortConflict( conflict, resolved, primaryProject.config.web.port_conflict, selectionCount, runtime, ); }; while (true) { try { await runtime.assertPortAvailable(resolved.host, resolved.port); } catch (error) { await recoverFromPortConflict(error); continue; } try { return await startWebServerAttempt( entryPath, projects, resolved, env, runtime, ); } catch (error) { await recoverFromPortConflict(error); } } }