import { captureDocParser } from "./internal/doc-metadata.ts"; import { identifyCommandUsage, scopeCommandUsage, } from "./internal/command-usage.ts"; import { joinedFileSuggestion } from "./internal/joined-file-suggestion.ts"; import { defineBareCommandDocPolicy, enterCommandDocPolicy, matchCommandDocPolicy, } from "./internal/command-doc-policy.ts"; import { attachedValuePrefix, combinedOptionScope, fullNameOwnsToken, prefixSuggestion, scopeParser, selectableOptionScope, } from "./short-option.ts"; import { getCommandDocMetadata, getSelectedCommandUsage, scopeCommandDocMetadata, withCommandDocMetadata, withSelectedCommandUsage, } from "./internal/command-doc-metadata.ts"; import { defineKnownCompletion, definePassThroughPriority, defineReachableChildren, getPassThroughFailure, } from "./internal/passthrough.ts"; import { defineEmptyInputFacts, failingStepFacts, UNCHANGED, } from "./internal/empty-input.ts"; import { getWrappedChildParseState, getWrappedChildState, isAnnotationWrappedInitialState, normalizeInjectedAnnotationState, } from "./annotation-state.ts"; import { type DerivedValueParser, getDefaultValuesFunction, getDependencyIds, getSnapshottedDefaultDependencyValues, isDerivedValueParser, suggestWithDependency, } from "./internal/dependency.ts"; import { annotateFreshArray, getAnnotations } from "./internal/annotations.ts"; import { extractDependencyMetadata } from "./dependency-metadata.ts"; import { type EffectfulSchedulingNodesFn, effectfulSchedulingNodesKey, exclusiveSourceScopeKey, includeSourceFailureChain, recordDerivedRawInput, replayDerivedParser, replayDerivedParserAsync, sourceCollectionExpansionKey, } from "./dependency-runtime.ts"; import { mergeChildExec, withChildContext, withChildExecPath, } from "./execution-context.ts"; import type { DocFragment } from "./doc.ts"; import { dispatchByMode, dispatchIterableByMode, wrapForMode, } from "./internal/mode-dispatch.ts"; import { createDeferredFailure } from "./internal/failure.ts"; import { completeOrExtractPhase2Seed, extractPhase2SeedKey, } from "./phase2-seed.ts"; import { hiddenCommandAliasesKey, type HiddenCommandAliasOptions, } from "./internal/command-alias.ts"; import type { TraceEntry } from "./input-trace.ts"; import { fluent, type FluentParser } from "./fluent.ts"; import type { DependencyRegistryLike } from "./registry-types.ts"; import { validateCommandNames, validateOptionNames } from "./validate.ts"; /** * A shared empty set used as the `leadingNames` value for parsers that * do not match any specific name at the first buffer position. */ const EMPTY_LEADING_NAMES: ReadonlySet = new Set(); /** @internal */ export type OptionState = ValueParserResult | undefined; function hasParsedOptionValue( state: ValueParserResult | undefined, valueParser: ValueParser | undefined, ): boolean { if (valueParser != null) { return ( state != null && typeof state === "object" && "success" in state && typeof state.success === "boolean" ); } return ( state != null && "success" in state && state.success && (state as { value?: boolean }).value === true ); } function isTerminalValueState( state: ValueParserResult | undefined, ): boolean { return ( state != null && typeof state === "object" && "success" in state && typeof state.success === "boolean" ); } /** * Helper function to create the stored state for an option or argument value. * * Primitive parsers now keep only the plain parse result as their local state. * Any dependency-aware replay information is recorded separately in the * execution trace. * @internal */ function createOptionParseState( parseResult: ValueParserResult, rawInput: string, valueParser: ValueParser, ): ValueParserResult { if (isDerivedValueParser(valueParser)) { recordDerivedRawInput(parseResult, rawInput); } return parseResult; } function buildTraceEntry( kind: TraceEntry["kind"], rawInput: string, consumed: readonly string[], valueParser: ValueParser, parseResult: ValueParserResult, optionNames?: readonly string[], ): TraceEntry { const entry: TraceEntry = { kind, rawInput, consumed, preliminaryResult: parseResult, ...(optionNames != null ? { optionNames } : {}), metavar: valueParser.metavar, }; if (isDerivedValueParser(valueParser)) { const defaults = getSnapshottedDefaultDependencyValues( parseResult as ValueParserResult, ); if (defaults != null) { return { ...entry, defaultDependencyValues: defaults }; } } return entry; } function recordTrace( context: ParserContext, entry: TraceEntry, ): ParserContext { if (context.exec?.trace == null) return context; const trace = context.exec.trace.set(context.exec.path, entry); return { ...context, trace, exec: { ...context.exec, trace, }, }; } function resolveDerivedCompletionSync( derivedMetadata: ReturnType | undefined, state: ValueParserResult, exec?: ExecutionContext, ): ValueParserResult { if (derivedMetadata?.derived == null || exec?.dependencyRuntime == null) { return state; } const traceEntry = exec.trace?.get(exec.path); if (traceEntry?.rawInput == null) { return (traceEntry?.preliminaryResult as ValueParserResult) ?? state; } if (traceEntry.preliminaryResult != null) { const resolution = exec.dependencyRuntime.resolveDependencies({ dependencyIds: derivedMetadata.derived.dependencyIds, defaultValues: traceEntry.defaultDependencyValues, }); if ( resolution.kind === "resolved" && resolution.usedDefaults.length > 0 && resolution.usedDefaults.every((used) => used) ) { return traceEntry.preliminaryResult as ValueParserResult; } } const replayed = replayDerivedParser( { path: exec.path, parser: { dependencyMetadata: { derived: derivedMetadata.derived } }, state, defaultDependencyValues: traceEntry.defaultDependencyValues, }, traceEntry.rawInput, exec.dependencyRuntime, ); return ( (replayed as ValueParserResult) ?? (traceEntry.preliminaryResult as ValueParserResult) ?? state ); } function includeDependencyFailureChain( error: Message, dependencyMetadata: ReturnType | undefined, exec: ExecutionContext | undefined, ): Message { const sourceId = dependencyMetadata?.source?.sourceId; if (sourceId == null || exec?.dependencyRuntime == null) return error; return includeSourceFailureChain(error, sourceId, exec.dependencyRuntime); } async function resolveDerivedCompletionAsync( derivedMetadata: ReturnType | undefined, state: ValueParserResult, exec?: ExecutionContext, ): Promise> { if (derivedMetadata?.derived == null || exec?.dependencyRuntime == null) { return state; } const traceEntry = exec.trace?.get(exec.path); if (traceEntry?.rawInput == null) { return (traceEntry?.preliminaryResult as ValueParserResult) ?? state; } if (traceEntry.preliminaryResult != null) { const resolution = exec.dependencyRuntime.resolveDependencies({ dependencyIds: derivedMetadata.derived.dependencyIds, defaultValues: traceEntry.defaultDependencyValues, }); if ( resolution.kind === "resolved" && resolution.usedDefaults.length > 0 && resolution.usedDefaults.every((used) => used) ) { return traceEntry.preliminaryResult as ValueParserResult; } } const replayed = await replayDerivedParserAsync( { path: exec.path, parser: { dependencyMetadata: { derived: derivedMetadata.derived } }, state, defaultDependencyValues: traceEntry.defaultDependencyValues, }, traceEntry.rawInput, exec.dependencyRuntime, ); return ( (replayed as ValueParserResult) ?? (traceEntry.preliminaryResult as ValueParserResult) ?? state ); } import { type Message, message, metavar, optionName as eOptionName, optionNames as eOptionNames, text, valueSet, } from "./message.ts"; import type { DocState, ExecutionContext, Mode, ModeValue, Parser, ParserContext, ParserResult, Suggestion, } from "./parser.ts"; import { createErrorWithSuggestions, createSuggestionMessage, DEFAULT_FIND_SIMILAR_OPTIONS, expandCommandAliasSuggestions, findSimilar, } from "./suggestion.ts"; import type { HiddenVisibility, OptionName, Usage, UsageTerm, } from "./usage.ts"; import { extractOptionNames, isDocHidden, isSuggestionHidden, } from "./usage.ts"; import { extractLeadingCommandNames } from "./usage-internals.ts"; import { isValueParser, type ValueParser, type ValueParserResult, } from "./valueparser.ts"; /** Defers option/flag typo work until a failure's message is requested. */ function unmatchedOptionFailure( invalidOption: string, usage: Usage, errors?: { readonly noMatch?: | Message | ((invalidOption: string, suggestions: readonly string[]) => Message); }, ): ParserResult & { readonly success: false } { const noMatch = errors?.noMatch; if (noMatch != null && typeof noMatch !== "function") { return { success: false, consumed: 0, error: noMatch }; } return createDeferredFailure(0, () => { if (noMatch != null) { const candidates = new Set(extractOptionNames(usage)); return noMatch.call( errors, invalidOption, findSimilar(invalidOption, candidates, DEFAULT_FIND_SIMILAR_OPTIONS), ); } return createErrorWithSuggestions( message`No matched option for ${eOptionName(invalidOption)}.`, invalidOption, usage, "option", ); }); } /** * Creates a parser that always succeeds without consuming any input and * produces a constant value of the type {@link T}. * @template T The type of the constant value produced by the parser. */ export function constant(value: T): FluentParser<"sync", T, T> { const result: Parser<"sync", T, T> = { $valueType: [], $stateType: [], mode: "sync", priority: 0, usage: [], leadingNames: EMPTY_LEADING_NAMES, acceptingAnyToken: false, initialState: value, canSkip() { return true; }, parse(context) { return { success: true, next: context, consumed: [] }; }, complete(state, _exec?: ExecutionContext) { return { success: true, value: state }; }, suggest(_context, _prefix) { return []; }, getDocFragments(_state: DocState, _defaultValue?) { return { fragments: [], sourceOnly: true }; }, }; defineKnownCompletion(result, (state) => normalizeInjectedAnnotationState(state), ); defineEmptyInputFacts(result, { step: "success", next: UNCHANGED, afterStep: true, fromInitial: true, }); Object.defineProperty(result, "placeholder", { value, configurable: true, enumerable: false, writable: false, }); return fluent(result); } /** * Creates a parser that always fails without consuming any input. * * This is the counterpart to {@link constant}: while `constant(value)` always * succeeds, `fail()` always fails. At the type level it is declared to * produce a value of type `T`, so it composes seamlessly with other parsers * that expect `Parser<"sync", T, …>`. * * The primary use case is as the inner parser for * `bindConfig(fail(), { … })` when a value should *only* come from a * config file and has no corresponding CLI flag or argument. Because `fail()` * always fails, `bindConfig` will always fall back to the config file (or the * supplied default). * * @template T The type of value this parser is declared to produce. * @returns A {@link Parser} that always fails at parse time and always fails at * complete time. * @since 1.0.0 */ export function fail(): FluentParser<"sync", T, undefined> { const result: Parser<"sync", T, undefined> = { $valueType: [], $stateType: [], mode: "sync", priority: 0, usage: [], leadingNames: EMPTY_LEADING_NAMES, acceptingAnyToken: false, initialState: undefined, canSkip() { return false; }, parse(_context) { return { success: false, consumed: 0, error: message`No value provided.`, }; }, complete(_state, _exec?: ExecutionContext) { return { success: false, error: message`No value provided.`, }; }, suggest(_context, _prefix) { return []; }, getDocFragments(_state, _defaultValue?) { return { fragments: [], sourceOnly: true }; }, }; defineEmptyInputFacts(result, failingStepFacts(false)); return fluent(result); } /** * Options for the {@link option} parser. */ export interface OptionOptions { /** * The description of the option, which can be used for help messages. */ readonly description?: Message; /** * Controls option visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions * * @since 0.9.0 */ readonly hidden?: HiddenVisibility; /** * Error message customization options. * @since 0.5.0 */ readonly errors?: OptionErrorOptions; } /** * Options for customizing error messages in the {@link option} parser. * @since 0.5.0 */ export interface OptionErrorOptions { /** * Custom error message when the option is missing (for required options). * Can be a static message or a function that receives the option names. */ missing?: Message | ((optionNames: readonly string[]) => Message); /** * Custom error message when options are terminated (after `--`). */ optionsTerminated?: Message; /** * Custom error message when input is empty but option is expected. */ endOfInput?: Message; /** * Custom error message when option is used multiple times. * Can be a static message or a function that receives the token. */ duplicate?: Message | ((token: string) => Message); /** * Custom error message when value parsing fails. * Can be a static message or a function that receives the error message. */ invalidValue?: Message | ((error: Message) => Message); /** * Custom error message when a Boolean flag receives an unexpected value. * Can be a static message or a function that receives the value. */ unexpectedValue?: Message | ((value: string) => Message); /** * Custom error message when no matching option is found. * Can be a static message or a function that receives: * - invalidOption: The invalid option name that was provided * - suggestions: Array of similar valid option names (can be empty) * The callback runs when a retained failure's error is read, and may be * skipped for discarded failures. It should not have side effects. * * @since 0.7.0 */ noMatch?: | Message | ((invalidOption: string, suggestions: readonly string[]) => Message); } /** * Internal helper to get suggestions from a value parser, using dependency values * if the parser is a derived parser and dependency values are available. * @internal */ function* getSuggestionsWithDependency( valueParser: ValueParser<"sync", T>, prefix: string, dependencyRegistry: DependencyRegistryLike | undefined, exec?: ExecutionContext, ): Generator { if (!valueParser.suggest) return; // Check if this is a derived parser with suggestWithDependency if ( isDerivedValueParser(valueParser) && suggestWithDependency in valueParser ) { const derived = valueParser as DerivedValueParser<"sync", T, unknown>; const suggestWithDep = derived[suggestWithDependency]; if (suggestWithDep && dependencyRegistry) { const dependencyRuntime = exec?.dependencyRuntime; // Get dependency values from registry const depIds = getDependencyIds(derived); const defaultsFn = getDefaultValuesFunction(derived); const defaults = defaultsFn?.(); // Collect dependency values, using defaults for missing ones const dependencyValues: unknown[] = []; let hasAnyValue = false; for (let i = 0; i < depIds.length; i++) { const depId = depIds[i]; if (dependencyRegistry.has(depId)) { dependencyValues.push(dependencyRegistry.get(depId)); hasAnyValue = true; } else if (dependencyRuntime?.isSourceFailed(depId)) { return; } else if (defaults && i < defaults.length) { dependencyValues.push(defaults[i]); } else { // Can't resolve, fall back to default suggest yield* valueParser.suggest(prefix); return; } } // If we have at least one actual value (not just defaults), use suggestWithDependency if (hasAnyValue) { const depValue = depIds.length === 1 ? dependencyValues[0] : dependencyValues; yield* suggestWithDep(prefix, depValue) as Iterable; return; } } } // Fall back to default suggest yield* valueParser.suggest(prefix); } /** Returns the joined prefix accepted by option parsing. */ function joinedOptionPrefix( names: readonly string[], input: string, ): string | undefined { return names .filter( (name) => name.startsWith("--") || name.startsWith("/") || (name.startsWith("-") && name.length > 2), ) .map((name) => name + (name.startsWith("/") ? ":" : "=")) .find((prefix) => input.startsWith(prefix)); } /** * Internal sync helper for option suggest functionality. * @internal */ function* suggestOptionSync( optionNames: readonly string[], valueParser: ValueParser<"sync", T> | undefined, hidden: boolean, description: Message | undefined, context: ParserContext | undefined>, prefix: string, ): Generator { if (hidden) return; if (context.optionsTerminated) return; const waitingForValue = context.buffer.length > 0 && optionNames.includes(context.buffer[context.buffer.length - 1]); if ( valueParser != null && !waitingForValue && !isTerminalValueState(context.state) ) { const attached = attachedValuePrefix(context, prefix, optionNames); if (attached != null) { if (attached.value.length === 0 && optionNames.includes(prefix)) { yield { kind: "literal", text: prefix, ...(description != null ? { description } : {}), }; } if (valueParser.suggest != null) { for (const suggestion of getSuggestionsWithDependency( valueParser, attached.value, context.dependencyRegistry, context.exec, )) { yield prefixSuggestion(attached.head, suggestion); } } return; } } // An expected value may itself contain '=' or resemble a joined option. const joinedPrefix = joinedOptionPrefix(optionNames, prefix); if (joinedPrefix !== undefined && !waitingForValue) { // Complete only joined forms accepted by the parser. const optionPart = joinedPrefix.slice(0, -1); const valuePart = prefix.slice(joinedPrefix.length); // Check if this option matches any of our option names if ( (optionNames as readonly string[]).includes(optionPart) && !/^-[^-]$/u.test(optionPart) ) { if (valueParser && valueParser.suggest) { const valueSuggestions = getSuggestionsWithDependency( valueParser, valuePart, context.dependencyRegistry, context.exec, ); // Restore the matched option prefix on each suggestion for (const suggestion of valueSuggestions) { if (suggestion.kind === "literal") { yield { kind: "literal", text: `${joinedPrefix}${suggestion.text}`, description: suggestion.description, }; } else { // File suggestions use a literal prefix fallback. yield joinedFileSuggestion(joinedPrefix, suggestion, valuePart); } } } } } else { // If the prefix looks like an option prefix, suggest matching option names if ( !waitingForValue && (prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+")) ) { for (const optionName of optionNames) { if (optionName.startsWith(prefix)) { // Special case: if prefix is exactly "-", only suggest short options if (prefix === "-" && !/^-[^-]$/u.test(optionName)) { continue; } yield { kind: "literal", text: optionName, ...(description && { description }), }; } } } // Check if we should suggest values for this option if (valueParser && valueParser.suggest) { let shouldSuggestValues = false; // Scenario 1: Buffer contains option name if (context.buffer.length > 0) { const lastToken = context.buffer[context.buffer.length - 1]; if ((optionNames as readonly string[]).includes(lastToken)) { shouldSuggestValues = true; } } // Scenario 2: Empty buffer, state is undefined, and the prefix is // not itself starting an option token. else if ( isAnnotationWrappedInitialState(context.state) && context.buffer.length === 0 && (context.exec?.path?.length ?? 0) === 0 && !( prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+") ) ) { shouldSuggestValues = true; } if (shouldSuggestValues) { yield* getSuggestionsWithDependency( valueParser, prefix, context.dependencyRegistry, context.exec, ); } } } } /** * Internal async helper to get suggestions from a value parser, using dependency values * if the parser is a derived parser and dependency values are available. * @internal */ async function* getSuggestionsWithDependencyAsync( valueParser: ValueParser, prefix: string, dependencyRegistry: DependencyRegistryLike | undefined, exec?: ExecutionContext, ): AsyncGenerator { if (!valueParser.suggest) return; // Check if this is a derived parser with suggestWithDependency if ( isDerivedValueParser(valueParser) && suggestWithDependency in valueParser ) { const derived = valueParser as DerivedValueParser; const suggestWithDep = derived[suggestWithDependency]; if (suggestWithDep && dependencyRegistry) { const dependencyRuntime = exec?.dependencyRuntime; // Get dependency values from registry const depIds = getDependencyIds(derived); const defaultsFn = getDefaultValuesFunction(derived); const defaults = defaultsFn?.(); // Collect dependency values, using defaults for missing ones const dependencyValues: unknown[] = []; let hasAnyValue = false; for (let i = 0; i < depIds.length; i++) { const depId = depIds[i]; if (dependencyRegistry.has(depId)) { dependencyValues.push(dependencyRegistry.get(depId)); hasAnyValue = true; } else if (dependencyRuntime?.isSourceFailed(depId)) { return; } else if (defaults && i < defaults.length) { dependencyValues.push(defaults[i]); } else { // Can't resolve, fall back to default suggest for await (const suggestion of valueParser.suggest(prefix)) { yield suggestion; } return; } } // If we have at least one actual value (not just defaults), use suggestWithDependency if (hasAnyValue) { const depValue = depIds.length === 1 ? dependencyValues[0] : dependencyValues; for await (const suggestion of suggestWithDep( prefix, depValue, ) as AsyncIterable) { yield suggestion; } return; } } } // Fall back to default suggest for await (const suggestion of valueParser.suggest(prefix)) { yield suggestion; } } /** * Internal async helper for option suggest functionality. * @internal */ async function* suggestOptionAsync( optionNames: readonly string[], valueParser: ValueParser | undefined, hidden: boolean, description: Message | undefined, context: ParserContext | undefined>, prefix: string, ): AsyncGenerator { if (hidden) return; if (context.optionsTerminated) return; const waitingForValue = context.buffer.length > 0 && optionNames.includes(context.buffer[context.buffer.length - 1]); if ( valueParser != null && !waitingForValue && !isTerminalValueState(context.state) ) { const attached = attachedValuePrefix(context, prefix, optionNames); if (attached != null) { if (attached.value.length === 0 && optionNames.includes(prefix)) { yield { kind: "literal", text: prefix, ...(description != null ? { description } : {}), }; } if (valueParser.suggest != null) { for await (const suggestion of getSuggestionsWithDependencyAsync( valueParser, attached.value, context.dependencyRegistry, context.exec, )) { yield prefixSuggestion(attached.head, suggestion); } } return; } } // An expected value may itself contain '=' or resemble a joined option. const joinedPrefix = joinedOptionPrefix(optionNames, prefix); if (joinedPrefix !== undefined && !waitingForValue) { // Complete only joined forms accepted by the parser. const optionPart = joinedPrefix.slice(0, -1); const valuePart = prefix.slice(joinedPrefix.length); // Check if this option matches any of our option names if ( (optionNames as readonly string[]).includes(optionPart) && !/^-[^-]$/u.test(optionPart) ) { if (valueParser && valueParser.suggest) { const valueSuggestions = getSuggestionsWithDependencyAsync( valueParser, valuePart, context.dependencyRegistry, context.exec, ); // Restore the matched option prefix on each suggestion - handle both sync and async for await (const suggestion of valueSuggestions) { if (suggestion.kind === "literal") { yield { kind: "literal", text: `${joinedPrefix}${suggestion.text}`, description: suggestion.description, }; } else { // File suggestions use a literal prefix fallback yield joinedFileSuggestion(joinedPrefix, suggestion, valuePart); } } } } } else { // If the prefix looks like an option prefix, suggest matching option names if ( !waitingForValue && (prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+")) ) { for (const optionName of optionNames) { if (optionName.startsWith(prefix)) { // Special case: if prefix is exactly "-", only suggest short options if (prefix === "-" && !/^-[^-]$/u.test(optionName)) { continue; } yield { kind: "literal", text: optionName, ...(description && { description }), }; } } } // Check if we should suggest values for this option if (valueParser && valueParser.suggest) { let shouldSuggestValues = false; // Scenario 1: Buffer contains option name if (context.buffer.length > 0) { const lastToken = context.buffer[context.buffer.length - 1]; if ((optionNames as readonly string[]).includes(lastToken)) { shouldSuggestValues = true; } } // Scenario 2: Empty buffer, state is undefined, and the prefix is // not itself starting an option token. else if ( isAnnotationWrappedInitialState(context.state) && context.buffer.length === 0 && (context.exec?.path?.length ?? 0) === 0 && !( prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+") ) ) { shouldSuggestValues = true; } if (shouldSuggestValues) { for await (const suggestion of getSuggestionsWithDependencyAsync( valueParser, prefix, context.dependencyRegistry, context.exec, )) { yield suggestion; } } } } } /** * Internal sync helper for argument suggest functionality. * @internal */ function* suggestArgumentSync( valueParser: ValueParser<"sync", T>, hidden: boolean, prefix: string, dependencyRegistry: DependencyRegistryLike | undefined, exec?: ExecutionContext, ): Generator { if (hidden) return; // Delegate to value parser if it has completion capabilities if (valueParser.suggest) { yield* getSuggestionsWithDependency( valueParser, prefix, dependencyRegistry, exec, ); } } /** * Internal async helper for argument suggest functionality. * @internal */ async function* suggestArgumentAsync( valueParser: ValueParser, hidden: boolean, prefix: string, dependencyRegistry: DependencyRegistryLike | undefined, exec?: ExecutionContext, ): AsyncGenerator { if (hidden) return; // Delegate to value parser if it has completion capabilities if (valueParser.suggest) { yield* getSuggestionsWithDependencyAsync( valueParser, prefix, dependencyRegistry, exec, ); } } /** * Creates a parser for various styles of command-line options that take an * argument value, such as `--option=value`, `-option=value`, `-o value`, * `-ovalue`, or `/option:value`. * @template M The execution mode of the parser. * @template T The type of value this parser produces. * @param args The {@link OptionName}s to parse, followed by * a {@link ValueParser} that defines how to parse the value of * the option. If no value parser is provided, the option is * treated as a boolean flag. * @returns A {@link Parser} that can parse the specified options and their * values. */ export function option( ...args: readonly [OptionName, ...(readonly OptionName[]), ValueParser] ): FluentParser | undefined>; /** * Creates a parser for various styles of command-line options that take an * argument value, such as `--option=value`, `-option=value`, `-o value`, * `-ovalue`, or `/option:value`. * @template M The execution mode of the parser. * @template T The type of value this parser produces. * @param args The {@link OptionName}s to parse, followed by * a {@link ValueParser} that defines how to parse the value of * the option, and an optional {@link OptionOptions} object * that allows you to specify a description or other metadata. * @returns A {@link Parser} that can parse the specified options and their * values. */ export function option( ...args: readonly [ OptionName, ...(readonly OptionName[]), ValueParser, OptionOptions, ] ): FluentParser | undefined>; /** * Creates a parser for various styles of command-line options that do not * take an argument value, such as `--option`, `-o`, or `/option`. * @param optionNames The {@link OptionName}s to parse. * @return A {@link Parser} that can parse the specified options as Boolean * flags, producing `true` if the option is present. */ export function option( ...optionNames: readonly [OptionName, ...(readonly OptionName[])] ): FluentParser<"sync", boolean, ValueParserResult | undefined>; /** * Creates a parser for various styles of command-line options that take an * argument value, such as `--option=value`, `-option=value`, `-o value`, * `-ovalue`, or `/option:value`. * @param args The {@link OptionName}s to parse, followed by * an optional {@link OptionOptions} object that allows you to * specify a description or other metadata. * @returns A {@link Parser} that can parse the specified options and their * values. */ export function option( ...args: readonly [OptionName, ...(readonly OptionName[]), OptionOptions] ): FluentParser<"sync", boolean, ValueParserResult | undefined>; export function option( ...args: | readonly [ OptionName, ...(readonly OptionName[]), ValueParser, OptionOptions, ] | readonly [OptionName, ...(readonly OptionName[]), ValueParser] | readonly [OptionName, ...(readonly OptionName[]), OptionOptions] | readonly [OptionName, ...(readonly OptionName[])] ): FluentParser | undefined> { const lastArg = args.at(-1); const secondLastArg = args.at(-2); let valueParser: ValueParser | undefined; let optionNames: readonly OptionName[]; let options: OptionOptions = {}; if (isValueParser(lastArg)) { valueParser = lastArg; optionNames = args.slice(0, -1) as OptionName[]; } else if (typeof lastArg === "object" && lastArg != null) { options = lastArg; if (isValueParser(secondLastArg)) { valueParser = secondLastArg; optionNames = args.slice(0, -2) as OptionName[]; } else { valueParser = undefined; optionNames = args.slice(0, -1) as OptionName[]; } } else { optionNames = args as readonly OptionName[]; valueParser = undefined; } validateOptionNames(optionNames, "Option"); const mode: M = (valueParser?.mode ?? "sync") as M; const isAsync = mode === "async"; const syncValueParser = valueParser as ValueParser<"sync", T> | undefined; const dependencyMetadata = valueParser != null ? extractDependencyMetadata(valueParser) : undefined; // Shared error formatter used by both complete() and validateValue() // so that fallback validation errors from bindEnv()/bindConfig() // carry the same option-name prefix and `options.errors.invalidValue` // customization as CLI-sourced errors (see issue #414). const formatInvalidValueError = (error: Message): Message => options.errors?.invalidValue ? typeof options.errors.invalidValue === "function" ? options.errors.invalidValue(error) : options.errors.invalidValue : message`${eOptionNames(optionNames)}: ${error}`; // Use 'as any' to allow both sync and async returns from parse method // The actual mode is set correctly at the end via spread with mode const result = { mode: mode, $valueType: [], $stateType: [], priority: 10, usage: [ valueParser == null ? { type: "optional", terms: [ { type: "option", names: optionNames, ...(options.hidden != null && { hidden: options.hidden }), }, ], } : { type: "option", names: optionNames, metavar: valueParser.metavar, ...(options.hidden != null && { hidden: options.hidden }), }, ], leadingNames: new Set(optionNames), acceptingAnyToken: false, initialState: valueParser == null ? { success: true, value: false } : undefined, canSkip(state: ValueParserResult | undefined) { return valueParser == null || isTerminalValueState(state); }, parse(context: ParserContext | undefined>) { if (context.optionsTerminated) { return { success: false, consumed: 0, error: options.errors?.optionsTerminated ?? message`No more options can be parsed.`, }; } else if (context.buffer.length < 1) { return { success: false, consumed: 0, error: options.errors?.endOfInput ?? message`Expected an option, but got end of input.`, }; } // When the input contains `--` it is a signal to stop parsing // options and treat the rest as positional arguments. if (context.buffer[0] === "--") { return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: context.state, optionsTerminated: true, }, consumed: context.buffer.slice(0, 1), }; } // When the input is split by spaces, the first element is the option name // E.g., `--option value` or `/O value` if ((optionNames as string[]).includes(context.buffer[0])) { if (hasParsedOptionValue(context.state, valueParser)) { return { success: false, consumed: 1, error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(context.buffer[0]) : options.errors.duplicate : message`${eOptionName( context.buffer[0], )} cannot be used multiple times.`, }; } if (valueParser == null) { return { success: true, next: { ...context, state: { success: true, value: true }, buffer: context.buffer.slice(1), }, consumed: context.buffer.slice(0, 1), }; } if (context.buffer.length < 2) { return { success: false, consumed: 1, error: options.errors?.endOfInput ?? message`${eOptionName(context.buffer[0])} requires ${metavar( valueParser.metavar, )}.`, }; } const rawInput = context.buffer[1]; return dispatchByMode( mode, () => { const parseResult = syncValueParser!.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "option-value", rawInput, context.buffer.slice(0, 2), syncValueParser!, parseResult, optionNames, ), ); return { success: true as const, next: { ...next, state: createOptionParseState( parseResult, rawInput, syncValueParser!, ), buffer: context.buffer.slice(2), }, consumed: context.buffer.slice(0, 2), }; }, async () => { const parseResult = await valueParser!.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "option-value", rawInput, context.buffer.slice(0, 2), valueParser!, parseResult, optionNames, ), ); return { success: true as const, next: { ...next, state: createOptionParseState( parseResult, rawInput, valueParser!, ), buffer: context.buffer.slice(2), }, consumed: context.buffer.slice(0, 2), }; }, ); } // When the input is not split by spaces, but joined by = or : // E.g., `--option=value` or `/O:value` const prefixes = optionNames .filter( (name) => name.startsWith("--") || name.startsWith("/") || (name.startsWith("-") && name.length > 2 && !/^-[^-]$/u.test(name)), ) .map((name) => ({ optionName: name, prefix: name.startsWith("/") ? `${name}:` : `${name}=`, })); if ( valueParser != null && optionNames.some( (name) => /^-[^-]$/u.test(name) && context.buffer[0].startsWith(name), ) && !fullNameOwnsToken(context, context.buffer[0]) ) { for (const name of optionNames) { if (/^-[^-]$/u.test(name)) { prefixes.push({ optionName: name, prefix: name }); } } } for (const { prefix, optionName } of prefixes) { if (!context.buffer[0].startsWith(prefix)) continue; if (hasParsedOptionValue(context.state, valueParser)) { return { success: false, consumed: 1, error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(prefix) : options.errors.duplicate : message`${eOptionName( optionName, )} cannot be used multiple times.`, }; } const rawInput = context.buffer[0].slice(prefix.length); if (valueParser == null) { return { success: false, consumed: 1, error: options.errors?.unexpectedValue ? typeof options.errors.unexpectedValue === "function" ? options.errors.unexpectedValue(rawInput) : options.errors.unexpectedValue : message`Option ${eOptionName( optionName, )} is a Boolean flag, but got a value: ${rawInput}.`, }; } return dispatchByMode( mode, () => { const parseResult = syncValueParser!.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "option-value", rawInput, context.buffer.slice(0, 1), syncValueParser!, parseResult, optionNames, ), ); return { success: true as const, next: { ...next, state: createOptionParseState( parseResult, rawInput, syncValueParser!, ), buffer: context.buffer.slice(1), }, consumed: context.buffer.slice(0, 1), }; }, async () => { const parseResult = await valueParser.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "option-value", rawInput, context.buffer.slice(0, 1), valueParser, parseResult, optionNames, ), ); return { success: true as const, next: { ...next, state: createOptionParseState( parseResult, rawInput, valueParser, ), buffer: context.buffer.slice(1), }, consumed: context.buffer.slice(0, 1), }; }, ); } if (valueParser == null) { // When the input contains bundled options, e.g., `-abc` const shortOptions = optionNames.filter((name) => name.match(/^-[^-]$/u), ); for (const shortOption of shortOptions) { if ( !context.buffer[0].startsWith(shortOption) || fullNameOwnsToken(context, context.buffer[0]) ) continue; if (hasParsedOptionValue(context.state, valueParser)) { return { success: false, consumed: 1, error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(shortOption) : options.errors.duplicate : message`${eOptionName( shortOption, )} cannot be used multiple times.`, }; } return { success: true, next: { ...context, state: { success: true, value: true }, buffer: [ `-${context.buffer[0].slice(shortOption.length)}`, ...context.buffer.slice(1), ], }, consumed: [context.buffer[0].slice(0, shortOption.length)], }; } } const invalidOption = context.buffer[0]; return unmatchedOptionFailure( invalidOption, context.usage, options.errors, ); }, complete( state: ValueParserResult | undefined, exec?: ExecutionContext, ): ModeValue> { const missing = valueParser == null ? { success: true as const, value: false } : { success: false as const, error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(optionNames) : options.errors.missing : message`Missing option ${eOptionNames(optionNames)}.`, }; const completeSync = (): ValueParserResult => { if (state == null) return missing; const resolvedState = valueParser != null && dependencyMetadata?.derived != null ? (resolveDerivedCompletionSync( dependencyMetadata, state as ValueParserResult, exec, ) as ValueParserResult) : state; return resolvedState.success ? resolvedState : { success: false, error: formatInvalidValueError( includeDependencyFailureChain( resolvedState.error, dependencyMetadata, exec, ), ), }; }; const completeAsync = async (): Promise< ValueParserResult > => { if (state == null) return missing; if (valueParser == null || dependencyMetadata?.derived == null) { return completeSync(); } const resolved = await resolveDerivedCompletionAsync( dependencyMetadata, state as ValueParserResult, exec, ); return resolved.success ? resolved : { success: false, error: formatInvalidValueError( includeDependencyFailureChain( resolved.error, dependencyMetadata, exec, ), ), }; }; return dispatchByMode(mode, completeSync, completeAsync); }, suggest( context: ParserContext | undefined>, prefix: string, ) { // For async parsers, use async generator; for sync parsers, use sync generator if (isAsync) { return suggestOptionAsync( optionNames, valueParser, isSuggestionHidden(options.hidden), options.description, context, prefix, ); } return suggestOptionSync( optionNames, valueParser as ValueParser<"sync", T> | undefined, isSuggestionHidden(options.hidden), options.description, context, prefix, ); }, getDocFragments( _state: DocState | undefined>, defaultValue?: T | boolean, ) { if (isDocHidden(options.hidden)) { return withCommandDocMetadata( { fragments: [], description: options.description, }, {}, ); } const choicesMessage: Message | undefined = valueParser?.choices != null && valueParser.choices.length > 0 ? valueSet( valueParser.choices.map((c) => valueParser.format(c)), { fallback: "", type: "unit" }, ) : undefined; const fragments: readonly DocFragment[] = [ { type: "entry", term: { type: "option", names: optionNames, metavar: valueParser?.metavar, }, description: options.description, default: defaultValue != null && valueParser != null ? message`${valueParser.format(defaultValue as T)}` : undefined, choices: choicesMessage, }, ]; return withCommandDocMetadata( { fragments, description: options.description, }, {}, ); }, [Symbol.for("Deno.customInspect")]() { return `option(${optionNames.map((o) => JSON.stringify(o)).join(", ")})`; }, }; // Define normalizeValue as non-enumerable so that ...parser spread in // map() does not propagate the inner normalizer to the mapped type. // Delegates to ValueParser.normalize() directly so that custom parsers // with lossy format() or non-string types are handled correctly. if (valueParser != null && typeof valueParser.normalize === "function") { const normalize = valueParser.normalize.bind(valueParser); Object.defineProperty(result, "normalizeValue", { value(v: T | boolean): T | boolean { try { return normalize(v as T); } catch { return v; } }, configurable: true, enumerable: false, }); } // Define validateValue as non-enumerable so that ...parser spread in // map() does not propagate it to the mapped type (see issue #414). // Re-validates a value as if it had been parsed from CLI input by // round-tripping through ValueParser.format() + ValueParser.parse(). // Used by bindEnv() and bindConfig() to enforce parser constraints // on fallback values. // // Derived value parsers (`deriveFrom`) are exempt: their `format()` // rebuilds the parser from *default* dependency values rather than // the live ones resolved at parse time, so a format+parse round-trip // would validate against the wrong branch. For those parsers we // return the value unchanged instead of mis-validating. if (valueParser == null) { // Flag-form option (no value parser): the runtime value is a plain // boolean—`true` when the flag is present and `false` when it is // missing (see `option().complete()`). There are no shape // constraints to enforce, but fallback values from `bindEnv()` / // `bindConfig()` originate in `unknown`-typed config/env sources // and a non-boolean would otherwise leak through as the parsed // result. Reject non-booleans with an option-scoped error and // accept any boolean unchanged. Having *some* validator attached // also lets bindEnv(flag-form)/bindConfig(flag-form) forward // validateValue through downstream wrappers without losing the hook. Object.defineProperty(result, "validateValue", { value(v: boolean): ModeValue> { if (typeof v !== "boolean") { const actualType = v === null ? "null" : typeof v; return wrapForMode(mode, { success: false as const, error: formatInvalidValueError( message`Expected a boolean value, but received ${actualType}.`, ), }); } return wrapForMode(mode, { success: true as const, value: v }); }, configurable: true, enumerable: false, }); } else if (!isDerivedValueParser(valueParser)) { const vp = valueParser; // Wraps a ValueParser.parse() failure with the same option-scoped // error formatting that `complete()` applies to CLI-sourced errors, // so fallback validation failures look identical to CLI failures. const wrapParseResult = ( parsed: ValueParserResult, ): ValueParserResult => parsed.success ? parsed : { success: false, error: formatInvalidValueError(parsed.error) }; Object.defineProperty(result, "validateValue", { value(v: T | boolean): ModeValue> { // Prefer the value parser's own validate() hook when present: // combinators like firstOf() can express validation failures // that a generic format()+parse() round-trip cannot (e.g. values // whose string form an earlier overlapping constituent claims). if (typeof vp.validate === "function") { return wrapForMode(mode, wrapParseResult(vp.validate(v as T))); } let stringified: string; try { stringified = vp.format(v as T); } catch { // format() may throw for sentinel defaults whose type cannot // be serialized by this value parser. Skip validation and // return success unchanged so sentinel-default users are // not broken. return wrapForMode(mode, { success: true as const, value: v, }); } if (typeof stringified !== "string") { // A non-string serialization is unsupported for the round- // trip; skip validation rather than crashing. return wrapForMode(mode, { success: true as const, value: v, }); } return dispatchByMode( mode, () => wrapParseResult((vp as ValueParser<"sync", T>).parse(stringified)), async () => wrapParseResult(await vp.parse(stringified)), ); }, configurable: true, enumerable: false, }); } // Define placeholder lazily to avoid triggering derived value parser // factory functions during parser construction. Non-enumerable so that // ...parser spread in map() does not eagerly evaluate the getter. if (valueParser != null) { Object.defineProperty(result, "placeholder", { get() { try { return valueParser!.placeholder; } catch { return undefined; } }, configurable: true, enumerable: false, }); } else { Object.defineProperty(result, "placeholder", { value: false, configurable: true, enumerable: false, writable: false, }); } // Populate dependency metadata from the value parser's markers. if (dependencyMetadata != null) { Object.defineProperty(result, "dependencyMetadata", { value: dependencyMetadata, configurable: true, enumerable: false, }); } else { // A Boolean option without a value parser completes to false when it // is absent; an option with a value is required. defineEmptyInputFacts(result, failingStepFacts(valueParser == null)); } // Type assertion via 'unknown' needed because TypeScript's conditional type // ModeValue cannot be verified when M is a generic type parameter. // At runtime, the isAsync flag ensures correct behavior: // - When M = "sync": parse() returns ParserResult directly // - When M = "async": parse() returns Promise return captureDocParser( fluent( result as unknown as Parser< M, T | boolean, ValueParserResult | undefined >, ), { kind: "leaf", description: options.description, valueParser, choicesRequested: valueParser != null, boolean: valueParser == null, }, ); } /** * Options for the {@link flag} parser. */ export interface FlagOptions { /** * The description of the flag, which can be used for help messages. */ readonly description?: Message; /** * Controls flag visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions * * @since 0.9.0 */ readonly hidden?: HiddenVisibility; /** * Error message customization options. * @since 0.5.0 */ readonly errors?: FlagErrorOptions; } /** * Options for customizing error messages in the {@link flag} parser. * @since 0.5.0 */ export interface FlagErrorOptions { /** * Custom error message when the flag is missing (for required flags). * Can be a static message or a function that receives the option names. */ missing?: Message | ((optionNames: readonly string[]) => Message); /** * Custom error message when options are terminated (after --). */ optionsTerminated?: Message; /** * Custom error message when input is empty but flag is expected. */ endOfInput?: Message; /** * Custom error message when flag is used multiple times. * Can be a static message or a function that receives the token. */ duplicate?: Message | ((token: string) => Message); /** * Custom error message when a flag receives an unexpected value. * Can be a static message or a function that receives the matched option * name and the value after the separator, including an empty value. * * @since 1.4.0 */ readonly unexpectedValue?: | Message | ((optionName: string, value: string) => Message); /** * Custom error message when no matching flag is found. * Can be a static message or a function that receives: * - invalidOption: The invalid option name that was provided * - suggestions: Array of similar valid option names (can be empty) * The callback runs when a retained failure's error is read, and may be * skipped for discarded failures. It should not have side effects. * * @since 0.7.0 */ noMatch?: | Message | ((invalidOption: string, suggestions: readonly string[]) => Message); } /** * Creates a parser for command-line flags that must be explicitly provided. * Unlike {@link option}, this parser fails if the flag is not present, making * it suitable for required boolean flags that don't have a meaningful default. * * The key difference from {@link option} is: * - {@link option} without a value parser: Returns `false` when not present * - {@link flag}: Fails parsing when not present, only produces `true` * * This is useful for dependent options where the presence of a flag changes * the shape of the result type. * * @param args The {@link OptionName}s to parse, followed by an optional * {@link FlagOptions} object that allows you to specify * a description or other metadata. * @returns A {@link Parser} that produces `true` when the flag is present * and fails when it is not present. * * @example * ```typescript * // Basic flag usage * const parser = flag("-f", "--force"); * // Succeeds with true: parse(parser, ["-f"]) * // Fails: parse(parser, []) * * // With description * const verboseFlag = flag("-v", "--verbose", { * description: "Enable verbose output" * }); * ``` */ export function flag( ...args: | readonly [OptionName, ...(readonly OptionName[]), FlagOptions] | readonly [OptionName, ...(readonly OptionName[])] ): FluentParser<"sync", true, ValueParserResult | undefined> { const lastArg = args.at(-1); let optionNames: readonly OptionName[]; let options: FlagOptions = {}; if ( typeof lastArg === "object" && lastArg != null && !Array.isArray(lastArg) ) { options = lastArg as FlagOptions; optionNames = args.slice(0, -1) as OptionName[]; } else { optionNames = args as readonly OptionName[]; } validateOptionNames(optionNames, "Flag"); const result: Parser<"sync", true, ValueParserResult | undefined> = { $valueType: [], $stateType: [], mode: "sync", priority: 10, usage: [ { type: "option", names: optionNames, ...(options.hidden != null && { hidden: options.hidden }), }, ], leadingNames: new Set(optionNames), acceptingAnyToken: false, initialState: undefined, canSkip(state) { return isTerminalValueState(state); }, parse(context) { if (context.optionsTerminated) { return { success: false, consumed: 0, error: options.errors?.optionsTerminated ?? message`No more options can be parsed.`, }; } else if (context.buffer.length < 1) { return { success: false, consumed: 0, error: options.errors?.endOfInput ?? message`Expected an option, but got end of input.`, }; } // When the input contains `--` it is a signal to stop parsing // options and treat the rest as positional arguments. if (context.buffer[0] === "--") { return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: context.state, optionsTerminated: true, }, consumed: context.buffer.slice(0, 1), }; } // When the input is split by spaces, the first element is the option name if ((optionNames as string[]).includes(context.buffer[0])) { if (context.state?.success) { return { success: false, consumed: 1, error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(context.buffer[0]) : options.errors.duplicate : message`${eOptionName( context.buffer[0], )} cannot be used multiple times.`, }; } return { success: true, next: { ...context, state: { success: true, value: true }, buffer: context.buffer.slice(1), }, consumed: context.buffer.slice(0, 1), }; } // Check for joined format (e.g., --flag=value) which should fail for flags const prefixes = optionNames .filter( (name) => name.startsWith("--") || name.startsWith("/") || (name.startsWith("-") && name.length > 2 && !/^-[^-]$/u.test(name)), ) .map((name) => (name.startsWith("/") ? `${name}:` : `${name}=`)); for (const prefix of prefixes) { if (context.buffer[0].startsWith(prefix)) { const optionName = prefix.slice(0, -1); const value = context.buffer[0].slice(prefix.length); return { success: false, consumed: 1, error: options.errors?.unexpectedValue ? typeof options.errors.unexpectedValue === "function" ? options.errors.unexpectedValue(optionName, value) : options.errors.unexpectedValue : message`Flag ${eOptionName( optionName, )} does not accept a value, but got: ${value}.`, }; } } // When the input contains bundled options, e.g., `-abc` const shortOptions = optionNames.filter((name) => name.match(/^-[^-]$/u)); for (const shortOption of shortOptions) { if ( !context.buffer[0].startsWith(shortOption) || fullNameOwnsToken(context, context.buffer[0]) ) continue; if (context.state?.success) { return { success: false, consumed: 1, error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(shortOption) : options.errors.duplicate : message`${eOptionName( shortOption, )} cannot be used multiple times.`, }; } return { success: true, next: { ...context, state: { success: true, value: true }, buffer: [ `-${context.buffer[0].slice(shortOption.length)}`, ...context.buffer.slice(1), ], }, consumed: [context.buffer[0].slice(0, shortOption.length)], }; } const invalidOption = context.buffer[0]; return unmatchedOptionFailure( invalidOption, context.usage, options.errors, ); }, complete(state, _exec?: ExecutionContext) { if (state == null) { return { success: false, error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(optionNames) : options.errors.missing : message`Required flag ${eOptionNames(optionNames)} is missing.`, }; } if (state.success) return { success: true, value: true }; return { success: false, error: message`${eOptionNames(optionNames)}: ${state.error}`, }; }, suggest(context, prefix) { if (isSuggestionHidden(options.hidden) || context.optionsTerminated) { return []; } const suggestions: Suggestion[] = []; // If the prefix looks like an option prefix, suggest matching option names if ( prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+") ) { for (const optionName of optionNames) { if (optionName.startsWith(prefix)) { // Special case: if prefix is exactly "-", only suggest short options (single dash + single char) if (prefix === "-" && !/^-[^-]$/u.test(optionName)) { continue; } suggestions.push({ kind: "literal", text: optionName, ...(options.description && { description: options.description, }), }); } } } return suggestions; }, getDocFragments( _state: DocState | undefined>, _defaultValue?, ) { if (isDocHidden(options.hidden)) { return withCommandDocMetadata( { fragments: [], description: options.description, }, {}, ); } const fragments: readonly DocFragment[] = [ { type: "entry", term: { type: "option", names: optionNames, }, description: options.description, }, ]; return withCommandDocMetadata( { fragments, description: options.description, }, {}, ); }, [Symbol.for("Deno.customInspect")]() { return `flag(${optionNames.map((o) => JSON.stringify(o)).join(", ")})`; }, }; // Non-enumerable so that ...parser spread in map() does not // eagerly evaluate the getter. Object.defineProperty(result, "placeholder", { value: true, configurable: true, enumerable: false, writable: false, }); defineEmptyInputFacts(result, failingStepFacts(false)); return captureDocParser(fluent(result), { kind: "leaf", description: options.description, boolean: true, }); } /** * A non-empty list of option names, or a single option name. * @since 1.1.0 */ export type NegatableFlagNameList = | OptionName | readonly [OptionName, ...(readonly OptionName[])]; /** * Option names for the {@link negatableFlag} parser. * @since 1.1.0 */ export interface NegatableFlagNames { /** * Option names that produce `true`. */ readonly positive: NegatableFlagNameList; /** * Option names that produce `false`. */ readonly negative: NegatableFlagNameList; } /** * Options for the {@link negatableFlag} parser. * @since 1.1.0 */ export interface NegatableFlagOptions { /** * The description of the flag pair, which can be used for help messages. */ readonly description?: Message; /** * Controls flag visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions */ readonly hidden?: HiddenVisibility; /** * Error message customization options. */ readonly errors?: NegatableFlagErrorOptions; } /** * Options for customizing error messages in the {@link negatableFlag} parser. * @since 1.1.0 */ export interface NegatableFlagErrorOptions { /** * Custom error message when neither flag is provided. * Can be a static message or a function that receives the positive and * negative option names. */ readonly missing?: | Message | (( positiveNames: readonly string[], negativeNames: readonly string[], ) => Message); /** * Custom error message when options are terminated (after --). */ readonly optionsTerminated?: Message; /** * Custom error message when input is empty but a flag is expected. */ readonly endOfInput?: Message; /** * Custom error message when the same polarity is used multiple times. */ readonly duplicate?: Message | ((token: string) => Message); /** * Custom error message when both positive and negative flags are used. */ readonly conflict?: | Message | ((previousToken: string, token: string) => Message); /** * Custom error message when a flag receives an unexpected value. */ readonly unexpectedValue?: | Message | ((optionName: string, value: string) => Message); /** * Custom error message when no matching flag is found. * Callbacks may be skipped when a mismatch is discarded. */ readonly noMatch?: | Message | ((invalidOption: string, suggestions: readonly string[]) => Message); } /** * State stored by the {@link negatableFlag} parser. * @since 1.1.0 */ export interface NegatableFlagState { readonly value: boolean; readonly token: string; } function normalizeNegatableFlagNameList( names: NegatableFlagNameList, ): readonly OptionName[] { return typeof names === "string" ? [names] : names; } function validateNoDuplicateOptionNames( names: readonly OptionName[], label: string, ): void { const seen = new Set(); for (const name of names) { if (seen.has(name)) { throw new TypeError(`${label} has a duplicate name: "${name}".`); } seen.add(name); } } function validateNoNegatableFlagNameCollision( positiveNames: readonly OptionName[], negativeNames: readonly OptionName[], ): void { const positiveSet = new Set(positiveNames); for (const name of negativeNames) { if (positiveSet.has(name)) { throw new TypeError( `Negatable flag name is both positive and negative: "${name}".`, ); } } } function formatNegatableFlagDuplicateError( options: NegatableFlagOptions, token: string, ): Message { return options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(token) : options.errors.duplicate : message`${eOptionName(token)} cannot be used multiple times.`; } function formatNegatableFlagConflictError( options: NegatableFlagOptions, previousToken: string, token: string, ): Message { return options.errors?.conflict ? typeof options.errors.conflict === "function" ? options.errors.conflict(previousToken, token) : options.errors.conflict : message`${eOptionName(previousToken)} and ${eOptionName( token, )} cannot be used together.`; } function formatNegatableFlagUnexpectedValueError( options: NegatableFlagOptions, optionName: string, value: string, ): Message { return options.errors?.unexpectedValue ? typeof options.errors.unexpectedValue === "function" ? options.errors.unexpectedValue(optionName, value) : options.errors.unexpectedValue : message`Flag ${eOptionName( optionName, )} does not accept a value, but got: ${value}.`; } function parseMatchedNegatableFlag( context: ParserContext, token: string, value: boolean, consumed: readonly string[], consumedOnFailure: number, buffer: readonly string[], options: NegatableFlagOptions, ): ParserResult { if (context.state != null) { return { success: false, consumed: consumedOnFailure, error: context.state.value === value ? formatNegatableFlagDuplicateError(options, token) : formatNegatableFlagConflictError( options, context.state.token, token, ), }; } return { success: true, next: { ...context, state: { value, token }, buffer, }, consumed, }; } /** * Creates a parser for a pair of command-line flags that explicitly enable or * disable a Boolean value. * * The positive names produce `true`; the negative names produce `false`. * Unlike {@link option}, this parser fails when neither side is present, * matching {@link flag} semantics. Wrap it in {@link optional} for a * tri-state override or {@link withDefault} for a concrete fallback. * * @param names The positive and negative option names to parse. * @param options Optional metadata and error customization. * @returns A {@link Parser} that produces `true` for positive names and * `false` for negative names. * @throws {TypeError} If any option name is invalid, duplicated within one * side, or shared by the positive and negative sides. * @since 1.1.0 */ export function negatableFlag( names: NegatableFlagNames, options: NegatableFlagOptions = {}, ): FluentParser<"sync", boolean, NegatableFlagState | undefined> { const positiveNames = normalizeNegatableFlagNameList(names.positive); const negativeNames = normalizeNegatableFlagNameList(names.negative); validateOptionNames(positiveNames, "Positive flag"); validateOptionNames(negativeNames, "Negative flag"); validateNoDuplicateOptionNames(positiveNames, "Positive flag"); validateNoDuplicateOptionNames(negativeNames, "Negative flag"); validateNoNegatableFlagNameCollision(positiveNames, negativeNames); const optionNames = [...positiveNames, ...negativeNames]; const valueByName = new Map(); for (const name of positiveNames) valueByName.set(name, true); for (const name of negativeNames) valueByName.set(name, false); const result: Parser<"sync", boolean, NegatableFlagState | undefined> = { $valueType: [], $stateType: [], mode: "sync", priority: 10, usage: [ { type: "option", names: optionNames, ...(options.hidden != null && { hidden: options.hidden }), }, ], leadingNames: new Set(optionNames), acceptingAnyToken: false, initialState: undefined, canSkip(state) { return state != null; }, parse(context) { if (context.optionsTerminated) { return { success: false, consumed: 0, error: options.errors?.optionsTerminated ?? message`No more options can be parsed.`, }; } else if (context.buffer.length < 1) { return { success: false, consumed: 0, error: options.errors?.endOfInput ?? message`Expected an option, but got end of input.`, }; } if (context.buffer[0] === "--") { return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: context.state, optionsTerminated: true, }, consumed: context.buffer.slice(0, 1), }; } const directValue = valueByName.get(context.buffer[0]); if (directValue != null) { return parseMatchedNegatableFlag( context, context.buffer[0], directValue, context.buffer.slice(0, 1), 1, context.buffer.slice(1), options, ); } for (const name of optionNames) { if ( !name.startsWith("--") && !name.startsWith("/") && !name.startsWith("+") && !(name.startsWith("-") && name.length > 2 && !/^-[^-]$/u.test(name)) ) { continue; } const prefix = name.startsWith("/") ? `${name}:` : `${name}=`; if (context.buffer[0].startsWith(prefix)) { const value = context.buffer[0].slice(prefix.length); return { success: false, consumed: 1, error: formatNegatableFlagUnexpectedValueError( options, prefix.slice(0, -1), value, ), }; } } for (const shortOption of optionNames) { if (!shortOption.match(/^-[^-]$/u)) continue; if ( !context.buffer[0].startsWith(shortOption) || fullNameOwnsToken(context, context.buffer[0]) ) continue; return parseMatchedNegatableFlag( context, shortOption, valueByName.get(shortOption)!, [context.buffer[0].slice(0, shortOption.length)], 1, [ `-${context.buffer[0].slice(shortOption.length)}`, ...context.buffer.slice(1), ], options, ); } return unmatchedOptionFailure( context.buffer[0], context.usage, options.errors, ); }, complete(state, _exec?: ExecutionContext) { if (state == null) { return { success: false, error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(positiveNames, negativeNames) : options.errors.missing : message`Required flag ${eOptionNames(optionNames)} is missing.`, }; } return { success: true, value: state.value }; }, suggest(_context, prefix) { if (isSuggestionHidden(options.hidden)) { return []; } const suggestions: Suggestion[] = []; if ( prefix.startsWith("--") || prefix.startsWith("-") || prefix.startsWith("/") || prefix.startsWith("+") ) { for (const optionName of optionNames) { if (optionName.startsWith(prefix)) { if (prefix === "-" && !/^-[^-]$/u.test(optionName)) { continue; } suggestions.push({ kind: "literal", text: optionName }); } } } return suggestions; }, getDocFragments( _state: DocState, _defaultValue?, ) { if (isDocHidden(options.hidden)) { return { fragments: [], description: options.description }; } const fragments: readonly DocFragment[] = [ { type: "entry", term: { type: "option", names: optionNames, }, description: options.description, }, ]; return { fragments, description: options.description }; }, [Symbol.for("Deno.customInspect")]() { const args = [ `positive: ${JSON.stringify(positiveNames)}`, `negative: ${JSON.stringify(negativeNames)}`, ]; return `negatableFlag({ ${args.join(", ")} })`; }, }; Object.defineProperty(result, "validateValue", { value(v: boolean): ValueParserResult { if (typeof v !== "boolean") { const actualType = v === null ? "null" : typeof v; return { success: false, error: message`${eOptionNames( optionNames, )}: Expected a boolean value, but received ${actualType}.`, }; } return { success: true, value: v }; }, configurable: true, enumerable: false, writable: false, }); Object.defineProperty(result, "placeholder", { value: false, configurable: true, enumerable: false, writable: false, }); return fluent(result); } /** * Options for the {@link argument} parser. */ export interface ArgumentOptions { /** * The description of the argument, which can be used for help messages. */ readonly description?: Message; /** * Controls argument visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions * * @since 0.9.0 */ readonly hidden?: HiddenVisibility; /** * Error message customization options. * @since 0.5.0 */ readonly errors?: ArgumentErrorOptions; } /** * Options for customizing error messages in the {@link argument} parser. * @since 0.5.0 */ export interface ArgumentErrorOptions { /** * Custom error message when input is empty but argument is expected. */ endOfInput?: Message; /** * Custom error message when value parsing fails. * Can be a static message or a function that receives the error message. */ invalidValue?: Message | ((error: Message) => Message); /** * Custom error message when argument is used multiple times. * Can be a static message or a function that receives the metavar. */ multiple?: Message | ((metavar: string) => Message); } /** * Creates a parser that expects a single argument value. * This parser is typically used for positional arguments * that are not options or flags. * @template M The execution mode of the parser. * @template T The type of the value produced by the parser. * @param valueParser The {@link ValueParser} that defines how to parse * the argument value. * @param options Optional configuration for the argument parser, * allowing you to specify a description or other metadata. * @returns A {@link Parser} that expects a single argument value and produces * the parsed value of type {@link T}. */ export function argument( valueParser: ValueParser, options: ArgumentOptions = {}, ): FluentParser | undefined> { const isAsync = valueParser.mode === "async"; const syncValueParser = valueParser as ValueParser<"sync", T>; const dependencyMetadata = extractDependencyMetadata(valueParser); // Shared error formatter used by both complete() and validateValue() // so that fallback validation errors from bindEnv()/bindConfig() // carry the same metavar prefix and `options.errors.invalidValue` // customization as CLI-sourced errors (see issue #414). const formatInvalidValueError = (error: Message): Message => options.errors?.invalidValue ? typeof options.errors.invalidValue === "function" ? options.errors.invalidValue(error) : options.errors.invalidValue : message`${metavar(valueParser.metavar)}: ${error}`; const optionPattern = /^(?!--=)(--?[a-z0-9-]+)(?:=|$)/i; const term: UsageTerm = { type: "argument", metavar: valueParser.metavar, ...(options.hidden != null && { hidden: options.hidden }), }; // Use type assertion to allow both sync and async returns from parse method const result = { mode: valueParser.mode, $valueType: [], $stateType: [], priority: 5, usage: [term], leadingNames: EMPTY_LEADING_NAMES, acceptingAnyToken: true, initialState: undefined, canSkip(state: ValueParserResult | undefined) { return isTerminalValueState(state); }, parse(context: ParserContext | undefined>) { const localState = normalizeInjectedAnnotationState(context.state); if (context.buffer.length < 1) { return { success: false, consumed: 0, error: options.errors?.endOfInput ?? message`Expected an argument, but got end of input.`, }; } let i = 0; let optionsTerminated = context.optionsTerminated; if (!optionsTerminated) { if (context.buffer[i] === "--") { optionsTerminated = true; i++; } else { const optionMatch = context.buffer[i].match(optionPattern); if (optionMatch != null) { return { success: false, consumed: i, error: message`Expected an argument, but got an option: ${eOptionName( optionMatch[1], )}.`, }; } } } if (context.buffer.length < i + 1) { return { success: false, consumed: i, error: message`Expected an argument, but got end of input.`, }; } if (localState != null) { return { success: false, consumed: i, error: options.errors?.multiple ? typeof options.errors.multiple === "function" ? options.errors.multiple(valueParser.metavar) : options.errors.multiple : message`The argument ${metavar( valueParser.metavar, )} cannot be used multiple times.`, }; } const rawInput = context.buffer[i]; return dispatchByMode( valueParser.mode, () => { const parseResult = syncValueParser.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "argument-value", rawInput, context.buffer.slice(0, i + 1), syncValueParser, parseResult, ), ); return { success: true as const, next: { ...next, buffer: context.buffer.slice(i + 1), state: createOptionParseState( parseResult, rawInput, syncValueParser, ), optionsTerminated, }, consumed: context.buffer.slice(0, i + 1), }; }, async () => { const parseResult = await valueParser.parse(rawInput); const next = recordTrace( context, buildTraceEntry( "argument-value", rawInput, context.buffer.slice(0, i + 1), valueParser, parseResult, ), ); return { success: true as const, next: { ...next, buffer: context.buffer.slice(i + 1), state: createOptionParseState(parseResult, rawInput, valueParser), optionsTerminated, }, consumed: context.buffer.slice(0, i + 1), }; }, ); }, complete( state: ValueParserResult | undefined, exec?: ExecutionContext, ): ModeValue> { const missing = { success: false as const, error: options.errors?.endOfInput ?? message`Expected a ${metavar( valueParser.metavar, )}, but too few arguments.`, }; const completeSync = (): ValueParserResult => { if (state == null) return missing; const resolvedState = dependencyMetadata?.derived != null ? resolveDerivedCompletionSync(dependencyMetadata, state, exec) : state; return resolvedState.success ? resolvedState : { success: false, error: formatInvalidValueError( includeDependencyFailureChain( resolvedState.error, dependencyMetadata, exec, ), ), }; }; const completeAsync = async (): Promise> => { if (state == null) return missing; if (dependencyMetadata?.derived == null) return completeSync(); const resolved = await resolveDerivedCompletionAsync( dependencyMetadata, state, exec, ); return resolved.success ? resolved : { success: false, error: formatInvalidValueError( includeDependencyFailureChain( resolved.error, dependencyMetadata, exec, ), ), }; }; return dispatchByMode(valueParser.mode, completeSync, completeAsync); }, suggest( context: ParserContext | undefined>, prefix: string, ) { if (normalizeInjectedAnnotationState(context.state) != null) { return dispatchIterableByMode( valueParser.mode, function* () {}, async function* () {}, ); } // For async parsers, use async generator; for sync parsers, use sync generator if (isAsync) { return suggestArgumentAsync( valueParser, isSuggestionHidden(options.hidden), prefix, context.dependencyRegistry, context.exec, ); } return suggestArgumentSync( valueParser as ValueParser<"sync", T>, isSuggestionHidden(options.hidden), prefix, context.dependencyRegistry, context.exec, ); }, getDocFragments( _state: DocState | undefined>, defaultValue?: T, ) { if (isDocHidden(options.hidden)) { return withCommandDocMetadata( { fragments: [], description: options.description, }, {}, ); } const choicesMessage: Message | undefined = valueParser.choices != null && valueParser.choices.length > 0 ? valueSet( valueParser.choices.map((c) => valueParser.format(c)), { fallback: "", type: "unit" }, ) : undefined; const fragments: readonly DocFragment[] = [ { type: "entry", term, description: options.description, default: defaultValue == null ? undefined : message`${valueParser.format(defaultValue)}`, choices: choicesMessage, }, ]; return withCommandDocMetadata( { fragments, description: options.description, }, {}, ); }, [Symbol.for("Deno.customInspect")]() { return `argument()`; }, }; // Define normalizeValue as non-enumerable so that ...parser spread in // map() does not propagate the inner normalizer to the mapped type. if (typeof valueParser.normalize === "function") { const normalize = valueParser.normalize.bind(valueParser); Object.defineProperty(result, "normalizeValue", { value(v: T): T { try { return normalize(v); } catch { return v; } }, configurable: true, enumerable: false, }); } // Define validateValue as non-enumerable so that ...parser spread in // map() does not propagate it to the mapped type (see issue #414). // Re-validates a value as if it had been parsed from CLI input by // round-tripping through ValueParser.format() + ValueParser.parse(). // // Derived value parsers (`deriveFrom`) are exempt: their `format()` // rebuilds the parser from *default* dependency values rather than // the live ones resolved at parse time, so a format+parse round-trip // would validate against the wrong branch. For those parsers we // skip attaching validateValue entirely. if (!isDerivedValueParser(valueParser)) { const vp = valueParser; const vpMode = valueParser.mode; // Wraps a ValueParser.parse() failure with the same metavar-scoped // error formatting that `complete()` applies to CLI-sourced errors, // so fallback validation failures look identical to CLI failures. const wrapParseResult = ( parsed: ValueParserResult, ): ValueParserResult => parsed.success ? parsed : { success: false, error: formatInvalidValueError(parsed.error) }; Object.defineProperty(result, "validateValue", { value(v: T): ModeValue> { // Prefer the value parser's own validate() hook when present: // combinators like firstOf() can express validation failures // that a generic format()+parse() round-trip cannot (e.g. values // whose string form an earlier overlapping constituent claims). if (typeof vp.validate === "function") { return wrapForMode>( vpMode, wrapParseResult(vp.validate(v)), ); } let stringified: string; try { stringified = vp.format(v); } catch { // format() may throw for sentinel defaults whose type cannot // be serialized by this value parser. Skip validation and // return success unchanged so sentinel-default users are // not broken. return wrapForMode>(vpMode, { success: true as const, value: v, }); } if (typeof stringified !== "string") { return wrapForMode>(vpMode, { success: true as const, value: v, }); } return dispatchByMode>( vpMode, () => wrapParseResult(syncValueParser.parse(stringified)), async () => wrapParseResult(await vp.parse(stringified)), ); }, configurable: true, enumerable: false, }); } // Define placeholder lazily to avoid triggering derived value parser // factory functions during parser construction. Non-enumerable so that // ...parser spread in map() does not eagerly evaluate the getter. Object.defineProperty(result, "placeholder", { get() { try { return valueParser.placeholder; } catch { return undefined; } }, configurable: true, enumerable: false, }); if (dependencyMetadata != null) { Object.defineProperty(result, "dependencyMetadata", { value: dependencyMetadata, configurable: true, enumerable: false, }); } else { defineEmptyInputFacts(result, failingStepFacts(false)); } // Type assertion via 'unknown' needed because TypeScript's conditional type // ModeValue cannot be verified when M is a generic type parameter. return captureDocParser( fluent(result as unknown as Parser | undefined>), { kind: "leaf", description: options.description, valueParser, choicesRequested: true, }, ); } /** * Options for the {@link command} parser. * @since 0.5.0 */ export interface CommandOptions { /** * A brief description of the command, shown in command lists. * If provided along with {@link description}, this will be used in * command listings (e.g., `myapp help`), while {@link description} * will be used for detailed help (e.g., `myapp help subcommand` or * `myapp subcommand --help`). * @since 0.6.0 */ readonly brief?: Message; /** * A description of the command, used for documentation. */ readonly description?: Message; /** * A footer message that appears at the bottom of the command's help text. * Useful for showing examples, notes, or additional information. * @since 0.6.0 */ readonly footer?: Message; /** * Usage line override for this command's own help page. * * This option customizes the usage tail shown when rendering help for this * command itself (e.g., `myapp config --help`). It does not change parsing * behavior or shell completion. * * - `Usage`: Replaces the default usage tail. * - `(defaultUsageLine) => Usage`: Computes the usage tail from the default. * * @since 1.0.0 */ readonly usageLine?: Usage | ((defaultUsageLine: Usage) => Usage); /** * Whether to show the usage synopsis in this command's full help. * Descendants inherit this setting unless they explicitly override it. * Omission inherits the nearest ancestor setting, then the runner setting, * with a final default of `true`. Usage-only error preambles are unaffected. * @since 1.4.0 */ readonly showUsage?: boolean; /** * Controls command visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions * * @since 0.9.0 */ readonly hidden?: HiddenVisibility; /** * Additional names that invoke this command. * * Aliases are functional at runtime and are suggested by shell completion. * By default they are hidden from usage and documentation output; set * {@link showAliases} or the help formatter's `showAliases` option to list * them next to the command in command lists. Usage lines always show * only the `name` parameter passed to {@link command}, which remains the * canonical display name. * * @since 1.1.0 */ readonly aliases?: readonly [string, ...string[]]; /** * Whether to show {@link aliases} next to this command in command lists * of help and documentation output, e.g., `(aliases: i, add)`. * * When omitted, the help formatter's `showAliases` option decides, which * defaults to hiding aliases. `true` shows them and `false` hides them * regardless of that option. This setting does not affect usage lines * and does not apply to nested subcommands. * * @since 1.4.0 */ readonly showAliases?: boolean; /** * Error messages customization. * @since 0.5.0 */ readonly errors?: CommandErrorOptions; } /** * Options for customizing error messages in the {@link command} parser. * @since 0.5.0 */ export interface CommandErrorOptions { /** * Error message when command is expected but not found. * Since version 0.7.0, the function signature now includes suggestions: * - expected: The expected command name * - actual: The actual input (or null if no input) * - suggestions: Array of similar valid command names (can be empty) * The callback runs when a retained failure's error is read, and may be * skipped for discarded failures. It should not have side effects. */ readonly notMatched?: | Message | (( expected: string, actual: string | null, suggestions?: readonly string[], ) => Message); /** * Error message when command was not matched during completion. */ readonly notFound?: Message; /** * Error message for invalid command state. */ readonly invalidState?: Message; } /** * The state type for the {@link command} parser. * @template TState The type of the inner parser's state. */ type CommandState = | undefined // Command not yet matched | ["matched", string] // Command matched but inner parser not started | ["parsing", TState]; // Command matched and inner parser active function normalizeCommandState( state: CommandState, ): CommandState { return normalizeInjectedAnnotationState(state); } function getCommandParseChildState( commandState: CommandState, childState: TState, parser: Parser, ): TState { return getWrappedChildParseState(commandState, childState, parser); } function getCommandChildState( commandState: CommandState, childState: TState, parser: Parser, ): TState { return getWrappedChildState(commandState, childState, parser); } function createCommandState( sourceState: unknown, state: Exclude, undefined>, ): Exclude, undefined> { return annotateFreshArray( sourceState, state as readonly unknown[], ) as Exclude, undefined>; } function appendCommandPath( exec: ExecutionContext | undefined, name: string, ): ExecutionContext | undefined { if (exec == null) return undefined; return { ...exec, commandPath: [...(exec.commandPath ?? []), name], }; } function getCommandNames( name: string, options: CommandOptions, ): readonly string[] { return [ name, ...getVisibleCommandAliases(options), ...getHiddenCommandAliases(options), ]; } function getVisibleCommandAliases(options: CommandOptions): readonly string[] { const aliases: unknown = options.aliases; if (aliases == null) return []; if (!isNonEmptyStringArray(aliases)) { throw new TypeError( "Command aliases must be a non-empty array of strings.", ); } return aliases; } function getShowCommandAliases(options: CommandOptions): boolean | undefined { const showAliases: unknown = options.showAliases; if (showAliases == null) return undefined; if (typeof showAliases !== "boolean") { throw new TypeError("Command showAliases must be a boolean."); } return showAliases; } function getShowCommandUsage(options: CommandOptions): boolean | undefined { const showUsage: unknown = options.showUsage; if (showUsage == null) return undefined; if (typeof showUsage !== "boolean") { throw new TypeError("Command showUsage must be a boolean."); } return showUsage; } function getHiddenCommandAliases(options: CommandOptions): readonly string[] { const hiddenAliases: unknown = ( options as CommandOptions & HiddenCommandAliasOptions )[hiddenCommandAliasesKey]; if (hiddenAliases == null) return []; if (!isNonEmptyStringArray(hiddenAliases)) { throw new TypeError( "Hidden command aliases must be a non-empty array of strings.", ); } return hiddenAliases; } function isNonEmptyStringArray( value: unknown, ): value is readonly [string, ...string[]] { if (!Array.isArray(value) || value.length === 0) return false; for (let i = 0; i < value.length; i++) { if (typeof value[i] !== "string") return false; } return true; } function validateUniqueCommandNames(names: readonly string[]): void { const seen = new Set(); for (const name of names) { if (seen.has(name)) { throw new TypeError(`Command has a duplicate name: "${name}".`); } seen.add(name); } } function* suggestCommandSync( context: ParserContext>, prefix: string, name: string, aliases: readonly string[], parser: Parser<"sync", T, TState>, options: CommandOptions, ): Generator { if (isSuggestionHidden(options.hidden)) { return; } const state = normalizeCommandState(context.state); // Handle different command states if (state === undefined) { // Command not yet matched - suggest command name if it matches prefix const description = options.brief ?? options.description; for (const commandName of [name, ...aliases]) { if (commandName.startsWith(prefix)) { yield { kind: "literal", text: commandName, ...(description && { description }), }; } } } else if (state[0] === "matched") { // Command matched but inner parser not started - delegate to inner parser yield* parser.suggest( withChildContext( context, name, getCommandChildState(context.state, parser.initialState, parser), parser.usage, ), prefix, ); } else if (state[0] === "parsing") { // Command in parsing state - delegate to inner parser yield* parser.suggest( withChildContext( context, name, getCommandChildState(context.state, state[1], parser), parser.usage, ), prefix, ); } } async function* suggestCommandAsync( context: ParserContext>, prefix: string, name: string, aliases: readonly string[], parser: Parser, options: CommandOptions, ): AsyncGenerator { if (isSuggestionHidden(options.hidden)) { return; } const state = normalizeCommandState(context.state); // Handle different command states if (state === undefined) { // Command not yet matched - suggest command name if it matches prefix const description = options.brief ?? options.description; for (const commandName of [name, ...aliases]) { if (commandName.startsWith(prefix)) { yield { kind: "literal", text: commandName, ...(description && { description }), }; } } } else if (state[0] === "matched") { // Command matched but inner parser not started - delegate to inner parser const suggestions = parser.suggest( withChildContext( context, name, getCommandChildState(context.state, parser.initialState, parser), parser.usage, ), prefix, ) as AsyncIterable; for await (const s of suggestions) { yield s; } } else if (state[0] === "parsing") { // Command in parsing state - delegate to inner parser const suggestions = parser.suggest( withChildContext( context, name, getCommandChildState(context.state, state[1], parser), parser.usage, ), prefix, ) as AsyncIterable; for await (const s of suggestions) { yield s; } } } /** * Creates a parser that matches a specific subcommand name and then applies * an inner parser to the remaining arguments. * This is useful for building CLI tools with subcommands like git, npm, etc. * @template M The execution mode of the parser. * @template T The type of the value returned by the inner parser. * @template TState The type of the state used by the inner parser. * @param name The subcommand name to match (e.g., `"show"`, `"edit"`). * @param parser The {@link Parser} to apply after the command is matched. * @param options Optional configuration for the command parser, such as * a description for documentation. * @returns A {@link Parser} that matches the command name and delegates * to the inner parser for the remaining arguments. * @throws {TypeError} If `name` is empty, whitespace-only, contains * embedded whitespace, or contains control characters. * @throws {TypeError} If `options.showAliases` or `options.showUsage` is * non-nullish and not a boolean. */ export function command( name: string, parser: Parser, options: CommandOptions = {}, ): FluentParser> { const commandNames = getCommandNames(name, options); const aliases = getVisibleCommandAliases(options); const showAliases = getShowCommandAliases(options); const showUsage = getShowCommandUsage(options); const commandId = Symbol("commandDocScope"); const hiddenAliases = getHiddenCommandAliases(options); validateCommandNames(commandNames, "Command"); validateUniqueCommandNames(commandNames); const isAsync = parser.mode === "async"; const syncInnerParser = parser as Parser<"sync", T, TState>; const asyncInnerParser = parser as Parser<"async", T, TState>; const getChildState = ( state: CommandState, active: Exclude, undefined>, ): TState => getCommandParseChildState( state, active[0] === "matched" ? parser.initialState : active[1], parser, ); const selectChild = (state: CommandState) => { const active = normalizeCommandState(state); return active == null ? undefined : { parser, state: getChildState(state, active), continuesCommand: true, }; }; const commandScope = selectableOptionScope(() => new Set()); const enteredScope = combinedOptionScope([parser], [name]); const commandUsageId = {}; const childUsageScope = new WeakMap(); // Use type assertion to allow both sync and async returns from parse method const result = { [Symbol.for("@optique/core/commandParser")]: true, mode: parser.mode, $valueType: [], $stateType: [], priority: 15, // Higher than options to match commands first usage: [ identifyCommandUsage( { type: "command" as const, name, ...(aliases.length > 0 && { aliases }), ...(hiddenAliases.length > 0 && { hiddenAliases }), ...(options.usageLine != null && { usageLine: options.usageLine }), ...(options.hidden != null && { hidden: options.hidden }), }, commandUsageId, ), ...scopeCommandUsage(parser.usage, childUsageScope), ], leadingNames: new Set(commandNames), acceptingAnyToken: false, initialState: undefined, canSkip(state: CommandState, exec?: ExecutionContext) { const normalizedState = normalizeCommandState(state); if (normalizedState === undefined) return false; if (normalizedState[0] === "matched") { return ( parser.canSkip?.( getCommandChildState(state, parser.initialState, parser), withChildExecPath(exec, name), ) === true ); } return ( parser.canSkip?.( getCommandChildState(state, normalizedState[1], parser), withChildExecPath(exec, name), ) === true ); }, getSuggestRuntimeNodes( state: CommandState, path: readonly PropertyKey[], ) { const normalizedState = normalizeCommandState(state); if (normalizedState === undefined) { return []; } const childState = normalizedState[0] === "matched" ? getCommandChildState(state, parser.initialState, parser) : getCommandChildState(state, normalizedState[1], parser); const childPath = [...path, name]; return ( parser.getSuggestRuntimeNodes?.(childState, childPath) ?? (parser.dependencyMetadata?.source != null ? [{ path: childPath, parser, state: childState }] : []) ); }, parse(context: ParserContext>) { const state = normalizeCommandState(context.state); // Handle different states if (state === undefined) { // Check if buffer starts with our command name if ( context.buffer.length < 1 || !commandNames.includes(context.buffer[0]) ) { const actual = context.buffer.length > 0 ? context.buffer[0] : null; const notMatched = options.errors?.notMatched; if (notMatched != null && typeof notMatched !== "function") { return { success: false, consumed: 0, error: notMatched }; } const usage = context.usage; return createDeferredFailure(0, () => { // Only names reachable here may be suggested; include aliases. const leadingCmds = extractLeadingCommandNames(usage); const rawSuggestions = actual ? findSimilar(actual, leadingCmds, DEFAULT_FIND_SIMILAR_OPTIONS) : []; const suggestions = expandCommandAliasSuggestions( usage, rawSuggestions, ); if (notMatched != null) { return notMatched(name, actual, suggestions); } if (actual == null) { return message`Expected command ${eOptionName( name, )}, but got end of input.`; } const baseError = message`Expected command ${eOptionName( name, )}, but got ${actual}.`; const suggestionMsg = createSuggestionMessage(suggestions); return suggestionMsg.length > 0 ? [...baseError, text("\n\n"), ...suggestionMsg] : baseError; }); } commandScope.select(context, enteredScope); // Command matched, consume it and move to "matched" state return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: createCommandState(context.state, ["matched", name] as [ "matched", string, ]), ...(context.exec != null ? { exec: matchCommandDocPolicy( appendCommandPath(context.exec, name), commandId, showUsage, ), } : {}), }, consumed: context.buffer.slice(0, 1), }; } else if (state[0] === "matched" || state[0] === "parsing") { // "matched": command was matched, start the inner parser // "parsing": delegate to inner parser with existing state const innerState = getChildState(context.state, state); const wrapState = (parseResult: ParserResult) => { if (parseResult.success) { const mergedExec = mergeChildExec( context.exec, parseResult.next.exec, ); return { success: true as const, next: { ...parseResult.next, state: createCommandState(context.state, [ "parsing", parseResult.next.state, ] as ["parsing", TState]), ...(mergedExec != null ? { exec: mergedExec, dependencyRegistry: mergedExec.dependencyRegistry, } : {}), }, consumed: parseResult.consumed, }; } return parseResult; }; return dispatchByMode( parser.mode, () => wrapState( syncInnerParser.parse( withChildContext( { ...context, exec: enterCommandDocPolicy(context.exec, commandId), }, name, innerState, parser.usage, ), ), ), async () => wrapState( await parser.parse( withChildContext( { ...context, exec: enterCommandDocPolicy(context.exec, commandId), }, name, innerState, parser.usage, ), ), ), ); } // Should never reach here return { success: false, consumed: 0, error: options.errors?.invalidState ?? message`Invalid command state.`, }; }, complete(state: CommandState, exec?: ExecutionContext) { const normalizedState = normalizeCommandState(state); if (typeof normalizedState === "undefined") { return { success: false, error: options.errors?.notFound ?? message`Command ${eOptionName(name)} was not matched.`, }; } else if (normalizedState[0] === "matched") { // Command matched but inner parser never started. // First give the inner parser a chance to run with empty buffer, // then complete with the resulting state. const childExec = withChildExecPath(exec, name); const childContext = { buffer: [], optionsTerminated: false, usage: parser.usage, state: getCommandParseChildState(state, parser.initialState, parser), ...(childExec != null ? { exec: childExec, trace: childExec.trace, dependencyRegistry: childExec.dependencyRegistry, } : {}), }; return dispatchByMode( parser.mode, () => { const parseResult = syncInnerParser.parse(childContext); const nextExec = parseResult.success ? mergeChildExec(childExec, parseResult.next.exec) : childExec; return syncInnerParser.complete( parseResult.success ? getCommandChildState(state, parseResult.next.state, parser) : getCommandChildState( state, syncInnerParser.initialState, parser, ), nextExec, ); }, async () => { const parseResult = await asyncInnerParser.parse(childContext); const nextExec = parseResult.success ? mergeChildExec(childExec, parseResult.next.exec) : childExec; return asyncInnerParser.complete( parseResult.success ? getCommandChildState(state, parseResult.next.state, parser) : getCommandChildState(state, parser.initialState, parser), nextExec, ); }, ); } else if (normalizedState[0] === "parsing") { // Delegate to inner parser const childExec = withChildExecPath(exec, name); return dispatchByMode( parser.mode, () => syncInnerParser.complete( getCommandChildState(state, normalizedState[1], parser), childExec, ), async () => await asyncInnerParser.complete( getCommandChildState(state, normalizedState[1], parser), childExec, ), ); } // Should never reach here return { success: false, error: options.errors?.invalidState ?? message`Invalid command state during completion.`, }; }, [extractPhase2SeedKey]( state: CommandState, exec?: ExecutionContext, ) { const normalizedState = normalizeCommandState(state); if (typeof normalizedState === "undefined") { return wrapForMode(parser.mode, null); } if (normalizedState[0] === "matched") { const childExec = withChildExecPath(exec, name); const childContext = { buffer: [], optionsTerminated: false, usage: parser.usage, state: getCommandParseChildState(state, parser.initialState, parser), ...(childExec != null ? { exec: childExec, trace: childExec.trace, dependencyRegistry: childExec.dependencyRegistry, } : {}), }; return dispatchByMode( parser.mode, () => { const parseResult = syncInnerParser.parse(childContext); const nextExec = parseResult.success ? mergeChildExec(childExec, parseResult.next.exec) : childExec; return completeOrExtractPhase2Seed( syncInnerParser, parseResult.success ? getCommandChildState(state, parseResult.next.state, parser) : getCommandChildState( state, syncInnerParser.initialState, parser, ), nextExec, ); }, async () => { const parseResult = await asyncInnerParser.parse(childContext); const nextExec = parseResult.success ? mergeChildExec(childExec, parseResult.next.exec) : childExec; return await completeOrExtractPhase2Seed( asyncInnerParser, parseResult.success ? getCommandChildState(state, parseResult.next.state, parser) : getCommandChildState(state, parser.initialState, parser), nextExec, ); }, ); } if (normalizedState[0] === "parsing") { return completeOrExtractPhase2Seed( parser, getCommandChildState(state, normalizedState[1], parser), withChildExecPath(exec, name), ); } return wrapForMode(parser.mode, null); }, suggest(context: ParserContext>, prefix: string) { if (isAsync) { return suggestCommandAsync( context, prefix, name, aliases, parser, options, ); } return suggestCommandSync( context, prefix, name, aliases, parser as Parser<"sync", T, TState>, options, ); }, getDocFragments(state: DocState>, defaultValue?: T) { const commandState = state.kind === "available" ? normalizeCommandState(state.state) : undefined; if (state.kind === "unavailable" || typeof commandState === "undefined") { // When the command is not matched (showing in a list), apply hidden option if (isDocHidden(options.hidden)) { return withCommandDocMetadata( { fragments: [], description: options.description, }, {}, ); } // When showing command in a list, use brief if available, // otherwise fall back to description return withCommandDocMetadata( { description: options.description, fragments: [ { type: "entry", term: { type: "command", name, ...(aliases.length > 0 && { aliases }), }, description: options.brief ?? options.description, ...(showAliases != null && { showAliases }), }, ], }, {}, ); } // When the command is matched and executing, show inner parser documentation // regardless of hidden status const innerState: DocState = commandState[0] === "parsing" ? { kind: "available", state: getCommandChildState(state.state, commandState[1], parser), } : { kind: "available", state: getCommandChildState( state.state, parser.initialState, parser, ), }; const innerFragments = parser.getDocFragments(innerState, defaultValue); // When the command is matched and we are rendering its *own* help page, // `brief` appears at the very top (before Usage) and `description` // appears below the Usage line. Inner parsers' values take precedence // via the spread; this command's own values fill in any gaps. // Built-in entry docs carry an empty payload. Unmarked custom parsers // can supply page fields through the public DocFragments contract. const innerMetadata = getCommandDocMetadata(innerFragments) ?? innerFragments; return withCommandDocMetadata( { ...innerFragments, brief: innerFragments.brief ?? options.brief, description: innerFragments.description ?? options.description, footer: innerFragments.footer ?? options.footer, }, withSelectedCommandUsage( { origin: "command", // Composite parents must not promote descriptions from ordinary entries // or unselected subcommands into this command's page metadata. brief: innerMetadata?.brief ?? options.brief, description: innerMetadata?.description ?? options.description, footer: innerMetadata?.footer ?? options.footer, }, [ commandUsageId, ...getSelectedCommandUsage( scopeCommandDocMetadata( getCommandDocMetadata(innerFragments), childUsageScope, ), ), ], ), ); }, [Symbol.for("Deno.customInspect")]() { return `command(${JSON.stringify(name)})`; }, }; defineBareCommandDocPolicy(result, showUsage); // Forward value normalization as non-enumerable so that withDefault() // can normalize defaults through command() wrappers. if (typeof parser.normalizeValue === "function") { Object.defineProperty(result, "normalizeValue", { value: parser.normalizeValue.bind(parser), configurable: true, enumerable: false, }); } // Forward fallback validation as non-enumerable (see issue #414). // command() is a transparent wrapper over its inner parser, so when // a command's result has a validateValue hook it is delegated as-is. if (typeof parser.validateValue === "function") { Object.defineProperty(result, "validateValue", { value: parser.validateValue.bind(parser), configurable: true, enumerable: false, }); } // Expose the inner parser to parent-level effectful scheduling once the // command's inner parsing has started, so a source nested in a selected // command completes before parent-level dependency replay. The node // path appends the command name, matching the execution path used when // the inner parser completes. Object.defineProperty(result, effectfulSchedulingNodesKey, { value: ((state, parentPath) => { const normalizedState = normalizeCommandState( state as CommandState, ); if (normalizedState == null) return []; // "matched" means the command name was consumed but the inner // parser has not started; scheduling then works from the inner // parser's initial state, mirroring the "matched" completion // branch below. const innerState = normalizedState[0] === "parsing" ? normalizedState[1] : parser.initialState; return [ { path: [...(parentPath ?? []), name], parser, state: getCommandChildState( state as CommandState, innerState, parser, ), }, ]; }) satisfies EffectfulSchedulingNodesFn, configurable: true, enumerable: false, }); // Command-line source values in a selected command register into the // parent's runtime through the same expansion the scheduling pass // uses, so a value behaves identically whether typed or prompted. Object.defineProperty(result, sourceCollectionExpansionKey, { value: true, configurable: true, enumerable: false, }); // Static source estimation reaches the inner parser even while the // command is unmatched. The edge is exclusive: an unmatched command // never provides its inner sources, so they must not count as // guaranteed providers (see exclusiveSourceScopeKey). Object.defineProperty(result, exclusiveSourceScopeKey, { value: [parser], configurable: true, enumerable: false, }); // Type assertion via 'unknown' needed because TypeScript's conditional type // ModeValue cannot be verified when M is a generic type parameter. defineReachableChildren, TState>( result, [parser], (state) => { const child = selectChild(state); return child == null ? [] : [child]; }, ); const scoped = scopeParser( result as unknown as Parser>, commandScope.source, (context) => { if (normalizeCommandState(context.state) != null) { commandScope.select(context, enteredScope); } }, ); defineEmptyInputFacts(scoped, failingStepFacts(false)); return captureDocParser(fluent(scoped), { kind: "command", name, aliases, hiddenAliases, showAliases, showUsage, hidden: options.hidden, brief: options.brief, description: options.description, footer: options.footer, usageLine: options.usageLine, children: [parser], }); } /** * Format options for how {@link passThrough} captures options. * @since 0.8.0 */ export type PassThroughFormat = "equalsOnly" | "nextToken" | "greedy"; /** * Options for the {@link passThrough} parser. * @since 0.8.0 */ export interface PassThroughOptions { /** * How to capture option values: * * - `"equalsOnly"`: Only capture `--opt=val` format (default, safest). * Values with spaces (`--opt val`) are not captured. * * - `"nextToken"`: Capture `--opt` and its value as separate tokens * (`--opt val`). The next token is captured if it doesn't start with `-`. * * - `"greedy"`: Capture *all* remaining tokens from first unrecognized token. * This is useful for wrapper/proxy tools that pass everything through. * * @default `"equalsOnly"` */ readonly format?: PassThroughFormat; /** * A description of what pass-through options are used for. */ readonly description?: Message; /** * Controls pass-through visibility: * * - `true`: hide from usage, docs, and suggestions * - `"usage"`: hide from usage only * - `"doc"`: hide from docs only * - `"help"`: hide from usage and docs, keep suggestions * * @since 0.9.0 */ readonly hidden?: HiddenVisibility; } /** * Creates a parser that collects unrecognized options and passes them through. * This is useful for building wrapper CLI tools that need to forward unknown * options to an underlying tool. * * **Important**: This parser intentionally weakens Optique's strict parsing * philosophy where "all input must be recognized." The benefit is enabling * legitimate wrapper/proxy tool patterns, but the trade-off is that typos * in pass-through options won't be caught. * * @param options Configuration for how to capture options. * @returns A {@link Parser} that captures unrecognized options as an array * of strings. * * @example * ```typescript * // Default format: only captures --opt=val * const parser = object({ * debug: option("--debug"), * extra: passThrough(), * }); * * // mycli --debug --foo=bar --baz=qux * // → { debug: true, extra: ["--foo=bar", "--baz=qux"] } * * // nextToken format: captures --opt val pairs * const parser = object({ * debug: option("--debug"), * extra: passThrough({ format: "nextToken" }), * }); * * // mycli --debug --foo bar * // → { debug: true, extra: ["--foo", "bar"] } * * // greedy format: require a program name before capturing the rest * const parser = command("exec", map( * seq( * argument(string({ metavar: "PROGRAM" })), * passThrough({ format: "greedy" }), * ), * ([program, args]) => ({ program, args }), * )); * * // myproxy exec my-program --help * // → { program: "my-program", args: ["--help"] } * ``` * * With built-in help enabled, `myproxy exec --help` displays help because `seq()` * does not reach pass-through until the program name is parsed. After the * program name, greedy capture can consume remaining tokens, including * `--help`, so they can be forwarded. Putting this parser last in an `object()` * does not establish the same boundary: fields are tried by priority, not * declaration order. * An immediate `--` after the program name is consumed by `seq()` as an * options terminator before greedy capture starts. Once capture starts, * subsequent `--` tokens are kept. * * @since 0.8.0 */ export function passThrough( options: PassThroughOptions = {}, ): FluentParser<"sync", readonly string[], readonly string[]> { const format = options.format ?? "equalsOnly"; const optionPattern = /^-[a-z0-9-]|^--[a-z0-9-]+/i; const equalsOptionPattern = /^--[a-z0-9-]+=/i; const result: Parser<"sync", readonly string[], readonly string[]> = { $valueType: [], $stateType: [], mode: "sync", priority: -10, // Lowest priority to be tried last usage: [ { type: "passthrough", ...(options.hidden != null && { hidden: options.hidden }), }, ], leadingNames: EMPTY_LEADING_NAMES, acceptingAnyToken: false, initialState: [], canSkip() { return true; }, parse(context) { if (context.buffer.length < 1) { return { success: false, consumed: 0, error: message`No input to pass through.`, }; } const failure = getPassThroughFailure(context, this?.priority ?? -10); if (failure != null) return failure.failure; const token = context.buffer[0]; if (format === "greedy") { // Greedy mode: capture ALL remaining tokens const captured = [...context.buffer]; return { success: true, next: { ...context, buffer: [], state: annotateFreshArray(context.state, [ ...context.state, ...captured, ]), }, consumed: captured, }; } // For equalsOnly and nextToken, don't capture after options terminator if (context.optionsTerminated) { return { success: false, consumed: 0, error: message`Options terminated; cannot capture pass-through options.`, }; } if (format === "equalsOnly") { // Only capture --opt=val format if (!equalsOptionPattern.test(token)) { return { success: false, consumed: 0, error: message`Expected --option=value format, but got: ${token}.`, }; } return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: annotateFreshArray(context.state, [...context.state, token]), }, consumed: [token], }; } if (format === "nextToken") { // Must start with an option-like token if (!optionPattern.test(token)) { return { success: false, consumed: 0, error: message`Expected option, but got: ${token}.`, }; } // Check for --opt=val format (already includes value) if (token.includes("=")) { return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: annotateFreshArray(context.state, [ ...context.state, token, ]), }, consumed: [token], }; } // Check if next token is a value (doesn't start with -) const nextToken = context.buffer[1]; if (nextToken !== undefined && !optionPattern.test(nextToken)) { // Capture both the option and its value return { success: true, next: { ...context, buffer: context.buffer.slice(2), state: annotateFreshArray(context.state, [ ...context.state, token, nextToken, ]), }, consumed: [token, nextToken], }; } // No value follows, just capture the option return { success: true, next: { ...context, buffer: context.buffer.slice(1), state: annotateFreshArray(context.state, [...context.state, token]), }, consumed: [token], }; } // Should never reach here return { success: false, consumed: 0, error: message`Unknown passThrough format: ${format}.`, }; }, complete(state, _exec?: ExecutionContext) { if (getAnnotations(state) == null) { return { success: true, value: state }; } const copied: readonly string[] = [...state]; return { success: true, value: copied }; }, suggest(_context, _prefix) { // passThrough cannot suggest specific values since it captures unknown options return []; }, getDocFragments(_state, _defaultValue?) { if (isDocHidden(options.hidden)) { return withCommandDocMetadata( { fragments: [], description: options.description, }, {}, ); } return withCommandDocMetadata( { fragments: [ { type: "entry", term: { type: "passthrough" }, description: options.description, }, ], description: options.description, }, {}, ); }, [Symbol.for("Deno.customInspect")]() { return `passThrough(${format})`; }, }; definePassThroughPriority(result, [result], (_state, token) => { if (token == null || format === "greedy") return result.priority; const accepts = format === "equalsOnly" ? equalsOptionPattern.test(token) : format === "nextToken" && optionPattern.test(token); return accepts ? result.priority : undefined; }); defineEmptyInputFacts(result, failingStepFacts(true)); return fluent(result); }