import type { SyntaxPunctuationTerm, TerminalFormatContext, TerminalTerm, TerminalTheme, } from "./terminal.ts"; import { cacheTerminalTheme, formatTerminalLeaf, fragmentTokens, serializeTokens, type TerminalToken, } from "./terminal-internal.ts"; import { copyCommandUsageId } from "./internal/command-usage.ts"; import { getDisplayWidth } from "./displaywidth.ts"; import { forgetEmptyInput, resolveUsageForDisplay } from "./internal/usage.ts"; import type { NonEmptyString } from "./nonempty.ts"; import { validateProgramName } from "./validate.ts"; /** * Represents the name of a command-line option. There are four types of * option syntax: * * - GNU-style long options (`--option`) * - POSIX-style short options (`-o`) or Java-style options (`-option`) * - MS-DOS-style options (`/o`, `/option`) * - Plus-prefixed options (`+o`) * * Each prefix must be followed by at least one character, so bare prefixes * like `"-"`, `"/"`, or `"+"` are rejected at compile time. Due to * TypeScript template literal limitations, `"--"` still matches the * `-${NonEmptyString}` branch and is only rejected at runtime by the * `option()` and `flag()` validators. */ export type OptionName = | `--${NonEmptyString}` | `-${NonEmptyString}` | `/${NonEmptyString}` | `+${NonEmptyString}`; /** * Visibility control for parser terms. * * - `true`: hidden from usage, documentation, and suggestions * - `"usage"`: hidden from usage only * - `"doc"`: hidden from documentation only * - `"help"`: hidden from usage and documentation, but shown in suggestions */ export type HiddenVisibility = boolean | "usage" | "doc" | "help"; /** * Returns whether the term should be hidden from usage output. */ export function isUsageHidden(hidden?: HiddenVisibility): boolean { return hidden === true || hidden === "usage" || hidden === "help"; } /** * Returns whether the term should be hidden from documentation output. */ export function isDocHidden(hidden?: HiddenVisibility): boolean { return hidden === true || hidden === "doc" || hidden === "help"; } /** * Returns whether the term should be hidden from suggestion/error candidates. */ export function isSuggestionHidden(hidden?: HiddenVisibility): boolean { return hidden === true; } /** * Merges two hidden visibility settings by taking the union of restrictions. */ export function mergeHidden( a?: HiddenVisibility, b?: HiddenVisibility, ): HiddenVisibility | undefined { if (a == null) return b; if (b == null) return a; if (a === true || b === true) return true; if (a === false) return b; if (b === false) return a; if (a === b) return a; if (a === "help" || b === "help") return "help"; if ((a === "usage" || a === "doc") && (b === "usage" || b === "doc")) { return "help"; } return a; } /** * Represents a single term in a command-line usage description. */ export type UsageTerm = /** * An argument term, which represents a positional argument in * the command-line usage. */ | { /** * The type of the term, which is always `"argument"` for this term. */ readonly type: "argument"; /** * The name of the argument, which is used to identify it in * the command-line usage. */ readonly metavar: NonEmptyString; /** * Visibility controls for this term. * @since 0.9.0 */ readonly hidden?: HiddenVisibility; } /** * An option term, which represents a command-line option that can * be specified by the user. */ | { /** * The type of the term, which is always `"option"` for this term. */ readonly type: "option"; /** * The names of the option, which can include multiple * short and long forms. */ readonly names: readonly OptionName[]; /** * An optional metavariable name for the option, which is used * to indicate what value the option expects. */ readonly metavar?: NonEmptyString; /** * Visibility controls for this term. * @since 0.9.0 */ readonly hidden?: HiddenVisibility; } /** * A command term, which represents a subcommand in the command-line * usage. */ | { /** * The type of the term, which is always `"command"` for this term. */ readonly type: "command"; /** * The name of the command, which is used to identify it * in the command-line usage. */ readonly name: string; /** * Additional command names that invoke the same parser. * These aliases participate in parsing, completion, and typo * suggestions. They are never rendered in usage lines, and are rendered * in documentation command lists only when enabled through * `DocEntry.showAliases` or the `showAliases` formatting option. * @since 1.1.0 */ readonly aliases?: readonly string[]; /** * Additional command names that invoke the same parser but are not * rendered or suggested. They are still available to parsers and * suggestion matchers so alias typos can resolve to the canonical command. * @since 1.1.0 */ readonly hiddenAliases?: readonly string[]; /** * Optional usage line override for this command's own help page. * This affects help/documentation rendering only. * @since 1.0.0 */ readonly usageLine?: Usage | ((defaultUsageLine: Usage) => Usage); /** * Visibility controls for this term. * @since 0.9.0 */ readonly hidden?: HiddenVisibility; } /** * An optional term, which represents an optional component * in the command-line usage. */ | { /** * The type of the term, which is always `"optional"` for this term. */ readonly type: "optional"; /** * The terms that are optional, which can be an argument, an option, * a command, or another usage term. */ readonly terms: Usage; } /** * A term of multiple occurrences, which allows a term to be specified * multiple times in the command-line usage. */ | { /** * The type of the term, which is always `"multiple"` for this term. */ readonly type: "multiple"; /** * The terms that can occur multiple times, which can be an argument, * an option, a command, or another usage term. */ readonly terms: Usage; /** * The minimum number of times the term must occur. */ readonly min: number; /** * Whether the parser that produced this group succeeds when it parses an * empty argument list on its own. Built-in combinators set this when * the outcome is statically known and omit it otherwise. Usage * formatters use it to decide whether to draw the group as omissible; * it is a declaration for display, not evidence about how any other * parser behaves. * @since 1.4.0 */ readonly acceptsEmpty?: boolean; } | /** * An exclusive term, which represents a group of terms that are mutually * exclusive, meaning that only one of the terms in the group can be * specified at a time. */ { /** * The type of the term, which is always `"exclusive"` for this term. */ readonly type: "exclusive"; /** * The terms that are mutually exclusive, which can include * arguments, options, commands, or other usage terms. */ readonly terms: readonly Usage[]; /** * Whether the parser that produced this group succeeds when it parses an * empty argument list on its own. Built-in combinators set this when * the outcome is statically known and omit it otherwise. Usage * formatters use it to decide whether to draw the group as omissible; * it is a declaration for display, not evidence about how any other * parser behaves. * @since 1.4.0 */ readonly acceptsEmpty?: boolean; } /** * A sequence term, which preserves the declaration order of its child * terms through usage normalization. * * This is used by ordered parser combinators where argument/command/option * order is part of the accepted grammar. * @since 1.1.0 */ | { /** * The type of the term, which is always `"sequence"` for this term. */ readonly type: "sequence"; /** * Terms that must be displayed in the given order. */ readonly terms: Usage; } /** * A literal term, which represents a fixed string value in the command-line * usage. Unlike metavars which are placeholders for user-provided values, * literals represent exact strings that must be typed as-is. * @since 0.8.0 */ | { /** * The type of the term, which is always `"literal"` for this term. */ readonly type: "literal"; /** * The literal value that must be provided exactly as written. */ readonly value: string; /** * When `true`, this literal was derived from an option's metavar by * `appendLiteralToUsage()` in `conditional()` and represents an option * value, not a standalone positional token. * {@link extractLeadingLiteralValues} and the `skipOptionValueLiterals` * mode of `branchConsumesToken()` use this to distinguish option values * from real positional literals. {@link extractLeadingOptionNames} and * {@link extractLeadingCommandNames} intentionally still treat these * literals as positional gates. * @since 1.0.0 */ readonly optionValue?: boolean; } /** * A pass-through term, which represents unrecognized options that are * collected and passed through to an underlying tool or command. * @since 0.8.0 */ | { /** * The type of the term, which is always `"passthrough"` for this term. */ readonly type: "passthrough"; /** * Visibility controls for this term. * @since 0.9.0 */ readonly hidden?: HiddenVisibility; } /** * An ellipsis term, which represents a summary placeholder in usage output. * Unlike {@link passthrough}, this term has no parsing semantics and is used * only for display. * @since 1.0.0 */ | { /** * The type of the term, which is always `"ellipsis"` for this term. */ readonly type: "ellipsis"; }; /** * Represents a command-line usage description, which is a sequence of * {@link UsageTerm} objects. This type is used to describe how a command-line * parser expects its input to be structured, including the required and * optional components, as well as any exclusive groups of terms. */ export type Usage = readonly UsageTerm[]; /** * Extracts all option names from a usage description. * * This function recursively traverses a {@link Usage} tree and collects all * option names defined within it, including those nested inside optional, * multiple, and exclusive terms. * * @param usage The usage description to extract option names from. * @param includeHidden Whether to include fully hidden options (`hidden: true`) * in the result. Defaults to `false`. * @returns A set containing all option names found in the usage description. * * @example * ```typescript * const usage: Usage = [ * { type: "option", names: ["--verbose", "-v"] }, * { type: "option", names: ["--quiet", "-q"] }, * ]; * const names = extractOptionNames(usage); * // names = Set(["--verbose", "-v", "--quiet", "-q"]) * ``` */ export function extractOptionNames( usage: Usage, includeHidden?: boolean, ): Set { const names = new Set(); function traverseUsage(terms: Usage): void { if (!terms || !Array.isArray(terms)) return; for (const term of terms) { if (term.type === "option") { if (!includeHidden && isSuggestionHidden(term.hidden)) continue; for (const name of term.names) { names.add(name); } } else if ( term.type === "optional" || term.type === "multiple" || term.type === "sequence" ) { traverseUsage(term.terms); } else if (term.type === "exclusive") { for (const exclusiveUsage of term.terms) { traverseUsage(exclusiveUsage); } } } } traverseUsage(usage); return names; } /** * Extracts all command names from a Usage array. * * This function recursively traverses the usage structure and collects * all command names, similar to {@link extractOptionNames}. * * @param usage The usage structure to extract command names from. * @param includeHidden Whether to include fully hidden commands * (`hidden: true`) in the result. Defaults to `false`. * @returns A set of all command names found in the usage structure. * * @example * ```typescript * const usage: Usage = [ * { type: "command", name: "build" }, * { type: "command", name: "test" }, * ]; * const names = extractCommandNames(usage); * // names = Set(["build", "test"]) * ``` * @since 0.7.0 */ export function extractCommandNames( usage: Usage, includeHidden?: boolean, ): Set { const names = new Set(); function traverseUsage(terms: Usage): void { if (!terms || !Array.isArray(terms)) return; for (const term of terms) { if (term.type === "command") { if (!includeHidden && isSuggestionHidden(term.hidden)) continue; names.add(term.name); for (const alias of term.aliases ?? []) { names.add(alias); } if (includeHidden) { for (const alias of term.hiddenAliases ?? []) { names.add(alias); } } } else if ( term.type === "optional" || term.type === "multiple" || term.type === "sequence" ) { traverseUsage(term.terms); } else if (term.type === "exclusive") { for (const exclusiveUsage of term.terms) { traverseUsage(exclusiveUsage); } } } } traverseUsage(usage); return names; } /** * Extracts all literal values from a usage description. * * This function recursively traverses the usage tree and collects all * `literal` term values. Literal values represent fixed strings that * the user must type (e.g., conditional discriminator values like * `"server"` in `conditional(option("--mode", string()), { server: ... })`). * * @param usage The usage description to extract literal values from. * @returns A set of all literal values found in the usage description. * @since 1.0.0 */ export function extractLiteralValues(usage: Usage): Set { const values = new Set(); function traverseUsage(terms: Usage): void { if (!terms || !Array.isArray(terms)) return; for (const term of terms) { if (term.type === "literal") { values.add(term.value); } else if ( term.type === "optional" || term.type === "multiple" || term.type === "sequence" ) { traverseUsage(term.terms); } else if (term.type === "exclusive") { for (const branch of term.terms) { traverseUsage(branch); } } } } traverseUsage(usage); return values; } /** * Extracts all argument metavars from a Usage array. * * This function recursively traverses the usage structure and collects * all argument metavariable names, similar to {@link extractOptionNames} * and {@link extractCommandNames}. * * @param usage The usage structure to extract argument metavars from. * @returns A Set of all argument metavars found in the usage structure. * * @example * ```typescript * const usage: Usage = [ * { type: "argument", metavar: "FILE" }, * { type: "argument", metavar: "OUTPUT" }, * ]; * const metavars = extractArgumentMetavars(usage); * // metavars = Set(["FILE", "OUTPUT"]) * ``` * @since 0.9.0 */ export function extractArgumentMetavars(usage: Usage): Set { const metavars = new Set(); function traverseUsage(terms: Usage): void { if (!terms || !Array.isArray(terms)) return; for (const term of terms) { if (term.type === "argument") { if (isSuggestionHidden(term.hidden)) continue; metavars.add(term.metavar); } else if ( term.type === "optional" || term.type === "multiple" || term.type === "sequence" ) { traverseUsage(term.terms); } else if (term.type === "exclusive") { for (const exclusiveUsage of term.terms) { traverseUsage(exclusiveUsage); } } } } traverseUsage(usage); return metavars; } /** * Options for formatting usage descriptions. */ export interface UsageFormatOptions { /** * Semantic terminal theme. * @since 1.3.0 */ readonly theme?: TerminalTheme; /** * When `true`, expands commands in the usage description * to multiple lines, showing each command on a new line. * This is useful for commands with many subcommands, making it easier * to read and understand the available commands. * @default `false` */ readonly expandCommands?: boolean; /** * When `true`, only shows the shortest option name for each option * instead of showing all aliases separated by `/`. * For example, `--verbose/-v` becomes just `-v`. * @default `false` */ readonly onlyShortestOptions?: boolean; /** * When `true`, applies ANSI color codes to the output for better readability. * Different elements (options, arguments, commands, etc.) will be styled * with different colors and formatting. * @default `false` */ readonly colors?: boolean; /** * The maximum width of the formatted output. If specified, the output * will be wrapped to fit within this width, breaking lines as necessary. * If not specified, the output will not be wrapped. * @default `undefined` */ readonly maxWidth?: number; } /** * Formats a usage description into a human-readable string representation * suitable for command-line help text. * * This function converts a structured {@link Usage} description into a * formatted string that follows common CLI conventions. It supports various * formatting options including colors and compact option display. * @param programName The name of the program or command for which the usage * description is being formatted. This is typically the * name of the executable or script that the user will run. * @param usage The usage description to format, consisting of an array * of usage terms representing the command-line structure. * @param options Optional formatting options to customize the output. * See {@link UsageFormatOptions} for available options. * @returns A formatted string representation of the usage description. * @throws {TypeError} If `programName` is not a string, is empty, * whitespace-only, or contains control characters. * @throws {RangeError} If a theme supplies an invalid RGB channel or palette * index, even when colors are disabled. */ export function formatUsage( programName: string, usage: Usage, options: UsageFormatOptions = {}, ): string { options = { ...options, theme: cacheTerminalTheme(options.theme) }; validateProgramName(programName); return formatUsageLines( programName, normalizeUsage( filterUsageForDisplay(resolveUsageForDisplay(usage, isUsageHidden)), ), normalizeUsage(filterUsageForDisplay(forgetEmptyInput(usage))), options, ); } /** * Formats a display-ready usage, expanding a trailing command group into one * line per command when requested. * @param programName The program name. * @param usage The usage to draw, already resolved, filtered and normalized. * @param declared The same usage as declared, without empty-input records, * filtered and normalized. It tells a group that was drawn * as optional because it accepts empty input apart from a * group declared optional. * @param options The formatting options. * @returns The formatted usage. */ function formatUsageLines( programName: string, usage: Usage, declared: Usage, options: UsageFormatOptions, ): string { if (options.expandCommands) { let lastTerm = usage.at(-1)!; const declaredLast = declared.at(-1); // A command group drawn as optional because it accepts empty input // still expands into one line per command, unlike a group declared // optional. if (lastTerm?.type === "optional" && declaredLast?.type === "exclusive") { if ( lastTerm.terms.length === 1 && lastTerm.terms[0].type === "exclusive" ) { lastTerm = lastTerm.terms[0]; } else if (lastTerm.terms[0]?.type === "command") { // When only one command is visible, the optional term holds that // command's alternative itself. Other lone alternatives, such as // a help option, keep their brackets. lastTerm = { type: "exclusive", terms: [lastTerm.terms] }; } } if ( usage.length > 0 && usage.slice(0, -1).every((t) => t.type === "command") && lastTerm.type === "exclusive" && lastTerm.terms.every( (t) => t.length > 0 && (t[0].type === "command" || t[0].type === "option" || t[0].type === "argument" || (t[0].type === "optional" && t[0].terms.length === 1 && (t[0].terms[0].type === "command" || t[0].terms[0].type === "option" || t[0].terms[0].type === "argument"))), ) ) { // Declared alternatives line up with the drawn ones unless drawing // dropped some; then each line falls back to its drawn form. const declaredBranches = declaredLast?.type === "exclusive" && declaredLast.terms.length === lastTerm.terms.length ? declaredLast.terms : undefined; const lines = []; for (const [index, command] of lastTerm.terms.entries()) { // Skip hidden commands in usage expansion const firstTerm = command[0]; if (firstTerm?.type === "command" && isUsageHidden(firstTerm.hidden)) { continue; } const line = normalizeUsage( filterUsageForDisplay([...usage.slice(0, -1), ...command]), ); lines.push( formatUsageLines( programName, line, declaredBranches == null ? line : normalizeUsage( filterUsageForDisplay([ ...declared.slice(0, -1), ...declaredBranches[index], ]), ), options, ), ); } if (lines.length > 0) { return lines.join("\n"); } // Fall through to normal rendering when all commands are hidden } } return wrapUsageTokens( (function* () { yield* usageLeafTokens({ type: "programName", programName }, options); yield { ...usageSpace, programBoundary: true }; yield* formatUsageTerms(usage, options); })(), options, ); } /** * Normalizes a usage description by flattening nested exclusive terms, * sorting terms for better readability, and ensuring consistent structure * throughout the usage tree. * * This function performs three main operations: * * 1. *Stripping*: Removes degenerate terms that would render as empty or * malformed output, such as options with no names, commands with empty * names, arguments with empty metavars, and container terms (`optional`, * `multiple`, `exclusive`) whose top-level terms array is empty after * recursive normalization. Exclusive branches representing valid * zero-token alternatives (e.g., `conditional()` default branches or * `optional(constant(...))`) and empty-value literals are preserved. * Only branches that become empty because all their content was * malformed are removed. * * 2. *Flattening*: Recursively processes all usage terms and merges any * nested exclusive terms into their parent exclusive term to avoid * redundant nesting. For example, an exclusive term containing another * exclusive term will have its nested terms flattened into the parent. * Similarly, nested optional terms are collapsed: * `optional(optional(X))` becomes `optional(X)` when the outer optional * contains only a single inner optional term. * * 3. *Sorting*: Reorders terms to improve readability by placing: * - Commands (subcommands) first * - Options and other terms in the middle * - Positional arguments last (including optional/multiple wrappers around * arguments) * * The sorting logic also recognizes when optional or multiple terms contain * positional arguments and treats them as arguments for sorting purposes. * * @param usage The usage description to normalize. * @returns A normalized usage description with degenerate terms removed, * nested exclusive and optional terms flattened, and remaining * terms sorted for optimal readability. */ export function normalizeUsage(usage: Usage): Usage { const terms = usage.map(normalizeUsageTerm).filter(isNonDegenerateTerm); terms.sort((a, b) => { const aCmd = a.type === "command"; const bCmd = b.type === "command"; const aArg = a.type === "argument" || ((a.type === "optional" || a.type === "multiple") && a.terms.at(-1)?.type === "argument"); const bArg = b.type === "argument" || ((b.type === "optional" || b.type === "multiple") && b.terms.at(-1)?.type === "argument"); // Sort commands first and arguments last: return aCmd === bCmd ? (aArg === bArg ? 0 : aArg ? 1 : -1) : aCmd ? -1 : 1; }); return terms; } function normalizeUsageTerm(term: UsageTerm): UsageTerm { if (term.type === "optional") { const normalized = normalizeUsage(term.terms); if (normalized.length === 1 && normalized[0].type === "optional") { return normalized[0]; } return { type: "optional", terms: normalized }; } else if (term.type === "multiple") { return { type: "multiple", terms: normalizeUsage(term.terms), min: term.min, ...acceptsEmptyOf(term), }; } else if (term.type === "sequence") { return { type: "sequence", terms: term.terms.map(normalizeUsageTerm).filter(isNonDegenerateTerm), }; } else if (term.type === "exclusive") { const terms: Usage[] = []; for (const usage of term.terms) { const normalized = normalizeUsage(usage); // An inner group that records its empty-input behavior keeps its // boundary, since flattening would lose that record. if ( normalized.length >= 1 && normalized[0].type === "exclusive" && normalized[0].acceptsEmpty == null ) { const rest = normalized.slice(1); for (const subUsage of normalized[0].terms) { terms.push([...subUsage, ...rest]); } } else if (normalized.length > 0 || !containsMalformedLeaf(usage)) { // Keep the branch if it still has content, or if it became // empty without any malformed terms (valid zero-token // alternative, e.g., conditional() default branches or // optional(constant(...))). Drop branches that became empty // solely because all their terms were malformed. terms.push(normalized); } } return { type: "exclusive", terms, ...acceptsEmptyOf(term) }; } else { // Clone leaf terms so the normalized output is referentially distinct // from the input. Use a manual spread instead of cloneUsageTerm() to // tolerate unknown term types that cloneUsageTerm() would not cover: if (term.type === "option") { return { ...term, names: [...term.names] }; } else if (term.type === "command") { if (term.usageLine == null || typeof term.usageLine === "function") { return copyCommandUsageId(term, { ...term }); } return copyCommandUsageId(term, { ...term, usageLine: cloneUsage(term.usageLine), }); } return { ...term }; } } function acceptsEmptyOf( term: UsageTerm & { readonly type: "multiple" | "exclusive" }, ): { readonly acceptsEmpty?: boolean } { return term.acceptsEmpty == null ? {} : { acceptsEmpty: term.acceptsEmpty }; } function isNonDegenerateTerm(term: UsageTerm): boolean { if (term.type === "option") return term.names.length > 0; if (term.type === "command") return term.name !== ""; if (term.type === "argument") return term.metavar.length > 0; if ( (term.type === "multiple" || term.type === "exclusive") && term.acceptsEmpty != null ) { // A group without visible terms still records whether its parser // accepts empty input. return true; } if ( term.type === "optional" || term.type === "multiple" || term.type === "exclusive" || term.type === "sequence" ) { return term.terms.length > 0; } return true; } function containsMalformedLeaf(usage: Usage): boolean { for (const term of usage) { if (term.type === "option" && term.names.length === 0) return true; if (term.type === "command" && term.name === "") return true; if (term.type === "argument" && term.metavar.length === 0) return true; if ( term.type === "optional" || term.type === "multiple" || term.type === "sequence" ) { if (containsMalformedLeaf(term.terms)) return true; } if (term.type === "exclusive") { for (const branch of term.terms) { if (containsMalformedLeaf(branch)) return true; } } } return false; } /** * Creates a deep clone of a single {@link UsageTerm}. Recursive term * variants (`optional`, `multiple`, `exclusive`) are cloned recursively. * For `command` terms, a function-valued `usageLine` is preserved by * reference (functions are stateless callbacks), while an array-valued * `usageLine` is deep-cloned. * * @param term The usage term to clone. * @returns A structurally equal but referentially distinct copy. * @since 1.0.0 */ export function cloneUsageTerm(term: UsageTerm): UsageTerm { switch (term.type) { case "argument": return { ...term }; case "option": return { ...term, names: [...term.names] }; case "command": { if (term.usageLine == null || typeof term.usageLine === "function") { return copyCommandUsageId(term, { ...term, ...(term.aliases != null ? { aliases: [...term.aliases] } : {}), ...(term.hiddenAliases != null ? { hiddenAliases: [...term.hiddenAliases] } : {}), }); } return copyCommandUsageId(term, { ...term, ...(term.aliases != null ? { aliases: [...term.aliases] } : {}), ...(term.hiddenAliases != null ? { hiddenAliases: [...term.hiddenAliases] } : {}), usageLine: term.usageLine.map(cloneUsageTerm), }); } case "optional": return { type: "optional", terms: term.terms.map(cloneUsageTerm) }; case "multiple": return { type: "multiple", terms: term.terms.map(cloneUsageTerm), min: term.min, ...acceptsEmptyOf(term), }; case "exclusive": return { type: "exclusive", terms: term.terms.map((u) => u.map(cloneUsageTerm)), ...acceptsEmptyOf(term), }; case "sequence": return { type: "sequence", terms: term.terms.map(cloneUsageTerm) }; case "literal": case "passthrough": case "ellipsis": return { ...term }; } } /** * Creates a deep clone of a {@link Usage} array and all of its terms. * * @param usage The usage array to clone. * @returns A mutable array of deeply cloned usage terms. * @since 1.0.0 */ export function cloneUsage(usage: Usage): UsageTerm[] { return usage.map(cloneUsageTerm); } function filterUsageForDisplay( usage: Usage, isHidden: (hidden?: HiddenVisibility) => boolean = isUsageHidden, ): Usage { const terms: UsageTerm[] = []; for (const term of usage) { if ( (term.type === "argument" || term.type === "option" || term.type === "command" || term.type === "passthrough") && isHidden(term.hidden) ) { continue; } // Skip degenerate zero-width leaf terms if (term.type === "option" && term.names.length === 0) continue; if (term.type === "command" && term.name === "") continue; if (term.type === "argument" && term.metavar.length === 0) continue; if (term.type === "literal" && term.value === "") continue; if (term.type === "optional") { const filtered = filterUsageForDisplay(term.terms, isHidden); if (filtered.length > 0) { terms.push({ type: "optional", terms: filtered }); } continue; } if (term.type === "multiple") { const filtered = filterUsageForDisplay(term.terms, isHidden); if (filtered.length > 0) { terms.push({ type: "multiple", terms: filtered, min: term.min, ...acceptsEmptyOf(term), }); } continue; } if (term.type === "exclusive") { const filteredBranches = term.terms .map((branch) => { const first = branch[0]; if (first?.type === "command" && isHidden(first.hidden)) { return [] as Usage; } return filterUsageForDisplay(branch, isHidden); }) .filter((branch) => branch.length > 0); if (filteredBranches.length > 0) { terms.push({ type: "exclusive", terms: filteredBranches, ...acceptsEmptyOf(term), }); } continue; } if (term.type === "sequence") { const filtered = filterUsageForDisplay(term.terms, isHidden); if (filtered.length > 0) { terms.push({ type: "sequence", terms: filtered }); } continue; } terms.push(term); } return terms; } const usageSpace: TerminalToken = { text: " ", width: 1, scopes: [], separator: true, }; function* usageLeafTokens( term: TerminalTerm, options: UsageFormatOptions, usage?: TerminalFormatContext["usage"], ): Generator { const { fragment, defaultOrigin } = formatTerminalLeaf( term, options.theme, false, usage, ); for (const token of fragmentTokens(fragment)) { yield { ...token, legacyWhitespace: defaultOrigin }; } } function* formatUsageTerms( terms: readonly UsageTerm[], options: UsageFormatOptions, ): Generator { let i = 0; for (const t of terms) { if (i > 0) { yield usageSpace; } yield* formatUsageTermInternal(t, options); i++; } } /** * Options for formatting a single {@link UsageTerm}. */ export interface UsageTermFormatOptions extends UsageFormatOptions { /** * A string that separates multiple option names in the formatted output. * @default `"/"` */ readonly optionsSeparator?: string; /** * The rendering context, which determines which hidden visibility values * cause terms to be filtered out. * * - `"usage"` (default): filters terms hidden from usage output * - `"doc"`: filters terms hidden from documentation output * @default `"usage"` * @since 1.0.0 */ readonly context?: "usage" | "doc"; } /** * Formats a single {@link UsageTerm} into a string representation * suitable for command-line help text. * @param term The usage term to format, which can be an argument, * option, command, optional term, exclusive term, or multiple term. * @param options Optional formatting options to customize the output. * See {@link UsageTermFormatOptions} for available options. * @returns A formatted string representation of the usage term. * @throws {RangeError} If a theme supplies an invalid RGB channel or palette * index, even when colors are disabled. */ export function formatUsageTerm( term: UsageTerm, options: UsageTermFormatOptions = {}, ): string { options = { ...options, theme: cacheTerminalTheme(options.theme) }; const hiddenCheck = options.context === "doc" ? isDocHidden : isUsageHidden; const visibleTerms = filterUsageForDisplay( resolveUsageForDisplay([term], hiddenCheck), hiddenCheck, ); if (visibleTerms.length < 1) return ""; return wrapUsageTokens( formatUsageTermInternal(visibleTerms[0], options), options, ); } function wrapUsageTokens( input: Iterable, options: UsageFormatOptions, ): string { return serializeTokens(layoutUsageTokens(input, options), options.colors); } /** Keeps one layout-owned space between nonempty outputs on the same line. */ function* normalizeUsageSeparators( input: Iterable, ): Generator { let previous: TerminalToken | undefined; let pending: TerminalToken[] = []; for (const token of input) { if (token.separator || token.text === "") { pending.push(token); continue; } let separated = false; for (const item of pending) { if (!item.separator) yield item; else if ( !separated && previous != null && previous.width !== -1 && token.width !== -1 ) { yield item; separated = true; } } pending = []; yield token; previous = token; } for (const item of pending) { if (!item.separator) yield item; } } function layoutUsageTokens( input: Iterable, options: UsageFormatOptions, ): TerminalToken[] { let lineWidth = 0; const output: TerminalToken[] = []; const tokens = [...normalizeUsageSeparators(input)]; for (const [index, token] of tokens.entries()) { if (token.programBoundary && options.maxWidth != null) { const next = tokens.find((item, i) => i > index && item.text !== ""); if ( next != null && lineWidth + token.width + next.width > options.maxWidth ) { output.push({ text: "\n", width: -1, scopes: [] }); lineWidth = 0; continue; } } if (token.width === -1) { output.push(token); lineWidth = 0; continue; } if ( options.maxWidth != null && lineWidth > 0 && token.width > 0 && lineWidth + token.width > options.maxWidth ) { let lastIndex = output.length - 1; while (lastIndex >= 0 && output[lastIndex].text === "") lastIndex--; const last = output[lastIndex]; // Only generated separators are generally disposable. Default leaves // retain the historical one-space trim, including its color exception. if ( last?.text.endsWith(" ") && (last.separator || (last.legacyWhitespace && (!options.colors || last.scopes.length === 0))) ) { output[lastIndex] = { ...last, text: last.text.slice(0, -1), width: last.width - 1, }; } output.push({ text: "\n", width: -1, scopes: [] }); lineWidth = 0; if (token.separator || (token.legacyWhitespace && token.text === " ")) { continue; } } output.push(token); lineWidth += token.width; } return output; } function* formatUsageTermInternal( term: UsageTerm, options: UsageTermFormatOptions, ): Generator { function leaf(t: TerminalTerm, usage?: TerminalFormatContext["usage"]) { return usageLeafTokens(t, options, usage); } function punctuation( punctuation: string, kind: SyntaxPunctuationTerm["kind"], ) { return leaf({ type: "syntaxPunctuation", punctuation, kind }); } const space = usageSpace; if (term.type === "argument") { yield* leaf({ type: "metavar", metavar: term.metavar }, "argument"); } else if (term.type === "option") { const names = options.onlyShortestOptions ? [ term.names.reduce((a, b) => getDisplayWidth(a) <= getDisplayWidth(b) ? a : b, ), ] : term.names; for (let i = 0; i < names.length; i++) { if (i > 0) { yield* punctuation(options.optionsSeparator ?? "/", "optionSeparator"); } yield* leaf({ type: "optionName", optionName: names[i] }); } if (!options.onlyShortestOptions && term.metavar != null) { yield space; yield* leaf({ type: "metavar", metavar: term.metavar }, "optionValue"); } } else if (term.type === "command") { yield* leaf({ type: "optionName", optionName: term.name }, "command"); } else if (term.type === "optional") { yield* punctuation("[", "optionalOpen"); yield* formatUsageTerms(term.terms, options); yield* punctuation("]", "optionalClose"); } else if (term.type === "exclusive") { yield* punctuation("(", "groupOpen"); for (let i = 0; i < term.terms.length; i++) { if (i > 0) { yield space; yield* punctuation("|", "alternative"); yield space; } yield* formatUsageTerms(term.terms[i], options); } yield* punctuation(")", "groupClose"); } else if (term.type === "sequence") { yield* formatUsageTerms(term.terms, options); } else if (term.type === "multiple") { if (term.min < 1) yield* punctuation("[", "optionalOpen"); for (let i = 0; i < Math.max(1, term.min); i++) { if (i > 0) yield space; yield* formatUsageTerms(term.terms, options); } yield* punctuation("...", "ellipsis"); if (term.min < 1) yield* punctuation("]", "optionalClose"); } else if (term.type === "literal") { yield* leaf({ type: "value", value: term.value }, "literal"); } else if (term.type === "passthrough") { yield* punctuation("[...]", "passthrough"); } else if (term.type === "ellipsis") { yield* punctuation("...", "ellipsis"); } else { throw new TypeError(`Unknown usage term type: ${term["type"]}.`); } }