import { ParseOptions } from "./annotations.cjs"; import { Message } from "../message.cjs"; import { Usage } from "../usage.cjs"; import { DocFragments, DocPage } from "../doc.cjs"; import { DependencyRegistryLike } from "../registry-types.cjs"; import { DeferredMap, ValueParserResult } from "../valueparser.cjs"; import { ParserDependencyMetadata } from "../dependency-metadata.cjs"; import { DependencyRuntimeContext, RuntimeNode } from "../dependency-runtime.cjs"; import { InputTrace } from "../input-trace.cjs"; //#region src/internal/parser.d.ts /** * Represents the execution mode for parsers. * * - `"sync"`: Synchronous execution where methods return values directly. * - `"async"`: Asynchronous execution where methods return Promises or * AsyncIterables. * * @since 0.9.0 */ type Mode = "sync" | "async"; /** * Wraps a value type based on the execution mode. * * - In sync mode: Returns `T` directly. * - In async mode: Returns `Promise`. * * @template M The execution mode. * @template T The value type to wrap. * @since 0.9.0 */ type ModeValue = M extends "async" ? Promise : T; /** * Wraps an iterable type based on the execution mode. * * - In sync mode: Returns `Iterable`. * - In async mode: Returns `AsyncIterable`. * * @template M The execution mode. * @template T The element type. * @since 0.9.0 */ type ModeIterable = M extends "async" ? AsyncIterable : Iterable; /** * Combines multiple modes into a single mode. * If any mode is `"async"`, the result is `"async"`; otherwise `"sync"`. * * @template T A tuple of Mode types. * @since 0.9.0 */ type CombineModes = "async" extends T[number] ? "async" : "sync"; /** * Represents the state passed to getDocFragments. * Can be either the actual parser state or an explicit indicator * that no state is available. * @template TState The type of the actual state when available. * @since 0.3.0 */ type DocState = { readonly kind: "available"; readonly state: TState; } | { readonly kind: "unavailable"; }; /** * Parser interface for command-line argument parsing. * @template M The execution mode of the parser (`"sync"` or `"async"`). * @template TValue The type of the value returned by the parser. * @template TState The type of the state used during parsing. * @since 0.9.0 Added the `M` type parameter for sync/async mode support. */ interface Parser { /** * A type tag for the result value of this parser, used for type inference. * Usually this is an empty array at runtime, but it does not matter * what it contains. * @internal */ readonly $valueType: readonly TValue[]; /** * A type tag for the state of this parser, used for type inference. * Usually this is an empty array at runtime, but it does not matter * what it contains. * @internal */ readonly $stateType: readonly TState[]; /** * The execution mode of this parser. * * - `"sync"`: All methods return values directly. * - `"async"`: Methods return Promises or AsyncIterables. * * @since 0.9.0 */ readonly mode: M; /** * The priority of this parser, which determines the order in which * parsers are applied when multiple parsers are available. The greater * the number, the higher the priority. */ readonly priority: number; /** * The usage information for this parser, which describes how * to use it in command-line interfaces. */ readonly usage: Usage; /** * Names that this parser could match at the first buffer position. * Used by `runParser()` to detect collisions with built-in meta * features (help, version, completion). * * Each built-in combinator computes this from its structural semantics. * Custom parser implementations must include every fixed token that * the parser accepts at `argv[0]`—command names, option names, and * literal values alike. For example, a parser whose usage declares * `{ type: "literal", value: "serve" }` should include `"serve"` in * this set. Parsers that accept *any* token (like `argument()`) should * return an empty set and set {@link acceptingAnyToken} to `true` * instead. * * @since 1.0.0 */ readonly leadingNames: ReadonlySet; /** * Whether this parser unconditionally consumes any positional token at * the first buffer position. A parser with this flag accepts any * non-option token but may still reject option-like tokens (those * starting with `"-"`). * * In shared-buffer compositions (`tuple()`, `object()`, `merge()`, * `concat()`), a catch-all parser blocks positional names (command * names) from lower-priority siblings but does not block option-like * names. In `conditional()`, option-like names from the default * branch remain reachable even when the discriminator is a catch-all. * * Only `argument()` is inherently accepting-any-token; combinators * like `or()` and `map()` propagate this from their children. * Wrappers that can succeed without consuming (`optional()`, * `withDefault()`, `multiple()` with `min = 0`) always set this * to `false`. * * @since 1.0.0 */ readonly acceptingAnyToken: boolean; /** * Returns whether this parser can be skipped at the current state without * consuming more CLI input or evaluating completion-time defaults. * * Sequential combinators use this as a lightweight boundary predicate. It * must be synchronous and side-effect free. Custom parsers that omit this * method are treated as not skippable. * * @param state The current parser state. * @param exec Optional shared execution context. * @returns `true` when parsing may advance past this parser. * @since 1.1.0 */ canSkip?(state: TState, exec?: ExecutionContext): boolean; /** * The initial state for this parser. This is used to initialize the * state when parsing starts. */ readonly initialState: TState; /** * Internal marker for wrappers whose `{ hasCliValue: false }` states should * be treated as unmatched dependency-source states during completion-time * Phase 1. * * @internal */ readonly [unmatchedNonCliDependencySourceStateMarker]?: true; /** * Parses the input context and returns a result indicating * whether the parsing was successful or not. * @param context The context of the parser, which includes the input buffer * and the current state. * @returns A result object indicating success or failure. * In async mode, returns a Promise that resolves to the result. */ parse(context: ParserContext): ModeValue>; /** * Transforms a {@link TState} into a {@link TValue}, if applicable. * If the transformation is not applicable, it should return * a `ValueParserResult` with `success: false` and an appropriate error * message. * @param state The current state of the parser, which may contain accumulated * data or context needed to produce the final value. * @param exec Optional shared execution context. When provided, gives the * parser access to cross-cutting runtime data such as the current * execution phase and dependency registry. * @returns A result object indicating success or failure of * the transformation. If successful, it should contain * the parsed value of type {@link TValue}. If not applicable, * it should return an error message. * In async mode, returns a Promise that resolves to the result. * @since 1.0.0 Added optional `exec` parameter. */ complete(state: TState, exec?: ExecutionContext): ModeValue>; /** * Generates next-step suggestions based on the current context * and an optional prefix. This can be used to provide shell completion * suggestions or to guide users in constructing valid commands. * @param context The context of the parser, which includes the input buffer * and the current state. * @param prefix A prefix string that can be used to filter suggestions. * Can be an empty string if no prefix is provided. * @returns An iterable of {@link Suggestion} objects, each containing * a suggestion text and an optional description. * In async mode, returns an AsyncIterable. * @since 0.6.0 */ suggest(context: ParserContext, prefix: string): ModeIterable; /** * Generates a documentation fragment for this parser, which can be used * to describe the parser's usage, description, and default value. * @param state The current state of the parser, wrapped in a DocState * to indicate whether the actual state is available or not. * @param defaultValue An optional default value that can be used * to provide a default value in the documentation. * @returns {@link DocFragments} object containing documentation * fragments for this parser. */ getDocFragments(state: DocState, defaultValue?: TValue): DocFragments; /** * A type-appropriate default value used as a stand-in during deferred * prompt resolution. When present, combinators like `prompt()` use this * value instead of an internal sentinel during two-phase parsing, so that * `map()` transforms and two-pass contexts always receive a valid value * of type {@link TValue}. * * This property is set automatically by `option()` and `argument()` from * the underlying {@link ValueParser}'s `placeholder`, and propagated by * combinators like `map()`, `optional()`, and `withDefault()`. * * @since 1.0.0 */ readonly placeholder?: TValue; /** * Optional predicate that determines whether completion should be * deferred for the given parser state. * * When present, combinator wrappers ({@link optional}, {@link withDefault}, * {@link group}) forward this field to the outer parser. This enables * packages like *\@optique/inquirer* to detect when interactive prompting * should be deferred until an outer context (like a configuration file * source) has resolved. * * @param state The current parser state. * @param exec Optional shared execution context. * @returns `true` if completion should be deferred. * @since 1.0.0 * @since 1.0.0 Added optional `exec` parameter. */ shouldDeferCompletion?(state: TState, exec?: ExecutionContext): boolean; /** * Normalizes a parsed value according to the underlying value parser's * configuration. When present, {@link withDefault} calls this method * on default values so that runtime defaults match the representation * that the value parser's `parse()` would produce. * * Primitive parsers ({@link option}, {@link argument}) implement this * by delegating to {@link ValueParser.normalize}. Combinator wrappers * ({@link optional}, {@link withDefault}) forward it from inner parsers. * * Exclusive combinators ({@link or}, `longestMatch()`) and * multi-source combinators (`merge()`) intentionally do *not* * implement this method because the active branch or key ownership * is unknown at default time. * * @param value The value to normalize. * @returns The normalized value. * @since 1.0.0 */ normalizeValue?(value: TValue): TValue; /** * Optionally re-validates a value as if it had been parsed from CLI * input, surfacing any constraint violations from the underlying value * parser (e.g., regex patterns, numeric bounds, `choice()` values). * * Wrappers like `bindEnv()` and `bindConfig()` call this on fallback * values—environment variables parsed by a looser env parser, * configured defaults, and values loaded from config files—so that * those values obey the same validation semantics as CLI input. * Without it, parser constraints can be silently bypassed through * fallback paths. * * Built-in primitive parsers ({@link option}, {@link argument}) * implement this method by round-tripping the value through the inner * {@link ValueParser.format} and {@link ValueParser.parse} calls: the * value is serialized back to a string and re-parsed, which re-runs * every constraint check. Combinator wrappers ({@link optional}, * {@link withDefault}) forward this method from their inner parser. * {@link map} intentionally does *not* forward it because the mapping * function is one-way: the mapped output type no longer corresponds * to the inner parser's constraints. Exclusive combinators * ({@link or}, `longestMatch()`) and multi-source combinators * (`merge()`, `concat()`) intentionally do not implement this method * because the active branch or key ownership is unknown at validation * time. * * Implementations must wrap any *exception* thrown by `format()` in * `try`/`catch` and return the original value as a successful * {@link ValueParserResult}. This specifically protects * dependency-derived parsers whose factory cannot run without the * current dependency value, and custom value parsers whose `format()` * intentionally throws for unsupported inputs. Values that * `format()` successfully serializes to a string are always re-parsed, * and any resulting parse failure is propagated—they represent the * bug class this method exists to surface. * * @param value The candidate value to validate. * @returns A {@link ValueParserResult} indicating success (with the * possibly-canonicalized value) or failure (with an error * message). In async mode, returns a `Promise` resolving to * the result. * @since 1.0.0 */ validateValue?(value: TValue): ModeValue>; /** * Internal dependency metadata describing this parser's dependency * capabilities. Used by the dependency runtime to resolve dependencies * without relying on state-shape protocols. * @internal */ readonly dependencyMetadata?: ParserDependencyMetadata; /** * Internal hook for top-level suggest-time dependency seeding. * * Wrapper parsers can expose the active parser/state pairs that should be * scanned when `suggestSync()` or `suggestAsync()` builds a fresh dependency * runtime. When omitted, only this parser's own dependency source metadata * is considered. * * @param state The current parser state. * @param path The path to this parser within the parse tree. * @returns Runtime nodes to seed into the suggestion-time dependency runtime. * @internal */ getSuggestRuntimeNodes?(state: TState, path: readonly PropertyKey[]): readonly RuntimeNode[]; } /** * Parser-local frame data containing the input buffer and parser state. * This represents the per-parser progress during parsing, separated from * cross-cutting execution context. * @template TState The type of the state used during parsing. * @since 1.0.0 */ interface ParseFrame { /** * The array of input strings that the parser is currently processing. */ readonly buffer: readonly string[]; /** * The current state of the parser, which is used to track * the progress of parsing and any accumulated data. */ readonly state: TState; /** * A flag indicating whether no more options should be parsed and instead * the remaining input should be treated as positional arguments. */ readonly optionsTerminated: boolean; } /** * The phase of the execution pipeline. * @since 1.0.0 */ type ExecutionPhase = "parse" | "precomplete" | "resolve" | "complete" | "suggest"; /** * Shared execution context carrying cross-cutting runtime data. * This includes information that is shared across all parsers in a parse * tree, such as usage information, dependency registries, and the current * execution phase. * @since 1.0.0 */ interface ExecutionContext { /** * Usage information for the entire parser tree. */ readonly usage: Usage; /** * The current phase of the execution pipeline. */ readonly phase: ExecutionPhase; /** * The path from the root to the current parser in the parse tree. * Used by constructs to track the current position during dependency * resolution and completion. */ readonly path: readonly PropertyKey[]; /** * Matched command names in parse order. * * This is tracked separately from {@link path} because parse-tree paths also * include object fields and other wrapper segments. Runners use it to * recover subcommand help context from partial parses. * * @internal */ readonly commandPath?: readonly string[]; /** * Immutable trace of raw primitive inputs recorded during parsing. * * Primitives append trace entries keyed by {@link path}, allowing later * completion phases to replay derived parsers with the resolved * dependency values. * * @internal */ readonly trace?: InputTrace; /** * A registry containing resolved dependency values from DependencySource * parsers. * @since 0.10.0 */ readonly dependencyRegistry?: DependencyRegistryLike; /** * The dependency runtime context for dependency resolution. * Coexists with `dependencyRegistry` during the transition period. * @internal */ readonly dependencyRuntime?: DependencyRuntimeContext; /** * Immutable map of pre-completed results from the parent construct's * Phase 1, keyed by field name. Each construct passes its own * `preCompleteAndRegisterDependencies` results directly to children * in Phase 3. Children read it in their own Phase 1 to avoid * re-evaluating non-idempotent default thunks, but never write to * it—this prevents sibling completions from leaking into each * other. * * Field-name keying naturally handles parser reuse across different * fields (e.g., `merge(object({a: shared}), object({b: shared}))`) * because each field maps to its own result regardless of whether * the underlying parser instance is the same. * * @see https://github.com/dahlia/optique/issues/762 * @internal */ readonly preCompletedByParser?: ReadonlyMap; /** * Field names that should be ignored when a construct seeds dependency * sources from child state during completion. * * Used by outer `merge()` completions to suppress ambiguous duplicate * keys while still allowing the child parser to finish its own value * completion. * * @internal */ readonly excludedSourceFields?: ReadonlySet; } /** * Internal marker for wrappers whose `{ hasCliValue: false }` states should * be treated as unmatched dependency-source states during completion-time * Phase 1. * * Wrappers like `bindEnv()` and `bindConfig()` opt in because their missing * CLI states still carry enough fallback context to pre-complete exactly * once. Wrappers like `prompt()` intentionally do not opt in because * prompted values are not yet registered as dependency sources. * * @internal */ declare const unmatchedNonCliDependencySourceStateMarker: unique symbol; /** * Internal marker for parsers that want parent-state annotations injected * directly into rebuilt child states instead of relying on structural * inheritance. * * Wrappers like `bindConfig()`, `bindEnv()`, and `prompt()` opt in because * their fallback contracts depend on carrying annotations through wrapper * state objects during parse, complete, and suggest. * * @internal */ declare const inheritParentAnnotationsKey: unique symbol; /** * Internal marker for wrapper parsers that should only treat annotation-only * primitive wrapper states as completable when a nested source-binding wrapper * produced them. * * @internal */ declare const annotationWrapperRequiresSourceBindingKey: unique symbol; /** * The context of the parser, which includes the input buffer and the state. * * `ParserContext` provides structured access to shared execution context * via {@link exec}, and flat access to all fields for backward * compatibility. * * @template TState The type of the state used during parsing. */ interface ParserContext { /** * Shared execution context (usage, phase, path, dependencyRegistry). * * Present when the context was created via {@link createParserContext}. * Later runtime work will make this field required. * * @since 1.0.0 */ readonly exec?: ExecutionContext; /** * Immutable trace of raw primitive inputs recorded during parsing. * * Preserved as a flat compatibility field so wrapper parsers can forward * trace data even when they rebuild the parser context without {@link exec}. * * @since 1.0.0 */ readonly trace?: InputTrace; /** * The array of input strings that the parser is currently processing. */ readonly buffer: readonly string[]; /** * The current state of the parser, which is used to track * the progress of parsing and any accumulated data. */ readonly state: TState; /** * A flag indicating whether no more options should be parsed and instead * the remaining input should be treated as positional arguments. * This is typically set when the parser encounters a `--` in the input, * which is a common convention in command-line interfaces to indicate * that no further options should be processed. */ readonly optionsTerminated: boolean; /** * Usage information for the entire parser tree. * Used to provide better error messages with suggestions for typos. * When a parser encounters an invalid option or command, it can use * this information to suggest similar valid options. * @since 0.7.0 */ readonly usage: Usage; /** * A registry containing resolved dependency values from DependencySource parsers. * This is used during shell completion to provide suggestions based on * the actual dependency values that have been parsed, rather than defaults. * @since 0.10.0 */ readonly dependencyRegistry?: DependencyRegistryLike; } /** * Creates a {@link ParserContext} from a {@link ParseFrame} and an * {@link ExecutionContext}. The returned object provides both structured * access (`frame`, `exec`) and flat access (`buffer`, `state`, etc.) * for backward compatibility. * * @template TState The type of the state used during parsing. * @param frame Parser-local frame data. * @param exec Shared execution context. * @returns A {@link ParserContext} instance. * @since 1.0.0 */ declare function createParserContext(frame: ParseFrame, exec: ExecutionContext): ParserContext; /** * Represents a suggestion for command-line completion or guidance. * @since 0.6.0 */ type Suggestion = { /** * A literal text suggestion. */ readonly kind: "literal"; /** * The suggestion text that can be used for completion or guidance. */ readonly text: string; /** * An optional description providing additional context * or information about the suggestion. */ readonly description?: Message; } | { /** * A file system completion suggestion that uses native shell completion. */ readonly kind: "file"; /** * The current prefix/pattern for fallback when native completion is unavailable. */ readonly pattern?: string; /** * The type of file system entries to complete. */ readonly type: "file" | "directory" | "any"; /** * File extensions to filter by (e.g., [".ts", ".js"]). */ readonly extensions?: readonly string[]; /** * Whether to include hidden files (those starting with a dot). */ readonly includeHidden?: boolean; /** * An optional description providing additional context * or information about the suggestion. */ readonly description?: Message; }; /** * A discriminated union type representing the result of a parser operation. * It can either indicate a successful parse with the next state and context, * or a failure with an error message. * @template TState The type of the state after parsing. It should match with * the `TState` type of the {@link Parser} interface. */ type ParserResult = { /** * Indicates that the parsing operation was successful. */ readonly success: true; /** * The next context after parsing, which includes the updated input buffer. */ readonly next: ParserContext; /** * The input elements consumed by the parser during this operation. */ readonly consumed: readonly string[]; /** * When `true`, indicates that this success is tentative or * speculative: the parser matched something but the match has not * been confirmed yet. This covers two cases: * * - A zero-consuming discriminator resolved to a branch key, but * the selected sub-parser has not consumed any input yet. * - A {@link conditional} parser speculatively committed to a * named branch that consumed tokens, before the discriminator * has had a chance to confirm the choice. In this case the * marker stays set across subsequent parse calls until * `complete()` verifies the speculative selection. * * Outer combinators should not treat provisional successes as * definitive. For example, {@link or} should still allow a * definitive branch to take priority, and a definitive * zero-consuming fallback must not be displaced by a provisional * consuming hit. {@link longestMatch} may still prefer a longer * provisional match over a shorter definitive one; when match * lengths are equal, definitive results take priority over * provisional ones. * * @since 1.0.0 */ readonly provisional?: true; } | { /** * Indicates that the parsing operation failed. */ readonly success: false; /** * The number of the consumed input elements. */ readonly consumed: number; /** * The error message describing why the parsing failed. */ readonly error: Message; }; /** * Infers the result value type of a {@link Parser}. * @template T The {@link Parser} to infer the result value type from. */ type InferValue> = T["$valueType"][number]; /** * Infers the execution mode of a {@link Parser}. * @template T The {@link Parser} to infer the execution mode from. * @since 0.9.0 */ type InferMode> = T["mode"]; /** * The result type of a whole parser operation, which can either be a successful * result with a value of type `T`, or a failure with an error message. * @template T The type of the value produced by the parser. */ type Result = { /** * Indicates that the parsing operation was successful. */ readonly success: true; /** * The successfully parsed value of type {@link T}. * This is the final result of the parsing operation after all parsers * have been applied and completed. */ readonly value: T; /** * When `true`, indicates that the value contains deferred prompt * placeholders. Propagated from {@link ValueParserResult.deferred}. * @since 1.0.0 */ readonly deferred?: true; /** * Property keys (object field names or array indices) whose values are * deferred placeholders. * Propagated from {@link ValueParserResult.deferredKeys}. * @since 1.0.0 */ readonly deferredKeys?: DeferredMap; } | { /** * Indicates that the parsing operation failed. */ readonly success: false; /** * The error message describing why the parsing failed. */ readonly error: Message; }; /** * Parses an array of command-line arguments using the provided combined parser. * This function processes the input arguments, applying the parser to each * argument until all arguments are consumed or an error occurs. * * This function only accepts synchronous parsers. For asynchronous parsers, * use {@link parseAsync}. * * @template T The type of the value produced by the parser. * @param parser The combined {@link Parser} to use for parsing the input * arguments. Must be a synchronous parser. * @param args The array of command-line arguments to parse. Usually this is * `process.argv.slice(2)` in Node.js or `Deno.args` in Deno. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns A {@link Result} object indicating whether the parsing was * successful or not. If successful, it contains the parsed value of * type `T`. If not, it contains an error message describing the * failure. * @throws {TypeError} When a synchronous dependency source extractor returns a * thenable during completion-time dependency seeding. * @since 0.9.0 Renamed from the original `parse` function which now delegates * to this for sync parsers. * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function parseSync(parser: Parser<"sync", T, unknown>, args: readonly string[], options?: ParseOptions): Result; /** * Parses an array of command-line arguments using the provided combined parser. * This function processes the input arguments, applying the parser to each * argument until all arguments are consumed or an error occurs. * * This function accepts any parser (sync or async) and always returns a Promise. * For synchronous parsing with sync parsers, use {@link parseSync} instead. * * @template T The type of the value produced by the parser. * @param parser The combined {@link Parser} to use for parsing the input * arguments. * @param args The array of command-line arguments to parse. Usually this is * `process.argv.slice(2)` in Node.js or `Deno.args` in Deno. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns A Promise that resolves to a {@link Result} object indicating * whether the parsing was successful or not. * @since 0.9.0 * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function parseAsync(parser: Parser, args: readonly string[], options?: ParseOptions): Promise>; /** * Parses an array of command-line arguments using the provided combined parser. * This function processes the input arguments, applying the parser to each * argument until all arguments are consumed or an error occurs. * * The return type depends on the parser's mode: * - Sync parsers return `Result` directly. * - Async parsers return `Promise>`. * * For explicit control, use {@link parseSync} or {@link parseAsync}. * * @template M The execution mode of the parser. * @template T The type of the value produced by the parser. * @param parser The combined {@link Parser} to use for parsing the input * arguments. * @param args The array of command-line arguments to parse. Usually this is * `process.argv.slice(2)` in Node.js or `Deno.args` in Deno. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns A {@link Result} object (for sync) or Promise thereof (for async) * indicating whether the parsing was successful or not. * @throws {TypeError} When a synchronous dependency source extractor returns a * thenable during completion-time dependency seeding. * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function parse(parser: Parser, args: readonly string[], options?: ParseOptions): ModeValue>; /** * Generates command-line suggestions based on current parsing state. * This function processes the input arguments up to the last argument, * then calls the parser's suggest method with the remaining prefix. * * This function only accepts synchronous parsers. For asynchronous parsers, * use {@link suggestAsync}. * * @template T The type of the value produced by the parser. * @param parser The {@link Parser} to use for generating suggestions. * Must be a synchronous parser. * @param args The array of command-line arguments including the partial * argument to complete. The last element is treated as * the prefix for suggestions. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns An array of {@link Suggestion} objects containing completion * candidates. * @example * ```typescript * const parser = object({ * verbose: option("-v", "--verbose"), * format: option("-f", "--format", choice(["json", "yaml"])) * }); * * // Get suggestions for options starting with "--" * const suggestions = suggestSync(parser, ["--"]); * // Returns: [{ text: "--verbose" }, { text: "--format" }] * * // Get suggestions after parsing some arguments * const suggestions2 = suggestSync(parser, ["-v", "--format="]); * // Returns: [{ text: "--format=json" }, { text: "--format=yaml" }] * ``` * @throws {TypeError} When a synchronous dependency source extractor returns a * thenable during suggestion seeding. * @since 0.6.0 * @since 0.9.0 Renamed from the original `suggest` function. * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function suggestSync(parser: Parser<"sync", T, unknown>, args: readonly [string, ...readonly string[]], options?: ParseOptions): readonly Suggestion[]; /** * Returns suggest-time runtime nodes for a parser, falling back to the * parser's own source metadata when it does not expose a custom hook. * * @param parser The parser whose suggest-time runtime nodes should be resolved. * @param state The current parser state. * @param path The path to this parser within the parse tree. * @returns The runtime nodes used to seed suggest-time dependency resolution. * @internal */ declare function getParserSuggestRuntimeNodes(parser: Parser, state: TState, path: readonly PropertyKey[]): readonly RuntimeNode[]; /** * Returns wrapper-aware suggest-time runtime nodes for parsers that delegate * to an inner parser while also exposing their own source metadata. * * The inner parser's nodes are always preserved so nested wrappers and * constructs can continue to seed the dependency runtime recursively. When * the outer parser itself owns source metadata, its `(path, parser, state)` * node is appended so outer precedence rules still apply. * * @internal */ declare function getDelegatingSuggestRuntimeNodes(innerParser: Parser, outerParser: Parser, state: unknown, path: readonly PropertyKey[], innerState: TInnerState, outerPosition?: "append" | "prepend"): readonly RuntimeNode[]; /** * Composes source metadata for a wrapper parser while preserving any derived * or transform capabilities from the inner parser unchanged. * * @internal */ declare function composeWrappedSourceMetadata(dependencyMetadata: ParserDependencyMetadata | undefined, wrapSource: (source: NonNullable) => NonNullable): ParserDependencyMetadata | undefined; /** * Marks a parser as inheriting parent-state annotations through wrapper-state * reconstruction. * * @internal */ declare function defineInheritedAnnotationParser(parser: object): void; /** * Marks a wrapper parser as requiring a real source-binding state before * annotation-only primitive wrappers should trigger completion. * * @internal */ declare function defineSourceBindingOnlyAnnotationCompletionParser(parser: object): void; /** * Generates command-line suggestions based on current parsing state. * This function processes the input arguments up to the last argument, * then calls the parser's suggest method with the remaining prefix. * * This function accepts any parser (sync or async) and always returns a Promise. * For synchronous suggestion generation with sync parsers, use * {@link suggestSync} instead. * * @template T The type of the value produced by the parser. * @param parser The {@link Parser} to use for generating suggestions. * @param args The array of command-line arguments including the partial * argument to complete. The last element is treated as * the prefix for suggestions. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns A Promise that resolves to an array of {@link Suggestion} objects * containing completion candidates. * @since 0.9.0 * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function suggestAsync(parser: Parser, args: readonly [string, ...readonly string[]], options?: ParseOptions): Promise; /** * Generates command-line suggestions based on current parsing state. * This function processes the input arguments up to the last argument, * then calls the parser's suggest method with the remaining prefix. * * The return type depends on the parser's mode: * - Sync parsers return `readonly Suggestion[]` directly. * - Async parsers return `Promise`. * * For explicit control, use {@link suggestSync} or {@link suggestAsync}. * * @template M The execution mode of the parser. * @template T The type of the value produced by the parser. * @param parser The {@link Parser} to use for generating suggestions. * @param args The array of command-line arguments including the partial * argument to complete. The last element is treated as * the prefix for suggestions. * @param options Optional {@link ParseOptions} for customizing parsing behavior. * @returns An array of {@link Suggestion} objects (for sync) or Promise thereof * (for async) containing completion candidates. * @throws {TypeError} When a synchronous dependency source extractor returns a * thenable during suggestion seeding. * @since 0.6.0 * @since 0.10.0 Added optional `options` parameter for annotations support. */ declare function suggest(parser: Parser, args: readonly [string, ...readonly string[]], options?: ParseOptions): ModeValue; /** * Generates a documentation page for a synchronous parser. * * This is the sync-specific version of {@link getDocPage}. It only accepts * sync parsers and returns the documentation page directly (not wrapped * in a Promise). * * @param parser The sync parser to generate documentation for. * @param argsOrOptions Optional array of command-line arguments for context, * or a {@link ParseOptions} object for annotations. When a * `ParseOptions` is passed here, the `options` parameter is ignored. * @param options Optional {@link ParseOptions} for customizing parsing * behavior. Only used when `argsOrOptions` is an array or omitted. * @returns A {@link DocPage} or `undefined`. * @since 0.9.0 * @since 0.10.0 Added optional `options` parameter for annotations support. * @since 1.0.0 The second parameter now also accepts a `ParseOptions` object * directly. */ declare function getDocPageSync(parser: Parser<"sync", unknown, unknown>, argsOrOptions?: readonly string[] | ParseOptions, options?: ParseOptions): DocPage | undefined; /** * Generates a documentation page for any parser, returning a Promise. * * This function accepts parsers of any mode (sync or async) and always * returns a Promise. Use this when working with parsers that may contain * async value parsers. * * @param parser The parser to generate documentation for. * @param argsOrOptions Optional array of command-line arguments for context, * or a {@link ParseOptions} object for annotations. When a * `ParseOptions` is passed here, the `options` parameter is ignored. * @param options Optional {@link ParseOptions} for customizing parsing * behavior. Only used when `argsOrOptions` is an array or omitted. * @returns A Promise of {@link DocPage} or `undefined`. * @since 0.9.0 * @since 0.10.0 Added optional `options` parameter for annotations support. * @since 1.0.0 The second parameter now also accepts a `ParseOptions` object * directly. */ declare function getDocPageAsync(parser: Parser, argsOrOptions?: readonly string[] | ParseOptions, options?: ParseOptions): Promise; /** * Generates a documentation page for a parser based on its current state after * attempting to parse the provided arguments. This function is useful for * creating help documentation that reflects the current parsing context. * * The function works by: * 1. Attempting to parse the provided arguments to determine the current state * 2. Generating documentation fragments from the parser's current state * 3. Organizing fragments into entries and sections * 4. Resolving command usage terms based on parsed arguments * * For sync parsers, returns the documentation page directly. * For async parsers, returns a Promise of the documentation page. * * @param parser The parser to generate documentation for * @param argsOrOptions Optional array of command-line arguments that have been * parsed so far, or a {@link ParseOptions} object for annotations. * When a `ParseOptions` is passed here, the `options` parameter is * ignored. Defaults to an empty array when omitted. * @param options Optional {@link ParseOptions} for customizing parsing * behavior. Only used when `argsOrOptions` is an array or omitted. * @returns For sync parsers, returns a {@link DocPage} directly. * For async parsers, returns a Promise of {@link DocPage}. * Returns `undefined` if no documentation can be generated. * * @example * ```typescript * const parser = object({ * verbose: option("-v", "--verbose"), * port: option("-p", "--port", integer()) * }); * * // Get documentation for sync parser * const rootDoc = getDocPage(parser); * * // Get documentation for async parser * const asyncDoc = await getDocPage(asyncParser); * ``` * @since 0.9.0 Updated to support async parsers. * @since 0.10.0 Added optional `options` parameter for annotations support. * @since 1.0.0 The second parameter now also accepts a `ParseOptions` object * directly. */ declare function getDocPage(parser: Parser<"sync", unknown, unknown>, argsOrOptions?: readonly string[] | ParseOptions, options?: ParseOptions): DocPage | undefined; declare function getDocPage(parser: Parser<"async", unknown, unknown>, argsOrOptions?: readonly string[] | ParseOptions, options?: ParseOptions): Promise; declare function getDocPage(parser: Parser, argsOrOptions?: readonly string[] | ParseOptions, options?: ParseOptions): ModeValue; //#endregion export { CombineModes, DocState, ExecutionContext, ExecutionPhase, InferMode, InferValue, Mode, ModeIterable, ModeValue, ParseFrame, type ParseOptions, Parser, ParserContext, ParserResult, Result, Suggestion, annotationWrapperRequiresSourceBindingKey, composeWrappedSourceMetadata, createParserContext, defineInheritedAnnotationParser, defineSourceBindingOnlyAnnotationCompletionParser, getDelegatingSuggestRuntimeNodes, getDocPage, getDocPageAsync, getDocPageSync, getParserSuggestRuntimeNodes, inheritParentAnnotationsKey, parse, parseAsync, parseSync, suggest, suggestAsync, suggestSync, unmatchedNonCliDependencySourceStateMarker };