refactor(cli): restructure CLI with new command router and merge verify/doctor

- Replace custom argument parsing with generic cli-router
- Add subcommand support (myst config init, myst config view)
- Merge verify and doctor into single command with --diagnostic flag
- Extract shared forgejo-checks to utils
- Remove unused code (generatePassword, EnvKey/ConfigKey types)
- Add dynamic package.json for help/version display
This commit is contained in:
ZTatman 2026-04-11 22:16:22 -04:00
parent 6884dffda6
commit d6b9677ca5
13 changed files with 705 additions and 662 deletions

View file

@ -0,0 +1,243 @@
import { parseArgs } from "node:util";
import * as c from "yoctocolors";
type Handler = (opts: Record<string, unknown>) => Promise<void>;
interface OptionSpec {
type: "string" | "boolean";
short?: string;
default?: string | boolean | string[] | boolean[];
}
type OptionsSpec = Record<string, OptionSpec>;
export interface CommandConfig {
description?: string;
options?: OptionsSpec;
subcommands?: Record<string, CommandConfig>;
handler?: Handler;
}
export type CommandRegistry = Record<string, CommandConfig>;
function showHelp(registry: CommandRegistry, description: string): void {
const PADDING = 4;
const INDENT = " ";
type HelpRow = { name: string; desc?: string };
const rows: HelpRow[] = [];
function addCommands(cmds: CommandRegistry, prefix = "") {
for (const [name, def] of Object.entries(cmds)) {
const fullName = prefix ? `${prefix} ${name}` : name;
if (def.subcommands) {
rows.push({ name: fullName });
addCommands(def.subcommands, fullName);
} else if (def.description) {
rows.push({ name: fullName, desc: def.description });
}
}
}
addCommands(registry);
const globalFlagRows: HelpRow[] = [
{ name: "-h, --help", desc: "Display help" },
{ name: "-v, --version", desc: "Display version" },
];
const allRows = [...rows, ...globalFlagRows];
const colWidth = Math.max(...allRows.map((r) => r.name.length)) + PADDING;
const lines: string[] = [];
lines.push(c.yellow("myst"));
lines.push("");
lines.push(`${INDENT}${description}`);
lines.push("");
lines.push(c.bold("Usage:"));
lines.push(`${INDENT}myst <command> [options]`);
lines.push("");
lines.push(c.bold("Commands:"));
for (const row of rows) {
if (row.desc) {
lines.push(`${INDENT}${row.name.padEnd(colWidth)}${c.dim(row.desc)}`);
} else {
lines.push(`${INDENT}${c.bold(row.name)}`);
}
}
lines.push("");
lines.push(c.bold("Global options:"));
for (const row of globalFlagRows) {
const desc = row.desc ?? "";
lines.push(`${INDENT}${row.name.padEnd(colWidth)}${c.dim(desc)}`);
}
process.stdout.write(lines.join("\n") + "\n");
}
function showCommandHelp(
command: string,
cmdConf: CommandConfig,
subcommand?: string,
): void {
const PADDING = 4;
const INDENT = " ";
type HelpRow = { name: string; desc?: string };
let targetConf: CommandConfig = cmdConf;
if (subcommand && cmdConf.subcommands) {
targetConf = cmdConf.subcommands[subcommand] ?? cmdConf;
}
const lines: string[] = [];
const fullName = subcommand ? `${command} ${subcommand}` : command;
lines.push(c.yellow("myst " + fullName));
lines.push("");
if (targetConf.description) {
lines.push(`${INDENT}${targetConf.description}`);
lines.push("");
}
const usageCmd = subcommand ? `${command} ${subcommand}` : command;
lines.push(c.bold("Usage:"));
lines.push(`${INDENT}myst ${usageCmd} [options]`);
lines.push("");
if (targetConf.options && Object.keys(targetConf.options).length > 0) {
const optionRows: HelpRow[] = [];
for (const [optName, optSpec] of Object.entries(targetConf.options)) {
const short = optSpec.short ? `, -${optSpec.short}` : "";
const typeHint = optSpec.type === "string" ? " <value>" : "";
optionRows.push({
name: `--${optName}${short}${typeHint}`,
desc: "",
});
}
const colWidth = Math.max(...optionRows.map((r) => r.name.length)) + PADDING;
lines.push(c.bold("Options:"));
for (const row of optionRows) {
lines.push(`${INDENT}${row.name.padEnd(colWidth)}`);
}
lines.push("");
}
lines.push(c.bold("Global options:"));
lines.push(`${INDENT}-h, --help Display help`);
lines.push(`${INDENT}-v, --version Display version`);
process.stdout.write(lines.join("\n") + "\n");
}
export async function runCli(
argv: string[],
registry: CommandRegistry,
): Promise<void> {
// Load package info once
const pkg = await import("../package.json", { with: { type: "json" } });
const description = pkg.default.description;
const version = pkg.default.version;
// Check for help/version flags
const isHelpFlag = (arg: string) => arg === "--help" || arg === "-h";
const isVersionFlag = (arg: string) => arg === "--version" || arg === "-v";
// Check for version flag (early exit)
if (argv.length > 0 && argv.every(isVersionFlag)) {
process.stdout.write(version);
return;
}
// If no args or only help flags, show global help
if (argv.length === 0 || argv.every(isHelpFlag)) {
showHelp(registry, description);
return;
}
// Extract command and subcommand directly from argv
const command = argv[0] ?? "";
const subcommand = argv[1] ?? "";
const remainingArgs = argv.slice(2);
// If user types myst -h or --help with a command
const wantsCommandHelp =
isHelpFlag(subcommand) || remainingArgs.some(isHelpFlag);
const cmdConf = registry[command];
// Check if the command exists
if (!cmdConf) {
process.stderr.write(`${c.red("Error:")} Unknown command: ${command}\n`);
process.exitCode = 1;
return;
}
// If help is requested for a specific command, show command-specific help
if (wantsCommandHelp) {
showCommandHelp(command, cmdConf, subcommand || undefined);
return;
}
let targetCmdConf: CommandConfig | undefined;
// Check if subcommand was passed and if it's a valid subcommand (not an option flag)
const subcommands = cmdConf.subcommands;
const isSubcommandAnOption = subcommand && subcommand.startsWith("-");
if (isSubcommandAnOption) {
// Subcommand looks like an option (e.g., --diagnostic), treat as option for parent
targetCmdConf = cmdConf.handler ? cmdConf : undefined;
} else if (subcommand && subcommands && subcommand in subcommands) {
targetCmdConf = subcommands[subcommand];
} else if (!subcommand && cmdConf.handler) {
// No subcommand passed, use the parent command handler directly
targetCmdConf = cmdConf;
}
// Check if the target subcommand handler exists
if (!targetCmdConf?.handler) {
if (subcommands && Object.keys(subcommands).length > 0) {
process.stderr.write(
`${c.red("Error:")} Missing subcommand for '${command}'. Available: ${Object.keys(subcommands).join(", ")}\n`,
);
} else {
// No subcommands available, treat as unknown subcommand
process.stderr.write(
`${c.red("Error:")} Unknown subcommand: ${subcommand}\n`,
);
}
process.exitCode = 1;
return;
}
// Build args for parseArgs - if subcommand is an option, include it
const argsForOptions = isSubcommandAnOption
? [subcommand, ...remainingArgs]
: remainingArgs;
// Parse target command options
const { values: cmdOpts } = parseArgs({
args: argsForOptions,
options: targetCmdConf.options || {},
allowPositionals: true,
});
try {
// Execute the target command handler
await targetCmdConf.handler(cmdOpts);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
process.stderr.write(`${c.red("Error:")} ${message}\n`);
process.exitCode = 1;
}
}

View file

@ -0,0 +1,14 @@
import * as configInit from "./commands/config/init.js";
import * as configView from "./commands/config/view.js";
import * as verify from "./commands/verify.js";
export const commandRegistry = {
config: {
description: "Configuration commands",
subcommands: {
init: configInit.commandConfig,
view: configView.commandConfig,
},
},
verify: verify.commandConfig,
};

View file

@ -1,44 +0,0 @@
import path from "node:path";
import * as c from "yoctocolors";
import { ENV_MAPPING, MystEnvironmentVariables, parseEnvFile } from "../config.js";
function redactSecret(value: string | undefined): string {
if (!value) return c.dim("not set");
if (value.length <= 4) return c.dim("****");
return value.slice(0, 4) + c.dim("****");
}
export async function configCommand(): Promise<void> {
const envPath = path.join(process.cwd(), ".env");
let config: Partial<MystEnvironmentVariables>;
try {
config = parseEnvFile(envPath);
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ENOENT") {
process.stderr.write(
`${c.red("Error:")} .env file not found in ${process.cwd()}\n`,
);
process.exitCode = 1;
return;
}
throw error;
}
process.stdout.write(c.bold("Myst Configuration\n"));
process.stdout.write(`${c.dim("─".repeat(40))}\n`);
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
const value = config[configKey];
const displayValue =
configKey === "forgejoPat" || configKey === "grantTokenSecret"
? redactSecret(value)
: value || c.dim("not set");
process.stdout.write(`${c.bold(envKey + ":")} ${displayValue}\n`);
}
process.exitCode = 0;
}

View file

@ -4,128 +4,72 @@ import path from "node:path";
import * as c from "yoctocolors";
import * as p from "@clack/prompts";
import { generateSecret } from "../utils/crypto.js";
import { generateEnvFile } from "../config.js";
import { generateSecret } from "../../utils/crypto.js";
import { generateEnvFile, DATABASE_PROTOCOLS } from "../../utils/config.js";
import { CommandConfig } from "../../cli-router.js";
/**
* Normalizes a URL to use https:// if no protocol is specified.
* @param value - The URL to normalize.
* @returns {string} The normalized URL.
*/
function normalizeHttpUrl(value: string): string {
const trimmed = value.trim();
const hasProtocol = /^[a-z]+:\/\//i.test(trimmed);
const isNotHttp = !/^https?:\/\//i.test(trimmed);
async function init(opts: { output?: string }) {
// Helper functions scoped to init
function normalizeHttpUrl(value: string): string {
const trimmed = value.trim();
const hasProtocol = /^[a-z]+:\/\//i.test(trimmed);
const isNotHttp = !/^https?:\/\//i.test(trimmed);
if (hasProtocol && isNotHttp) {
throw new Error("URLs must use http:// or https://");
}
return hasProtocol ? trimmed : `https://${trimmed}`;
}
/**
* Validates a URL or host, returning the normalized URL or undefined if valid.
* @param value - The URL or host to validate.
* @param label - The label to use in error messages.
* @returns {string | undefined} The normalized URL or undefined if valid.
*/
function validateHttpUrlOrHost(
value: string | undefined,
label: string,
): string | undefined {
if (!value?.trim()) return `${label} is required`;
try {
const normalized = normalizeHttpUrl(value);
const url = new URL(normalized);
if (!url.hostname) {
return `${label} must include a domain or hostname`;
if (hasProtocol && isNotHttp) {
throw new Error("URLs must use http:// or https://");
}
} catch {
return `${label} must be a valid URL or hostname`;
return hasProtocol ? trimmed : `https://${trimmed}`;
}
return undefined;
}
function validateHttpUrlOrHost(
value: string | undefined,
label: string,
): string | undefined {
if (!value?.trim()) return `${label} is required`;
/**
* Validates a Postgres URL, returning undefined if valid.
* @param value - The Postgres URL to validate.
* @returns {string | undefined} The error message or undefined if valid.
*/
function validatePostgresUrl(value: string | undefined): string | undefined {
if (!value?.trim()) {
return "Database URL is required";
}
try {
const url = new URL(value);
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
return "Database URL must start with postgres:// or postgresql://";
try {
const normalized = normalizeHttpUrl(value);
const url = new URL(normalized);
if (!url.hostname) {
return `${label} must include a domain or hostname`;
}
} catch {
return `${label} must be a valid URL or hostname`;
}
} catch {
return "Database URL must be a valid Postgres connection string";
return undefined;
}
return undefined;
}
function validatePostgresUrl(value: string | undefined): string | undefined {
if (!value?.trim()) {
return "Database URL is required";
}
/**
* Writes a private file to disk, throwing an error if the file already exists.
* @param filePath - The path to the file to write.
* @param content - The content to write to the file.
* @returns {Promise<void>} A promise that resolves when the file is written.
*/
async function writePrivateFile(
filePath: string,
content: string,
): Promise<void> {
try {
try {
const url = new URL(value);
if (!DATABASE_PROTOCOLS.includes(url.protocol as "postgres:" | "postgresql:")) {
return "Database URL must start with postgres:// or postgresql://";
}
} catch {
return "Database URL must be a valid Postgres connection string";
}
return undefined;
}
async function writePrivateFile(
filePath: string,
content: string,
): Promise<void> {
await fs.writeFile(filePath, content, {
encoding: "utf8",
flag: "wx",
mode: 0o600,
});
} catch (e) {
const error = e as NodeJS.ErrnoException;
if (error.code === "EEXIST") {
throw new Error(
`Error: the file '${c.underline(path.basename(filePath))}' already exists in directory ${c.underline(path.dirname(filePath))}`,
);
}
throw error; // throw any other errors back if not EEXIST code
}
}
/**
* Preflight check for write targets, throwing an error if any target file already exists.
* @param filePaths - The paths of the files to write.
* @returns {Promise<void>} A promise that resolves when all targets are checked.
*/
async function preflightWriteTargets(filePaths: string[]): Promise<void> {
for (const filePath of filePaths) {
try {
await fs.access(filePath);
throw new Error(
`Error: the file '${c.underline(path.basename(filePath))}' already exists in directory ${c.underline(path.dirname(filePath))}`,
);
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code !== "ENOENT") {
throw error;
}
}
}
}
/**
* Initializes a Myst project by creating the necessary configuration files.
* @param _args - The command arguments.
* @returns {Promise<void>} A promise that resolves when the initialization is complete.
*/
export async function initCommand(args?: string[]): Promise<void> {
p.intro(c.bold("myst init"));
p.intro(c.bold("myst config init"));
p.note(
[
`${c.bold("Run this in the directory where you plan to deploy Myst.")}`,
@ -145,6 +89,48 @@ export async function initCommand(args?: string[]): Promise<void> {
c.yellow("Before you start:"),
);
const outDir = opts.output ? path.dirname(opts.output) : process.cwd();
const envPath = opts.output || path.join(outDir, ".env");
let envExists = false;
try {
await fs.stat(envPath);
envExists = true;
} catch {
// .env file does not exist
}
if (envExists) {
while (true) {
const choice = await p.select({
message: c.red(
`The file .env already exists at ${envPath}. What would you like to do?`,
),
options: [
{ value: "view", label: "View .env content" },
{ value: "overwrite", label: "Overwrite .env" },
{ value: "cancel", label: "Cancel" },
],
});
if (p.isCancel(choice) || choice === "cancel") {
p.cancel("\nOperation cancelled.");
process.exit(0);
}
if (choice === "view") {
const envContent = await fs.readFile(envPath, { encoding: "utf-8" });
p.note(c.dim(envContent), c.yellow("Current .env"));
continue;
}
if (choice === "overwrite") {
await fs.unlink(envPath);
break;
}
}
}
const answers = await p.group(
{
publicUrl: () =>
@ -223,29 +209,21 @@ export async function initCommand(args?: string[]): Promise<void> {
publicUrl,
});
const outDir = process.cwd();
const envPath = path.join(outDir, ".env");
await preflightWriteTargets([envPath]);
await writePrivateFile(envPath, envContent);
s.stop("Config files generated");
p.note(c.green(".env"), c.yellow("File written to current directory"));
s.stop(c.yellow(`.env created at ${envPath}`));
p.note(
[
`${c.bold("Public viewer URL:")} ${c.cyan(publicUrl)}`,
`${c.bold("Private admin URL:")} ${c.cyan(adminUrl)}`,
`${c.bold("Admin URL:")} ${c.cyan(adminUrl)}`,
`${c.bold("Forgejo base URL:")} ${c.cyan(forgejoBaseUrl)}`,
`${c.bold("Forgejo bot username:")} ${c.green(answers.forgejoBotUsername)}`,
`${c.bold("Myst bot username:")} ${c.cyan(answers.forgejoBotUsername)}`,
"",
`${c.bold("Admin URL reminder:")} protect this upstream with Tailscale, VPN, Cloudflare Access, or reverse-proxy auth.`,
].join("\n"),
c.yellow("Next steps"),
);
p.outro(
c.green(
"Done. Deploy Myst, then run forgejo bootstrap and doctor commands to verify setup.",
),
p.log.success(
"Done. Verify myst's connection using the 'verify' command.\nOnce verified, deploy!",
);
} catch (error) {
s.stop();
@ -255,3 +233,11 @@ export async function initCommand(args?: string[]): Promise<void> {
process.exitCode = 1;
}
}
export const commandConfig: CommandConfig = {
description: "Generate .env file",
options: {
output: { type: "string", short: "o" },
},
handler: init,
};

View file

@ -0,0 +1,53 @@
import path from "node:path";
import * as c from "yoctocolors";
import {
ENV_MAPPING,
MystEnvironmentVariables,
parseEnvFile,
} from "../../utils/config.js";
import { CommandConfig } from "../../cli-router.js";
function redactSecret(value: string | undefined): string {
if (!value) return c.dim("not set");
if (value.length <= 4) return c.dim("****");
return value.slice(0, 4) + c.dim("****");
}
export const commandConfig: CommandConfig = {
description: "Display current configuration",
handler: async () => {
const envPath = path.join(process.cwd(), ".env");
let config: Partial<MystEnvironmentVariables>;
try {
config = parseEnvFile(envPath);
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ENOENT") {
process.stderr.write(
`${c.red("Error:")} .env file not found in ${process.cwd()}\n`,
);
process.exitCode = 1;
return;
}
throw error;
}
process.stdout.write(c.bold("Myst Configuration\n"));
process.stdout.write(`${c.dim("─".repeat(40))}\n`);
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
const value = config[configKey];
const displayValue =
configKey === "forgejoPat" || configKey === "grantTokenSecret"
? redactSecret(value)
: value || c.dim("not set");
process.stdout.write(`${c.bold(envKey + ":")} ${displayValue}\n`);
}
process.exitCode = 0;
},
};

View file

@ -1,157 +0,0 @@
import path from "node:path";
import * as c from "yoctocolors";
import * as p from "@clack/prompts";
import { ENV_MAPPING, MystEnvironmentVariables, parseEnvFile, validateDatabaseUrl, REQUIRED_KEYS } from "../config.js";
type CheckResult = {
name: string;
success: boolean;
message?: string;
};
async function checkForgejoReachability(baseUrl: string): Promise<CheckResult> {
try {
const response = await fetch(baseUrl, { method: "GET" });
if (response.ok || response.status === 200) {
return { name: "Forgejo reachability", success: true };
}
return {
name: "Forgejo reachability",
success: false,
message: `HTTP ${response.status}`,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return {
name: "Forgejo reachability",
success: false,
message,
};
}
}
async function checkForgejoApi(
baseUrl: string,
pat: string,
): Promise<CheckResult> {
try {
const response = await fetch(`${baseUrl}/api/v1/user`, {
method: "GET",
headers: {
Authorization: `Bearer ${pat}`,
},
});
if (response.status === 401) {
return {
name: "Forgejo API token",
success: false,
message: "Invalid or expired token",
};
}
if (!response.ok) {
return {
name: "Forgejo API token",
success: false,
message: `HTTP ${response.status}`,
};
}
const user = (await response.json()) as { login: string };
return {
name: "Forgejo API token",
success: true,
message: `Authenticated as ${c.green(user.login)}`,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return {
name: "Forgejo API token",
success: false,
message,
};
}
}
export async function doctorCommand(): Promise<void> {
p.intro(c.bold("myst doctor"));
const envPath = path.join(process.cwd(), ".env");
const results: CheckResult[] = [];
let config: Partial<MystEnvironmentVariables>;
try {
config = parseEnvFile(envPath);
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ENOENT") {
p.cancel(`${c.red("Error:")} .env file not found in ${process.cwd()}`);
process.exitCode = 1;
return;
}
throw error;
}
function addResult(name: string, success: boolean, message?: string) {
results.push({ name, success, ...(message && { message }) });
}
addResult("Config file exists", true, envPath);
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
const value = config[configKey];
addResult(`${envKey} set`, !!value, value ? "configured" : "missing");
}
if (config.databaseUrl) {
const valid = validateDatabaseUrl(config.databaseUrl);
addResult("Database URL format", valid, valid ? "valid" : "invalid");
}
if (config.forgejoBaseUrl && config.forgejoPat) {
const reachability = await checkForgejoReachability(config.forgejoBaseUrl);
results.push(reachability);
if (reachability.success) {
const apiToken = await checkForgejoApi(
config.forgejoBaseUrl,
config.forgejoPat,
);
results.push(apiToken);
}
}
const s = p.spinner();
try {
s.start("Running diagnostics");
s.stop("Diagnostics complete");
const lines = results.map((r) => {
const icon = r.success ? c.green("✓") : c.red("✗");
const msg = r.message ? ` ${r.message}` : "";
return `${icon} ${r.name}${msg}`;
});
p.note(lines.join("\n"), c.yellow("Results"));
const failures = results.filter((r) => !r.success);
if (failures.length > 0) {
p.outro(c.red(`${failures.length} issue(s) found`));
process.exitCode = 1;
return;
}
p.outro(c.green("All checks passed"));
} catch (error) {
s.stop();
const message = error instanceof Error ? error.message : "Unknown error";
p.cancel(`${c.red("Error:")} ${message}`);
process.exitCode = 1;
}
}

View file

@ -2,129 +2,28 @@ import path from "node:path";
import * as c from "yoctocolors";
import * as p from "@clack/prompts";
import { MystEnvironmentVariables, parseEnvFile, REQUIRED_KEYS } from "../config.js";
type CheckResult = {
name: string;
success: boolean;
message?: string;
};
import {
ENV_MAPPING,
MystEnvironmentVariables,
parseEnvFile,
validateDatabaseUrl,
REQUIRED_KEYS,
} from "../utils/config.js";
import {
checkForgejoReachability,
checkForgejoApi,
checkRepoAccess,
} from "../utils/forgejo-checks.js";
import { CommandConfig } from "../cli-router.js";
async function checkForgejoReachability(baseUrl: string): Promise<CheckResult> {
try {
const response = await fetch(baseUrl, { method: "GET" });
if (response.ok || response.status === 200) {
return { name: "Forgejo reachability", success: true };
}
return {
name: "Forgejo reachability",
success: false,
message: `HTTP ${response.status}`,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return {
name: "Forgejo reachability",
success: false,
message,
};
}
interface VerifyOptions {
diagnostic?: boolean;
}
async function checkForgejoApi(
baseUrl: string,
pat: string,
): Promise<CheckResult> {
try {
const response = await fetch(`${baseUrl}/api/v1/user`, {
method: "GET",
headers: {
Authorization: `Bearer ${pat}`,
},
});
if (response.status === 401) {
return {
name: "Forgejo API token",
success: false,
message: "Invalid or expired token",
};
}
if (!response.ok) {
return {
name: "Forgejo API token",
success: false,
message: `HTTP ${response.status}`,
};
}
const user = (await response.json()) as { login: string };
return {
name: "Forgejo API token",
success: true,
message: `Authenticated as ${user.login}`,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return {
name: "Forgejo API token",
success: false,
message,
};
}
}
async function checkRepoAccess(
baseUrl: string,
pat: string,
username: string,
): Promise<CheckResult> {
try {
const response = await fetch(
`${baseUrl}/api/v1/users/${username}/repos?limit=1`,
{
method: "GET",
headers: {
Authorization: `Bearer ${pat}`,
},
},
);
if (!response.ok) {
return {
name: "Repo access",
success: false,
message: `HTTP ${response.status}`,
};
}
const repos = (await response.json()) as { name: string }[];
if (repos.length > 0) {
return {
name: "Repo access",
success: true,
message: `Found ${repos.length} repo(s)`,
};
}
return {
name: "Repo access",
success: true,
message: "No repos found (service account may not have repo access)",
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return {
name: "Repo access",
success: false,
message,
};
}
}
export async function verifyCommand(): Promise<void> {
p.intro(c.bold("myst verify"));
async function verifyCommand(opts: VerifyOptions): Promise<void> {
const diagnostic = opts.diagnostic ?? false;
p.intro(c.bold("myst config verify"));
const envPath = path.join(process.cwd(), ".env");
@ -135,91 +34,166 @@ export async function verifyCommand(): Promise<void> {
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === "ENOENT") {
p.cancel(
`${c.red("Error:")} .env file not found in ${process.cwd()}`,
);
p.cancel(`${c.red("Error:")} .env file not found in ${process.cwd()}`);
process.exitCode = 1;
return;
}
throw error;
}
const missing: string[] = [];
const results: { name: string; success: boolean; message?: string }[] = [];
for (const key of REQUIRED_KEYS) {
if (!config[key]) {
const envKey = Object.entries({
forgejoBaseUrl: "FORGEJO_BASE_URL",
forgejoBotUsername: "FORGEJO_BOT_USERNAME",
forgejoPat: "FORGEJO_PAT",
}).find(([, v]) => v === key)?.[0];
if (envKey) missing.push(envKey);
function addResult(name: string, success: boolean, message?: string) {
results.push({ name, success, ...(message !== undefined && { message }) });
}
if (diagnostic) {
addResult("Config file exists", true, envPath);
for (const [envKey, configKey] of Object.entries(ENV_MAPPING)) {
const value = config[configKey];
addResult(`${envKey} set`, !!value, value ? "configured" : "missing");
}
if (config.databaseUrl) {
const valid = validateDatabaseUrl(config.databaseUrl);
addResult("Database URL format", valid, valid ? "valid" : "invalid");
}
}
if (missing.length > 0) {
p.cancel(
`${c.red("Error:")} Missing required config: ${missing.join(", ")}`,
);
process.exitCode = 1;
return;
const forgejoConfigured =
config.forgejoBaseUrl && config.forgejoPat && config.forgejoBotUsername;
if (forgejoConfigured && config.forgejoBaseUrl && config.forgejoPat) {
const reachability = await checkForgejoReachability(config.forgejoBaseUrl);
results.push(reachability);
if (reachability.success) {
const apiToken = await checkForgejoApi(
config.forgejoBaseUrl,
config.forgejoPat,
diagnostic,
);
results.push(apiToken);
if (apiToken.success && config.forgejoBotUsername) {
const repoAccess = await checkRepoAccess(
config.forgejoBaseUrl,
config.forgejoPat,
config.forgejoBotUsername,
);
results.push(repoAccess);
}
}
}
const s = p.spinner();
try {
s.start("Verifying Forgejo configuration");
if (diagnostic) {
s.start("Running diagnostics");
s.stop("Diagnostics complete");
const reachability: CheckResult = await checkForgejoReachability(
config.forgejoBaseUrl!,
);
const lines = results.map((r) => {
const icon = r.success ? c.green("✓") : c.red("✗");
const msg = r.message ? ` ${r.message}` : "";
return `${icon} ${r.name}${msg}`;
});
if (!reachability.success) {
s.stop(reachability.message);
p.cancel(`${c.red("✗")} ${reachability.name}: ${reachability.message}`);
process.exitCode = 1;
return;
p.note(lines.join("\n"), c.yellow("Results"));
const failures = results.filter((r) => !r.success);
if (failures.length > 0) {
p.outro(c.red(`${failures.length} issue(s) found`));
process.exitCode = 1;
return;
}
p.outro(c.green("All checks passed"));
} else {
const missing: string[] = [];
for (const key of REQUIRED_KEYS) {
if (!config[key]) {
const envKey = Object.entries({
forgejoBaseUrl: "FORGEJO_BASE_URL",
forgejoBotUsername: "FORGEJO_BOT_USERNAME",
forgejoPat: "FORGEJO_PAT",
}).find(([, v]) => v === key)?.[0];
if (envKey) missing.push(envKey);
}
}
if (missing.length > 0) {
p.cancel(
`${c.red("Error:")} Missing required config: ${missing.join(", ")}`,
);
process.exitCode = 1;
return;
}
s.start("Verifying Forgejo configuration");
const reachability = await checkForgejoReachability(
config.forgejoBaseUrl!,
);
if (!reachability.success) {
s.stop(reachability.message);
p.cancel(`${c.red("✗")} ${reachability.name}: ${reachability.message}`);
process.exitCode = 1;
return;
}
const apiToken = await checkForgejoApi(
config.forgejoBaseUrl!,
config.forgejoPat!,
);
if (!apiToken.success) {
s.stop(apiToken.message);
p.cancel(`${c.red("✗")} ${apiToken.name}: ${apiToken.message}`);
process.exitCode = 1;
return;
}
const repoAccess = await checkRepoAccess(
config.forgejoBaseUrl!,
config.forgejoPat!,
config.forgejoBotUsername!,
);
s.stop("Verification complete");
p.note(
[
`${c.green("✓")} ${reachability.name}`,
`${c.green("✓")} ${apiToken.name}: ${apiToken.message}`,
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
].join("\n"),
c.yellow("Results"),
);
if (!repoAccess.success) {
process.exitCode = 1;
return;
}
p.outro(c.green("Verification passed"));
}
const apiToken: CheckResult = await checkForgejoApi(
config.forgejoBaseUrl!,
config.forgejoPat!,
);
if (!apiToken.success) {
s.stop(apiToken.message);
p.cancel(`${c.red("✗")} ${apiToken.name}: ${apiToken.message}`);
process.exitCode = 1;
return;
}
const repoAccess = await checkRepoAccess(
config.forgejoBaseUrl!,
config.forgejoPat!,
config.forgejoBotUsername!,
);
s.stop("Verification complete");
p.note(
[
`${c.green("✓")} ${reachability.name}`,
`${c.green("✓")} ${apiToken.name}: ${apiToken.message}`,
`${c.green(repoAccess.success ? "✓" : "✗")} ${repoAccess.name}: ${repoAccess.message}`,
].join("\n"),
c.yellow("Results"),
);
if (!repoAccess.success) {
process.exitCode = 1;
return;
}
p.outro(c.green("Forgejo verification passed"));
} catch (error) {
s.stop();
const message = error instanceof Error ? error.message : "Unknown error";
p.cancel(`${c.red("Error:")} ${message}`);
process.exitCode = 1;
}
}
}
export const commandConfig: CommandConfig = {
description: "Verify Myst configuration and connection to Forgejo",
options: {
diagnostic: { type: "boolean" },
},
handler: verifyCommand,
};

View file

@ -1,64 +0,0 @@
import * as c from "yoctocolors";
import pkg from "../package.json" with { type: "json" };
const PADDING = 4;
const INDENT = " ";
type HelpRow = {
name: string;
desc?: string;
};
const commandRows: HelpRow[] = [
{ name: "init", desc: "Generate config files with the proper env variables" },
];
const globalFlagRows: HelpRow[] = [
{ name: "-h, --help", desc: "Display help information" },
{ name: "-v, --version", desc: "Display package version number" },
];
function formatSection(
header: string,
rows: HelpRow[],
colWidth: number,
): string {
return [
c.bold(`${header}:`),
...rows.map((row) =>
row.desc
? `${INDENT}${row.name.padEnd(colWidth)}${row.desc}`
: `${INDENT}${row.name}`,
),
].join("\n");
}
/**
* Returns the help text for the CLI.
* @returns The help text.
*/
export function getHelpText(): string {
const allRows = [...commandRows, ...globalFlagRows];
const colWidth = Math.max(...allRows.map((row) => row.name.length)) + PADDING;
return [
c.yellow("myst"),
"",
`${INDENT}${pkg.description}`,
"",
formatSection(
"Usage",
[
{
name: "myst <command> [options/flags] [arguments]",
},
],
colWidth,
),
"",
formatSection("Commands", commandRows, colWidth),
"",
formatSection("Global flags", globalFlagRows, colWidth),
"",
].join("\n");
}

View file

@ -1,82 +1,5 @@
#!/usr/bin/env node
import { parseArgs } from "node:util";
import { runCli } from "./cli-router.js";
import { commandRegistry } from "./commandRegistry.js";
import * as c from "yoctocolors";
import pkg from "../package.json" with { type: "json" };
import { initCommand } from "./commands/init.js";
import { configCommand } from "./commands/config.js";
import { verifyCommand } from "./commands/verify.js";
import { doctorCommand } from "./commands/doctor.js";
import { getHelpText } from "./help.js";
type CommandName = "init" | "config" | "verify" | "doctor";
type CommandHandler = (args?: string[]) => Promise<void>;
const commandHandlers: Record<CommandName, CommandHandler> = {
init: initCommand,
config: configCommand,
verify: verifyCommand,
doctor: doctorCommand,
};
async function main(): Promise<void> {
const { values, positionals } = parseArgs({
args: process.argv.slice(2),
options: {
version: {
type: "boolean",
short: "v",
},
help: {
type: "boolean",
short: "h",
},
output: {
type: "string",
short: "o",
},
},
allowPositionals: true,
});
const command = positionals[0];
if (!command) {
process.stdout.write(getHelpText());
process.exitCode = 0;
return;
}
const isKnownCommand = (cmd: string): cmd is CommandName =>
cmd in commandHandlers;
if (!isKnownCommand(command)) {
process.stderr.write(`Unknown command: ${command}\n`);
process.exitCode = 1;
return;
}
if (values.help) {
process.stdout.write(getHelpText());
process.exitCode = 0;
return;
}
if (values.version) {
process.stdout.write(`${pkg.version}`);
process.exitCode = 0;
return;
}
try {
await commandHandlers[command]();
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
process.stderr.write(`${c.red("Error:")} ${message}\n`);
process.exitCode = 1;
}
}
await main();
await runCli(process.argv.slice(2), commandRegistry);

View file

@ -28,10 +28,9 @@ export const REQUIRED_KEYS = [
export const DATABASE_PROTOCOLS = ["postgres:", "postgresql:"] as const;
export type EnvKey = keyof typeof ENV_MAPPING;
export type ConfigKey = (typeof ENV_MAPPING)[EnvKey];
export function parseEnvFile(envPath: string): Partial<MystEnvironmentVariables> {
export function parseEnvFile(
envPath: string,
): Partial<MystEnvironmentVariables> {
const config: Partial<MystEnvironmentVariables> = {};
const content = fs.readFileSync(envPath, "utf-8");
const lines = content.split("\n");
@ -44,7 +43,7 @@ export function parseEnvFile(envPath: string): Partial<MystEnvironmentVariables>
if (!key) continue;
const value = valueParts.join("=").trim();
const configKey = ENV_MAPPING[key as EnvKey];
const configKey = ENV_MAPPING[key as keyof typeof ENV_MAPPING];
if (configKey) {
config[configKey] = value;
@ -58,7 +57,7 @@ export function validateDatabaseUrl(url: string | undefined): boolean {
if (!url) return false;
try {
const parsed = new URL(url);
return parsed.protocol === "postgres:" || parsed.protocol === "postgresql:";
return DATABASE_PROTOCOLS.includes(parsed.protocol as "postgres:" | "postgresql:");
} catch {
return false;
}
@ -93,4 +92,4 @@ export function generateEnvFile(options: MystEnvironmentVariables): string {
];
return lines.join("\n");
}
}

View file

@ -3,7 +3,3 @@ import { randomBytes } from "node:crypto";
export function generateSecret(bytes = 32): string {
return randomBytes(bytes).toString("hex");
}
export function generatePassword(bytes = 16): string {
return randomBytes(bytes).toString("base64url");
}

View file

@ -0,0 +1,122 @@
export type CheckResult = {
name: string;
success: boolean;
message?: string;
};
export function createCheckResult(
name: string,
success: boolean,
message?: string,
): CheckResult {
const result: CheckResult = { name, success };
if (message !== undefined) {
result.message = message;
}
return result;
}
export async function checkForgejoReachability(
baseUrl: string,
): Promise<CheckResult> {
try {
const response = await fetch(baseUrl, { method: "GET" });
if (response.ok || response.status === 200) {
return createCheckResult("Forgejo reachability", true);
}
return createCheckResult(
"Forgejo reachability",
false,
`HTTP ${response.status}`,
);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return createCheckResult("Forgejo reachability", false, message);
}
}
export async function checkForgejoApi(
baseUrl: string,
pat: string,
colorize = false,
): Promise<CheckResult> {
try {
const response = await fetch(`${baseUrl}/api/v1/user`, {
method: "GET",
headers: {
Authorization: `Bearer ${pat}`,
},
});
if (response.status === 401) {
return createCheckResult(
"Forgejo API token",
false,
"Invalid or expired token",
);
}
if (!response.ok) {
return createCheckResult(
"Forgejo API token",
false,
`HTTP ${response.status}`,
);
}
const user = (await response.json()) as { login: string };
let login = user.login;
if (colorize) {
const { default: c } = await import("yoctocolors");
login = c.green(user.login);
}
return createCheckResult(
"Forgejo API token",
true,
`Authenticated as ${login}`,
);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return createCheckResult("Forgejo API token", false, message);
}
}
export async function checkRepoAccess(
baseUrl: string,
pat: string,
username: string,
): Promise<CheckResult> {
try {
const response = await fetch(
`${baseUrl}/api/v1/users/${username}/repos?limit=1`,
{
method: "GET",
headers: {
Authorization: `Bearer ${pat}`,
},
},
);
if (!response.ok) {
return createCheckResult("Repo access", false, `HTTP ${response.status}`);
}
const repos = (await response.json()) as { name: string }[];
if (repos.length > 0) {
return createCheckResult(
"Repo access",
true,
`Found ${repos.length} repo(s)`,
);
}
return createCheckResult(
"Repo access",
true,
"No repos found (service account may not have repo access)",
);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return createCheckResult("Repo access", false, message);
}
}

View file

@ -3,10 +3,8 @@
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist"
"outDir": "dist",
},
"references": [
{ "path": "../shared" }
],
"include": ["src/**/*.ts"]
"references": [{ "path": "../shared" }],
"include": ["src/**/*.ts"],
}