feat(cli): serve, init and doctor commands
serve is the one people run. doctor is the one that saves the support thread: it reports what was detected, which backends are on PATH and which are not, instead of leaving a failed start to be guessed at.
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* `airship doctor` — why it did not work.
|
||||
*
|
||||
* The CLI has never had an answer to that. Every failure mode it has (an agent
|
||||
* that is not signed in, a dev server that is not running, a project that is not
|
||||
* a git repo, an overlay bundle that was never built) previously surfaced either
|
||||
* as a warning buried in a launch it was too late to stop, or as nothing at all.
|
||||
*/
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { type AgentKind, checkAuth, isGitRepo } from "@airship/server";
|
||||
import { defineCommand } from "citty";
|
||||
import {
|
||||
AGENTS,
|
||||
argsFor,
|
||||
assertKnownFlags,
|
||||
GLOBAL_FLAGS,
|
||||
requirePort,
|
||||
} from "../lib/args";
|
||||
import { asBoolean, asString, CONFIG_FILENAME } from "../lib/config";
|
||||
import { detectTarget, isListening } from "../lib/detect";
|
||||
import { resolveSettings } from "../lib/settings";
|
||||
import {
|
||||
note,
|
||||
out,
|
||||
setColorEnabled,
|
||||
shouldColor,
|
||||
style,
|
||||
} from "../lib/terminal";
|
||||
import { VERSION } from "../lib/version";
|
||||
|
||||
export const DOCTOR_FLAGS: readonly string[] = [
|
||||
"cwd",
|
||||
"target",
|
||||
"agent",
|
||||
...GLOBAL_FLAGS,
|
||||
];
|
||||
|
||||
type Level = "ok" | "warn" | "fail";
|
||||
|
||||
interface Check {
|
||||
/** What to do about it. Omitted when there is nothing to do. */
|
||||
hint?: string;
|
||||
label: string;
|
||||
level: Level;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const MARKS: Record<Level, (text: string) => string> = {
|
||||
fail: (text) => style.red(text),
|
||||
ok: (text) => style.green(text),
|
||||
warn: (text) => style.yellow(text),
|
||||
};
|
||||
|
||||
const GLYPHS: Record<Level, string> = { fail: "✗", ok: "✓", warn: "⚠" };
|
||||
|
||||
/** Node's own floor, from the workspace `engines` field. */
|
||||
const MIN_NODE_MAJOR = 22;
|
||||
const MIN_NODE_MINOR = 13;
|
||||
|
||||
function checkNode(): Check {
|
||||
const [major = 0, minor = 0] = process.versions.node
|
||||
.split(".")
|
||||
.map((part) => Number(part));
|
||||
const ok =
|
||||
major > MIN_NODE_MAJOR ||
|
||||
(major === MIN_NODE_MAJOR && minor >= MIN_NODE_MINOR);
|
||||
return {
|
||||
hint: ok
|
||||
? undefined
|
||||
: `airship needs Node ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR} or newer.`,
|
||||
label: "node",
|
||||
level: ok ? "ok" : "fail",
|
||||
value: process.versions.node,
|
||||
};
|
||||
}
|
||||
|
||||
async function checkAgents(preferred: AgentKind | undefined): Promise<Check[]> {
|
||||
const results = await Promise.all(
|
||||
AGENTS.map(async (agent) => {
|
||||
const auth = await checkAuth(agent as AgentKind);
|
||||
// Only the agent actually being used is a failure; the other two not
|
||||
// being installed is the normal state and must not read as broken.
|
||||
const isPreferred = agent === (preferred ?? "claude");
|
||||
let level: Level = "ok";
|
||||
if (!auth.ok) {
|
||||
level = isPreferred ? "fail" : "warn";
|
||||
}
|
||||
return {
|
||||
hint: auth.ok ? undefined : auth.reason,
|
||||
label: `agent ${agent}`,
|
||||
level,
|
||||
value: auth.ok ? "ready" : "not available",
|
||||
} satisfies Check;
|
||||
})
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
function checkOverlay(): Check {
|
||||
const require = createRequire(import.meta.url);
|
||||
try {
|
||||
require.resolve("@airship/overlay/bundle");
|
||||
return { label: "overlay bundle", level: "ok", value: "built" };
|
||||
} catch {
|
||||
// Same two-place lookup the proxy does, and for the same reason: in a
|
||||
// published install @airship/overlay is not on disk, and the bundle lives
|
||||
// in this CLI's own dist/vendor/. Checking only the workspace copy would
|
||||
// report "missing" on every working npm install.
|
||||
const vendored = fileURLToPath(
|
||||
new URL("./vendor/overlay.global.js", import.meta.url)
|
||||
);
|
||||
if (existsSync(vendored)) {
|
||||
return { label: "overlay bundle", level: "ok", value: "bundled" };
|
||||
}
|
||||
return {
|
||||
hint: "Run `pnpm build` — without it the editor cannot be injected.",
|
||||
label: "overlay bundle",
|
||||
level: "fail",
|
||||
value: "missing",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function render(checks: readonly Check[]): string {
|
||||
const width = Math.max(...checks.map((check) => check.label.length));
|
||||
const lines: string[] = [""];
|
||||
for (const check of checks) {
|
||||
const mark = MARKS[check.level](GLYPHS[check.level]);
|
||||
const label = check.label.padEnd(width);
|
||||
lines.push(` ${mark} ${label} ${check.value}`);
|
||||
if (check.hint) {
|
||||
lines.push(` ${style.dim(`↳ ${check.hint}`)}`);
|
||||
}
|
||||
}
|
||||
lines.push("");
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
|
||||
function checkConfig(configSource: string | undefined): Check {
|
||||
return {
|
||||
hint: configSource
|
||||
? undefined
|
||||
: `No ${CONFIG_FILENAME} found — run \`airship init\` to create one.`,
|
||||
label: "config",
|
||||
level: configSource ? "ok" : "warn",
|
||||
value: configSource ?? "none (flags and env only)",
|
||||
};
|
||||
}
|
||||
|
||||
function checkGit(cwd: string): Check {
|
||||
const repo = isGitRepo(cwd);
|
||||
return {
|
||||
hint: repo
|
||||
? undefined
|
||||
: "codex and opencode need git for their diff baseline, and undo needs it.",
|
||||
label: "git repo",
|
||||
level: repo ? "ok" : "warn",
|
||||
value: cwd,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A named `--target` is a claim the user made, so a dead port there is a
|
||||
* failure. A detected one is only a guess, so the same dead port is a warning.
|
||||
*/
|
||||
async function checkDevServer(
|
||||
cwd: string,
|
||||
targetFlag: string | undefined
|
||||
): Promise<Check> {
|
||||
if (targetFlag) {
|
||||
const port = requirePort(targetFlag, "target");
|
||||
const live = await isListening(port);
|
||||
return {
|
||||
hint: live ? undefined : "Start it, or pass a different --target.",
|
||||
label: "dev server",
|
||||
level: live ? "ok" : "fail",
|
||||
value: live ? `listening on ${port}` : `nothing on ${port}`,
|
||||
};
|
||||
}
|
||||
|
||||
const detected = await detectTarget(cwd);
|
||||
if (!detected) {
|
||||
return {
|
||||
hint: "Pass --target <port>.",
|
||||
label: "dev server",
|
||||
level: "warn",
|
||||
value: "no candidate ports found",
|
||||
};
|
||||
}
|
||||
return {
|
||||
hint: detected.listening
|
||||
? undefined
|
||||
: "Start your dev server, or pass --target <port>.",
|
||||
label: "dev server",
|
||||
level: detected.listening ? "ok" : "warn",
|
||||
value: `${detected.listening ? "listening on" : "nothing on"} ${detected.port} (${detected.reason})`,
|
||||
};
|
||||
}
|
||||
|
||||
export const doctor = defineCommand({
|
||||
args: argsFor(DOCTOR_FLAGS),
|
||||
meta: {
|
||||
description: "Check your environment and report what is wrong.",
|
||||
name: "doctor",
|
||||
},
|
||||
run: async ({ args, rawArgs }) => {
|
||||
assertKnownFlags(rawArgs, DOCTOR_FLAGS);
|
||||
const { configSource, cwd, settings } = resolveSettings({
|
||||
args,
|
||||
names: DOCTOR_FLAGS,
|
||||
rawArgs,
|
||||
});
|
||||
const json = asBoolean(settings, "json");
|
||||
setColorEnabled(shouldColor({ json }));
|
||||
|
||||
const agent = asString(settings, "agent") as AgentKind | undefined;
|
||||
|
||||
const checks: Check[] = [
|
||||
checkNode(),
|
||||
{ label: "airship", level: "ok", value: VERSION },
|
||||
checkConfig(configSource),
|
||||
checkGit(cwd),
|
||||
checkOverlay(),
|
||||
...(await checkAgents(agent)),
|
||||
// The dev server last: it is the check most likely to be a transient
|
||||
// "not started yet", and it reads better after the things that stay true.
|
||||
await checkDevServer(cwd, asString(settings, "target")),
|
||||
];
|
||||
|
||||
if (json) {
|
||||
out(`${JSON.stringify({ checks, cwd }, null, 2)}\n`);
|
||||
} else {
|
||||
note(render(checks));
|
||||
}
|
||||
|
||||
// A failing check is a failing run, so `airship doctor && airship` is a
|
||||
// usable thing to write in a script.
|
||||
if (checks.some((check) => check.level === "fail")) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* `airship init` — write the config file so the flags stop being retyped.
|
||||
*
|
||||
* Shares the wizard's prompts, so the questions and their detection are asked
|
||||
* one way only. Writes JSON rather than a `.ts` module deliberately: the file is
|
||||
* read by the CLI before anything is compiled, and a config that needs a build
|
||||
* step to be read is a config that can break the tool that reads it.
|
||||
*/
|
||||
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import { confirm, isCancel } from "@clack/prompts";
|
||||
import { defineCommand } from "citty";
|
||||
import { argsFor, assertKnownFlags, GLOBAL_FLAGS } from "../lib/args";
|
||||
import { asBoolean, CONFIG_FILENAME } from "../lib/config";
|
||||
import { CliError, EXIT } from "../lib/errors";
|
||||
import { resolveSettings } from "../lib/settings";
|
||||
import {
|
||||
isInteractive,
|
||||
note,
|
||||
setColorEnabled,
|
||||
shouldColor,
|
||||
style,
|
||||
} from "../lib/terminal";
|
||||
import { runWizard } from "../lib/wizard";
|
||||
|
||||
export const INIT_FLAGS: readonly string[] = ["cwd", ...GLOBAL_FLAGS];
|
||||
|
||||
export const init = defineCommand({
|
||||
args: argsFor(INIT_FLAGS),
|
||||
meta: {
|
||||
description: `Create an ${CONFIG_FILENAME} for this project.`,
|
||||
name: "init",
|
||||
},
|
||||
run: async ({ args, rawArgs }) => {
|
||||
assertKnownFlags(rawArgs, INIT_FLAGS);
|
||||
const { cwd, settings } = resolveSettings({
|
||||
args,
|
||||
names: INIT_FLAGS,
|
||||
rawArgs,
|
||||
});
|
||||
setColorEnabled(shouldColor({ json: asBoolean(settings, "json") }));
|
||||
|
||||
if (!isInteractive()) {
|
||||
throw new CliError("`airship init` needs a terminal", {
|
||||
exitCode: EXIT.usage,
|
||||
hint: `Write ${CONFIG_FILENAME} by hand instead — see \`airship --help\` for the settings it takes.`,
|
||||
});
|
||||
}
|
||||
|
||||
const path = join(cwd, CONFIG_FILENAME);
|
||||
if (existsSync(path)) {
|
||||
const replace = await confirm({
|
||||
initialValue: false,
|
||||
message: `${CONFIG_FILENAME} already exists. Replace it?`,
|
||||
});
|
||||
if (isCancel(replace) || !replace) {
|
||||
throw new CliError("Left the existing config alone", {
|
||||
exitCode: EXIT.interrupted,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const answers = await runWizard(cwd);
|
||||
// Only the answers worth persisting. `safe: false` is the default, so
|
||||
// writing it would state a posture the user did not actually choose.
|
||||
const config: Record<string, unknown> = {
|
||||
agent: answers.agent,
|
||||
mode: answers.mode,
|
||||
target: answers.target,
|
||||
};
|
||||
if (answers.safe) {
|
||||
config.safe = true;
|
||||
}
|
||||
|
||||
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);
|
||||
note(
|
||||
`\n ${style.green("✓")} wrote ${style.cyan(relative(process.cwd(), path) || CONFIG_FILENAME)}\n` +
|
||||
` ${style.dim("Run `airship` with no flags from now on.")}\n\n`
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
/**
|
||||
* `airship` — the default command. Launch the editor against a dev server.
|
||||
*
|
||||
* Everything the old single-file CLI did, plus the settings chain, port
|
||||
* detection and dev-server supervision. The order below is deliberate: resolve
|
||||
* and validate everything that can fail cheaply *before* starting a child
|
||||
* process or binding a port, so a typo never leaves a dev server orphaned.
|
||||
*/
|
||||
|
||||
import {
|
||||
type AgentKind,
|
||||
type AirshipSurface,
|
||||
type CodexSettings,
|
||||
checkAuth,
|
||||
type Effort,
|
||||
type OpencodeSettings,
|
||||
startServer,
|
||||
} from "@airship/server";
|
||||
import { defineCommand } from "citty";
|
||||
import {
|
||||
argsFor,
|
||||
assertKnownFlags,
|
||||
GLOBAL_FLAGS,
|
||||
requireAmount,
|
||||
requireEnum,
|
||||
requireInteger,
|
||||
requirePort,
|
||||
} from "../lib/args";
|
||||
import { parseCodexConfig, readOpencodeConfig } from "../lib/backends";
|
||||
import { launchBanner, warnBackendLimits } from "../lib/banner";
|
||||
import { asBoolean, asList, asString, type Settings } from "../lib/config";
|
||||
import {
|
||||
candidatePorts,
|
||||
detectTarget,
|
||||
firstFreePort,
|
||||
isListening,
|
||||
} from "../lib/detect";
|
||||
import { CliError, EXIT } from "../lib/errors";
|
||||
import { type DevServer, openInBrowser, startDevServer } from "../lib/exec";
|
||||
import { resolveSettings } from "../lib/settings";
|
||||
import { note, out, setColorEnabled, shouldColor } from "../lib/terminal";
|
||||
|
||||
export const SERVE_FLAGS: readonly string[] = [
|
||||
"target",
|
||||
"port",
|
||||
"cwd",
|
||||
"mode",
|
||||
"exec",
|
||||
"open",
|
||||
"agent",
|
||||
"model",
|
||||
"effort",
|
||||
"max-turns",
|
||||
"max-budget",
|
||||
"commit",
|
||||
"safe",
|
||||
"codex-path",
|
||||
"codex-config",
|
||||
"opencode-path",
|
||||
"opencode-url",
|
||||
"opencode-agent",
|
||||
"opencode-config",
|
||||
...GLOBAL_FLAGS,
|
||||
];
|
||||
|
||||
export interface ServeOptions {
|
||||
agent: AgentKind;
|
||||
autoCommit: boolean;
|
||||
codex: CodexSettings;
|
||||
cwd: string;
|
||||
effort?: Effort;
|
||||
exec?: string;
|
||||
json: boolean;
|
||||
maxBudgetUsd?: number;
|
||||
maxTurns?: number;
|
||||
model?: string;
|
||||
open: boolean;
|
||||
opencode: OpencodeSettings;
|
||||
port?: number;
|
||||
quiet: boolean;
|
||||
safe: boolean;
|
||||
surface: AirshipSurface;
|
||||
target?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merged settings → validated options.
|
||||
*
|
||||
* Exported for the tests: this is where every "invalid --x" message is decided,
|
||||
* and none of it was reachable when it lived inside `main`.
|
||||
*/
|
||||
export function toServeOptions(settings: Settings, cwd: string): ServeOptions {
|
||||
const agent = asString(settings, "agent");
|
||||
const effort = asString(settings, "effort");
|
||||
const mode = asString(settings, "mode");
|
||||
const target = asString(settings, "target");
|
||||
const port = asString(settings, "port");
|
||||
const turns = asString(settings, "max-turns");
|
||||
const budget = asString(settings, "max-budget");
|
||||
const codexConfig = parseCodexConfig(asList(settings, "codex-config"));
|
||||
|
||||
return {
|
||||
agent: (agent ? requireEnum(agent, "agent") : "claude") as AgentKind,
|
||||
autoCommit: asBoolean(settings, "commit"),
|
||||
codex: {
|
||||
codexPath: asString(settings, "codex-path"),
|
||||
config: Object.keys(codexConfig).length > 0 ? codexConfig : undefined,
|
||||
} satisfies CodexSettings,
|
||||
cwd,
|
||||
effort: effort ? (requireEnum(effort, "effort") as Effort) : undefined,
|
||||
exec: asString(settings, "exec"),
|
||||
json: asBoolean(settings, "json"),
|
||||
maxBudgetUsd: budget ? requireAmount(budget, "max-budget") : undefined,
|
||||
maxTurns: turns ? requireInteger(turns, "max-turns") : undefined,
|
||||
model: asString(settings, "model"),
|
||||
open: asBoolean(settings, "open"),
|
||||
opencode: {
|
||||
agent: asString(settings, "opencode-agent"),
|
||||
config: readOpencodeConfig(asString(settings, "opencode-config")),
|
||||
opencodePath: asString(settings, "opencode-path"),
|
||||
url: asString(settings, "opencode-url"),
|
||||
} satisfies OpencodeSettings,
|
||||
port: port ? requirePort(port, "port") : undefined,
|
||||
quiet: asBoolean(settings, "quiet"),
|
||||
safe: asBoolean(settings, "safe"),
|
||||
surface: (mode ? requireEnum(mode, "mode") : "canvas") as AirshipSurface,
|
||||
target: target ? requirePort(target, "target") : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Settle on a target port.
|
||||
*
|
||||
* With `--exec` we are about to start the server ourselves, so a port nothing
|
||||
* is listening on yet is exactly right. Without it, the port has to be live —
|
||||
* proxying a dead port produces a 502 on the first request and looks like
|
||||
* airship is broken rather than like the dev server is not running.
|
||||
*/
|
||||
async function resolveTarget(opts: ServeOptions): Promise<number> {
|
||||
if (opts.target !== undefined) {
|
||||
if (opts.exec) {
|
||||
await assertFree(opts.target);
|
||||
return opts.target;
|
||||
}
|
||||
if (!(await isListening(opts.target))) {
|
||||
throw new CliError(`Nothing is listening on port ${opts.target}`, {
|
||||
hint: 'Start your dev server first, or let airship start it with --exec "pnpm dev".',
|
||||
});
|
||||
}
|
||||
return opts.target;
|
||||
}
|
||||
|
||||
if (opts.exec) {
|
||||
// Deliberately *not* `detectTarget`: that returns the first candidate
|
||||
// already answering, which is the right answer when we are attaching to a
|
||||
// running server and the wrong one when we are about to start it. Some
|
||||
// other project's dev server on 3000 would outrank the port this project's
|
||||
// own dev script declares, and we would proxy the wrong app.
|
||||
const [first] = candidatePorts(opts.cwd);
|
||||
if (!first) {
|
||||
throw new CliError("Could not work out your dev server's port", {
|
||||
hint: "Pass it with --target <port>.",
|
||||
});
|
||||
}
|
||||
await assertFree(first.port);
|
||||
if (!opts.quiet) {
|
||||
note(` → expecting port ${first.port} — ${first.reason}\n`);
|
||||
}
|
||||
return first.port;
|
||||
}
|
||||
|
||||
const detected = await detectTarget(opts.cwd);
|
||||
if (!detected) {
|
||||
throw new CliError("Could not work out your dev server's port", {
|
||||
hint: "Pass it with --target <port>.",
|
||||
});
|
||||
}
|
||||
if (!detected.listening) {
|
||||
throw new CliError(
|
||||
`Nothing is listening on port ${detected.port} (${detected.reason})`,
|
||||
{
|
||||
hint: 'Start your dev server first, pass --target <port>, or let airship start it with --exec "pnpm dev".',
|
||||
}
|
||||
);
|
||||
}
|
||||
if (!opts.quiet) {
|
||||
note(` → using port ${detected.port} — ${detected.reason}\n`);
|
||||
}
|
||||
return detected.port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse to `--exec` onto an occupied port.
|
||||
*
|
||||
* Without this the readiness poll sees whatever is already there, declares the
|
||||
* dev server up, and proxies someone else's app while the one we spawned is
|
||||
* failing to bind behind it.
|
||||
*/
|
||||
async function assertFree(port: number): Promise<void> {
|
||||
if (await isListening(port)) {
|
||||
throw new CliError(`Something is already listening on port ${port}`, {
|
||||
hint: "Stop it, or drop --exec to attach to it instead.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const serve = defineCommand({
|
||||
args: argsFor(SERVE_FLAGS),
|
||||
meta: {
|
||||
description: "Launch the visual editor against your dev server.",
|
||||
name: "airship",
|
||||
},
|
||||
run: async ({ args, rawArgs }) => {
|
||||
assertKnownFlags(rawArgs, SERVE_FLAGS);
|
||||
const { cwd, settings } = resolveSettings({
|
||||
args,
|
||||
names: SERVE_FLAGS,
|
||||
rawArgs,
|
||||
});
|
||||
const opts = toServeOptions(settings, cwd);
|
||||
setColorEnabled(shouldColor({ json: opts.json }));
|
||||
|
||||
const targetPort = await resolveTarget(opts);
|
||||
// Default to target + 1, but step past anything already bound so a second
|
||||
// airship in another project does not fail on EADDRINUSE.
|
||||
const port = opts.port ?? (await firstFreePort(targetPort + 1));
|
||||
|
||||
// Attaching to a remote server needs no local binary, so the PATH half of
|
||||
// `checkAuth` would be a false alarm there.
|
||||
if (!(opts.agent === "opencode" && opts.opencode.url)) {
|
||||
const auth = await checkAuth(opts.agent);
|
||||
if (!auth.ok) {
|
||||
note(`\n ⚠ ${auth.reason}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
warnBackendLimits({
|
||||
agent: opts.agent,
|
||||
cwd: opts.cwd,
|
||||
effort: opts.effort,
|
||||
maxBudgetUsd: opts.maxBudgetUsd,
|
||||
maxTurns: opts.maxTurns,
|
||||
model: opts.model,
|
||||
});
|
||||
|
||||
let dev: DevServer | undefined;
|
||||
if (opts.exec) {
|
||||
dev = await startDevServer({
|
||||
command: opts.exec,
|
||||
cwd: opts.cwd,
|
||||
port: targetPort,
|
||||
quiet: opts.quiet,
|
||||
});
|
||||
}
|
||||
|
||||
let server: Awaited<ReturnType<typeof startServer>>;
|
||||
try {
|
||||
server = await startServer({
|
||||
agent: opts.agent,
|
||||
autoCommit: opts.autoCommit,
|
||||
codex: opts.codex,
|
||||
cwd: opts.cwd,
|
||||
effort: opts.effort,
|
||||
maxBudgetUsd: opts.maxBudgetUsd,
|
||||
maxTurns: opts.maxTurns,
|
||||
model: opts.model,
|
||||
opencode: opts.opencode,
|
||||
port,
|
||||
safe: opts.safe,
|
||||
surface: opts.surface,
|
||||
targetPort,
|
||||
});
|
||||
} catch (err) {
|
||||
// We started the dev server; if the proxy cannot come up it is ours to
|
||||
// clean up, or the user is left with a stray process holding the port.
|
||||
await dev?.stop();
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (opts.json) {
|
||||
out(
|
||||
`${JSON.stringify(
|
||||
{
|
||||
agent: opts.agent,
|
||||
cwd: opts.cwd,
|
||||
mode: opts.surface,
|
||||
port,
|
||||
safe: opts.safe,
|
||||
targetPort,
|
||||
url: server.url,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}\n`
|
||||
);
|
||||
} else if (!opts.quiet) {
|
||||
note(
|
||||
launchBanner({
|
||||
agent: opts.agent,
|
||||
cwd: opts.cwd,
|
||||
safe: opts.safe,
|
||||
surface: opts.surface,
|
||||
targetPort,
|
||||
url: server.url,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (opts.open) {
|
||||
openInBrowser(server.url);
|
||||
}
|
||||
|
||||
// A second Ctrl-C is an escape hatch: if a socket somehow outlives
|
||||
// `server.close()`, the user should never be stuck holding a dead terminal.
|
||||
let stopping = false;
|
||||
const shutdown = async (): Promise<void> => {
|
||||
if (stopping) {
|
||||
process.exit(EXIT.interrupted);
|
||||
}
|
||||
stopping = true;
|
||||
// The dev server goes first: it is the one that holds the port, and
|
||||
// closing the proxy under it would strand in-flight requests.
|
||||
await dev?.stop();
|
||||
await server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
// Signal handlers cannot await. If `shutdown()` itself rejects we still have
|
||||
// to leave the terminal in a usable state, so force the exit rather than
|
||||
// surfacing an unhandled rejection and hanging on the open server.
|
||||
const onSignal = () => {
|
||||
shutdown().catch(() => process.exit(EXIT.fail));
|
||||
};
|
||||
process.on("SIGINT", onSignal);
|
||||
process.on("SIGTERM", onSignal);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { FLAGS, GROUP_ORDER } from "./args";
|
||||
import { setColorEnabled } from "./terminal";
|
||||
import { renderHelp } from "./usage";
|
||||
|
||||
/** Indent, a dashed label, then the gutter that precedes a description. */
|
||||
const FLAG_ROW_GUTTER = /^ {2}(-|\s{4}--)\S.*? {2,}(?=\S)/;
|
||||
// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ESC is the point
|
||||
const ANSI = /\[/;
|
||||
|
||||
const HELP = {
|
||||
examples: [{ command: "airship --target 3000", note: "the usual case" }],
|
||||
flags: ["target", "port", "opencode-config", "safe", "help"],
|
||||
sections: [{ body: "Some prose.\n\nA second paragraph.", title: "Notes" }],
|
||||
subcommands: [{ name: "doctor", summary: "Check the environment." }],
|
||||
tagline: "airship — a tagline",
|
||||
usage: ["airship --target <port>"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Where the description starts on each flag row that has one, i.e. the column
|
||||
* every description is supposed to share.
|
||||
*/
|
||||
function descriptionColumns(text: string): number[] {
|
||||
const columns: number[] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
const match = FLAG_ROW_GUTTER.exec(line);
|
||||
if (match) {
|
||||
columns.push(match[0].length);
|
||||
}
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
describe("renderHelp", () => {
|
||||
beforeAll(() => {
|
||||
// Rendered with colour off so the assertions measure characters, not ANSI.
|
||||
setColorEnabled(false);
|
||||
process.stdout.columns = 80;
|
||||
});
|
||||
|
||||
it("emits no ANSI when colour is off", () => {
|
||||
expect(renderHelp(HELP)).not.toMatch(ANSI);
|
||||
});
|
||||
|
||||
// The defect the old hand-padded help string had shipped with, and which
|
||||
// nothing could detect: one flag a character too wide broke the column.
|
||||
it("aligns every description to one column", () => {
|
||||
const columns = descriptionColumns(renderHelp(HELP));
|
||||
expect(columns.length).toBeGreaterThan(1);
|
||||
expect(new Set(columns).size).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps that column across every group, not just within one", () => {
|
||||
const columns = descriptionColumns(
|
||||
renderHelp({ ...HELP, flags: FLAGS.map((flag) => flag.name) })
|
||||
);
|
||||
expect(columns.length).toBeGreaterThan(10);
|
||||
expect(new Set(columns).size).toBe(1);
|
||||
});
|
||||
|
||||
it("never exceeds the terminal width", () => {
|
||||
const lines = renderHelp(HELP).split("\n");
|
||||
expect(Math.max(...lines.map((line) => line.length))).toBeLessThanOrEqual(
|
||||
80
|
||||
);
|
||||
});
|
||||
|
||||
it("renders every requested section", () => {
|
||||
const text = renderHelp(HELP);
|
||||
expect(text).toContain("USAGE");
|
||||
expect(text).toContain("COMMANDS");
|
||||
expect(text).toContain("EXAMPLES");
|
||||
expect(text).toContain("NOTES");
|
||||
expect(text).toContain("# the usual case");
|
||||
expect(text).toContain("doctor");
|
||||
});
|
||||
|
||||
it("shows the default alongside the description", () => {
|
||||
expect(renderHelp(HELP)).toContain("(default:");
|
||||
});
|
||||
|
||||
it("omits a group with no flags in this command", () => {
|
||||
// The fixture has core, sandbox, backend and global flags but no agent one.
|
||||
expect(renderHelp(HELP)).not.toContain("AGENT FLAGS");
|
||||
expect(renderHelp(HELP)).toContain("BACKEND FLAGS");
|
||||
});
|
||||
|
||||
it("groups flags in the declared order", () => {
|
||||
const text = renderHelp({
|
||||
...HELP,
|
||||
flags: FLAGS.map((flag) => flag.name),
|
||||
});
|
||||
const positions = GROUP_ORDER.map((group) =>
|
||||
text.indexOf(`${group} FLAGS`)
|
||||
);
|
||||
expect(positions.every((position) => position > 0)).toBe(true);
|
||||
expect([...positions].sort((a, b) => a - b)).toEqual(positions);
|
||||
});
|
||||
|
||||
it("stays within width at a narrow terminal", () => {
|
||||
process.stdout.columns = 60;
|
||||
const lines = renderHelp({
|
||||
...HELP,
|
||||
flags: FLAGS.map((flag) => flag.name),
|
||||
}).split("\n");
|
||||
expect(Math.max(...lines.map((line) => line.length))).toBeLessThanOrEqual(
|
||||
60
|
||||
);
|
||||
process.stdout.columns = 80;
|
||||
});
|
||||
});
|
||||
|
||||
describe("the flag registry", () => {
|
||||
it("gives every flag a description", () => {
|
||||
expect(FLAGS.filter((flag) => !flag.help)).toEqual([]);
|
||||
});
|
||||
|
||||
it("has no duplicate names", () => {
|
||||
const names = FLAGS.map((flag) => flag.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
it("has no duplicate short aliases", () => {
|
||||
const aliases = FLAGS.flatMap((flag) => flag.alias ?? []);
|
||||
expect(new Set(aliases).size).toBe(aliases.length);
|
||||
});
|
||||
|
||||
it("gives every value-taking flag a placeholder", () => {
|
||||
const missing = FLAGS.filter(
|
||||
(flag) => flag.type === "string" && !flag.hint
|
||||
);
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Help rendering.
|
||||
*
|
||||
* Columns are measured from the specs rather than typed by hand, which is what
|
||||
* the old help string could not do — it had drifted a character out of
|
||||
* alignment and nothing could notice. Padding is computed on the plain label and
|
||||
* colour applied to the visible content only, so ANSI never skews a column.
|
||||
*/
|
||||
|
||||
import type { FlagSpec } from "./args";
|
||||
import { GROUP_ORDER, specsFor } from "./args";
|
||||
import { style } from "./terminal";
|
||||
|
||||
const MIN_WIDTH = 60;
|
||||
const MAX_WIDTH = 100;
|
||||
const INDENT = " ";
|
||||
/** Past this the description reads as a second column of noise, so it wraps. */
|
||||
const MAX_GUTTER = 28;
|
||||
const MIN_TEXT_WIDTH = 20;
|
||||
const WHITESPACE = /\s+/;
|
||||
|
||||
function terminalWidth(): number {
|
||||
const columns = process.stdout.columns ?? 80;
|
||||
return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, columns));
|
||||
}
|
||||
|
||||
function wrap(text: string, width: number): string[] {
|
||||
const lines: string[] = [];
|
||||
let line = "";
|
||||
for (const word of text.split(WHITESPACE).filter(Boolean)) {
|
||||
if (line && line.length + 1 + word.length > width) {
|
||||
lines.push(line);
|
||||
line = word;
|
||||
} else {
|
||||
line = line ? `${line} ${word}` : word;
|
||||
}
|
||||
}
|
||||
if (line) {
|
||||
lines.push(line);
|
||||
}
|
||||
return lines.length > 0 ? lines : [""];
|
||||
}
|
||||
|
||||
interface Row {
|
||||
/** Uncoloured, for measuring. */
|
||||
plain: string;
|
||||
/** Coloured, for printing. Same visible width as `plain`. */
|
||||
pretty: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
function gutterFor(rows: readonly Row[]): number {
|
||||
const widest = Math.max(...rows.map((row) => row.plain.length));
|
||||
return Math.min(widest, MAX_GUTTER) + 2;
|
||||
}
|
||||
|
||||
function renderRows(
|
||||
rows: readonly Row[],
|
||||
width: number,
|
||||
gutter: number
|
||||
): string[] {
|
||||
const textWidth = Math.max(MIN_TEXT_WIDTH, width - gutter - INDENT.length);
|
||||
const out: string[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const body = wrap(row.text, textWidth);
|
||||
const continuation = `${INDENT}${" ".repeat(gutter)}`;
|
||||
if (row.plain.length > gutter - 2) {
|
||||
// Too wide to share a line — give the label its own rather than pushing
|
||||
// every other row's gutter out to match it.
|
||||
out.push(`${INDENT}${row.pretty}`);
|
||||
out.push(...body.map((line) => `${continuation}${line}`));
|
||||
continue;
|
||||
}
|
||||
const pad = " ".repeat(gutter - row.plain.length);
|
||||
out.push(`${INDENT}${row.pretty}${pad}${body[0] ?? ""}`);
|
||||
out.push(...body.slice(1).map((line) => `${continuation}${line}`));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `-t, --target <port>` — the four leading spaces keep long flags aligned. */
|
||||
function flagRow(spec: FlagSpec): Row {
|
||||
const plainAlias = spec.alias ? `-${spec.alias}, ` : " ";
|
||||
const prettyAlias = spec.alias ? `${style.cyan(`-${spec.alias}`)}, ` : " ";
|
||||
const hint = spec.hint ? ` ${spec.hint}` : "";
|
||||
return {
|
||||
plain: `${plainAlias}--${spec.name}${hint}`,
|
||||
pretty: `${prettyAlias}${style.cyan(`--${spec.name}`)}${spec.hint ? ` ${style.dim(spec.hint)}` : ""}`,
|
||||
text: spec.defaultHint
|
||||
? `${spec.help} (default: ${spec.defaultHint})`
|
||||
: spec.help,
|
||||
};
|
||||
}
|
||||
|
||||
export interface HelpSection {
|
||||
body: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface CommandHelp {
|
||||
examples?: readonly { command: string; note?: string }[];
|
||||
/** Flag names, resolved against the registry. */
|
||||
flags: readonly string[];
|
||||
/** Trailing prose — Sandboxing, Backends. */
|
||||
sections?: readonly HelpSection[];
|
||||
subcommands?: readonly { name: string; summary: string }[];
|
||||
tagline: string;
|
||||
usage: readonly string[];
|
||||
}
|
||||
|
||||
export function renderHelp(help: CommandHelp): string {
|
||||
const width = terminalWidth();
|
||||
const lines: string[] = ["", help.tagline, "", style.bold("USAGE")];
|
||||
|
||||
for (const line of help.usage) {
|
||||
lines.push(`${INDENT}${style.dim("$")} ${line}`);
|
||||
}
|
||||
|
||||
if (help.subcommands?.length) {
|
||||
const rows = help.subcommands.map((cmd) => ({
|
||||
plain: cmd.name,
|
||||
pretty: style.cyan(cmd.name),
|
||||
text: cmd.summary,
|
||||
}));
|
||||
lines.push(
|
||||
"",
|
||||
style.bold("COMMANDS"),
|
||||
...renderRows(rows, width, gutterFor(rows))
|
||||
);
|
||||
}
|
||||
|
||||
// One gutter across every group, so the eye tracks a single column down the
|
||||
// whole page instead of re-finding it at each heading.
|
||||
const specs = specsFor(help.flags);
|
||||
const gutter = gutterFor(specs.map(flagRow));
|
||||
for (const group of GROUP_ORDER) {
|
||||
const inGroup = specs.filter((spec) => spec.group === group);
|
||||
if (inGroup.length === 0) {
|
||||
continue;
|
||||
}
|
||||
lines.push(
|
||||
"",
|
||||
style.bold(`${group} FLAGS`),
|
||||
...renderRows(inGroup.map(flagRow), width, gutter)
|
||||
);
|
||||
}
|
||||
|
||||
if (help.examples?.length) {
|
||||
lines.push("", style.bold("EXAMPLES"));
|
||||
for (const example of help.examples) {
|
||||
if (example.note) {
|
||||
lines.push(`${INDENT}${style.dim(`# ${example.note}`)}`);
|
||||
}
|
||||
lines.push(`${INDENT}${style.dim("$")} ${example.command}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const section of help.sections ?? []) {
|
||||
lines.push("", style.bold(section.title.toUpperCase()));
|
||||
const paragraphs = section.body.trim().split("\n\n");
|
||||
for (const [index, paragraph] of paragraphs.entries()) {
|
||||
lines.push(
|
||||
...wrap(paragraph, width - INDENT.length).map(
|
||||
(line) => `${INDENT}${line}`
|
||||
)
|
||||
);
|
||||
if (index < paragraphs.length - 1) {
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
Reference in New Issue
Block a user