/** @jsxRuntime automatic */
/** @jsxImportSource @alchemy.run/sigil */
/** Branded help screens + the CliOutput formatter that renders them. */
import { stripVTControlCharacters } from "node:util";
import * as CliOutput from "effect/cli/CliOutput";
import type { HelpDoc } from "effect/cli/HelpDoc";
import * as Option from "effect/Option";
import type { JSX } from "react";
import packageJson from "../../../../package.json" with { type: "json" };
import type { Interaction } from "../../../Interaction.ts";
import { terminalStyle, truncate } from "../../../Util/Terminal.ts";
import { glyphsFor, theme } from "../../../Util/Theme.ts";
import { Box, Heading, Text, useGlyphs } from "../ui/index.ts";
import { formatView } from "./Format.tsx";
import { Logo } from "./Logo.tsx";
const commandLabel = (command: { readonly name: string; readonly alias?: string | undefined }) =>
command.alias ? `${command.name}, ${command.alias}` : command.name;
/** Shell-like highlighting shared by usage lines, examples, and help hints. */
function CommandText({ command }: { readonly command: string }): JSX.Element {
const tokens = command.match(/\s+|"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]+/g) ?? [command];
let word = 0;
let valueAfterFlag = false;
return (
{tokens.map((token, index) => {
if (/^\s+$/.test(token)) return token;
const currentWord = word++;
const isFlag = token.startsWith("-");
const isPlaceholder =
(token.startsWith("<") && token.endsWith(">")) ||
(token.startsWith("[") && token.endsWith("]"));
const isQuoted =
(token.startsWith('"') && token.endsWith('"')) ||
(token.startsWith("'") && token.endsWith("'"));
const isValue = valueAfterFlag || isQuoted;
valueAfterFlag = isFlag;
return (
{token}
);
})}
);
}
/** One aligned help row: fixed-width bold label cell + description. */
type RowProps = {
label: JSX.Element | string;
description: string;
width: number;
};
function Row({ label, description, width }: RowProps) {
return (
{typeof label === "string" ? (
{label}
) : (
label
)}
{description}
);
}
function BrandLine(): JSX.Element {
const glyphs = useGlyphs();
return (
{glyphs.selected}{" "}
alchemy
{" "}
— Infrastructure as Effects
);
}
/**
* Branded help for every command. The root gets a brand header and shows
* only `--help`/`--version` (as OPTIONS); subcommands list all global flags.
*/
type SubHelpProps = {
doc: HelpDoc;
root?: boolean;
};
function SubHelp({ doc, root = false }: SubHelpProps): JSX.Element {
const commands = doc.subcommands?.flatMap((group) => group.commands) ?? [];
const flags = doc.flags ?? [];
const globalFlags = root
? (doc.globalFlags ?? []).filter((flag) => flag.name === "help" || flag.name === "version")
: (doc.globalFlags ?? []);
const args = doc.args ?? [];
const flagLabel = (flag: (typeof flags)[number]) => {
const aliases = flag.aliases.length > 0 ? `, ${flag.aliases.join(", ")}` : "";
return `--${flag.name}${aliases}`;
};
const argLabel = (arg: (typeof args)[number]) =>
arg.required ? `<${arg.name}>` : `[${arg.name}]`;
// width from labels only — enum types (--log-level's choice list) would
// otherwise blow the column out; long types truncate inside the cell
const nameWidth =
Math.min(
30,
Math.max(
12,
...commands.map((c) => commandLabel(c).length),
...[...flags, ...globalFlags].map((f) => flagLabel(f).length),
...args.map((a) => argLabel(a).length),
),
) + 4;
type FlagRowProps = { readonly flag: (typeof flags)[number] };
function FlagRow({ flag }: FlagRowProps) {
const label = flagLabel(flag);
const typeRoom = nameWidth - label.length - 2;
return (
"")}
label={
--{flag.name}
{flag.aliases.map((alias) => (
, {alias}
))}
{flag.type === "boolean" || typeRoom < 8 ? null : (
{truncate(flag.type, typeRoom)}
)}
}
/>
);
}
return (
{root ? : null}
{doc.description === "" ? null : (
{doc.description}
)}
USAGE
{" "}
$
{args.length === 0 ? null : (
<>
ARGUMENTS
{args.map((arg) => (
{argLabel(arg)}
}
description={Option.getOrElse(arg.description, () => "")}
/>
))}
>
)}
{commands.length === 0 ? null : (
<>
COMMANDS
{commands.map((command) => (
{command.name}
{command.alias === undefined ? null : (
, {command.alias}
)}
}
description={command.description || ""}
/>
))}
>
)}
{flags.length === 0 ? null : (
<>
FLAGS
{flags.map((flag) => (
))}
>
)}
{globalFlags.length === 0 ? null : (
<>
{root ? "OPTIONS" : "GLOBAL FLAGS"}
{globalFlags.map((flag) => (
))}
>
)}
{doc.examples === undefined || doc.examples.length === 0 ? null : (
<>
EXAMPLES
{doc.examples.map((example) => (
{" "}
$
))}
>
)}
{commands.length === 0 ? null : (
Run '
.*$/, "")} --help`}
/>
' for more information on a command.
)}
);
}
const formatSubHelp = (cli: Interaction["Service"], doc: HelpDoc) => {
const termCols = cli.terminal.columns;
return formatView(
,
cli.terminal,
{ columns: termCols },
);
};
/** Hide the logo entirely when it can't be at least this many columns wide. */
const MIN_LOGO_COLS = 20;
const formatRootHelp = (cli: Interaction["Service"], doc: HelpDoc) => {
const termCols = cli.terminal.columns;
// First pass: render the text alone to measure its exact footprint (post
// ANSI codes and wrapping), then size the logo into the leftover space.
const text = formatView(
,
cli.terminal,
{ columns: termCols },
);
// The braille logo is mojibake without Unicode support.
if (!cli.terminal.unicode) return text;
const lines = text.split("\n");
const textWidth = Math.max(
...lines.map((line) => stripVTControlCharacters(line).trimEnd().length),
);
const textHeight = lines.length;
// Fill the free space beside the text: a logo of C columns is C/2 rows
// tall (braille cell is 1:2). Reserve two rows for the wordmark caption.
const logoCols = Math.min(termCols - textWidth - 2, (textHeight - 2) * 2);
if (logoCols < MIN_LOGO_COLS) return text;
return formatView(
ALCHEMY
{" "}
v{packageJson.version}
,
cli.terminal,
{ columns: termCols },
);
};
export const brandedCliFormatter = (cli: Interaction["Service"]): CliOutput.Formatter => {
const fallback = CliOutput.defaultFormatter();
const glyphs = glyphsFor(cli.terminal.unicode);
const style = terminalStyle();
const formatErrorLine = (message: string) =>
`${style.hex(theme.color.danger)(`${glyphs.error} error:`)} ${message}`;
return {
formatCliError: fallback.formatCliError,
formatHelpDoc: (doc) =>
doc.usage.startsWith("alchemy ")
? formatRootHelp(cli, doc)
: formatSubHelp(cli, doc),
formatVersion: (name, version) =>
`${style.hex(theme.color.brand)(glyphs.selected)} ${style.bold(name)} ${style.dim(`v${version}`)}`,
formatError: (error) => `\n${formatErrorLine(error.message)}`,
formatErrors: (errors) => {
if (errors.length === 0) return "";
if (errors.length === 1) return `\n${formatErrorLine(errors[0].message)}`;
return `\n${formatErrorLine(`${errors.length} problems`)}\n${errors
.map((error) => ` ${style.dim(glyphs.bullet)} ${error.message}`)
.join("\n")}`;
},
};
};