#!/usr/bin/env node import { bootstrapAskDbEnv } from "@askdb/config"; import { existsSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { dotenvCandidates } from "./dotenv-candidates.js"; import { createAskDbHttpServer } from "./server.js"; type CliOptions = { schemaPath?: string; port?: number; host?: string; help?: boolean; }; let cliOptions: CliOptions; try { cliOptions = parseOptions(process.argv.slice(2)); } catch (error) { process.stderr.write(`askdb-http: ${formatError(error)}\n\n`); printHelp(process.stderr); process.exit(1); } if (cliOptions.help) { printHelp(process.stdout); process.exit(0); } { const here = dirname(fileURLToPath(import.meta.url)); // `src` isn't published, so it sits beside `dist` only in AskDB's own source checkout. const fromSourceCheckout = existsSync(resolve(here, "../src/bin.ts")); const candidates = dotenvCandidates(here, process.cwd(), fromSourceCheckout).filter((p) => existsSync(p)); try { bootstrapAskDbEnv({ cwd: process.cwd(), dotenvCandidatePaths: candidates.length > 0 ? candidates : undefined, }); } catch (error) { process.stderr.write(`askdb-http: ${formatError(error)}\n`); process.exit(1); } } // The server reuses the runtime installed above and falls back to `httpApi.listen.*` for // an omitted flag. Defensive: bootstrap installs only flattened, already-validated values (an // invalid `httpApi.requestTimeoutMs` fails above), so building the server is not expected to throw. let app: ReturnType; try { app = createAskDbHttpServer({ port: cliOptions.port, host: cliOptions.host, schemaPath: cliOptions.schemaPath, }); } catch (error) { process.stderr.write(`askdb-http: ${formatError(error)}\n`); process.exit(1); } try { await app.listen(); } catch (error) { process.stderr.write(`askdb-http: ${formatListenError(error, app.host, app.port)}\n`); process.exit(1); } console.log(`AskDB HTTP API listening on http://${app.host}:${app.port}`); function formatListenError(error: unknown, host: string, port: number): string { const code = (error as { code?: unknown } | undefined)?.code; if (code === "EADDRINUSE") { return `cannot listen on ${host}:${port} — address already in use. Pick another port with --port or httpApi.listen.port.`; } if (code === "EACCES") { return `cannot listen on ${host}:${port} — permission denied. Use a port above 1023 or run with the required privileges.`; } if (code === "EADDRNOTAVAIL") { return `cannot listen on ${host}:${port} — address not available on this machine. Check --host or httpApi.listen.host.`; } return `cannot listen on ${host}:${port} — ${formatError(error)}`; } function parseOptions(argv: readonly string[]): CliOptions { const opts: CliOptions = {}; for (let i = 0; i < argv.length; i += 1) { const arg = argv[i]!; switch (arg) { case "--schema-path": opts.schemaPath = readValue(argv, ++i, arg); break; case "--port": { const raw = readValue(argv, ++i, arg); if (!/^[0-9]+$/.test(raw)) { throw new Error(`Invalid --port: ${raw}`); } const port = Number(raw); if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error(`Invalid --port: ${raw}`); } opts.port = port; break; } case "--host": opts.host = readValue(argv, ++i, arg); break; case "--help": case "-h": opts.help = true; break; default: throw new Error(`Unknown option: ${arg}`); } } return opts; } function readValue(argv: readonly string[], index: number, flag: string): string { const value = argv[index]; if (!value || value.startsWith("--")) { throw new Error(`${flag} requires a value.`); } return value; } function printHelp(stream: NodeJS.WriteStream): void { stream.write( [ "askdb-http - Standalone AskDB HTTP API server", "", "Usage:", " askdb-http [--schema-path ] [--port ] [--host ]", "", "Options:", " --schema-path Server-default schema artifact path", " --port Port to listen on (0-65535; 0 picks a free port)", " --host Host to bind", " -h, --help Print this help", "", "CLI flags override askdb.config.ts values.", "", ].join("\n"), ); } function formatError(error: unknown): string { return error instanceof Error ? error.message : String(error); }