diff --git a/apps/cli/src/lib/backends.test.ts b/apps/cli/src/lib/backends.test.ts new file mode 100644 index 0000000..cdffa21 --- /dev/null +++ b/apps/cli/src/lib/backends.test.ts @@ -0,0 +1,86 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { coerce, parseCodexConfig, readOpencodeConfig } from "./backends"; +import { CliError } from "./errors"; + +describe("coerce", () => { + // The bug this exists for: the SDK serializes a JS string as a quoted TOML + // string, so a bare "true" would reach Codex as the string "true" where its + // config expects a boolean. + it("reads the TOML scalar the text looks like", () => { + expect(coerce("true")).toBe(true); + expect(coerce("false")).toBe(false); + expect(coerce("42")).toBe(42); + expect(coerce("2.5")).toBe(2.5); + expect(coerce("-1")).toBe(-1); + }); + + it("keeps a non-scalar as a string", () => { + expect(coerce("gpt-5")).toBe("gpt-5"); + expect(coerce("")).toBe(""); + }); + + it("lets explicit quotes force a string", () => { + expect(coerce('"true"')).toBe("true"); + expect(coerce('"42"')).toBe("42"); + }); +}); + +describe("parseCodexConfig", () => { + it("splits on the first = so a value may contain one", () => { + expect(parseCodexConfig(["a=b=c"])).toEqual({ a: "b=c" }); + }); + + it("collects every pair", () => { + expect(parseCodexConfig(["a=1", "b=true"])).toEqual({ a: 1, b: true }); + }); + + it("returns nothing for no pairs", () => { + expect(parseCodexConfig([])).toEqual({}); + }); + + it.each(["noequals", "=novalue"])("rejects %o", (pair) => { + expect(() => parseCodexConfig([pair])).toThrow(CliError); + }); +}); + +describe("readOpencodeConfig", () => { + const write = (contents: string): string => { + const path = join( + mkdtempSync(join(tmpdir(), "airship-opencode-")), + "config.json" + ); + writeFileSync(path, contents); + return path; + }; + + it("returns nothing when no path is given", () => { + expect(readOpencodeConfig(undefined)).toBeUndefined(); + }); + + it("parses an object", () => { + expect(readOpencodeConfig(write('{ "model": "x" }'))).toEqual({ + model: "x", + }); + }); + + it("names the missing file", () => { + let err: CliError | undefined; + try { + readOpencodeConfig("/nope/does-not-exist.json"); + } catch (caught) { + err = caught as CliError; + } + expect(err?.message).toContain("not found"); + }); + + it("rejects malformed JSON", () => { + expect(() => readOpencodeConfig(write("{ nope"))).toThrow(CliError); + }); + + it.each(["[]", '"a string"', "null", "42"])("rejects %o", (contents) => { + expect(() => readOpencodeConfig(write(contents))).toThrow(CliError); + }); +}); diff --git a/apps/cli/src/lib/backends.ts b/apps/cli/src/lib/backends.ts new file mode 100644 index 0000000..5865801 --- /dev/null +++ b/apps/cli/src/lib/backends.ts @@ -0,0 +1,105 @@ +/** + * The two backend escape hatches, and the value parsing they need. + * + * Extracted from the command so they can be tested: every one of these has a + * coercion rule that is easy to get subtly wrong and impossible to notice from + * the outside — a boolean silently becoming the string "true" changes what the + * agent is configured with, not whether it runs. + */ + +import { readFileSync } from "node:fs"; +import type { CodexConfigValue } from "@airship/server"; +import { CliError, EXIT } from "./errors"; + +/** + * Interpret a flag value as the TOML scalar it looks like. + * + * The SDK serializes a JS string as a quoted TOML string, so passing everything + * through verbatim would turn `network_access=true` into `network_access="true"` + * — a string where Codex's config expects a boolean. Since argv has no types, + * the shape of the text is the only signal available. Quote a value + * (`k='"true"'`) to force it to stay a string. + */ +export function coerce(raw: string): CodexConfigValue { + if (raw === "true") { + return true; + } + if (raw === "false") { + return false; + } + if (raw !== "" && Number.isFinite(Number(raw))) { + return Number(raw); + } + // An explicitly quoted value keeps its quotes stripped but stays a string. + if (raw.length > 1 && raw.startsWith('"') && raw.endsWith('"')) { + return raw.slice(1, -1); + } + return raw; +} + +/** `--codex-config k=v`, repeatable. Rejects a pair with no `=`. */ +export function parseCodexConfig( + pairs: readonly string[] +): Record { + const out: Record = {}; + for (const pair of pairs) { + const eq = pair.indexOf("="); + if (eq < 1) { + throw new CliError(`Invalid --codex-config '${pair}'`, { + exitCode: EXIT.usage, + hint: "Expected key=value, e.g. --codex-config network_access=true.", + }); + } + out[pair.slice(0, eq)] = coerce(pair.slice(eq + 1)); + } + return out; +} + +/** + * `--opencode-config ` — a file path, not `k=v`. + * + * Deliberately a different shape from `--codex-config`. Codex's escape hatch is + * a flat list of TOML scalars, which `k=v` fits exactly. OpenCode's config is a + * deeply nested JSON document (`provider.anthropic.options.thinking.budget`), + * and supporting that through `k=v` would mean inventing a dotted-path + * mini-language plus a value parser. A file fails fast with a real parse error + * and is the form users already have on disk. + */ +export function readOpencodeConfig( + path: string | undefined +): Record | undefined { + if (!path) { + return; + } + let raw: string; + try { + raw = readFileSync(path, "utf8"); + } catch (err) { + if (err instanceof Error && "code" in err && err.code === "ENOENT") { + throw new CliError(`--opencode-config file not found: ${path}`, { + cause: err, + hint: "Check the path, or drop the flag to use opencode's own config.", + }); + } + throw new CliError( + `--opencode-config ${path} could not be read: ${err instanceof Error ? err.message : String(err)}`, + { cause: err } + ); + } + + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (err) { + throw new CliError( + `--opencode-config ${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, + { cause: err } + ); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new CliError(`--opencode-config ${path} must contain a JSON object`, { + hint: "The file is merged into opencode's server config, so it has to be an object.", + }); + } + return parsed as Record; +} diff --git a/apps/cli/src/lib/detect.test.ts b/apps/cli/src/lib/detect.test.ts new file mode 100644 index 0000000..b8847c5 --- /dev/null +++ b/apps/cli/src/lib/detect.test.ts @@ -0,0 +1,105 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { candidatePorts } from "./detect"; + +function project(pkg: Record | null): string { + const root = mkdtempSync(join(tmpdir(), "airship-detect-")); + if (pkg) { + writeFileSync(join(root, "package.json"), JSON.stringify(pkg)); + } + return root; +} + +const portsOf = (cwd: string): number[] => + candidatePorts(cwd).map((candidate) => candidate.port); + +describe("candidatePorts", () => { + it("takes an explicit --port from the dev script first", () => { + const cwd = project({ + devDependencies: { vite: "^7" }, + scripts: { dev: "vite dev --port 4000" }, + }); + const [first] = candidatePorts(cwd); + expect(first).toEqual({ + port: 4000, + reason: "the port in your dev script", + }); + }); + + it("reads the --port=N form", () => { + const cwd = project({ scripts: { dev: "next dev --port=4100" } }); + expect(portsOf(cwd)[0]).toBe(4100); + }); + + it("reads the -p form", () => { + const cwd = project({ scripts: { dev: "astro dev -p 4200" } }); + expect(portsOf(cwd)[0]).toBe(4200); + }); + + it("reads a PORT= prefix", () => { + const cwd = project({ scripts: { dev: "PORT=4300 remix dev" } }); + expect(portsOf(cwd)[0]).toBe(4300); + }); + + it("falls back to start, then serve", () => { + expect(portsOf(project({ scripts: { start: "x --port 4400" } }))[0]).toBe( + 4400 + ); + expect(portsOf(project({ scripts: { serve: "x --port 4500" } }))[0]).toBe( + 4500 + ); + }); + + it("uses the framework's default port when the script says nothing", () => { + const cwd = project({ + devDependencies: { vite: "^7" }, + scripts: { dev: "vite dev" }, + }); + expect(candidatePorts(cwd)[0]).toEqual({ + port: 5173, + reason: "vite's default port", + }); + }); + + it("prefers the more specific framework when both are present", () => { + const cwd = project({ devDependencies: { next: "^15", vite: "^7" } }); + expect(portsOf(cwd)[0]).toBe(3000); + }); + + it("recognises storybook by its scoped packages", () => { + const cwd = project({ devDependencies: { "@storybook/react": "^9" } }); + expect(portsOf(cwd)).toContain(6006); + }); + + it("finds frameworks in dependencies as well as devDependencies", () => { + const cwd = project({ dependencies: { nuxt: "^3" } }); + expect(portsOf(cwd)[0]).toBe(3000); + }); + + it("always offers the common ports as a fallback", () => { + expect(portsOf(project({}))).toEqual([3000, 5173, 8080, 4321, 4200]); + }); + + it("survives a project with no package.json", () => { + expect(portsOf(project(null))).toEqual([3000, 5173, 8080, 4321, 4200]); + }); + + it("survives a malformed package.json", () => { + const root = mkdtempSync(join(tmpdir(), "airship-detect-")); + writeFileSync(join(root, "package.json"), "{ not json"); + expect(portsOf(root)).toEqual([3000, 5173, 8080, 4321, 4200]); + }); + + it("never repeats a port", () => { + const cwd = project({ + devDependencies: { vite: "^7" }, + scripts: { dev: "vite dev --port 5173" }, + }); + const ports = portsOf(cwd); + expect(new Set(ports).size).toBe(ports.length); + // The reason for the first sighting is kept — it is the more specific one. + expect(candidatePorts(cwd)[0]?.reason).toBe("the port in your dev script"); + }); +}); diff --git a/apps/cli/src/lib/detect.ts b/apps/cli/src/lib/detect.ts new file mode 100644 index 0000000..666847d --- /dev/null +++ b/apps/cli/src/lib/detect.ts @@ -0,0 +1,190 @@ +/** + * Working out which port the user's dev server is on, so `--target` can be + * optional. + * + * Two sources, in order of how much they actually know: the project's own dev + * script, which may state a port outright, and the framework it depends on, + * whose default port is a good guess. Every candidate is then probed, because a + * guess that nothing is listening on is worse than no guess — it would send the + * proxy at a dead port and produce a 502 on the first request. + */ + +import { existsSync, readFileSync } from "node:fs"; +import net from "node:net"; +import { join } from "node:path"; + +export interface Candidate { + port: number; + /** Said back to the user, so a wrong guess is obvious rather than magic. */ + reason: string; +} + +export interface Detection extends Candidate { + /** Whether something is accepting connections there right now. */ + listening: boolean; +} + +/** + * Default dev-server ports, by the package that owns them. Ordered most + * specific first: a project with both `vite` and `storybook` is a Vite app that + * also has a catalogue, not the other way round. + */ +const FRAMEWORK_PORTS: readonly [string, number, string][] = [ + ["next", 3000, "next"], + ["nuxt", 3000, "nuxt"], + ["@remix-run/dev", 3000, "remix"], + ["react-scripts", 3000, "create-react-app"], + ["astro", 4321, "astro"], + ["@sveltejs/kit", 5173, "sveltekit"], + ["vite", 5173, "vite"], + ["@angular/cli", 4200, "angular"], + ["gatsby", 8000, "gatsby"], + ["@11ty/eleventy", 8080, "eleventy"], + ["parcel", 1234, "parcel"], + ["storybook", 6006, "storybook"], +]; + +/** Ports worth trying when the project says nothing useful. */ +const COMMON_PORTS: readonly number[] = [3000, 5173, 8080, 4321, 4200]; + +const PORT_FLAG = /(?:--port[= ]|-p[= ])(\d{2,5})/; +const PORT_ENV = /\bPORT=(\d{2,5})/; + +/** + * The project's package.json, or nothing. + * + * A malformed one is the app's problem, not a reason to refuse to launch — port + * detection just falls through to the common ports. + */ +function readPackageJson(cwd: string): Record | undefined { + const path = join(cwd, "package.json"); + if (!existsSync(path)) { + return; + } + const parsed: unknown = tryParse(readFileSafe(path)); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; +} + +function readFileSafe(path: string): string { + try { + return readFileSync(path, "utf8"); + } catch { + return ""; + } +} + +function tryParse(raw: string): unknown { + try { + return JSON.parse(raw); + } catch { + return null; + } +} + +/** Every port worth trying, best guess first, deduplicated. */ +export function candidatePorts(cwd: string): Candidate[] { + const pkg = readPackageJson(cwd); + const out: Candidate[] = []; + const seen = new Set(); + const add = (port: number, reason: string): void => { + if (!seen.has(port)) { + seen.add(port); + out.push({ port, reason }); + } + }; + + const scripts = (pkg?.scripts ?? {}) as Record; + const devScript = scripts.dev ?? scripts.start ?? scripts.serve; + if (devScript) { + const flag = PORT_FLAG.exec(devScript) ?? PORT_ENV.exec(devScript); + if (flag?.[1]) { + add(Number(flag[1]), "the port in your dev script"); + } + } + + const deps = { + ...((pkg?.dependencies ?? {}) as Record), + ...((pkg?.devDependencies ?? {}) as Record), + }; + for (const [name, port, label] of FRAMEWORK_PORTS) { + const matched = + name in deps || + // Storybook publishes a dozen scoped packages and no single stable id. + (name === "storybook" && + Object.keys(deps).some((dep) => dep.startsWith("@storybook/"))); + if (matched) { + add(port, `${label}'s default port`); + } + } + + for (const port of COMMON_PORTS) { + add(port, "a common dev-server port"); + } + return out; +} + +const PROBE_TIMEOUT_MS = 400; + +/** Whether anything is listening. Used for detection and by `doctor`. */ +export function isListening( + port: number, + host = "localhost", + timeoutMs = PROBE_TIMEOUT_MS +): Promise { + return new Promise((resolvePromise) => { + const socket = net.connect({ host, port }); + const done = (result: boolean): void => { + socket.destroy(); + resolvePromise(result); + }; + socket.setTimeout(timeoutMs); + socket.once("connect", () => done(true)); + socket.once("timeout", () => done(false)); + socket.once("error", () => done(false)); + }); +} + +/** + * The best guess at the dev server's port. + * + * Returns the first candidate that answers. When nothing answers it still + * returns the best guess with `listening: false`, because the wizard wants a + * sensible prefilled value even before the server is up — only `serve` insists + * on something live. + */ +export async function detectTarget( + cwd: string, + host = "localhost" +): Promise { + const candidates = candidatePorts(cwd); + for (const candidate of candidates) { + // Sequential on purpose: the candidates are in priority order and the first + // hit wins, so probing them together would open connections to ports we have + // already decided against and could pick the one that merely answered first. + // biome-ignore lint/performance/noAwaitInLoops: ordered first-match search + if (await isListening(candidate.port, host)) { + return { ...candidate, listening: true }; + } + } + const [first] = candidates; + return first ? { ...first, listening: false } : undefined; +} + +/** A port nothing is bound to, so the proxy does not collide on startup. */ +export async function firstFreePort( + start: number, + host = "localhost", + attempts = 20 +): Promise { + for (let port = start; port < start + attempts; port += 1) { + // Also ordered: "the first free port at or after `start`" is the answer, so + // the probes cannot be collapsed into one parallel batch. + // biome-ignore lint/performance/noAwaitInLoops: ordered first-match search + if (!(await isListening(port, host))) { + return port; + } + } + return start; +} diff --git a/apps/cli/src/lib/exec.ts b/apps/cli/src/lib/exec.ts new file mode 100644 index 0000000..b315872 --- /dev/null +++ b/apps/cli/src/lib/exec.ts @@ -0,0 +1,160 @@ +/** + * Running the user's dev server for them. + * + * Airship proxies a dev server rather than starting one, which has always meant + * two terminals and a remembered port. `--exec "pnpm dev"` collapses that: we + * start it, wait for its port to answer, and take it down again on the way out. + * + * The child goes in its own process group so a Ctrl-C in the terminal reaches + * only us. Otherwise the shell would signal both, the dev server would die + * first, and our own shutdown would be racing a corpse. + */ + +import { type ChildProcess, spawn } from "node:child_process"; +import { isListening } from "./detect"; +import { CliError } from "./errors"; +import { style } from "./terminal"; + +const READY_TIMEOUT_MS = 90_000; +const POLL_INTERVAL_MS = 250; +const STOP_GRACE_MS = 3000; + +export interface DevServer { + /** Resolves once the child is gone, or after the grace period. */ + stop: () => Promise; +} + +function sleep(ms: number): Promise { + return new Promise((done) => setTimeout(done, ms)); +} + +function killTree(child: ChildProcess, signal: NodeJS.Signals): void { + if (child.pid === undefined || child.exitCode !== null) { + return; + } + try { + if (process.platform === "win32") { + // No process groups to negate; Node maps this to TerminateProcess. + child.kill(signal); + return; + } + // Negative pid = the whole group, which is what actually stops a dev server + // that has forked workers of its own. + process.kill(-child.pid, signal); + } catch { + // Already gone between the check and the signal. Nothing left to do. + } +} + +/** + * Start the dev server and resolve once `port` accepts connections. + * + * Fails fast if the child exits first: waiting the full timeout on a process + * that has already printed its own error and quit tells the user nothing. + */ +export async function startDevServer(opts: { + command: string; + cwd: string; + host?: string; + port: number; + quiet?: boolean; + timeoutMs?: number; +}): Promise { + const host = opts.host ?? "localhost"; + const timeoutMs = opts.timeoutMs ?? READY_TIMEOUT_MS; + + if (!opts.quiet) { + process.stderr.write( + `${style.dim(` → starting your dev server: ${opts.command}`)}\n` + ); + } + + const child = spawn(opts.command, { + cwd: opts.cwd, + detached: process.platform !== "win32", + shell: true, + // The child's output is passed through — including the errors that explain + // a failure to start — but *both* its streams go to our stderr (fd 2), not + // to fd 1. Our stdout is the data channel: with `--json` the dev server's + // startup banner would otherwise land in the middle of the launch record + // and stop it parsing. Nothing is lost — stderr is still the terminal. + stdio: opts.quiet ? "ignore" : ["ignore", 2, 2], + }); + + let exited: + | { code: number | null; signal: NodeJS.Signals | null } + | undefined; + child.once("exit", (code, signal) => { + exited = { code, signal }; + }); + + const stop = async (): Promise => { + if (exited) { + return; + } + killTree(child, "SIGTERM"); + for (let waited = 0; waited < STOP_GRACE_MS; waited += POLL_INTERVAL_MS) { + if (exited) { + return; + } + // Polling for a state change that only another process can cause; there + // is nothing to run alongside it. + // biome-ignore lint/performance/noAwaitInLoops: sequential poll + await sleep(POLL_INTERVAL_MS); + } + // It ignored SIGTERM. The user asked to stop; leaving an orphaned dev + // server holding the port is the worse outcome. + killTree(child, "SIGKILL"); + }; + + const deadline = Date.now() + timeoutMs; + for (;;) { + if (exited) { + throw new CliError( + `Your dev server exited before it started listening on port ${opts.port}`, + { + hint: `Run \`${opts.command}\` on its own to see why, or pass --target with the port it actually uses.`, + } + ); + } + // biome-ignore lint/performance/noAwaitInLoops: sequential poll + if (await isListening(opts.port, host)) { + return { stop }; + } + if (Date.now() > deadline) { + await stop(); + throw new CliError( + `Your dev server did not start listening on port ${opts.port} within ${Math.round(timeoutMs / 1000)}s`, + { + hint: "Pass --target with the port it actually uses, or raise the wait if it is just slow to boot.", + } + ); + } + await sleep(POLL_INTERVAL_MS); + } +} + +const BROWSER_OPENERS: Record = { + darwin: "open", + win32: "start", +}; + +/** Open a URL in the default browser, best-effort. */ +export function openInBrowser(url: string): void { + const command = BROWSER_OPENERS[process.platform] ?? "xdg-open"; + try { + // Detached and fully ignored: the browser outliving airship is the point, + // and its stdio would otherwise pollute the terminal. + const child = spawn(command, [url], { + detached: true, + shell: process.platform === "win32", + stdio: "ignore", + }); + child.unref(); + child.on("error", () => { + // No browser, no display, no `open` — the URL is printed either way. + }); + } catch { + // Same: --open is a convenience, never a reason to fail a launch. + } +}