@clo4/cli 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +324 -312
- package/dist/index.js.map +1 -1
- package/dist/testing.js +414 -369
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["hasName","builtinUsageAction","maybeProcess"],"sources":["../src/util.ts","../src/suggest.ts","../src/subcommands.ts","../src/directives.ts","../src/scope.ts","../src/help.ts","../src/errors.ts","../src/parse.ts","../src/completion.ts","../src/run.ts","../src/index.ts"],"sourcesContent":["import type { Arg, NonEmptyArray } from \"./types.js\";\n\nexport function isArray<T>(o: T | readonly T[]): o is readonly T[] {\n return Array.isArray(o);\n}\n\n/** Convert the value, if any, to an array with 0 or more elements */\nexport function makeArray<T>(thing: T | readonly T[] | undefined): T[] {\n if (thing === undefined) {\n return [];\n }\n if (isArray(thing)) {\n return thing.slice();\n }\n return [thing];\n}\n\n/**\n * Like {@link makeArray}, but without copying when the input is already an\n * array. Only safe when the caller treats the result as read-only — use it on\n * the hot path to avoid slicing read-only spec metadata.\n */\nexport function asArray<T>(thing: T | readonly T[] | undefined): readonly T[] {\n if (thing === undefined) {\n return [];\n }\n if (isArray(thing)) {\n return thing;\n }\n return [thing];\n}\n\n/** Convert the value to an array with at least one element */\nexport function makeArray1<T>(thing: T | NonEmptyArray<T>): [T, ...T[]] {\n if (isArray(thing)) {\n // We know that this array has at least one element in it\n return thing.slice() as [T, ...T[]];\n }\n return [thing];\n}\n\nexport function assert(expr: unknown, msg = \"\"): asserts expr {\n if (!expr) {\n throw new Error(msg);\n }\n}\n\n// Output {{{\n\ninterface WriteSyncFs {\n writeSync(fd: number, buffer: Uint8Array, offset: number, length: number): number;\n}\n\ninterface NodeProcess {\n getBuiltinModule?(id: \"node:fs\"): WriteSyncFs;\n stdout?: { write(data: Uint8Array): unknown };\n stderr?: { write(data: Uint8Array): unknown };\n}\n\nconst nodeProcess = (globalThis as { process?: NodeProcess }).process;\n\n/**\n * Write text to stdout (1) or stderr (2) with a synchronous `write` on the file\n * descriptor.\n *\n * The first `console.log` in a Node process builds the stdout stream, which\n * costs 1-3 ms. That's more than parsing takes, so all of this library's output\n * goes through here instead. Without `node:fs` it falls back to `console`.\n */\nfunction writeFd(fd: 1 | 2, text: string): void {\n const fs = nodeProcess?.getBuiltinModule?.(\"node:fs\");\n if (!fs) {\n (fd === 1 ? console.log : console.error)(text.endsWith(\"\\n\") ? text.slice(0, -1) : text);\n return;\n }\n const bytes = new TextEncoder().encode(text);\n let offset = 0;\n try {\n while (offset < bytes.length) {\n offset += fs.writeSync(fd, bytes, offset, bytes.length - offset);\n }\n } catch (error) {\n const code = (error as { code?: string }).code;\n // A non-blocking pipe that's full: let Node's stream queue the rest.\n if (code === \"EAGAIN\") {\n (fd === 1 ? nodeProcess?.stdout : nodeProcess?.stderr)?.write(bytes.subarray(offset));\n }\n // Anything else, like EPIPE from `cli --help | head -1`, is dropped, the\n // same as `console` does.\n }\n}\n\n/**\n * Where this library's output goes. Tests replace `write` to capture output.\n *\n * @internal\n */\nexport const output: { write: (fd: 1 | 2, text: string) => void } = { write: writeFd };\n\n/** Print a message to stdout, trimming trailing whitespace. */\nexport function print(text: string): void {\n output.write(1, `${text.trimEnd()}\\n`);\n}\n\n/** Print `Error:` and the given values to stderr, separated by spaces. */\nexport function printError(...strings: unknown[]): void {\n output.write(2, `${[\"Error:\", ...strings].map(String).join(\" \")}\\n`);\n}\n\n// }}}\n\n/**\n * Add the defaults of the arguments from index `from` on to `values`, stopping\n * at the first argument without one. The parser and help both use this, so\n * help only shows the defaults the parser uses.\n */\nexport function addDefaults(values: string[], args: readonly Arg[], from = 0): void {\n for (let i = from; i < args.length; i++) {\n const value = args[i].default;\n if (value === undefined) {\n return;\n }\n values.push(value);\n }\n}\n\n/**\n * Returns the minimum number of arguments that satisfies the args.\n *\n * Accepts the raw spec value (a single arg, an array, or `undefined`) so the\n * hot path doesn't have to copy it into an array first.\n */\nexport function getMinArgs(\n args: { isOptional?: boolean } | readonly { isOptional?: boolean }[] | undefined,\n): number {\n if (args === undefined) {\n return 0;\n }\n if (!isArray(args)) {\n return args.isOptional ? 0 : 1;\n }\n let count = 0;\n for (let i = 0; i < args.length; i++) {\n if (args[i].isOptional) {\n break;\n }\n count++;\n }\n return count;\n}\n\n/** Returns the maximum number of arguments that satisfies the args. */\nexport function getMaxArgs(\n args: { isVariadic?: boolean } | readonly { isVariadic?: boolean }[] | undefined,\n): number {\n if (args === undefined) {\n return 0;\n }\n if (!isArray(args)) {\n return args.isVariadic ? Infinity : 1;\n }\n // Loop over the array backwards because variadic arguments are\n // more likely to be at the end of the array. They don't _need_\n // to be, but it's more idiomatic.\n for (let i = 0; i < args.length; i++) {\n if (args[args.length - 1 - i].isVariadic) {\n return Infinity;\n }\n }\n // None of the arguments are variadic, max is the number of args\n return args.length;\n}\n","/**\n * \"Did you mean\" suggestions for unknown commands and options.\n *\n * This only runs after a mistake, but it's loaded on every run, so it's kept\n * small and does nothing until it's called.\n *\n * @module\n */\n\n/** How many `-` or `+` characters `name` starts with. */\nfunction dashCount(name: string): number {\n let i = 0;\n while (i < name.length && (name[i] === \"-\" || name[i] === \"+\")) {\n i++;\n }\n return i;\n}\n\n/** Whether every character of `short` appears in `long`, in order. */\nfunction isAbbreviation(short: string, long: string): boolean {\n let i = 0;\n for (let j = 0; j < long.length && i < short.length; j++) {\n if (long[j] === short[i]) {\n i++;\n }\n }\n return i === short.length;\n}\n\n/**\n * Levenshtein distance where swapping two adjacent characters also counts as\n * one edit (optimal string alignment). Returns `limit + 1` as soon as the\n * distance must be larger than `limit`.\n */\nfunction editDistance(a: string, b: string, limit: number): number {\n // Three rows of the usual table: two rows back, the previous row and this one.\n let before = new Uint32Array(b.length + 1);\n let previous = new Uint32Array(b.length + 1);\n let current = new Uint32Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) {\n previous[j] = j;\n }\n\n for (let i = 1; i <= a.length; i++) {\n current[0] = i;\n let rowMin = i;\n for (let j = 1; j <= b.length; j++) {\n const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);\n let d = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d = Math.min(d, before[j - 2] + 1);\n }\n current[j] = d;\n if (d < rowMin) {\n rowMin = d;\n }\n }\n // Every later row is at least this row's minimum.\n if (rowMin > limit) {\n return limit + 1;\n }\n const recycled = before;\n before = previous;\n previous = current;\n current = recycled;\n }\n return previous[b.length];\n}\n\n/**\n * A name to suggest, or every name of one command or option. The names of one\n * command or option count as one choice, so an alias can't make a match\n * ambiguous.\n */\nexport type Choice = string | readonly string[];\n\n/** The first name of the only choice with a name that `matches`, if exactly one has one. */\nfunction onlyMatch(choices: readonly Choice[], matches: (name: string) => boolean): string | undefined {\n let match: string | undefined;\n for (const choice of choices) {\n const name = (typeof choice === \"string\" ? [choice] : choice).find(matches);\n if (name === undefined) {\n continue;\n }\n if (match !== undefined) {\n return undefined;\n }\n match = name;\n }\n return match;\n}\n\n/**\n * The name the user most likely meant by `input`, or `undefined` if none is\n * close enough to be worth suggesting. In order:\n *\n * 1. The only choice that starts with the input (`--verb` for `--verbose`).\n * 2. The only choice that contains every character of the input in order, for\n * inputs of 3 or more characters (`bld` for `build`).\n * 3. The name with the fewest edits, allowing one edit per three characters\n * of the input. Leading dashes don't count toward the length or the edits.\n */\nexport function closestChoice(input: string, choices: readonly Choice[]): string | undefined {\n const inputDashes = dashCount(input);\n const bare = input.slice(inputDashes);\n\n if (bare.length >= 2) {\n const match = onlyMatch(choices, (name) => name.startsWith(input));\n if (match !== undefined) {\n return match;\n }\n }\n\n if (bare.length >= 3) {\n const match = onlyMatch(choices, (name) => isAbbreviation(bare, name.slice(dashCount(name))));\n if (match !== undefined) {\n return match;\n }\n }\n\n let best: string | undefined;\n let limit = Math.floor(bare.length / 3);\n for (const name of choices.flat()) {\n const other = name.slice(dashCount(name));\n // The length difference is a lower bound on the number of edits.\n if (Math.abs(other.length - bare.length) > limit) {\n continue;\n }\n const distance = editDistance(bare, other, limit);\n if (distance <= limit && (best === undefined || distance < limit)) {\n best = name;\n // Later names have to be strictly closer to replace this one.\n limit = distance;\n if (distance === 0) {\n break;\n }\n }\n }\n return best;\n}\n","import type { Action, Subcommand } from \"./types.js\";\nimport type { Directives } from \"./directives.js\";\nimport type { DidYouMean } from \"./errors.js\";\nimport { asArray, print } from \"./util.js\";\n\n/** The subcommand a token names, or why it names none. See {@link matchSubcommand}. */\nexport type SubcommandMatch = { command: Subcommand } | NoSubcommand;\n\n/**\n * Find the subcommand `token` names among `subcommands`, in a command where\n * `directives` are in effect, or else among the persistent subcommands the\n * command `inherited`. An exact name always wins. With\n * `subcommandsMatchUniquePrefix`, a token that's a prefix of exactly one\n * of the command's own names matches that command, unless `exactOnly`. A\n * hidden or inherited command only matches its exact name, so it can't make a\n * visible command's prefix ambiguous or take a prefix meant as an argument,\n * and an empty token is no command's prefix.\n */\nexport function matchSubcommand(\n subcommands: readonly Subcommand[],\n token: string,\n directives: Readonly<Directives>,\n exactOnly = false,\n inherited: readonly Subcommand[] = [],\n): SubcommandMatch {\n for (const candidate of subcommands) {\n if (hasName(candidate, token)) {\n return { command: candidate };\n }\n }\n for (const candidate of inherited) {\n if (hasName(candidate, token)) {\n return { command: candidate };\n }\n }\n const allowPrefix = directives.subcommandsMatchUniquePrefix && !exactOnly;\n const matches = allowPrefix ? prefixMatches(subcommands, token) : [];\n if (matches.length === 1) {\n return { command: matches[0] };\n }\n return new NoSubcommand(withInherited(subcommands, inherited), token, matches);\n}\n\n/**\n * A command's own `subcommands` followed by the `inherited` ones it can use,\n * leaving out each inherited one that an earlier command shadows a name of.\n */\nexport function withInherited(\n subcommands: readonly Subcommand[],\n inherited: readonly Subcommand[],\n): readonly Subcommand[] {\n if (inherited.length === 0) {\n return subcommands;\n }\n const all = [...subcommands];\n for (const candidate of inherited) {\n if (!asArray(candidate.name).some((name) => all.some((earlier) => hasName(earlier, name)))) {\n all.push(candidate);\n }\n }\n return all;\n}\n\nfunction hasName(command: Subcommand, token: string): boolean {\n const names = command.name;\n return typeof names === \"string\" ? names === token : names.includes(token);\n}\n\n/** The visible commands that `token` is a prefix of a name of, each listed once. */\nfunction prefixMatches(subcommands: readonly Subcommand[], token: string): Subcommand[] {\n if (token === \"\") {\n return [];\n }\n return subcommands.filter(\n (candidate) => !candidate.hidden && asArray(candidate.name).some((name) => name.startsWith(token)),\n );\n}\n\n/**\n * A token that names no subcommand. The reason is only worked out when asked\n * for, since most tokens the parser tries aren't subcommands.\n */\nexport class NoSubcommand {\n readonly command = null;\n\n /**\n * `prefixOf` are the commands `token` is a prefix of a name of, where\n * prefixes match. There is never exactly one of them.\n */\n constructor(\n private readonly subcommands: readonly Subcommand[],\n private readonly token: string,\n private readonly prefixOf: readonly Subcommand[],\n ) {}\n\n /** Why the token names none of the subcommands, as an error message and suggestions. */\n reason(): { message: string; didYouMean?: DidYouMean } {\n const token = this.token;\n if (token === \"\") {\n return { message: \"Expected a command, but the value was empty\" };\n }\n if (this.prefixOf.length > 0) {\n const possible = this.prefixOf.flatMap((command) =>\n asArray(command.name).filter((name) => name.startsWith(token)),\n );\n return { message: `Ambiguous command '${token}', could be: ${possible.join(\", \")}` };\n }\n const choices = visibleSubcommands(this.subcommands).map((command) => asArray(command.name));\n return { message: `Unknown command '${token}'`, didYouMean: { input: token, choices } };\n }\n}\n\n/** The subcommands that help, completion and suggestions show. */\nexport function visibleSubcommands(subcommands: readonly Subcommand[] | undefined): Subcommand[] {\n return subcommands?.filter((subcommand) => !subcommand.hidden) ?? [];\n}\n\n/** The action of a command that has none of its own: print the command's help. */\nexport const usage: Action = ({ help }) => {\n print(help());\n return 0;\n};\n","import type { Spec, Subcommand } from \"./types.js\";\nimport { asArray } from \"./util.js\";\n\n/** The parser directives in effect for a command, with defaults filled in. */\nexport interface Directives {\n optionArgSeparators: readonly string[];\n flagsArePosixNoncompliant: boolean;\n optionsMustPrecedeArguments: boolean;\n subcommandsMatchUniquePrefix: boolean;\n}\n\n/** The directives in effect when no command sets any. */\nexport function defaultDirectives(): Directives {\n return {\n optionArgSeparators: [\"=\"],\n flagsArePosixNoncompliant: false,\n optionsMustPrecedeArguments: false,\n subcommandsMatchUniquePrefix: false,\n };\n}\n\n/**\n * Update `directives` for entering `command`. A subcommand inherits each\n * directive until it sets its own.\n */\nexport function applyDirectives(directives: Directives, command: Spec | Subcommand): void {\n const configured = command.parserDirectives;\n if (!configured) {\n return;\n }\n if (configured.optionArgSeparators) {\n directives.optionArgSeparators = asArray(configured.optionArgSeparators);\n }\n if (typeof configured.subcommandsMatchUniquePrefix === \"boolean\") {\n directives.subcommandsMatchUniquePrefix = configured.subcommandsMatchUniquePrefix;\n }\n if (typeof configured.optionsMustPrecedeArguments === \"boolean\") {\n directives.optionsMustPrecedeArguments = configured.optionsMustPrecedeArguments;\n }\n if (typeof configured.flagsArePosixNoncompliant === \"boolean\") {\n directives.flagsArePosixNoncompliant = configured.flagsArePosixNoncompliant;\n }\n}\n","import type { Option, Spec, Subcommand } from \"./types.js\";\nimport { applyDirectives, defaultDirectives } from \"./directives.js\";\nimport type { Directives } from \"./directives.js\";\nimport { asArray, getMaxArgs } from \"./util.js\";\n\n/** An option that can be used here, and the names that still refer to it. */\nexport interface VisibleOption {\n option: Option;\n names: string[];\n}\n\n/** How one name of an option is written with its value, at one command. */\nexport interface OptionForm {\n name: string;\n /**\n * What joins the name to the option's first value in the same token, or null\n * if the value is the next token. It's the required separator for an option\n * that requires one, and \"\" for an option named \"-\" or \"+\", which reads its\n * value straight after the name, like `-5`. It's null for an option without\n * arguments.\n */\n join: string | null;\n}\n\n/**\n * The options and directives in effect at one command on a path.\n *\n * Moving to a subcommand replaces the local options and adds its persistent\n * options to the inherited ones. A name refers to one option: a local option\n * wins over a persistent one, and a later option wins over an earlier one in\n * the same list. The parser, help, completion and the spec checker all ask\n * this module which option a name refers to, so they can't disagree. It also\n * holds the persistent subcommands the current command inherits.\n */\nexport class OptionScope {\n /** Non-persistent options of the current command, in definition order. */\n readonly local: Option[] = [];\n /** Persistent options from every command on the path, in definition order. */\n readonly persistent: Option[] = [];\n /**\n * Persistent subcommands of the commands above the current one, nearest\n * command first, so a nearer one wins a name.\n */\n readonly inheritedSubcommands: Subcommand[] = [];\n /** The directives in effect. A subcommand inherits each until it sets its own. */\n readonly directives: Directives = defaultDirectives();\n private command: Spec | Subcommand | null = null;\n\n /** The scope at the last command on `path`. */\n static at(path: readonly (Spec | Subcommand)[]): OptionScope {\n const scope = new OptionScope();\n for (const command of path) {\n scope.enter(command);\n }\n return scope;\n }\n\n /** Move to `command`, a subcommand of the current one. */\n enter(command: Spec | Subcommand): void {\n const parentSubcommands = this.command?.subcommands;\n if (parentSubcommands) {\n const persistent = parentSubcommands.filter((subcommand) => subcommand.isPersistent);\n if (persistent.length > 0) {\n this.inheritedSubcommands.unshift(...persistent);\n }\n }\n this.command = command;\n this.local.length = 0;\n if (command.options) {\n for (const option of command.options) {\n (option.isPersistent ? this.persistent : this.local).push(option);\n }\n }\n applyDirectives(this.directives, command);\n }\n\n /** The option `name` refers to, if any. */\n resolve(name: string): Option | null {\n const { local, persistent } = this;\n for (let i = local.length - 1; i >= 0; i--) {\n if (hasName(local[i].name, name)) {\n return local[i];\n }\n }\n for (let i = persistent.length - 1; i >= 0; i--) {\n if (hasName(persistent[i].name, name)) {\n return persistent[i];\n }\n }\n return null;\n }\n\n /**\n * The options that can be used here, in definition order, each with only\n * its live names: the names that still refer to it. Options with every name\n * shadowed are left out.\n */\n live(): { local: VisibleOption[]; persistent: VisibleOption[] } {\n // Which option each name refers to, built in one pass so the later and the\n // local options overwrite the ones they shadow. Same answer as `resolve`.\n const owner = new Map<string, Option>();\n for (const options of [this.persistent, this.local]) {\n for (const option of options) {\n for (const name of asArray(option.name)) {\n owner.set(name, option);\n }\n }\n }\n const pick = (options: readonly Option[]) => {\n const picked: VisibleOption[] = [];\n for (const option of options) {\n const names = asArray(option.name).filter((name) => owner.get(name) === option);\n if (names.length > 0) {\n picked.push({ option, names });\n }\n }\n return picked;\n };\n return { local: pick(this.local), persistent: pick(this.persistent) };\n }\n\n /** The options a user can see here: the {@link live} ones that aren't hidden. */\n visible(): { local: VisibleOption[]; persistent: VisibleOption[] } {\n const { local, persistent } = this.live();\n const shown = (visible: VisibleOption) => !visible.option.hidden;\n return { local: local.filter(shown), persistent: persistent.filter(shown) };\n }\n\n /** The live names of each option a user could have meant, for \"did you mean\" suggestions. */\n suggestionNames(): string[][] {\n const { local, persistent } = this.visible();\n return [...local, ...persistent].map((visible) => visible.names);\n }\n\n /** The options that must be used, local first. */\n required(): Option[] {\n return [...this.local, ...this.persistent].filter((option) => option.isRequired);\n }\n\n /**\n * How each of `names` is written with `option`'s value here. Help shows\n * these, completion offers them, and the spec checker reads each one back\n * through the parser.\n */\n forms(option: Option, names: readonly string[] = asArray(option.name)): OptionForm[] {\n const join = (name: string): string | null => {\n if (getMaxArgs(option.args) === 0) {\n return null;\n }\n if (option.requiresSeparator) {\n return this.requiredSeparator(option);\n }\n const glued = !this.directives.flagsArePosixNoncompliant && (name === \"-\" || name === \"+\");\n return glued ? \"\" : null;\n };\n return names.map((name) => ({ name, join: join(name) }));\n }\n\n /**\n * The separator that must come between `option` and its value, or null if\n * it can take a value as a separate token.\n */\n requiredSeparator(option: Option): string | null {\n const required = option.requiresSeparator;\n if (typeof required === \"string\") {\n return required;\n }\n return required ? (this.directives.optionArgSeparators[0] ?? \"=\") : null;\n }\n}\n\nconst optionKeys = new WeakMap<Option, string>();\n\n/**\n * A key for the set of `option`'s names. Options with the same names, in any\n * order, get the same key and are one option: the parser continues a\n * repeatable option's uses across them, counts one as used when the other was,\n * and stores their values under the same names, which is how they're read.\n * Options that share only some names are different options, and each shared\n * name refers to whichever one `resolve` picks.\n */\nexport function optionKey(option: Option): string {\n let key = optionKeys.get(option);\n if (key === undefined) {\n key = typeof option.name === \"string\" ? option.name : [...option.name].sort().join(\"\\0\");\n optionKeys.set(option, key);\n }\n return key;\n}\n\nfunction hasName(names: string | readonly string[], name: string): boolean {\n return typeof names === \"string\" ? names === name : names.includes(name);\n}\n","import type { Arg, Option, NonEmptyArray, Subcommand } from \"./types.js\";\nimport { closestChoice } from \"./suggest.js\";\nimport { matchSubcommand, visibleSubcommands } from \"./subcommands.js\";\nimport { OptionScope } from \"./scope.js\";\nimport type { OptionForm, VisibleOption } from \"./scope.js\";\nimport type { DidYouMean } from \"./errors.js\";\nimport { addDefaults, asArray, getMaxArgs, makeArray, makeArray1, print, printError } from \"./util.js\";\n\nfunction dedent(str: string) {\n if (str[0] !== \"\\n\") {\n return str;\n }\n const lines = str.split(\"\\n\").slice(1, -1);\n const margin = lines[0].length - lines[0].trimStart().length;\n return lines.map((line) => line.slice(margin)).join(\"\\n\");\n}\n\nexport interface HelpConfig {\n /** Include the command description? Default: true. */\n description?: boolean;\n\n /** Include the usage summary? Default: true. */\n usage?: boolean;\n\n /** Ask if the user intended the input to be one of these choices. */\n didYouMean?: DidYouMean;\n}\n\n/** Get the help message used by the built-in help option and command. */\nexport function getHelp(path: NonEmptyArray<Subcommand>, config: HelpConfig = {}): string {\n const { description = true, usage = true, didYouMean } = config;\n const sections = getSections(path);\n if (didYouMean) {\n sections.didYouMean = closestChoice(didYouMean.input, didYouMean.choices);\n }\n if (!description) {\n sections.description = undefined;\n }\n if (!usage) {\n sections.usage = undefined;\n }\n return formatHelpSections(sections);\n}\n\n/**\n * Print `message` as an error, then the usage and flags of the last command on\n * `path`, suggesting the closest of `didYouMean.choices` if one is close.\n */\nexport function printUsageError(\n path: NonEmptyArray<Subcommand>,\n message: string,\n didYouMean?: DidYouMean,\n): void {\n printError(`${message}\\n\\n${getHelp(path, { description: false, didYouMean })}`);\n}\n\n/**\n * A subcommand that prints help for its parent, or for the command the names\n * after it lead to from there, so `cli help a b` prints the help of `cli a b`.\n * It reads names until one isn't a subcommand. A token where the command takes\n * arguments, or where it has no subcommands, ends the names, so\n * `cli help completion zsh` prints the help of `completion`. Any other token\n * is an unknown command. Add `{ ...helpCommand, isPersistent: true }` instead\n * to make `cli a b help` work too.\n */\nexport const helpCommand: Subcommand = {\n name: \"help\",\n description: \"Print a help message\",\n args: {\n name: \"command\",\n isOptional: true,\n isVariadic: true,\n },\n action({ path, args, help }) {\n const self = path[path.length - 1];\n const helpPath = path.slice(0, -1) as unknown as [Subcommand, ...Subcommand[]];\n\n for (const name of args) {\n const command = helpPath[helpPath.length - 1];\n if (!command.subcommands) {\n break;\n }\n // Match the name the way the parser would have matched it in place of `help`.\n const scope = OptionScope.at(helpPath);\n const match = matchSubcommand(\n command.subcommands,\n name,\n scope.directives,\n false,\n scope.inheritedSubcommands,\n );\n // With a persistent help command, `cli help a help` is `cli a help`.\n if (match.command === self && !command.subcommands.includes(self)) {\n break;\n }\n if (match.command) {\n helpPath.push(match.command);\n continue;\n }\n if (!command.requiresSubcommand && getMaxArgs(command.args) > 0) {\n break;\n }\n const { message, didYouMean } = match.reason();\n printUsageError(helpPath, message, didYouMean);\n return 1;\n }\n\n print(help({ path: helpPath }));\n return 0;\n },\n};\n\n/** A persistent help option that prints help for the selected command. */\nexport const help: Option = {\n name: [\"-h\", \"--help\"],\n description: \"Print a help message\",\n isPersistent: true,\n action({ path }) {\n print(formatHelpSections(getSections(path)));\n return 0;\n },\n};\n\ntype HelpSections = {\n description?: string;\n usage?: string;\n didYouMean?: string;\n args: [name: string, description: string][];\n options: [formattedName: string, description: string][];\n persistentOptions: [formattedName: string, description: string][];\n subcommands: [formattedName: string, description: string][];\n};\n\nfunction getSubcommandPathString(commands: NonEmptyArray<Subcommand>): string {\n return commands.map((command) => getLongestString(makeArray1(command.name))).join(\" \");\n}\n\nfunction getSections(commands: NonEmptyArray<Subcommand>): HelpSections {\n const command = commands[commands.length - 1];\n const scope = OptionScope.at(commands);\n const show = ({ option, names }: VisibleOption) => optionToString(option, scope.forms(option, names));\n\n const description = command.description;\n const defaultDesc = \"No description\";\n\n const subcommands: HelpSections[\"subcommands\"] = visibleSubcommands(command.subcommands).map(\n (subcommand) => [\n makeArray1(subcommand.name)\n .sort((a, b) => a.length - b.length)\n .join(\", \"),\n subcommand.description ?? defaultDesc,\n ],\n );\n\n const visible = scope.visible();\n let optionObjects = visible.local;\n let persistentOptionObjects = visible.persistent;\n // A command without parents or subcommands has no global flags to set apart.\n if (commands.length === 1 && subcommands.length === 0) {\n const byOption = new Map([...optionObjects, ...persistentOptionObjects].map((v) => [v.option, v]));\n optionObjects = (command.options ?? []).flatMap((option) => byOption.get(option) ?? []);\n persistentOptionObjects = [];\n }\n const row = (visible: VisibleOption): [string, string] => {\n const defaults: string[] = [];\n addDefaults(defaults, asArray(visible.option.args));\n return [show(visible), withDefaults(visible.option.description, defaults, defaultDesc)];\n };\n const options = optionObjects.map(row);\n const persistentOptions = persistentOptionObjects.map(row);\n\n const usage = (() => {\n const parts = [getSubcommandPathString(commands)];\n for (const visible of [...optionObjects, ...persistentOptionObjects]) {\n if (visible.option.isRequired) {\n parts.push(show(visible));\n }\n }\n if (options.length || persistentOptions.length) {\n parts.push(\"[flags]\");\n }\n if (command.requiresSubcommand) {\n parts.push(\"<command>\");\n } else {\n const args = makeArray(command.args);\n if (args.length > 0) {\n parts.push(summarizeArguments(args));\n }\n }\n return parts.join(\" \");\n })();\n\n // The positional arguments are only listed when there's more to say about\n // them than the usage line does. An argument's name is often description\n // enough, so one without a description is listed by name alone.\n const positionals = command.requiresSubcommand ? [] : asArray(command.args);\n const described = positionals.some((arg) => arg.description !== undefined || arg.default !== undefined);\n const args: HelpSections[\"args\"] = described\n ? positionals.map((arg) => [\n (arg.name || \"argument\") + (arg.isVariadic ? \"...\" : \"\"),\n withDefaults(arg.description, arg.default === undefined ? [] : [arg.default], \"\"),\n ])\n : [];\n\n return {\n usage,\n description,\n args,\n persistentOptions,\n options,\n subcommands,\n };\n}\n\n/**\n * A description ending with the defaults the parser uses. They go on a line of\n * their own when the last line would be too long for the 68 characters the\n * spec checks allow.\n */\nfunction withDefaults(\n description: string | undefined,\n defaults: readonly string[],\n defaultDesc: string,\n): string {\n if (defaults.length === 0) {\n return description ?? defaultDesc;\n }\n const shown = `(default: ${defaults.join(\" \")})`;\n if (description === undefined) {\n return shown;\n }\n const lastLine = description.slice(description.lastIndexOf(\"\\n\") + 1);\n return `${description}${lastLine.length + 1 + shown.length <= 68 ? \" \" : \"\\n\"}${shown}`;\n}\n\nexport function formatHelpSections(sections: HelpSections): string {\n const parts = [];\n\n const indent = \" \";\n\n if (sections.didYouMean) {\n parts.push(` Did you mean '${sections.didYouMean}'?`);\n }\n\n if (sections.description) {\n parts.push(dedent(sections.description));\n }\n\n if (sections.usage) {\n parts.push(`Usage:\\n${indent}${sections.usage}`);\n }\n\n const longestOptionName = Math.max(\n 0,\n ...sections.options.map(([name]) => name.length),\n ...sections.persistentOptions.map(([name]) => name.length),\n );\n const minSpacingBetweenNameAndDesc = 2;\n\n // Each name, then its description in a column `width` wide names leave.\n const formatRows = (rows: [string, string][], width: number) => {\n const lines = [];\n const newline = indent + \" \".repeat(width + minSpacingBetweenNameAndDesc);\n for (const [name, desc] of rows) {\n if (desc === \"\") {\n lines.push(`${indent}${name}`);\n continue;\n }\n const spaces = \" \".repeat(width - name.length + minSpacingBetweenNameAndDesc);\n const [head, ...tail] = desc.split(\"\\n\");\n const description = [head, ...tail.map((line) => newline + line)].join(\"\\n\");\n lines.push(`${indent}${name}${spaces}${description}`);\n }\n return lines;\n };\n const formatOptions = (options: [string, string][]) => formatRows(options, longestOptionName);\n\n if (sections.args.length > 0) {\n const longestArgName = Math.max(...sections.args.map(([name]) => name.length));\n parts.push([\"Arguments:\", ...formatRows(sections.args, longestArgName)].join(\"\\n\"));\n }\n\n if (sections.subcommands.length > 0) {\n const lines = [\"Commands:\"];\n const longestName = Math.max(...sections.subcommands.map(([name]) => name.length));\n const newline = indent + \" \".repeat(longestName + minSpacingBetweenNameAndDesc);\n for (const [name, desc] of sections.subcommands) {\n const spaces = \" \".repeat(longestName - name.length + minSpacingBetweenNameAndDesc);\n const [head, ...tail] = desc.split(\"\\n\\n\")[0].split(\"\\n\");\n const description = [head, ...tail.map((line) => newline + line)].join(\"\\n\");\n lines.push(`${indent}${name}${spaces}${description}`);\n }\n parts.push(lines.join(\"\\n\"));\n }\n\n if (sections.options.length > 0) {\n const lines = [\"Flags:\", ...formatOptions(sections.options)];\n parts.push(lines.join(\"\\n\"));\n }\n\n if (sections.persistentOptions.length > 0) {\n const lines = [\"Global flags:\", ...formatOptions(sections.persistentOptions)];\n parts.push(lines.join(\"\\n\"));\n }\n return parts.join(\"\\n\\n\") + \"\\n\";\n}\n\nexport function getLongestString(strings: NonEmptyArray<string>): string {\n let longest = strings[0];\n for (let i = 1; i < strings.length; i++) {\n const string = strings[i];\n if (string.length > longest.length) {\n longest = string;\n }\n }\n return longest;\n}\n\n/**\n * Show an option's names, each written with its arguments the way `forms`\n * says. Names written the same way share one copy of the arguments.\n */\nexport function optionToString(option: Option, forms: readonly OptionForm[]): string {\n const optionArgs = makeArray(option.args);\n const sorted = [...forms].sort((a, b) => a.name.length - b.name.length);\n const joins = [...new Set(sorted.map((form) => form.join))];\n return joins\n .map((join) => {\n const names = sorted.filter((form) => form.join === join).map((form) => form.name);\n return names.join(\", \") + argumentsAfterName(optionArgs, join);\n })\n .join(\", \");\n}\n\n/** The text after an option's name that shows its arguments, joined to the name by `join`. */\nfunction argumentsAfterName(args: Arg[], join: string | null): string {\n if (args.length === 0) {\n return \"\";\n }\n if (join === null) {\n return ` ${summarizeArguments(args)}`;\n }\n const [first, ...rest] = args;\n const name = first.name || \"argument\";\n const joined =\n (first.isOptional ? `[${join}${name}]` : `${join}<${name}>`) + (first.isVariadic ? \"...\" : \"\");\n return rest.length > 0 ? `${joined} ${summarizeArguments(rest)}` : joined;\n}\n\nexport function summarizeArguments(args: Arg[]) {\n return args.map((arg) => argToString(arg)).join(\" \");\n}\n\nexport function argToString(arg: Arg): string {\n const name = arg.name || \"argument\";\n let lhs = \"<\";\n let rhs = \">\";\n let suffix = \"\";\n if (arg.isOptional) {\n lhs = \"[\";\n rhs = \"]\";\n }\n if (arg.isVariadic) {\n suffix = \"...\";\n }\n return `${lhs}${name}${rhs}${suffix}`;\n}\n","import type { CommandPath } from \"./types.js\";\nimport type { Choice } from \"./suggest.js\";\n\nconst repr = JSON.stringify as (str: string) => string;\n\nexport interface ErrorContext {\n path: CommandPath;\n}\n\n/** What the user typed, and the names they could have meant. */\nexport interface DidYouMean {\n input: string;\n choices: readonly Choice[];\n}\n\n/**\n * A command line the parser can't accept. `run` prints the message with the\n * help for the command at `context.path`, and suggests the closest of\n * `didYouMean.choices` if there is one.\n */\nexport class ParseError extends Error {\n readonly context: ErrorContext;\n readonly didYouMean: DidYouMean | undefined;\n constructor(context: ErrorContext, message: string, didYouMean?: DidYouMean) {\n super(message);\n this.context = context;\n this.didYouMean = didYouMean;\n this.name = this.constructor.name;\n }\n}\n\nexport class UnknownOption extends ParseError {\n readonly option: string;\n constructor(option: string, validOptions: readonly Choice[], context: ErrorContext) {\n const msg = `${repr(option)} looks like a flag, but is unknown in this context`;\n super(context, msg, { input: option, choices: validOptions });\n this.option = option;\n }\n}\n\nexport class InvalidOptionArg extends ParseError {\n readonly option: string;\n constructor(option: string, context: ErrorContext) {\n super(context, `Option ${option} doesn't take arguments`);\n this.option = option;\n }\n}\n\nexport class TooManyArguments extends ParseError {\n constructor(value: string, context: ErrorContext) {\n super(context, `Too many arguments, ${repr(value)} was unexpected`);\n }\n}\n\nexport class TooFewOptionArguments extends ParseError {\n constructor(option: string, min: number, max: number, context: ErrorContext) {\n const msg =\n min === max\n ? `Option ${option} needs ${min} argument${min === 1 ? \"\" : \"s\"}`\n : !Number.isFinite(max)\n ? `Option ${option} needs at least ${min} argument${min === 1 ? \"\" : \"s\"}`\n : `Option ${option} needs between ${min} and ${max} arguments`;\n super(context, msg);\n }\n}\n\nexport class TooFewArguments extends ParseError {\n constructor(min: number, max: number, context: ErrorContext) {\n const msg =\n min === max\n ? `Expected ${min} argument${min === 1 ? \"\" : \"s\"}`\n : !Number.isFinite(max)\n ? `Expected at least ${min} argument${min === 1 ? \"\" : \"s\"}`\n : `Expected between ${min} and ${max} arguments`;\n super(context, msg);\n }\n}\n\nexport class MissingRequiredOption extends ParseError {\n constructor(name: string, context: ErrorContext) {\n const msg = `Option ${name} is required, but wasn't found`;\n super(context, msg);\n }\n}\n","import type { Action, Arg, CommandPath, Option, Spec, Subcommand } from \"./types.js\";\nimport { addDefaults, asArray, getMaxArgs, getMinArgs } from \"./util.js\";\nimport {\n InvalidOptionArg,\n MissingRequiredOption,\n ParseError,\n TooFewArguments,\n TooFewOptionArguments,\n TooManyArguments,\n UnknownOption,\n} from \"./errors.js\";\nimport type { ErrorContext } from \"./errors.js\";\nimport type { Directives } from \"./directives.js\";\nimport { OptionScope, optionKey } from \"./scope.js\";\nimport type { OptionForm } from \"./scope.js\";\nimport { matchSubcommand, usage as builtinUsageAction, withInherited } from \"./subcommands.js\";\nimport type { NoSubcommand, SubcommandMatch } from \"./subcommands.js\";\n\nexport interface ParseResult {\n args: string[];\n argSeparatorIndex: number;\n options: Map<string, string[]>;\n /**\n * The defaults of the arguments of the option `name` refers to, for an\n * option that wasn't used. Undefined if it was used, or if its first\n * argument is optional or has no default.\n */\n defaults(name: string): string[] | undefined;\n path: CommandPath;\n /**\n * The action to run: the last option action used, or else the selected\n * command's action. A command without an action prints its help.\n */\n action: Action;\n}\n\n/** What the token after a command line can be, as the parser would read it. */\nexport interface NextToken {\n /** The commands from the root to the current one. */\n path: CommandPath;\n /** The directives in effect. */\n directives: Readonly<Directives>;\n /** Whether the token can be an option. */\n optionsAllowed: boolean;\n /**\n * The subcommands the token can name, hidden ones included. While the open\n * option can still take a value, only an exact name matches.\n */\n subcommands: readonly Subcommand[];\n /**\n * The options the token can use, hidden ones included, local options first.\n * Empty when the token can't be an option.\n */\n options: readonly UsableOption[];\n /** The open option, if the token can be its value, and whether it must be. */\n value: { option: Option; arg: Arg | undefined; required: boolean } | null;\n /** The argument the token fills if it isn't an option, subcommand or value. */\n arg: Arg | undefined;\n /**\n * The partial token, if the parser reads it as an option with a value\n * attached. `prefix` is everything before the value.\n */\n attached: { option: Option; arg: Arg; prefix: string; value: string } | null;\n}\n\n/**\n * An option the next token can use without going over its repeat limit or\n * breaking an `exclusiveOn` rule.\n */\nexport interface UsableOption {\n option: Option;\n /**\n * How each name the parser reads as this option here is written. A name\n * that another option shadows, or that a subcommand matches, isn't one of\n * them.\n */\n forms: readonly OptionForm[];\n /**\n * Whether the option was used earlier on the line. Options with the same\n * names count as the same option, like a subcommand's copy of a parent's.\n */\n used: boolean;\n}\n\n/** What the parser read one token as. See {@link readToken}. */\nexport type TokenReading =\n /** `--`, the end of options. */\n | { kind: \"separator\" }\n | { kind: \"subcommand\"; command: Subcommand }\n /**\n * One option, or several chained short options, in the order used. If the\n * token also carries a value the option accepts, `attached` says where it starts.\n */\n | { kind: \"options\"; options: readonly Option[]; attached: { option: Option; start: number } | null }\n /** A value of the option before it. */\n | { kind: \"value\"; option: Option }\n | { kind: \"argument\" }\n /** An option that doesn't exist. */\n | { kind: \"unknown\" };\n\n/** The first of `separators` that `text` starts with, or \"\" if none. */\nfunction leadingSeparator(text: string, separators: readonly string[]): string {\n for (const sep of separators) {\n if (text.startsWith(sep)) {\n return sep;\n }\n }\n return \"\";\n}\n\n/**\n * Find the separator that appears first in `token`, so the value after it can\n * contain the other separators. When two separators start at the same place,\n * the longer one wins. Returns null if there's no separator, or if the one\n * found is empty.\n */\nfunction firstSeparator(token: string, separators: readonly string[]): { index: number; sep: string } | null {\n let sep = \"\";\n let index = -1;\n for (const candidate of separators) {\n const at = token.indexOf(candidate);\n if (at === -1) {\n continue;\n }\n if (index === -1 || at < index || (at === index && candidate.length > sep.length)) {\n sep = candidate;\n index = at;\n }\n }\n return sep ? { index, sep } : null;\n}\n\n/** The values a repeatable option has collected, and how many times it's been used. */\ninterface RepeatedUses {\n values: string[];\n count: number;\n}\n\n/**\n * Throw if the options used break a `dependsOn` or `exclusiveOn` rule, or if\n * any of `required` is missing.\n */\nfunction checkOptionRules(\n options: ReadonlyMap<string, string[]>,\n seenOptions: readonly Option[],\n required: readonly Option[],\n context: ErrorContext,\n): void {\n for (const option of seenOptions) {\n if (!option.dependsOn) {\n continue;\n }\n for (const name of option.dependsOn) {\n if (!options.has(name)) {\n throw new ParseError(\n context,\n `${asArray(option.name).join(\"/\")} requires ${name}, add it to fix this error`,\n );\n }\n }\n }\n for (const option of seenOptions) {\n if (!option.exclusiveOn) {\n continue;\n }\n for (const name of option.exclusiveOn) {\n if (options.has(name)) {\n throw new ParseError(\n context,\n `${asArray(option.name).join(\"/\")} can't be used together with ${name}`,\n );\n }\n }\n }\n for (const option of required) {\n for (const name of asArray(option.name)) {\n if (!options.has(name)) {\n throw new MissingRequiredOption(name, context);\n }\n }\n }\n}\n\n/**\n * The state of reading one command line in a single pass. This is the only\n * code that decides what each input token is. When `strict`, it throws on the\n * first problem, which is what {@link parse} needs. Otherwise it never throws:\n * it skips whatever is invalid and keeps going, so {@link readNext} can still\n * read a line that's wrong at the moment. Each method handles one kind of\n * token.\n */\nclass Scanner {\n readonly path: [Spec, ...Subcommand[]];\n // The last option action used.\n private optionAction: Action | undefined = undefined;\n readonly args: string[] = [];\n readonly options: Map<string, string[]> = new Map();\n readonly seenOptions: Option[] = [];\n argSeparatorIndex = -1;\n\n // What the current command allows.\n readonly scope: OptionScope = new OptionScope();\n private subcommands: readonly Subcommand[] | undefined = undefined;\n private commandArgsMin = 0;\n private commandArgsMax = 0;\n readonly directives: Directives = this.scope.directives;\n\n hasFoundArg = false;\n\n // The last option used, and how many more separate tokens it can take as\n // values. While it has room, a token that isn't an option or `--` becomes its\n // value. A subcommand's exact name ends it unless a value is required.\n // `useOption` sets all of these and `closeOption` clears them.\n openOption: Option | null = null;\n private openOptionName = \"\";\n valueCount = 0;\n private valueMin = 0;\n private separateValueMax = 0;\n\n // The values of the last option, checked against its arity when it ends.\n // Unlike the counts above, this includes values attached with a separator.\n // A repeatable option keeps adding to the same array, so this use's values\n // start at `valuesStart`.\n private values: string[] | null = null;\n private valuesStart = 0;\n private valuesMin = 0;\n private valuesMax = 0;\n private valueArgs: readonly Arg[] = [];\n private requiredSeparator: string | boolean = false;\n\n // The first argument past the command's limit, or a subcommand that didn't\n // match. It's only an error once the whole line is read, because an option\n // action like --help allows it.\n private tooManyArgs: ParseError | null = null;\n\n // The uses of each repeatable option, keyed by `optionKey`.\n // A subcommand's copy of a parent's option has the same names, so it\n // continues the parent's uses. An option with other names, even a subset,\n // has uses of its own.\n private readonly repeatedUses: Map<string, RepeatedUses> = new Map();\n\n // The last value attached to an option's own token, and where it starts.\n private attached: { option: Option; index: number; start: number } | null = null;\n\n constructor(\n spec: Spec,\n private readonly strict: boolean,\n ) {\n this.path = [spec];\n this.enterCommand(spec);\n }\n\n private ctx(): ErrorContext {\n return { path: this.path };\n }\n\n /** Whether the open option can take the next token as a value. */\n get hasRoomForValue(): boolean {\n return this.valueCount < this.separateValueMax;\n }\n\n // Make `command` the current command.\n private enterCommand(command: Spec | Subcommand): void {\n this.scope.enter(command);\n this.subcommands = command.subcommands;\n this.commandArgsMin = getMinArgs(command.args);\n this.commandArgsMax = getMaxArgs(command.args);\n }\n\n private findOption(name: string): Option | null {\n return this.scope.resolve(name);\n }\n\n private unknownOption(option: string): UnknownOption {\n return new UnknownOption(option, this.scope.suggestionNames(), this.ctx());\n }\n\n // Every token except an option's value, or an unknown option, ends the\n // previous option. A strict read then adds the defaults of the optional\n // arguments that weren't given, so a bare `--inspect` gets its port.\n private endOption(): void {\n const values = this.values;\n if (this.strict && values) {\n const given = values.length - this.valuesStart;\n if (given < this.valuesMin) {\n throw new TooFewOptionArguments(this.openOptionName, this.valuesMin, this.valuesMax, this.ctx());\n }\n addDefaults(values, this.valueArgs, given);\n }\n this.values = null;\n }\n\n /** End the open option, so no later token can be its value. */\n private closeOption(): void {\n this.endOption();\n this.openOption = null;\n this.valueCount = this.valueMin = this.separateValueMax = 0;\n }\n\n private useOption(option: Option, name: string): void {\n this.endOption();\n this.openOption = option;\n this.openOptionName = name;\n this.valueCount = 0;\n this.valueMin = getMinArgs(option.args);\n // Options that require a separator only take attached values.\n this.separateValueMax = option.requiresSeparator ? 0 : getMaxArgs(option.args);\n this.seenOptions.push(option);\n if (option.action) {\n this.optionAction = option.action;\n }\n const names = asArray(option.name);\n const options = this.options;\n\n let optionValues: string[];\n if (option.isRepeatable) {\n // A repeatable option collects the values from every use. Without\n // arguments, each use adds an empty string, so the values count the uses.\n const maxRepeat = option.isRepeatable === true ? Infinity : option.isRepeatable;\n const key = optionKey(option);\n let uses = this.repeatedUses.get(key);\n if (!uses) {\n uses = { values: [], count: 0 };\n this.repeatedUses.set(key, uses);\n }\n if (this.strict && uses.count >= maxRepeat) {\n throw new ParseError(this.ctx(), \"Too many repetitions\");\n }\n uses.count += 1;\n // Another option may have taken one of the names since the last use.\n for (const other of names) {\n options.set(other, uses.values);\n }\n if (!option.args) {\n uses.values.push(\"\");\n return;\n }\n optionValues = uses.values;\n } else {\n // The last use of an option wins, so a user can override a flag that a\n // shell alias already sets.\n optionValues = [];\n for (const other of names) {\n options.set(other, optionValues);\n }\n }\n\n this.valuesMin = this.valueMin;\n this.valuesMax = getMaxArgs(option.args);\n this.requiredSeparator = option.requiresSeparator ?? false;\n if (this.valuesMax > 0) {\n this.values = optionValues;\n this.valuesStart = optionValues.length;\n this.valueArgs = asArray(option.args);\n }\n }\n\n /**\n * Add a value to the open option. Returns whether it's a value the option\n * accepts. A lenient read keeps going either way.\n */\n private addValue(value: string, separator: string): boolean {\n this.valueCount += 1;\n if (!this.values) {\n if (this.strict) {\n throw new InvalidOptionArg(this.openOptionName, this.ctx());\n }\n return false;\n }\n const requiredSeparator = this.requiredSeparator;\n let accepted = true;\n if (typeof requiredSeparator === \"string\" && separator !== requiredSeparator) {\n if (this.strict) {\n throw new ParseError(\n this.ctx(),\n `Incorrect separator, use '${requiredSeparator}' instead of '${separator}'`,\n );\n }\n accepted = false;\n }\n if (requiredSeparator === true && separator === \"\") {\n if (this.strict) {\n const suggested = this.scope.requiredSeparator(this.openOption!);\n throw new ParseError(\n this.ctx(),\n `Missing separator, use '${suggested}' between ${this.openOptionName} and its value`,\n );\n }\n accepted = false;\n }\n this.values.push(value);\n return accepted;\n }\n\n /**\n * Add a value attached to the option's own token, the token at `index`,\n * starting at `start`. It's the option's only value, so no later token can be\n * one.\n */\n private addAttachedValue(index: number, start: number, value: string, separator: string): void {\n if (this.addValue(value, separator)) {\n this.attached = { option: this.openOption!, index, start };\n }\n this.valueMin = this.separateValueMax = 0;\n }\n\n /**\n * Whether the command already has all the arguments it takes. A command that\n * requires a subcommand takes none.\n */\n private get argsAreFull(): boolean {\n const path = this.path;\n return path[path.length - 1].requiresSubcommand === true || this.args.length >= this.commandArgsMax;\n }\n\n private addArg(value: string): void {\n this.endOption();\n if (this.strict && this.argsAreFull) {\n this.tooManyArgs ??= new TooManyArguments(value, this.ctx());\n }\n this.args.push(value);\n }\n\n /** Read `--` and every token after it as arguments. */\n argSeparator(input: readonly string[], index: number): void {\n this.closeOption();\n // A command that requires a subcommand allows `--` alone, and reports\n // any argument after it.\n const command = this.path[this.path.length - 1];\n if (this.strict && this.argsAreFull && !command.requiresSubcommand) {\n this.tooManyArgs ??= new ParseError(\n this.ctx(),\n \"Unexpected argument '--', did you mean to use an option instead?\",\n );\n }\n this.argSeparatorIndex = this.args.length;\n for (index += 1; index < input.length; index++) {\n this.addArg(input[index]);\n }\n }\n\n /**\n * Whether the next token can name a subcommand, its own or an inherited\n * one. It can't once an argument is found, or while the open option needs\n * the next token as its value. A required or variadic option value takes\n * priority over a subcommand.\n */\n private get canMatchSubcommand(): boolean {\n if (this.hasFoundArg) {\n return false;\n }\n if (!this.subcommands && this.scope.inheritedSubcommands.length === 0) {\n return false;\n }\n return !(this.valueCount < this.valueMin || (this.hasRoomForValue && this.separateValueMax === Infinity));\n }\n\n /**\n * The subcommand the next token enters if it's `token`, or why it enters\n * none. Null if the next token can't be a subcommand at all.\n */\n private subcommandFor(token: string): SubcommandMatch | null {\n if (!this.canMatchSubcommand) {\n return null;\n }\n // A short optional value could be a prefix of a subcommand's name, so only\n // an exact match can end an option that still has room.\n return matchSubcommand(\n this.subcommands ?? [],\n token,\n this.directives,\n this.hasRoomForValue,\n this.scope.inheritedSubcommands,\n );\n }\n\n private enterSubcommand(command: Subcommand): void {\n this.closeOption();\n this.path.push(command);\n this.enterCommand(command);\n }\n\n /** Read a token like `-abc`, `+x` or `-ovalue`. */\n shortOptions(token: string, index: number): void {\n const leadingChar = token[0];\n\n // Parse as a single dash or plus with an arg. Try dash and plus options\n // first if:\n // - the options exist\n // - the options take args\n // - the first non-leading character isn't an option\n const dashOption = this.findOption(leadingChar);\n if (dashOption?.args && !this.findOption(token.slice(0, 2))) {\n this.useOption(dashOption, leadingChar);\n this.addAttachedValue(index, 1, token.slice(1), \"\");\n return;\n }\n\n // Parse as chained short options. If we got here, the option wasn't `-` or `+`.\n for (let char = 1; char < token.length; char++) {\n const optionName = leadingChar + token[char];\n const option = this.findOption(optionName);\n if (!option) {\n // An open option takes anything unknown as a value, like `-5`.\n if (char === 1 && this.hasRoomForValue) {\n this.addValue(token, \"\");\n return;\n }\n if (this.strict) {\n throw this.unknownOption(optionName);\n }\n continue;\n }\n\n this.useOption(option, optionName);\n if (char === token.length - 1) {\n return;\n }\n\n const sep = leadingSeparator(token.slice(char + 1), this.directives.optionArgSeparators);\n // An option without args still takes a separated value, so that `-v=1`\n // fails like `--verbose=1`, unless the next character is an option.\n if (option.args || (sep && !this.findOption(leadingChar + token[char + 1]))) {\n const argStart = char + sep.length + 1;\n this.addAttachedValue(index, argStart, token.slice(argStart), sep);\n return;\n }\n }\n }\n\n /**\n * Read a token like `--name` or `--name=value`, or any token when options\n * aren't POSIX compliant. Returns false if the token should be an argument.\n */\n longOption(token: string, index: number): boolean {\n const found = firstSeparator(token, this.directives.optionArgSeparators);\n const optionName = found ? token.slice(0, found.index) : token;\n const option = this.findOption(optionName);\n if (option) {\n this.useOption(option, optionName);\n if (found) {\n const valueStart = found.index + found.sep.length;\n this.addAttachedValue(index, valueStart, token.slice(valueStart), found.sep);\n }\n return true;\n }\n // POSIX-noncompliant option means that there's nothing \"option-like\". Any\n // token can be an option if it matches an option name, and if it's not an\n // option then it's just a regular argument.\n if (this.directives.flagsArePosixNoncompliant) {\n return false;\n }\n if (this.hasRoomForValue) {\n this.addValue(token, \"\");\n return true;\n }\n // The option is unknown and looks like a POSIX-compliant option, so\n // it's an unknown option instead of an arg.\n if (this.strict) {\n throw this.unknownOption(optionName);\n }\n return true;\n }\n\n /**\n * Read a token that isn't `--`, a subcommand or an option. It's a value of\n * the open option if that has room, and otherwise an argument, which stops\n * later tokens from being subcommands. `unmatched` is why the token isn't a\n * subcommand, if it could have been one.\n */\n valueOrArg(token: string, unmatched: NoSubcommand | null): void {\n if (this.hasRoomForValue) {\n this.addValue(token, \"\");\n return;\n }\n // Where a subcommand could be, a token the command has no room for is a\n // subcommand that didn't match.\n if (this.strict && unmatched && this.argsAreFull) {\n const command = this.path[this.path.length - 1];\n if (command.subcommands?.length || command.requiresSubcommand) {\n const { message, didYouMean } = unmatched.reason();\n this.tooManyArgs ??= new ParseError(this.ctx(), message, didYouMean);\n }\n }\n this.hasFoundArg = true;\n this.addArg(token);\n }\n\n /**\n * Throw if the finished command line is missing anything. Returns the action\n * to run.\n */\n finish(): Action {\n // An option with an action, like --help, works however the rest of the\n // command line is wrong, as long as every token could be read. So does the\n // usage a command shows when no subcommand is named.\n const command = this.path[this.path.length - 1];\n const showsUsage = command.requiresSubcommand && !command.action && this.args.length === 0;\n const skipsChecks = this.optionAction !== undefined || showsUsage;\n if (!skipsChecks && this.tooManyArgs) {\n throw this.tooManyArgs;\n }\n if (!skipsChecks && this.args.length < this.commandArgsMin) {\n throw new TooFewArguments(this.commandArgsMin, this.commandArgsMax, this.ctx());\n }\n this.endOption();\n if (!skipsChecks) {\n checkOptionRules(this.options, this.seenOptions, this.scope.required(), this.ctx());\n }\n // Defaults are added after the checks, so they never count as typed. An\n // option action can run with required arguments missing, and then the\n // first default would fill a required argument's place.\n if (!command.requiresSubcommand && this.args.length >= this.commandArgsMin) {\n addDefaults(this.args, asArray(command.args), this.args.length);\n }\n return this.optionAction ?? command.action ?? builtinUsageAction;\n }\n\n /** See {@link ParseResult.defaults}. */\n defaults(name: string): string[] | undefined {\n if (this.options.has(name)) {\n return undefined;\n }\n const args = asArray(this.scope.resolve(name)?.args);\n // An option whose first argument is optional, like `--inspect[=port]`,\n // means something different when it's left out than when it's bare, so\n // its defaults are only for the bare option.\n if (args.length === 0 || args[0].isOptional) {\n return undefined;\n }\n const values: string[] = [];\n addDefaults(values, args);\n return values.length > 0 ? values : undefined;\n }\n\n /** Whether using `option` next would go over its repeat limit or break an `exclusiveOn` rule. */\n private conflicts(option: Option): boolean {\n const names = asArray(option.name);\n const options = this.options;\n if (typeof option.isRepeatable === \"number\") {\n if ((this.repeatedUses.get(optionKey(option))?.count ?? 0) >= option.isRepeatable) {\n return true;\n }\n }\n if (option.exclusiveOn?.some((name) => options.has(name))) {\n return true;\n }\n return this.seenOptions.some((seen) => seen.exclusiveOn?.some((name) => names.includes(name)));\n }\n\n /** The options the next token can use. See {@link NextToken.options}. */\n private usableOptions(): UsableOption[] {\n const used = new Set(this.seenOptions.map(optionKey));\n const { local, persistent } = this.scope.live();\n const usable: UsableOption[] = [];\n for (const { option, names } of [...local, ...persistent]) {\n if (this.conflicts(option)) {\n continue;\n }\n // The parser reads a name that a subcommand matches as that subcommand.\n const typeable = names.filter((name) => !this.subcommandFor(name)?.command);\n if (typeable.length === 0) {\n continue;\n }\n usable.push({ option, forms: this.scope.forms(option, typeable), used: used.has(optionKey(option)) });\n }\n return usable;\n }\n\n /** What the next token can be. See {@link readNext}. */\n next(): Omit<NextToken, \"attached\"> {\n const open = this.openOption && this.hasRoomForValue ? this.openOption : null;\n const command = this.path[this.path.length - 1];\n // Every token after `--` is an argument.\n const afterSeparator = this.argSeparatorIndex !== -1;\n const optionsAllowed = !afterSeparator && this.optionsAllowed;\n return {\n path: this.path,\n directives: this.directives,\n optionsAllowed,\n subcommands:\n !afterSeparator && this.canMatchSubcommand\n ? withInherited(this.subcommands ?? [], this.scope.inheritedSubcommands)\n : [],\n options: optionsAllowed ? this.usableOptions() : [],\n value: open && {\n option: open,\n arg: argAt(asArray(open.args), this.valueCount),\n required: this.valueCount < this.valueMin,\n },\n arg: open ? undefined : argAt(asArray(command.args), this.args.length),\n };\n }\n\n /** Read the token at `index`, the next one, and say what it was read as. */\n readAndClassify(input: readonly string[], index: number): TokenReading {\n // Every token after `--` is an argument.\n if (this.argSeparatorIndex !== -1) {\n return { kind: \"argument\" };\n }\n const depth = this.path.length;\n const seen = this.seenOptions.length;\n const args = this.args.length;\n const values = this.valueCount;\n if (this.readAt(input, index)) {\n return { kind: \"separator\" };\n }\n if (this.path.length > depth) {\n return { kind: \"subcommand\", command: this.path[depth] as Subcommand };\n }\n if (this.seenOptions.length > seen) {\n const found = this.attachedAt(index);\n const attached = found && { option: found.option, start: found.start };\n return { kind: \"options\", options: this.seenOptions.slice(seen), attached };\n }\n if (this.args.length > args) {\n return { kind: \"argument\" };\n }\n if (this.valueCount > values) {\n return { kind: \"value\", option: this.openOption! };\n }\n return { kind: \"unknown\" };\n }\n\n /** The value attached to the token at `index`, if it has one the option accepts. */\n attachedAt(index: number): { option: Option; start: number } | null {\n return this.attached?.index === index ? this.attached : null;\n }\n\n /** Whether the next token can be an option. Once options must stop, every token is an argument. */\n get optionsAllowed(): boolean {\n return !(this.directives.optionsMustPrecedeArguments && this.hasFoundArg);\n }\n\n /** Read every token of `input`. */\n read(input: readonly string[]): void {\n for (let index = 0; index < input.length; index++) {\n if (this.readAt(input, index)) {\n return;\n }\n }\n }\n\n /**\n * Read the token at `index`. Returns true if it was `--`, which reads every\n * token after it too.\n */\n private readAt(input: readonly string[], index: number): boolean {\n const token = input[index];\n const optionsAllowed = this.optionsAllowed;\n\n // \"--\" disables option & subcommand parsing, so it's checked first.\n if (token === \"--\" && optionsAllowed) {\n this.argSeparator(input, index);\n return true;\n }\n\n const subcommand = this.subcommandFor(token);\n if (subcommand?.command) {\n this.enterSubcommand(subcommand.command);\n return false;\n }\n\n if (optionsAllowed) {\n const flagsArePosixNoncompliant = this.directives.flagsArePosixNoncompliant;\n const first = token.charCodeAt(0);\n const isDoubleDash = first === 45 /* - */ && token.charCodeAt(1) === 45;\n if (\n !flagsArePosixNoncompliant &&\n token.length > 1 &&\n (first === 45 || first === 43) /* + */ &&\n !isDoubleDash\n ) {\n this.shortOptions(token, index);\n return false;\n }\n if (flagsArePosixNoncompliant || (token.length > 2 && isDoubleDash)) {\n if (this.longOption(token, index)) {\n return false;\n }\n }\n }\n\n this.valueOrArg(token, subcommand);\n return false;\n }\n}\n\n/** The argument at `index`, reusing a final variadic argument. */\nfunction argAt(args: readonly Arg[], index: number): Arg | undefined {\n if (index < args.length) {\n return args[index];\n }\n const last = args[args.length - 1];\n return last?.isVariadic ? last : undefined;\n}\n\n/**\n * Work out what the token after `before` can be, and how the parser reads\n * `partial` if it's an option with a value attached. Reads leniently, so a\n * line that's wrong at the moment still has an answer. Completion is built on\n * this.\n */\nexport function readNext(spec: Spec, before: readonly string[], partial: string): NextToken {\n const s = new Scanner(spec, false);\n s.read(before);\n const next = s.next();\n let attached: NextToken[\"attached\"] = null;\n if (partial !== \"\" && next.optionsAllowed) {\n // Read the line again with the partial token, so `next` stays as it was.\n const reading = readToken(spec, before, partial);\n const found = reading.kind === \"options\" ? reading.attached : null;\n const arg = found && asArray(found.option.args)[0];\n if (found && arg) {\n attached = {\n option: found.option,\n arg,\n prefix: partial.slice(0, found.start),\n value: partial.slice(found.start),\n };\n }\n }\n return { ...next, attached };\n}\n\n/**\n * Say what the parser reads `token` as when it comes after `before`. Reads\n * leniently, like {@link readNext}.\n */\nexport function readToken(spec: Spec, before: readonly string[], token: string): TokenReading {\n const s = new Scanner(spec, false);\n s.read(before);\n return s.readAndClassify([...before, token], before.length);\n}\n\n/**\n * Parse the input tokens using the given CLI spec.\n *\n * This returns a `ParseResult`, which contains the array of\n * subcommands used, the provided options, the arguments, and the action to\n * run.\n *\n * If parsing fails, this function throws.\n */\nexport function parse(input: readonly string[], spec: Spec): ParseResult {\n const s = new Scanner(spec, true);\n s.read(input);\n const action = s.finish();\n return {\n path: s.path,\n action,\n args: s.args,\n argSeparatorIndex: s.argSeparatorIndex,\n options: s.options,\n defaults: (name) => s.defaults(name),\n };\n}\n","/**\n * Shell completion.\n *\n * The `completion` subcommand prints a short script for a supported shell. On\n * every Tab, that script runs the CLI's hidden `completion complete` command\n * with the command line typed so far. The CLI then works out the candidates\n * with the parser's own `readNext`, so completion always matches what the parser\n * accepts at that position: subcommands, options with their\n * relationship rules, and argument values from `template`, `suggestions` and\n * `generators`.\n *\n * @module\n */\n\nimport type { Arg, Spec, Subcommand, Template } from \"./types.js\";\nimport { makeArray, print } from \"./util.js\";\nimport { printUsageError } from \"./help.js\";\nimport { visibleSubcommands } from \"./subcommands.js\";\nimport { readNext } from \"./parse.js\";\nimport type { NextToken } from \"./parse.js\";\n\n/** Shells that {@link getCompletion} can generate scripts for. */\nexport type Shell = \"bash\" | \"zsh\" | \"fish\" | \"powershell\" | \"nushell\";\n\nexport const SHELLS: readonly Shell[] = [\"bash\", \"zsh\", \"fish\", \"powershell\", \"nushell\"];\n\nfunction isShell(value: string): value is Shell {\n return (SHELLS as readonly string[]).includes(value);\n}\n\nconst firstLine = (description: string | undefined): string =>\n description ? description.split(\"\\n\", 1)[0].trim() : \"\";\n\n/** Turn an arbitrary name into a safe shell identifier fragment. */\nconst sanitize = (value: string): string => value.replace(/[^A-Za-z0-9]+/g, \"_\");\n\n/** Single-quote a string for bash/zsh. */\nfunction shQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Single-quote a string for fish (only `\\` and `'` are special). */\nfunction fishQuote(value: string): string {\n return `'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\")}'`;\n}\n\n/** Single-quote a string for PowerShell (a quote is written twice). */\nfunction psQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Quote a string for Nushell. A single-quoted string has no escapes, so a name\n * with a quote in it is written as a double-quoted string instead.\n */\nfunction nuQuote(value: string): string {\n if (!value.includes(\"'\")) {\n return `'${value}'`;\n }\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\n// Runtime resolver {{{\n\n/** A single completion candidate. */\ninterface Candidate {\n value: string;\n description?: string;\n}\n\n/** Enumerate filesystem entries matching `partial` for a path template. */\nasync function enumeratePaths(partial: string, template: Template): Promise<Candidate[]> {\n // Imported through a variable so the Node-free `src` build doesn't need\n // @types/node; this only runs inside the (Node-only) completion runtime.\n const specifier = \"node:fs\";\n const { readdirSync } = (await import(specifier)) as {\n readdirSync(path: string, options: { withFileTypes: true }): { name: string; isDirectory(): boolean }[];\n };\n // Windows paths can use either separator. Elsewhere `\\` is part of a name.\n const isWindows = (globalThis as { process?: { platform?: string } }).process?.platform === \"win32\";\n const slash = Math.max(partial.lastIndexOf(\"/\"), isWindows ? partial.lastIndexOf(\"\\\\\") : -1);\n const dir = slash >= 0 ? partial.slice(0, slash + 1) : \"\";\n const base = slash >= 0 ? partial.slice(slash + 1) : partial;\n // A folder ends with the separator the user typed last.\n const separator = slash >= 0 ? partial[slash] : \"/\";\n const foldersOnly = template === \"folders\";\n let entries: { name: string; isDirectory(): boolean }[];\n try {\n entries = readdirSync((isWindows ? dir.replaceAll(\"\\\\\", \"/\") : dir) || \".\", { withFileTypes: true });\n } catch {\n return [];\n }\n const candidates: Candidate[] = [];\n for (const entry of entries as { name: string; isDirectory(): boolean }[]) {\n if (!entry.name.startsWith(base)) {\n continue;\n }\n const isDir = entry.isDirectory();\n if (foldersOnly && !isDir) {\n continue;\n }\n candidates.push({ value: `${dir}${entry.name}${isDir ? separator : \"\"}` });\n }\n return candidates;\n}\n\n/** All candidate values for a single argument (suggestions/generators/template). */\nasync function argValues(arg: Arg, tokens: string[], partial: string): Promise<Candidate[]> {\n const candidates: Candidate[] = [];\n\n for (const suggestion of arg.suggestions ?? []) {\n candidates.push(\n typeof suggestion === \"string\"\n ? { value: suggestion }\n : { value: makeArray(suggestion.name)[0], description: suggestion.description },\n );\n }\n\n for (const generator of makeArray(arg.generators)) {\n if (!generator.custom) {\n continue;\n }\n const produced = await generator.custom([...tokens, partial]);\n for (const suggestion of produced) {\n candidates.push(\n typeof suggestion === \"string\"\n ? { value: suggestion }\n : { value: makeArray(suggestion.name)[0], description: suggestion.description },\n );\n }\n }\n\n if (arg.template) {\n candidates.push(...(await enumeratePaths(partial, arg.template)));\n }\n\n return candidates;\n}\n\n/** Decide which kinds of candidate the word being completed can use. */\nfunction wantedCandidates(next: NextToken, req: CompletionRequest) {\n const posixNoncompliant = next.directives.flagsArePosixNoncompliant;\n // After `--`, or once options must stop, a dashed word is an argument.\n const partialIsOption =\n next.optionsAllowed && !posixNoncompliant && (req.partial.startsWith(\"-\") || req.partial.startsWith(\"+\"));\n // When gating, a dashed word completes options only; everything else completes\n // commands/positionals. Posix-noncompliant options have no dash, so they're\n // exempt and always offered alongside the other candidates.\n return {\n wantValues: !(req.gateOptions && partialIsOption),\n wantOptions: !req.gateOptions || partialIsOption || posixNoncompliant,\n };\n}\n\n/** Inputs for the runtime completion resolver. */\nexport interface CompletionRequest {\n spec: Spec;\n /** Tokens after the program name, excluding the word being completed. */\n before: readonly string[];\n /** The word being completed. */\n partial: string;\n /** Only offer options once the word being completed starts with a dash. */\n gateOptions?: boolean;\n}\n\n/**\n * Resolve completion candidates for a partial command line. The parser works\n * out what the word can be with {@link readNext}, and this offers candidates\n * for each of those.\n */\nexport async function completeRuntime(req: CompletionRequest): Promise<Candidate[]> {\n const next = readNext(req.spec, req.before, req.partial);\n const tokens = [...req.before];\n\n // The word is an option with a value attached, like `--mode=fa`.\n if (next.attached) {\n const { prefix, arg, value } = next.attached;\n const values = await argValues(arg, tokens, value);\n return values.map((candidate) => ({\n value: prefix + candidate.value,\n description: candidate.description,\n }));\n }\n\n // The open option needs this word as its value.\n if (next.value?.required) {\n return next.value.arg ? argValues(next.value.arg, tokens, req.partial) : [];\n }\n\n const candidates: Candidate[] = [];\n const { wantValues, wantOptions } = wantedCandidates(next, req);\n if (wantValues) {\n // While an option can take another value, a word that isn't an option or\n // subcommand is its value instead of an argument.\n const arg = next.value ? next.value.arg : next.arg;\n if (arg) {\n candidates.push(...(await argValues(arg, tokens, req.partial)));\n }\n for (const sub of visibleSubcommands(next.subcommands)) {\n const description = firstLine(sub.description);\n for (const token of makeArray(sub.name)) {\n candidates.push({ value: token, description });\n }\n }\n }\n if (wantOptions) {\n candidates.push(...optionCandidates(next));\n }\n return candidates;\n}\n\n/** The options a user can use next, required ones first. */\nfunction optionCandidates(next: NextToken): Candidate[] {\n const required: Candidate[] = [];\n const optional: Candidate[] = [];\n\n for (const { option, forms, used } of next.options) {\n if (option.hidden) {\n continue;\n }\n // The parser lets a later use of an option override an earlier one, but\n // that's rarely what someone wants, so an option that isn't repeatable is\n // offered once.\n if (used && !option.isRepeatable) {\n continue;\n }\n\n let description = firstLine(option.description);\n if (option.dependsOn) {\n const needs = option.dependsOn.join(\", \");\n description = description ? `${description} (requires ${needs})` : `requires ${needs}`;\n }\n if (option.isRequired) {\n description = description ? `${description} [required]` : \"[required]\";\n }\n\n // A name joined to its value by a separator is offered with the separator,\n // so the next Tab completes the value. A name joined with nothing between,\n // like `-` in `-5`, is only the option once the value is typed, so it isn't\n // offered.\n const bucket = option.isRequired ? required : optional;\n for (const { name, join } of forms) {\n if (join === \"\") {\n continue;\n }\n bucket.push({ value: name + (join ?? \"\"), description });\n }\n }\n\n return [...required, ...optional];\n}\n\n/**\n * Render the thin shim that forwards the line to `completion complete`. The\n * binary is invoked as typed (so `./pack` works) and guarded so a missing\n * command degrades to no completion instead of an error.\n */\nfunction renderRuntimeShim(spec: Spec, shell: Shell): string {\n const id = sanitize(spec.name);\n const name = spec.name;\n if (shell === \"bash\") {\n return [\n `_${id}_complete() {`,\n ` local bin=\"\\${COMP_WORDS[0]}\"`,\n ` command -v \"$bin\" >/dev/null 2>&1 || return`,\n ` local cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`,\n ` local out`,\n ` out=\"$(\"$bin\" completion complete --gate-options -- \"\\${COMP_WORDS[@]:1:COMP_CWORD-1}\" \"$cur\" 2>/dev/null | cut -f1)\"`,\n ` local IFS=$'\\\\n'`,\n ` COMPREPLY=( $(compgen -W \"$out\" -- \"$cur\") )`,\n `}`,\n `complete -F _${id}_complete ${shQuote(name)}`,\n ].join(\"\\n\");\n }\n if (shell === \"zsh\") {\n return [\n `#compdef ${name}`,\n `_${id}_complete() {`,\n ` local bin=\"$words[1]\"`,\n ` command -v \"$bin\" >/dev/null 2>&1 || return`,\n ` local -a lines`,\n ` lines=( \"\\${(@f)$(\"$bin\" completion complete -- \"\\${words[2,CURRENT-1]}\" \"\\${words[CURRENT]}\" 2>/dev/null)}\" )`,\n ` local -a disp`,\n ` local line`,\n ` for line in $lines; do disp+=( \"\\${line//$'\\\\t'/:}\" ); done`,\n ` _describe -t values ${shQuote(name)} disp`,\n `}`,\n `_${id}_complete \"$@\"`,\n ].join(\"\\n\");\n }\n if (shell === \"powershell\") {\n // PowerShell doesn't filter or quote a native command's candidates, so the\n // script does both. The arguments go through an array so that PowerShell\n // passes `--` on to the CLI. Windows PowerShell drops an empty argument,\n // so an empty word is passed as --empty-word. The word is passed and\n // matched without the quote it was opened with.\n const stringAst = \"[System.Management.Automation.Language.StringConstantExpressionAst]\";\n return [\n `Register-ArgumentCompleter -Native -CommandName ${psQuote(name)} -ScriptBlock {`,\n ` param($wordToComplete, $commandAst, $cursorPosition)`,\n ` $elements = $commandAst.CommandElements`,\n ` $first = $elements[0]`,\n ` $bin = if ($first -is ${stringAst}) { $first.Value } else { $first.Extent.Text }`,\n ` if (-not (Get-Command $bin -ErrorAction SilentlyContinue)) { return }`,\n ` $partial = $wordToComplete`,\n ` if ($partial.StartsWith(\"'\")) { $partial = $partial.Substring(1).TrimEnd(\"'\").Replace(\"''\", \"'\") }`,\n ` elseif ($partial.StartsWith('\"')) { $partial = $partial.Substring(1).TrimEnd('\"') }`,\n ` $arguments = @('completion', 'complete', '--gate-options')`,\n ` if ($partial -eq '') { $arguments += '--empty-word' }`,\n ` $arguments += '--'`,\n ` for ($i = 1; $i -lt $elements.Count; $i++) {`,\n ` $element = $elements[$i]`,\n ` if ($element.Extent.EndOffset -ge $cursorPosition) { break }`,\n ` if ($element -is ${stringAst}) {`,\n ` $arguments += $element.Value`,\n ` } else {`,\n ` $arguments += $element.Extent.Text`,\n ` }`,\n ` }`,\n ` if ($partial -ne '') { $arguments += $partial }`,\n ` & $bin @arguments 2>$null | ForEach-Object {`,\n ' $value, $description = $_ -split \"`t\", 2',\n ` if (-not $value.StartsWith($partial, [System.StringComparison]::OrdinalIgnoreCase)) { return }`,\n \" $text = if ($value -match '[\\\\s''\\\"`$&|;,(){}<>@#]') { \\\"'$($value.Replace(\\\"'\\\", \\\"''\\\"))'\\\" } else { $value }\",\n ` if (-not $description) { $description = $value }`,\n ` [System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $description)`,\n ` }`,\n `}`,\n ].join(\"\\n\");\n }\n if (shell === \"nushell\") {\n // Nushell has one completer for every external command, so the script\n // keeps the completer that was set before and hands it other commands.\n // The spans keep the quotes they were typed with, the command's included,\n // so the script removes them. A command on Windows can be typed with its\n // extension. Nushell doesn't filter or quote what an external completer\n // returns, so the script does both.\n const previous = `$__${id}_previous_completer`;\n const names = [\"\", \".exe\", \".cmd\", \".bat\"].map((extension) => nuQuote(name + extension)).join(\" \");\n return [\n `let __${id}_previous_completer = $env.config.completions.external.completer?`,\n `$env.config.completions.external.completer = {|spans|`,\n ` let words = $spans | each {|span|`,\n ` let quote = $span | str substring 0..0`,\n ` if $quote in [\"'\", '\"', '\\`'] { $span | str substring 1.. | str trim --right --char $quote } else { $span }`,\n ` }`,\n ` let command = $words.0`,\n ` if ($command | path basename) not-in [${names}] {`,\n ` return (if ${previous} != null { do ${previous} $spans })`,\n ` }`,\n ` if (which $command | is-empty) { return }`,\n ` let args = $words | skip 1`,\n ` let partial = $args | last | default \"\"`,\n ` ^$command completion complete --gate-options -- ...$args`,\n ` | complete`,\n ` | get stdout`,\n ` | lines`,\n ` | each {|line|`,\n ` let parts = $line | split row \"\\\\t\"`,\n ` { value: $parts.0, description: ($parts | get 1? | default \"\") }`,\n ` }`,\n ` | where { $in.value | str starts-with --ignore-case $partial }`,\n \" | update value {|candidate|\",\n \" let value = $candidate.value\",\n ' if ($value !~ \"[\\\\\\\\s\\'\\\\\"`$|;#()\\\\\\\\[\\\\\\\\]{}]\") {',\n \" $value\",\n ' } else if ($value | str contains \"\\'\") {',\n \" $value | to json\",\n \" } else {\",\n \" $\\\"'($value)'\\\"\",\n \" }\",\n \" }\",\n `}`,\n ].join(\"\\n\");\n }\n // fish\n return [\n `function __${id}_complete`,\n ` set -l toks (commandline -opc)`,\n ` set -l cur (commandline -ct)`,\n ` set -l bin $toks[1]`,\n ` command -q -- $bin; or test -x \"$bin\"; or return`,\n ` $bin completion complete --gate-options -- $toks[2..-1] $cur 2>/dev/null`,\n `end`,\n `complete -c ${fishQuote(name)} -f -a '(__${id}_complete)'`,\n ].join(\"\\n\");\n}\n\n// }}}\n\n/** Generate a completion script for `shell` from a CLI spec. */\nexport function getCompletion(spec: Spec, shell: Shell): string {\n return renderRuntimeShim(spec, shell);\n}\n\n// Completion commands {{{\n\n/**\n * Hidden machine-facing subcommand the `--runtime` shim calls on every Tab.\n * The tokens after `--` are the command line; the last is the word being\n * completed. Prints `value\\tdescription` lines.\n */\nconst completeCommand: Subcommand = {\n name: \"complete\",\n description: \"Resolve completion candidates for a partial command line\",\n hidden: true,\n options: [\n {\n name: \"--gate-options\",\n description: \"Only suggest options after a leading dash\",\n },\n {\n name: \"--empty-word\",\n description: \"The word being completed is empty, so every token is before it\",\n },\n ],\n args: { name: \"tokens\", isVariadic: true, isOptional: true },\n async action({ path, args, options }) {\n const spec = path[0] as Spec;\n // Windows PowerShell drops an empty argument, so its script says the word\n // is empty with --empty-word instead of passing \"\".\n const emptyWord = options.has(\"--empty-word\");\n const partial = emptyWord || args.length === 0 ? \"\" : args[args.length - 1];\n const before = emptyWord ? args : args.slice(0, -1);\n const candidates = await completeRuntime({\n spec,\n before,\n partial,\n gateOptions: options.has(\"--gate-options\"),\n });\n const lines = candidates.map((candidate) =>\n candidate.description ? `${candidate.value}\\t${candidate.description}` : candidate.value,\n );\n if (lines.length > 0) {\n print(lines.join(\"\\n\"));\n }\n return 0;\n },\n};\n\n// }}}\n\n/** A subcommand that prints a shell completion script for the whole CLI. */\nexport const completion: Subcommand = {\n name: \"completion\",\n description: \"Print a shell completion script\",\n args: {\n name: \"shell\",\n isOptional: true,\n suggestions: SHELLS,\n description: `One of: ${SHELLS.join(\", \")}`,\n },\n subcommands: [completeCommand],\n action({ path, args: [shell] }) {\n const spec = path[0] as Spec;\n if (shell === undefined) {\n print(`Supported shells: ${SHELLS.join(\", \")}`);\n return 0;\n }\n\n if (!isShell(shell)) {\n printUsageError(path, `Unsupported shell '${shell}'`, { input: shell, choices: SHELLS });\n return 1;\n }\n\n print(getCompletion(spec, shell));\n return 0;\n },\n};\n","import type { ActionInit, Spec } from \"./types.js\";\nimport { getHelp, printUsageError } from \"./help.js\";\nimport { ParseError } from \"./errors.js\";\nimport { parse } from \"./parse.js\";\nimport { printError } from \"./util.js\";\nimport type { ParseResult } from \"./parse.js\";\n\nexport { printError };\n\n/**\n * Parse argv and execute the selected action.\n *\n * The selected command's action runs unless a parsed option has an action.\n * Option actions take precedence so helpers like `--help` can run without\n * satisfying the selected command's required arguments. A command without an\n * action prints its help.\n */\nexport async function run(spec: Spec, args: readonly string[] = defaultArgs()): Promise<number> {\n let result: ParseResult;\n\n try {\n result = parse(args, spec);\n } catch (error: unknown) {\n if (error instanceof ParseError) {\n printUsageError(error.context.path, error.message, error.didYouMean);\n } else {\n printError(`${error}`);\n }\n return 1;\n }\n\n const { action, options } = result;\n const actionInit: ActionInit = {\n help: (helpOptions) => getHelp(helpOptions?.path ?? result.path, helpOptions),\n args: result.args,\n path: result.path,\n argSeparatorIndex: result.argSeparatorIndex,\n options: {\n options,\n has: (name) => options.has(name),\n get: (name) => (options.get(name) ?? result.defaults(name))?.[0],\n all: (name) => options.get(name) ?? result.defaults(name),\n count: (name) => options.get(name)?.length ?? 0,\n },\n };\n\n let exitCode: number | void;\n try {\n const actionResult = action(actionInit);\n exitCode = typeof actionResult === \"object\" ? await actionResult : actionResult;\n } catch (error) {\n printError(describeThrown(error));\n return 1;\n }\n\n return Math.min(Math.max(exitCode ?? 0, 0), 255);\n}\n\n/**\n * The message for a value an action threw. A value that isn't an Error is shown\n * as JSON where it can be, since `String` turns an object into\n * \"[object Object]\".\n */\nfunction describeThrown(value: unknown): string {\n if (value instanceof Error) {\n return value.message;\n }\n if (typeof value === \"object\" && value !== null) {\n try {\n return JSON.stringify(value);\n } catch {\n // A cycle or a BigInt, which JSON can't show.\n }\n }\n return String(value);\n}\n\nfunction defaultArgs(): readonly string[] {\n const maybeProcess = globalThis as typeof globalThis & {\n process?: { argv?: readonly string[] };\n };\n return maybeProcess.process?.argv?.slice(2) ?? [];\n}\n","export type {\n Action,\n ActionInit,\n Arg,\n CommandPath,\n Generator,\n NonEmptyArray,\n Option,\n OptionArgs,\n SingleOrArray,\n SingleOrArrayOrEmpty,\n Spec,\n Subcommand,\n Suggestion,\n Template,\n} from \"./types.js\";\n\nexport { completion } from \"./completion.js\";\nexport type { Shell } from \"./completion.js\";\nexport { help, helpCommand } from \"./help.js\";\nexport { printError, run } from \"./run.js\";\n\nimport { completion } from \"./completion.js\";\nimport { help, helpCommand } from \"./help.js\";\nimport { printError, run } from \"./run.js\";\n\nexport default {\n completion,\n help,\n helpCommand,\n printError,\n run,\n};\n"],"mappings":";AAEA,SAAgB,QAAW,GAAwC;CACjE,OAAO,MAAM,QAAQ,CAAC;AACxB;;AAGA,SAAgB,UAAa,OAA0C;CACrE,IAAI,UAAU,KAAA,GACZ,OAAO,CAAC;CAEV,IAAI,QAAQ,KAAK,GACf,OAAO,MAAM,MAAM;CAErB,OAAO,CAAC,KAAK;AACf;;;;;;AAOA,SAAgB,QAAW,OAAmD;CAC5E,IAAI,UAAU,KAAA,GACZ,OAAO,CAAC;CAEV,IAAI,QAAQ,KAAK,GACf,OAAO;CAET,OAAO,CAAC,KAAK;AACf;;AAGA,SAAgB,WAAc,OAA0C;CACtE,IAAI,QAAQ,KAAK,GAEf,OAAO,MAAM,MAAM;CAErB,OAAO,CAAC,KAAK;AACf;AAoBA,MAAM,cAAe,WAAyC;;;;;;;;;AAU9D,SAAS,QAAQ,IAAW,MAAoB;CAC9C,MAAM,KAAK,aAAa,mBAAmB,SAAS;CACpD,IAAI,CAAC,IAAI;EACP,CAAC,OAAO,IAAI,QAAQ,MAAM,QAAQ,MAAA,CAAO,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI,IAAI;EACvF;CACF;CACA,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,IAAI;EACF,OAAO,SAAS,MAAM,QACpB,UAAU,GAAG,UAAU,IAAI,OAAO,QAAQ,MAAM,SAAS,MAAM;CAEnE,SAAS,OAAO;EAGd,IAFc,MAA4B,SAE7B,UACX,CAAC,OAAO,IAAI,aAAa,SAAS,aAAa,OAAA,EAAS,MAAM,MAAM,SAAS,MAAM,CAAC;CAIxF;AACF;;;;;;AAOA,MAAa,SAAuD,EAAE,OAAO,QAAQ;;AAGrF,SAAgB,MAAM,MAAoB;CACxC,OAAO,MAAM,GAAG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5B,MAAM,aAAyB;EAC7B,OAAO,gBAAgB,QAAQ,aAAa,QAAQ,OAAO,MAAM,WAAW;EAC5E,MAAM,OAAO;EACb,MAAM,OAAO;EACb,mBAAmB,OAAO;EAC1B,SAAS;GACP;GACA,MAAM,SAAS,QAAQ,IAAI,IAAI;GAC/B,MAAM,UAAU,QAAQ,IAAI,IAAI,KAAK,OAAO,SAAS,IAAI,EAAA,GAAK;GAC9D,MAAM,SAAS,QAAQ,IAAI,IAAI,KAAK,OAAO,SAAS,IAAI;GACxD,QAAQ,SAAS,QAAQ,IAAI,IAAI,CAAC,EAAE,UAAU;EAChD;CACF;CAEA,IAAI;CACJ,IAAI;EACF,MAAM,eAAe,OAAO,UAAU;EACtC,WAAW,OAAO,iBAAiB,WAAW,MAAM,eAAe;CACrE,SAAS,OAAO;EACd,WAAW,eAAe,KAAK,CAAC;EAChC,OAAO;CACT;CAEA,OAAO,KAAK,IAAI,KAAK,IAAI,YAAY,GAAG,CAAC,GAAG,GAAG;AACjD;;;;;;AAOA,SAAS,eAAe,OAAwB;CAC9C,IAAI,iBAAiB,OACnB,OAAO,MAAM;CAEf,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ,CAER;CAEF,OAAO,OAAO,KAAK;AACrB;AAEA,SAAS,cAAiC;CAIxC,OAAOC,WAAa,SAAS,MAAM,MAAM,CAAC,KAAK,CAAC;AAClD;;ACxDA,IAAA,cAAe;CACb;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["builtinUsageAction","maybeProcess"],"sources":["../src/util.ts","../src/suggest.ts","../src/subcommands.ts","../src/directives.ts","../src/scope.ts","../src/help.ts","../src/errors.ts","../src/parse.ts","../src/completion.ts","../src/run.ts","../src/index.ts"],"sourcesContent":["import type { Arg, NonEmptyArray } from \"./types.js\";\n\nexport function isArray<T>(o: T | readonly T[]): o is readonly T[] {\n return Array.isArray(o);\n}\n\n/** Convert the value, if any, to an array with 0 or more elements */\nexport function makeArray<T>(thing: T | readonly T[] | undefined): T[] {\n if (thing === undefined) {\n return [];\n }\n if (isArray(thing)) {\n return thing.slice();\n }\n return [thing];\n}\n\n/**\n * Like {@link makeArray}, but without copying when the input is already an\n * array. Only safe when the caller treats the result as read-only — use it on\n * the hot path to avoid slicing read-only spec metadata.\n */\nexport function asArray<T>(thing: T | readonly T[] | undefined): readonly T[] {\n if (thing === undefined) {\n return [];\n }\n if (isArray(thing)) {\n return thing;\n }\n return [thing];\n}\n\n/** Convert the value to an array with at least one element */\nexport function makeArray1<T>(thing: T | NonEmptyArray<T>): [T, ...T[]] {\n if (isArray(thing)) {\n // We know that this array has at least one element in it\n return thing.slice() as [T, ...T[]];\n }\n return [thing];\n}\n\nexport function assert(expr: unknown, msg = \"\"): asserts expr {\n if (!expr) {\n throw new Error(msg);\n }\n}\n\n// Output {{{\n\ninterface WriteSyncFs {\n writeSync(fd: number, buffer: Uint8Array, offset: number, length: number): number;\n}\n\ninterface NodeProcess {\n getBuiltinModule?(id: \"node:fs\"): WriteSyncFs;\n stdout?: { write(data: Uint8Array): unknown };\n stderr?: { write(data: Uint8Array): unknown };\n}\n\nconst nodeProcess = (globalThis as { process?: NodeProcess }).process;\n\n/**\n * Write text to stdout (1) or stderr (2) with a synchronous `write` on the file\n * descriptor.\n *\n * The first `console.log` in a Node process builds the stdout stream, which\n * costs 1-3 ms. That's more than parsing takes, so all of this library's output\n * goes through here instead. Without `node:fs` it falls back to `console`.\n */\nfunction writeFd(fd: 1 | 2, text: string): void {\n const fs = nodeProcess?.getBuiltinModule?.(\"node:fs\");\n if (!fs) {\n (fd === 1 ? console.log : console.error)(text.endsWith(\"\\n\") ? text.slice(0, -1) : text);\n return;\n }\n const bytes = new TextEncoder().encode(text);\n let offset = 0;\n try {\n while (offset < bytes.length) {\n offset += fs.writeSync(fd, bytes, offset, bytes.length - offset);\n }\n } catch (error) {\n const code = (error as { code?: string }).code;\n // A non-blocking pipe that's full: let Node's stream queue the rest.\n if (code === \"EAGAIN\") {\n (fd === 1 ? nodeProcess?.stdout : nodeProcess?.stderr)?.write(bytes.subarray(offset));\n }\n // Anything else, like EPIPE from `cli --help | head -1`, is dropped, the\n // same as `console` does.\n }\n}\n\n/**\n * Where this library's output goes. Tests replace `write` to capture output.\n *\n * @internal\n */\nexport const output: { write: (fd: 1 | 2, text: string) => void } = { write: writeFd };\n\n/** Print a message to stdout, trimming trailing whitespace. */\nexport function print(text: string): void {\n output.write(1, `${text.trimEnd()}\\n`);\n}\n\n/** Print `Error:` and the given values to stderr, separated by spaces. */\nexport function printError(...strings: unknown[]): void {\n output.write(2, `${[\"Error:\", ...strings].map(String).join(\" \")}\\n`);\n}\n\n// }}}\n\n/**\n * Add the defaults of the arguments from index `from` on to `values`, stopping\n * at the first argument without one. The parser and help both use this, so\n * help only shows the defaults the parser uses.\n */\nexport function addDefaults(values: string[], args: readonly Arg[], from = 0): void {\n for (let i = from; i < args.length; i++) {\n const value = args[i].default;\n if (value === undefined) {\n return;\n }\n values.push(value);\n }\n}\n\n/**\n * Returns the minimum number of arguments that satisfies the args.\n *\n * Accepts the raw spec value (a single arg, an array, or `undefined`) so the\n * hot path doesn't have to copy it into an array first.\n */\nexport function getMinArgs(\n args: { isOptional?: boolean } | readonly { isOptional?: boolean }[] | undefined,\n): number {\n if (args === undefined) {\n return 0;\n }\n if (!isArray(args)) {\n return args.isOptional ? 0 : 1;\n }\n let count = 0;\n for (let i = 0; i < args.length; i++) {\n if (args[i].isOptional) {\n break;\n }\n count++;\n }\n return count;\n}\n\n/** Returns the maximum number of arguments that satisfies the args. */\nexport function getMaxArgs(\n args: { isVariadic?: boolean } | readonly { isVariadic?: boolean }[] | undefined,\n): number {\n if (args === undefined) {\n return 0;\n }\n if (!isArray(args)) {\n return args.isVariadic ? Infinity : 1;\n }\n // Loop over the array backwards because variadic arguments are\n // more likely to be at the end of the array. They don't _need_\n // to be, but it's more idiomatic.\n for (let i = 0; i < args.length; i++) {\n if (args[args.length - 1 - i].isVariadic) {\n return Infinity;\n }\n }\n // None of the arguments are variadic, max is the number of args\n return args.length;\n}\n","/**\n * \"Did you mean\" suggestions for unknown commands and options.\n *\n * This only runs after a mistake, but it's loaded on every run, so it's kept\n * small and does nothing until it's called.\n *\n * @module\n */\n\n/** How many `-` or `+` characters `name` starts with. */\nfunction dashCount(name: string): number {\n let i = 0;\n while (i < name.length && (name[i] === \"-\" || name[i] === \"+\")) {\n i++;\n }\n return i;\n}\n\n/** Whether every character of `short` appears in `long`, in order. */\nfunction isAbbreviation(short: string, long: string): boolean {\n let i = 0;\n for (let j = 0; j < long.length && i < short.length; j++) {\n if (long[j] === short[i]) {\n i++;\n }\n }\n return i === short.length;\n}\n\n/**\n * Levenshtein distance where swapping two adjacent characters also counts as\n * one edit (optimal string alignment). Returns `limit + 1` as soon as the\n * distance must be larger than `limit`.\n */\nfunction editDistance(a: string, b: string, limit: number): number {\n // Three rows of the usual table: two rows back, the previous row and this one.\n let before = new Uint32Array(b.length + 1);\n let previous = new Uint32Array(b.length + 1);\n let current = new Uint32Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) {\n previous[j] = j;\n }\n\n for (let i = 1; i <= a.length; i++) {\n current[0] = i;\n let rowMin = i;\n for (let j = 1; j <= b.length; j++) {\n const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);\n let d = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d = Math.min(d, before[j - 2] + 1);\n }\n current[j] = d;\n if (d < rowMin) {\n rowMin = d;\n }\n }\n // Every later row is at least this row's minimum.\n if (rowMin > limit) {\n return limit + 1;\n }\n const recycled = before;\n before = previous;\n previous = current;\n current = recycled;\n }\n return previous[b.length];\n}\n\n/**\n * A name to suggest, or every name of one command or option. The names of one\n * command or option count as one choice, so an alias can't make a match\n * ambiguous.\n */\nexport type Choice = string | readonly string[];\n\n/** The first name of the only choice with a name that `matches`, if exactly one has one. */\nfunction onlyMatch(choices: readonly Choice[], matches: (name: string) => boolean): string | undefined {\n let match: string | undefined;\n for (const choice of choices) {\n const name = (typeof choice === \"string\" ? [choice] : choice).find(matches);\n if (name === undefined) {\n continue;\n }\n if (match !== undefined) {\n return undefined;\n }\n match = name;\n }\n return match;\n}\n\n/**\n * The name the user most likely meant by `input`, or `undefined` if none is\n * close enough to be worth suggesting. In order:\n *\n * 1. The only choice that starts with the input (`--verb` for `--verbose`).\n * 2. The only choice that contains every character of the input in order, for\n * inputs of 3 or more characters (`bld` for `build`).\n * 3. The name with the fewest edits, allowing one edit per three characters\n * of the input. Leading dashes don't count toward the length or the edits.\n */\nexport function closestChoice(input: string, choices: readonly Choice[]): string | undefined {\n const inputDashes = dashCount(input);\n const bare = input.slice(inputDashes);\n\n if (bare.length >= 2) {\n const match = onlyMatch(choices, (name) => name.startsWith(input));\n if (match !== undefined) {\n return match;\n }\n }\n\n if (bare.length >= 3) {\n const match = onlyMatch(choices, (name) => isAbbreviation(bare, name.slice(dashCount(name))));\n if (match !== undefined) {\n return match;\n }\n }\n\n let best: string | undefined;\n let limit = Math.floor(bare.length / 3);\n for (const name of choices.flat()) {\n const other = name.slice(dashCount(name));\n // The length difference is a lower bound on the number of edits.\n if (Math.abs(other.length - bare.length) > limit) {\n continue;\n }\n const distance = editDistance(bare, other, limit);\n if (distance <= limit && (best === undefined || distance < limit)) {\n best = name;\n // Later names have to be strictly closer to replace this one.\n limit = distance;\n if (distance === 0) {\n break;\n }\n }\n }\n return best;\n}\n","import type { Action, Subcommand } from \"./types.js\";\nimport type { DidYouMean } from \"./errors.js\";\nimport { asArray, print } from \"./util.js\";\n\n/**\n * A token that names no subcommand. The reason is only worked out when asked\n * for, since most tokens the parser tries aren't subcommands.\n */\nexport class NoSubcommand {\n readonly command = null;\n\n /**\n * `prefixOf` are the commands `token` is a prefix of a name of, where\n * prefixes match. There is never exactly one of them.\n */\n constructor(\n private readonly subcommands: readonly Subcommand[],\n private readonly token: string,\n private readonly prefixOf: readonly Subcommand[],\n ) {}\n\n /** Why the token names none of the subcommands, as an error message and suggestions. */\n reason(): { message: string; didYouMean?: DidYouMean } {\n const token = this.token;\n if (token === \"\") {\n return { message: \"Expected a command, but the value was empty\" };\n }\n if (this.prefixOf.length > 0) {\n const possible = this.prefixOf.flatMap((command) =>\n asArray(command.name).filter((name) => name.startsWith(token)),\n );\n return { message: `Ambiguous command '${token}', could be: ${possible.join(\", \")}` };\n }\n const choices = visibleSubcommands(this.subcommands).map((command) => asArray(command.name));\n return { message: `Unknown command '${token}'`, didYouMean: { input: token, choices } };\n }\n}\n\n/** The subcommands that help, completion and suggestions show. */\nexport function visibleSubcommands(subcommands: readonly Subcommand[] | undefined): Subcommand[] {\n return subcommands?.filter((subcommand) => !subcommand.hidden) ?? [];\n}\n\n/** The action of a command that has none of its own: print the command's help. */\nexport const usage: Action = ({ help }) => {\n print(help());\n return 0;\n};\n","import type { Spec, Subcommand } from \"./types.js\";\nimport { asArray } from \"./util.js\";\n\n/** The parser directives in effect for a command, with defaults filled in. */\nexport interface Directives {\n optionArgSeparators: readonly string[];\n flagsArePosixNoncompliant: boolean;\n optionsMustPrecedeArguments: boolean;\n subcommandsMatchUniquePrefix: boolean;\n}\n\n/** The directives in effect when no command sets any. */\nexport function defaultDirectives(): Directives {\n return {\n optionArgSeparators: [\"=\"],\n flagsArePosixNoncompliant: false,\n optionsMustPrecedeArguments: false,\n subcommandsMatchUniquePrefix: false,\n };\n}\n\n/**\n * Update `directives` for entering `command`. A subcommand inherits each\n * directive until it sets its own.\n */\nexport function applyDirectives(directives: Directives, command: Spec | Subcommand): void {\n const configured = command.parserDirectives;\n if (!configured) {\n return;\n }\n if (configured.optionArgSeparators) {\n directives.optionArgSeparators = asArray(configured.optionArgSeparators);\n }\n if (typeof configured.subcommandsMatchUniquePrefix === \"boolean\") {\n directives.subcommandsMatchUniquePrefix = configured.subcommandsMatchUniquePrefix;\n }\n if (typeof configured.optionsMustPrecedeArguments === \"boolean\") {\n directives.optionsMustPrecedeArguments = configured.optionsMustPrecedeArguments;\n }\n if (typeof configured.flagsArePosixNoncompliant === \"boolean\") {\n directives.flagsArePosixNoncompliant = configured.flagsArePosixNoncompliant;\n }\n}\n","import type { Option, Spec, Subcommand } from \"./types.js\";\nimport { applyDirectives, defaultDirectives } from \"./directives.js\";\nimport type { Directives } from \"./directives.js\";\nimport { NoSubcommand } from \"./subcommands.js\";\nimport { asArray, getMaxArgs, getMinArgs } from \"./util.js\";\n\n/** The subcommand a token names, or why it names none. See {@link CommandScope.matchSubcommand}. */\nexport type SubcommandMatch = { command: Subcommand } | NoSubcommand;\n\n/**\n * How the next token can match a subcommand: by any name the command's\n * directives allow, or only by an exact name.\n */\nexport interface SubcommandMatching {\n exactOnly: boolean;\n}\n\n/** An option that can be used here, and the names that still refer to it. */\nexport interface VisibleOption {\n option: Option;\n names: string[];\n}\n\n/** How one name of an option is written with its value, at one command. */\nexport interface OptionForm {\n name: string;\n /**\n * What joins the name to the option's first value in the same token, or null\n * if the value is the next token. It's the required separator for an option\n * that requires one, and \"\" for an option named \"-\" or \"+\", which reads its\n * value straight after the name, like `-5`. It's null for an option without\n * arguments.\n */\n join: string | null;\n}\n\n/**\n * What a name means at one command on a path: the options, subcommands,\n * directives and argument limits in effect there.\n *\n * Moving to a subcommand replaces the local options and adds its persistent\n * options to the inherited ones. A name refers to one option: a local option\n * wins over a persistent one, and a later option wins over an earlier one in\n * the same list. A subcommand wins over an option where the next token can\n * name a subcommand. The parser, help, completion and the spec checker all\n * ask this module what a name refers to, so they can't disagree.\n */\nexport class CommandScope {\n /** Non-persistent options of the current command, in definition order. */\n readonly local: Option[] = [];\n /** Persistent options from every command on the path, in definition order. */\n readonly persistent: Option[] = [];\n /**\n * Persistent subcommands of the commands above the current one, nearest\n * command first, so a nearer one wins a name.\n */\n readonly inheritedSubcommands: Subcommand[] = [];\n /** The directives in effect. A subcommand inherits each until it sets its own. */\n readonly directives: Directives = defaultDirectives();\n private current: Spec | Subcommand | null = null;\n /** The fewest positional arguments the current command takes. */\n argsMin = 0;\n /** The most positional arguments the current command takes. */\n argsMax = 0;\n\n /** The scope at the last command on `path`. */\n static at(path: readonly (Spec | Subcommand)[]): CommandScope {\n const scope = new CommandScope();\n for (const command of path) {\n scope.enter(command);\n }\n return scope;\n }\n\n /** Move to `command`, a subcommand of the current one. */\n enter(command: Spec | Subcommand): void {\n const parentSubcommands = this.current?.subcommands;\n if (parentSubcommands) {\n const persistent = parentSubcommands.filter((subcommand) => subcommand.isPersistent);\n if (persistent.length > 0) {\n this.inheritedSubcommands.unshift(...persistent);\n }\n }\n this.current = command;\n this.argsMin = getMinArgs(command.args);\n this.argsMax = getMaxArgs(command.args);\n this.local.length = 0;\n if (command.options) {\n for (const option of command.options) {\n (option.isPersistent ? this.persistent : this.local).push(option);\n }\n }\n applyDirectives(this.directives, command);\n }\n\n /** The current command. */\n get command(): Spec | Subcommand {\n if (!this.current) {\n throw new Error(\"The scope hasn't entered a command\");\n }\n return this.current;\n }\n\n /** Whether the current command has subcommands of its own or inherits any. */\n get hasSubcommands(): boolean {\n return this.current?.subcommands !== undefined || this.inheritedSubcommands.length > 0;\n }\n\n /**\n * The subcommands the next token can name: the current command's own,\n * followed by each inherited one that an earlier one doesn't shadow a name\n * of. Hidden ones are included.\n */\n subcommands(): readonly Subcommand[] {\n const own = this.current?.subcommands ?? [];\n if (this.inheritedSubcommands.length === 0) {\n return own;\n }\n const all = [...own];\n for (const candidate of this.inheritedSubcommands) {\n if (!asArray(candidate.name).some((name) => all.some((earlier) => hasName(earlier.name, name)))) {\n all.push(candidate);\n }\n }\n return all;\n }\n\n /**\n * Find the subcommand `token` names: one of the current command's own, or\n * else an inherited persistent one. An exact name always wins. With\n * `subcommandsMatchUniquePrefix`, a token that's a prefix of exactly one of\n * the command's own names matches that command, unless `exactOnly`. A hidden\n * or inherited command only matches its exact name, so it can't make a\n * visible command's prefix ambiguous or take a prefix meant as an argument,\n * and an empty token is no command's prefix.\n */\n matchSubcommand(token: string, exactOnly = false): SubcommandMatch {\n const own = this.current?.subcommands ?? [];\n for (const candidate of own) {\n if (hasName(candidate.name, token)) {\n return { command: candidate };\n }\n }\n for (const candidate of this.inheritedSubcommands) {\n if (hasName(candidate.name, token)) {\n return { command: candidate };\n }\n }\n const allowPrefix = this.directives.subcommandsMatchUniquePrefix && !exactOnly;\n const matches = allowPrefix ? prefixMatches(own, token) : [];\n if (matches.length === 1) {\n return { command: matches[0] };\n }\n return new NoSubcommand(this.subcommands(), token, matches);\n }\n\n /** The option `name` refers to, if any. */\n resolve(name: string): Option | null {\n const { local, persistent } = this;\n for (let i = local.length - 1; i >= 0; i--) {\n if (hasName(local[i].name, name)) {\n return local[i];\n }\n }\n for (let i = persistent.length - 1; i >= 0; i--) {\n if (hasName(persistent[i].name, name)) {\n return persistent[i];\n }\n }\n return null;\n }\n\n /**\n * The options that can be used here, in definition order, each with only\n * its live names: the names that still refer to it. Options with every name\n * shadowed are left out. Where the next token can name a subcommand, as\n * `subcommands` says, a name that one matches is that subcommand's.\n */\n live(subcommands: SubcommandMatching | null = null): {\n local: VisibleOption[];\n persistent: VisibleOption[];\n } {\n // Which option each name refers to, built in one pass so the later and the\n // local options overwrite the ones they shadow. Same answer as `resolve`.\n const owner = new Map<string, Option>();\n for (const options of [this.persistent, this.local]) {\n for (const option of options) {\n for (const name of asArray(option.name)) {\n owner.set(name, option);\n }\n }\n }\n const pick = (options: readonly Option[]) => {\n const picked: VisibleOption[] = [];\n for (const option of options) {\n const names = asArray(option.name).filter(\n (name) =>\n owner.get(name) === option &&\n !(subcommands && this.matchSubcommand(name, subcommands.exactOnly).command),\n );\n if (names.length > 0) {\n picked.push({ option, names });\n }\n }\n return picked;\n };\n return { local: pick(this.local), persistent: pick(this.persistent) };\n }\n\n /**\n * The options a user can see at the start of the current command: the\n * {@link live} ones that aren't hidden, without the names a subcommand takes.\n */\n visible(): { local: VisibleOption[]; persistent: VisibleOption[] } {\n const { local, persistent } = this.live(this.hasSubcommands ? { exactOnly: false } : null);\n const shown = (visible: VisibleOption) => !visible.option.hidden;\n return { local: local.filter(shown), persistent: persistent.filter(shown) };\n }\n\n /** The live names of each option a user could have meant, for \"did you mean\" suggestions. */\n suggestionNames(): string[][] {\n const { local, persistent } = this.live();\n const shown = (visible: VisibleOption) => !visible.option.hidden;\n return [...local, ...persistent].filter(shown).map((visible) => visible.names);\n }\n\n /** The options that must be used, local first. */\n required(): Option[] {\n return [...this.local, ...this.persistent].filter((option) => option.isRequired);\n }\n\n /*\n * How an option is written with its value, and how the parser splits a\n * token into an option name and a value. Both use the option arg separators\n * in effect, so what help shows and completion offers is what the parser\n * reads, as long as every separator an option requires is one of them. The\n * spec checker reports one that isn't.\n */\n\n /**\n * How each of `names` is written with `option`'s value here. Help shows\n * these, completion offers them, and the spec checker reads each one back\n * through the parser.\n */\n forms(option: Option, names: readonly string[] = asArray(option.name)): OptionForm[] {\n const join = (name: string): string | null => {\n if (getMaxArgs(option.args) === 0) {\n return null;\n }\n if (option.requiresSeparator) {\n return this.requiredSeparator(option);\n }\n const glued = !this.directives.flagsArePosixNoncompliant && (name === \"-\" || name === \"+\");\n return glued ? \"\" : null;\n };\n return names.map((name) => ({ name, join: join(name) }));\n }\n\n /**\n * The separator that must come between `option` and its value, or null if\n * it can take a value as a separate token.\n */\n requiredSeparator(option: Option): string | null {\n const required = option.requiresSeparator;\n if (typeof required === \"string\") {\n return required;\n }\n return required ? (this.directives.optionArgSeparators[0] ?? \"=\") : null;\n }\n\n /** Whether the parser splits an option from its value at `separator` here. */\n readsSeparator(separator: string): boolean {\n return this.directives.optionArgSeparators.includes(separator);\n }\n\n /** The separator that `text` starts with, or \"\" if none. Used after a short option. */\n leadingSeparator(text: string): string {\n for (const separator of this.directives.optionArgSeparators) {\n if (text.startsWith(separator)) {\n return separator;\n }\n }\n return \"\";\n }\n\n /**\n * The separator that appears first in `token`, so the value after it can\n * contain the other separators. When two separators start at the same place,\n * the longer one wins. Null if there's none, or if the one found is empty.\n */\n firstSeparator(token: string): { index: number; separator: string } | null {\n let found = \"\";\n let index = -1;\n for (const candidate of this.directives.optionArgSeparators) {\n const at = token.indexOf(candidate);\n if (at === -1) {\n continue;\n }\n if (index === -1 || at < index || (at === index && candidate.length > found.length)) {\n found = candidate;\n index = at;\n }\n }\n return found ? { index, separator: found } : null;\n }\n\n /**\n * Why `option`, used as `name`, can't take a value given after `separator`,\n * or null if it can. A separate token has the separator \"\".\n */\n separatorProblem(option: Option, name: string, separator: string): string | null {\n const required = option.requiresSeparator;\n if (typeof required === \"string\" && separator !== required) {\n return `Incorrect separator, use '${required}' instead of '${separator}'`;\n }\n if (required === true && separator === \"\") {\n return `Missing separator, use '${this.requiredSeparator(option)}' between ${name} and its value`;\n }\n return null;\n }\n}\n\nconst optionKeys = new WeakMap<Option, string>();\n\n/**\n * A key for the set of `option`'s names. Options with the same names, in any\n * order, get the same key and are one option: the parser continues a\n * repeatable option's uses across them, counts one as used when the other was,\n * and stores their values under the same names, which is how they're read.\n * Options that share only some names are different options, and each shared\n * name refers to whichever one `resolve` picks.\n */\nexport function optionKey(option: Option): string {\n let key = optionKeys.get(option);\n if (key === undefined) {\n key = typeof option.name === \"string\" ? option.name : [...option.name].sort().join(\"\\0\");\n optionKeys.set(option, key);\n }\n return key;\n}\n\nfunction hasName(names: string | readonly string[], name: string): boolean {\n return typeof names === \"string\" ? names === name : names.includes(name);\n}\n\n/** The visible commands that `token` is a prefix of a name of, each listed once. */\nfunction prefixMatches(subcommands: readonly Subcommand[], token: string): Subcommand[] {\n if (token === \"\") {\n return [];\n }\n return subcommands.filter(\n (candidate) => !candidate.hidden && asArray(candidate.name).some((name) => name.startsWith(token)),\n );\n}\n","import type { Arg, Option, NonEmptyArray, Subcommand } from \"./types.js\";\nimport { closestChoice } from \"./suggest.js\";\nimport { visibleSubcommands } from \"./subcommands.js\";\nimport { CommandScope } from \"./scope.js\";\nimport type { OptionForm, VisibleOption } from \"./scope.js\";\nimport type { DidYouMean } from \"./errors.js\";\nimport { addDefaults, asArray, getMaxArgs, makeArray, makeArray1, print, printError } from \"./util.js\";\n\nfunction dedent(str: string) {\n if (str[0] !== \"\\n\") {\n return str;\n }\n const lines = str.split(\"\\n\").slice(1, -1);\n const margin = lines[0].length - lines[0].trimStart().length;\n return lines.map((line) => line.slice(margin)).join(\"\\n\");\n}\n\nexport interface HelpConfig {\n /** Include the command description? Default: true. */\n description?: boolean;\n\n /** Include the usage summary? Default: true. */\n usage?: boolean;\n\n /** Ask if the user intended the input to be one of these choices. */\n didYouMean?: DidYouMean;\n}\n\n/** Get the help message used by the built-in help option and command. */\nexport function getHelp(path: NonEmptyArray<Subcommand>, config: HelpConfig = {}): string {\n const { description = true, usage = true, didYouMean } = config;\n const sections = getSections(path);\n if (didYouMean) {\n sections.didYouMean = closestChoice(didYouMean.input, didYouMean.choices);\n }\n if (!description) {\n sections.description = undefined;\n }\n if (!usage) {\n sections.usage = undefined;\n }\n return formatHelpSections(sections);\n}\n\n/**\n * Print `message` as an error, then the usage and flags of the last command on\n * `path`, suggesting the closest of `didYouMean.choices` if one is close.\n */\nexport function printUsageError(\n path: NonEmptyArray<Subcommand>,\n message: string,\n didYouMean?: DidYouMean,\n): void {\n printError(`${message}\\n\\n${getHelp(path, { description: false, didYouMean })}`);\n}\n\n/**\n * A subcommand that prints help for its parent, or for the command the names\n * after it lead to from there, so `cli help a b` prints the help of `cli a b`.\n * It reads names until one isn't a subcommand. A token where the command takes\n * arguments, or where it has no subcommands, ends the names, so\n * `cli help completion zsh` prints the help of `completion`. Any other token\n * is an unknown command. Add `{ ...helpCommand, isPersistent: true }` instead\n * to make `cli a b help` work too.\n */\nexport const helpCommand: Subcommand = {\n name: \"help\",\n description: \"Print a help message\",\n args: {\n name: \"command\",\n isOptional: true,\n isVariadic: true,\n },\n action({ path, args, help }) {\n const self = path[path.length - 1];\n const helpPath = path.slice(0, -1) as unknown as [Subcommand, ...Subcommand[]];\n // Match each name the way the parser would have matched it in place of `help`.\n const scope = CommandScope.at(helpPath);\n\n for (const name of args) {\n const command = helpPath[helpPath.length - 1];\n if (!command.subcommands) {\n break;\n }\n const match = scope.matchSubcommand(name);\n // With a persistent help command, `cli help a help` is `cli a help`.\n if (match.command === self && !command.subcommands.includes(self)) {\n break;\n }\n if (match.command) {\n helpPath.push(match.command);\n scope.enter(match.command);\n continue;\n }\n if (!command.requiresSubcommand && getMaxArgs(command.args) > 0) {\n break;\n }\n const { message, didYouMean } = match.reason();\n printUsageError(helpPath, message, didYouMean);\n return 1;\n }\n\n print(help({ path: helpPath }));\n return 0;\n },\n};\n\n/** A persistent help option that prints help for the selected command. */\nexport const help: Option = {\n name: [\"-h\", \"--help\"],\n description: \"Print a help message\",\n isPersistent: true,\n action({ path }) {\n print(formatHelpSections(getSections(path)));\n return 0;\n },\n};\n\ntype HelpSections = {\n description?: string;\n usage?: string;\n didYouMean?: string;\n args: [name: string, description: string][];\n options: [formattedName: string, description: string][];\n persistentOptions: [formattedName: string, description: string][];\n subcommands: [formattedName: string, description: string][];\n};\n\nfunction getSubcommandPathString(commands: NonEmptyArray<Subcommand>): string {\n return commands.map((command) => getLongestString(makeArray1(command.name))).join(\" \");\n}\n\nfunction getSections(commands: NonEmptyArray<Subcommand>): HelpSections {\n const command = commands[commands.length - 1];\n const scope = CommandScope.at(commands);\n const show = ({ option, names }: VisibleOption) => optionToString(option, scope.forms(option, names));\n\n const description = command.description;\n const defaultDesc = \"No description\";\n\n const subcommands: HelpSections[\"subcommands\"] = visibleSubcommands(command.subcommands).map(\n (subcommand) => [\n makeArray1(subcommand.name)\n .sort((a, b) => a.length - b.length)\n .join(\", \"),\n subcommand.description ?? defaultDesc,\n ],\n );\n\n const visible = scope.visible();\n let optionObjects = visible.local;\n let persistentOptionObjects = visible.persistent;\n // A command without parents or subcommands has no global flags to set apart.\n if (commands.length === 1 && subcommands.length === 0) {\n const byOption = new Map([...optionObjects, ...persistentOptionObjects].map((v) => [v.option, v]));\n optionObjects = (command.options ?? []).flatMap((option) => byOption.get(option) ?? []);\n persistentOptionObjects = [];\n }\n const row = (visible: VisibleOption): [string, string] => {\n const defaults: string[] = [];\n addDefaults(defaults, asArray(visible.option.args));\n return [show(visible), withDefaults(visible.option.description, defaults, defaultDesc)];\n };\n const options = optionObjects.map(row);\n const persistentOptions = persistentOptionObjects.map(row);\n\n const usage = (() => {\n const parts = [getSubcommandPathString(commands)];\n for (const visible of [...optionObjects, ...persistentOptionObjects]) {\n if (visible.option.isRequired) {\n parts.push(show(visible));\n }\n }\n if (options.length || persistentOptions.length) {\n parts.push(\"[flags]\");\n }\n if (command.requiresSubcommand) {\n parts.push(\"<command>\");\n } else {\n const args = makeArray(command.args);\n if (args.length > 0) {\n parts.push(summarizeArguments(args));\n }\n }\n return parts.join(\" \");\n })();\n\n // The positional arguments are only listed when there's more to say about\n // them than the usage line does. An argument's name is often description\n // enough, so one without a description is listed by name alone.\n const positionals = command.requiresSubcommand ? [] : asArray(command.args);\n const described = positionals.some((arg) => arg.description !== undefined || arg.default !== undefined);\n const args: HelpSections[\"args\"] = described\n ? positionals.map((arg) => [\n (arg.name || \"argument\") + (arg.isVariadic ? \"...\" : \"\"),\n withDefaults(arg.description, arg.default === undefined ? [] : [arg.default], \"\"),\n ])\n : [];\n\n return {\n usage,\n description,\n args,\n persistentOptions,\n options,\n subcommands,\n };\n}\n\n/**\n * A description ending with the defaults the parser uses. They go on a line of\n * their own when the last line would be too long for the 68 characters the\n * spec checks allow.\n */\nfunction withDefaults(\n description: string | undefined,\n defaults: readonly string[],\n defaultDesc: string,\n): string {\n if (defaults.length === 0) {\n return description ?? defaultDesc;\n }\n const shown = `(default: ${defaults.join(\" \")})`;\n if (description === undefined) {\n return shown;\n }\n const lastLine = description.slice(description.lastIndexOf(\"\\n\") + 1);\n return `${description}${lastLine.length + 1 + shown.length <= 68 ? \" \" : \"\\n\"}${shown}`;\n}\n\nexport function formatHelpSections(sections: HelpSections): string {\n const parts = [];\n\n const indent = \" \";\n\n if (sections.didYouMean) {\n parts.push(` Did you mean '${sections.didYouMean}'?`);\n }\n\n if (sections.description) {\n parts.push(dedent(sections.description));\n }\n\n if (sections.usage) {\n parts.push(`Usage:\\n${indent}${sections.usage}`);\n }\n\n const longestOptionName = Math.max(\n 0,\n ...sections.options.map(([name]) => name.length),\n ...sections.persistentOptions.map(([name]) => name.length),\n );\n const minSpacingBetweenNameAndDesc = 2;\n\n // Each name, then its description in a column `width` wide names leave.\n const formatRows = (rows: [string, string][], width: number) => {\n const lines = [];\n const newline = indent + \" \".repeat(width + minSpacingBetweenNameAndDesc);\n for (const [name, desc] of rows) {\n if (desc === \"\") {\n lines.push(`${indent}${name}`);\n continue;\n }\n const spaces = \" \".repeat(width - name.length + minSpacingBetweenNameAndDesc);\n const [head, ...tail] = desc.split(\"\\n\");\n const description = [head, ...tail.map((line) => newline + line)].join(\"\\n\");\n lines.push(`${indent}${name}${spaces}${description}`);\n }\n return lines;\n };\n const formatOptions = (options: [string, string][]) => formatRows(options, longestOptionName);\n\n if (sections.args.length > 0) {\n const longestArgName = Math.max(...sections.args.map(([name]) => name.length));\n parts.push([\"Arguments:\", ...formatRows(sections.args, longestArgName)].join(\"\\n\"));\n }\n\n if (sections.subcommands.length > 0) {\n const lines = [\"Commands:\"];\n const longestName = Math.max(...sections.subcommands.map(([name]) => name.length));\n const newline = indent + \" \".repeat(longestName + minSpacingBetweenNameAndDesc);\n for (const [name, desc] of sections.subcommands) {\n const spaces = \" \".repeat(longestName - name.length + minSpacingBetweenNameAndDesc);\n const [head, ...tail] = desc.split(\"\\n\\n\")[0].split(\"\\n\");\n const description = [head, ...tail.map((line) => newline + line)].join(\"\\n\");\n lines.push(`${indent}${name}${spaces}${description}`);\n }\n parts.push(lines.join(\"\\n\"));\n }\n\n if (sections.options.length > 0) {\n const lines = [\"Flags:\", ...formatOptions(sections.options)];\n parts.push(lines.join(\"\\n\"));\n }\n\n if (sections.persistentOptions.length > 0) {\n const lines = [\"Global flags:\", ...formatOptions(sections.persistentOptions)];\n parts.push(lines.join(\"\\n\"));\n }\n return parts.join(\"\\n\\n\") + \"\\n\";\n}\n\nexport function getLongestString(strings: NonEmptyArray<string>): string {\n let longest = strings[0];\n for (let i = 1; i < strings.length; i++) {\n const string = strings[i];\n if (string.length > longest.length) {\n longest = string;\n }\n }\n return longest;\n}\n\n/**\n * Show an option's names, each written with its arguments the way `forms`\n * says. Names written the same way share one copy of the arguments.\n */\nexport function optionToString(option: Option, forms: readonly OptionForm[]): string {\n const optionArgs = makeArray(option.args);\n const sorted = [...forms].sort((a, b) => a.name.length - b.name.length);\n const joins = [...new Set(sorted.map((form) => form.join))];\n return joins\n .map((join) => {\n const names = sorted.filter((form) => form.join === join).map((form) => form.name);\n return names.join(\", \") + argumentsAfterName(optionArgs, join);\n })\n .join(\", \");\n}\n\n/** The text after an option's name that shows its arguments, joined to the name by `join`. */\nfunction argumentsAfterName(args: Arg[], join: string | null): string {\n if (args.length === 0) {\n return \"\";\n }\n if (join === null) {\n return ` ${summarizeArguments(args)}`;\n }\n const [first, ...rest] = args;\n const name = first.name || \"argument\";\n const joined =\n (first.isOptional ? `[${join}${name}]` : `${join}<${name}>`) + (first.isVariadic ? \"...\" : \"\");\n return rest.length > 0 ? `${joined} ${summarizeArguments(rest)}` : joined;\n}\n\nexport function summarizeArguments(args: Arg[]) {\n return args.map((arg) => argToString(arg)).join(\" \");\n}\n\nexport function argToString(arg: Arg): string {\n const name = arg.name || \"argument\";\n let lhs = \"<\";\n let rhs = \">\";\n let suffix = \"\";\n if (arg.isOptional) {\n lhs = \"[\";\n rhs = \"]\";\n }\n if (arg.isVariadic) {\n suffix = \"...\";\n }\n return `${lhs}${name}${rhs}${suffix}`;\n}\n","import type { CommandPath } from \"./types.js\";\nimport type { Choice } from \"./suggest.js\";\n\nconst repr = JSON.stringify as (str: string) => string;\n\nexport interface ErrorContext {\n path: CommandPath;\n}\n\n/** What the user typed, and the names they could have meant. */\nexport interface DidYouMean {\n input: string;\n choices: readonly Choice[];\n}\n\n/**\n * A command line the parser can't accept. `run` prints the message with the\n * help for the command at `context.path`, and suggests the closest of\n * `didYouMean.choices` if there is one.\n */\nexport class ParseError extends Error {\n readonly context: ErrorContext;\n readonly didYouMean: DidYouMean | undefined;\n constructor(context: ErrorContext, message: string, didYouMean?: DidYouMean) {\n super(message);\n this.context = context;\n this.didYouMean = didYouMean;\n this.name = this.constructor.name;\n }\n}\n\nexport class UnknownOption extends ParseError {\n readonly option: string;\n constructor(option: string, validOptions: readonly Choice[], context: ErrorContext) {\n const msg = `${repr(option)} looks like a flag, but is unknown in this context`;\n super(context, msg, { input: option, choices: validOptions });\n this.option = option;\n }\n}\n\nexport class InvalidOptionArg extends ParseError {\n readonly option: string;\n constructor(option: string, context: ErrorContext) {\n super(context, `Option ${option} doesn't take arguments`);\n this.option = option;\n }\n}\n\nexport class TooManyArguments extends ParseError {\n constructor(value: string, context: ErrorContext) {\n super(context, `Too many arguments, ${repr(value)} was unexpected`);\n }\n}\n\nexport class TooFewOptionArguments extends ParseError {\n constructor(option: string, min: number, max: number, context: ErrorContext) {\n const msg =\n min === max\n ? `Option ${option} needs ${min} argument${min === 1 ? \"\" : \"s\"}`\n : !Number.isFinite(max)\n ? `Option ${option} needs at least ${min} argument${min === 1 ? \"\" : \"s\"}`\n : `Option ${option} needs between ${min} and ${max} arguments`;\n super(context, msg);\n }\n}\n\nexport class TooFewArguments extends ParseError {\n constructor(min: number, max: number, context: ErrorContext) {\n const msg =\n min === max\n ? `Expected ${min} argument${min === 1 ? \"\" : \"s\"}`\n : !Number.isFinite(max)\n ? `Expected at least ${min} argument${min === 1 ? \"\" : \"s\"}`\n : `Expected between ${min} and ${max} arguments`;\n super(context, msg);\n }\n}\n\nexport class MissingRequiredOption extends ParseError {\n constructor(name: string, context: ErrorContext) {\n const msg = `Option ${name} is required, but wasn't found`;\n super(context, msg);\n }\n}\n","import type { Action, Arg, CommandPath, Option, Spec, Subcommand } from \"./types.js\";\nimport { addDefaults, asArray, getMaxArgs, getMinArgs } from \"./util.js\";\nimport {\n InvalidOptionArg,\n MissingRequiredOption,\n ParseError,\n TooFewArguments,\n TooFewOptionArguments,\n TooManyArguments,\n UnknownOption,\n} from \"./errors.js\";\nimport type { ErrorContext } from \"./errors.js\";\nimport type { Directives } from \"./directives.js\";\nimport { CommandScope, optionKey } from \"./scope.js\";\nimport type { OptionForm, SubcommandMatch, SubcommandMatching } from \"./scope.js\";\nimport { usage as builtinUsageAction } from \"./subcommands.js\";\nimport type { NoSubcommand } from \"./subcommands.js\";\n\nexport interface ParseResult {\n args: string[];\n argSeparatorIndex: number;\n options: Map<string, string[]>;\n /**\n * The defaults of the arguments of the option `name` refers to, for an\n * option that wasn't used. Undefined if it was used, or if its first\n * argument is optional or has no default.\n */\n defaults(name: string): string[] | undefined;\n path: CommandPath;\n /**\n * The action to run: the last option action used, or else the selected\n * command's action. A command without an action prints its help.\n */\n action: Action;\n}\n\n/** What the token after a command line can be, as the parser would read it. */\nexport interface NextToken {\n /** The commands from the root to the current one. */\n path: CommandPath;\n /** The directives in effect. */\n directives: Readonly<Directives>;\n /** Whether the token can be an option. */\n optionsAllowed: boolean;\n /**\n * The subcommands the token can name, hidden ones included. While the open\n * option can still take a value, only an exact name matches.\n */\n subcommands: readonly Subcommand[];\n /**\n * The options the token can use, hidden ones included, local options first.\n * Empty when the token can't be an option.\n */\n options: readonly UsableOption[];\n /** The open option, if the token can be its value, and whether it must be. */\n value: { option: Option; arg: Arg | undefined; required: boolean } | null;\n /** The argument the token fills if it isn't an option, subcommand or value. */\n arg: Arg | undefined;\n /**\n * The partial token, if the parser reads it as an option with a value\n * attached. `prefix` is everything before the value.\n */\n attached: { option: Option; arg: Arg; prefix: string; value: string } | null;\n /**\n * Whether the parser reads the partial token as an option, known or\n * unknown, or as `--`. If it doesn't, the token is a value, argument or\n * subcommand.\n */\n partialIsOption: boolean;\n}\n\n/**\n * An option the next token can use without going over its repeat limit or\n * breaking an `exclusiveOn` rule.\n */\nexport interface UsableOption {\n option: Option;\n /**\n * How each name the parser reads as this option here is written. A name\n * that another option shadows, or that a subcommand matches, isn't one of\n * them.\n */\n forms: readonly OptionForm[];\n /**\n * Whether the option was used earlier on the line. Options with the same\n * names count as the same option, like a subcommand's copy of a parent's.\n */\n used: boolean;\n}\n\n/** What the parser read one token as. See {@link readToken}. */\nexport type TokenReading =\n /** `--`, the end of options. */\n | { kind: \"separator\" }\n | { kind: \"subcommand\"; command: Subcommand }\n /**\n * One option, or several chained short options, in the order used. If the\n * token also carries a value the option accepts, `attached` says where it starts.\n */\n | { kind: \"options\"; options: readonly Option[]; attached: { option: Option; start: number } | null }\n /** A value of the option before it. */\n | { kind: \"value\"; option: Option }\n | { kind: \"argument\" }\n /** An option that doesn't exist. */\n | { kind: \"unknown\" };\n\n/** The values a repeatable option has collected, and how many times it's been used. */\ninterface RepeatedUses {\n values: string[];\n count: number;\n}\n\n/** How many times `option` can be used. */\nfunction repeatLimit(option: Option): number {\n return typeof option.isRepeatable === \"number\" ? option.isRepeatable : Infinity;\n}\n\n/**\n * Throw if the options used break a `dependsOn` or `exclusiveOn` rule, or if\n * any of `required` is missing.\n */\nfunction checkOptionRules(\n options: ReadonlyMap<string, string[]>,\n seenOptions: readonly Option[],\n required: readonly Option[],\n context: ErrorContext,\n): void {\n for (const option of seenOptions) {\n if (!option.dependsOn) {\n continue;\n }\n for (const name of option.dependsOn) {\n if (!options.has(name)) {\n throw new ParseError(\n context,\n `${asArray(option.name).join(\"/\")} requires ${name}, add it to fix this error`,\n );\n }\n }\n }\n for (const option of seenOptions) {\n if (!option.exclusiveOn) {\n continue;\n }\n for (const name of option.exclusiveOn) {\n if (options.has(name)) {\n throw new ParseError(\n context,\n `${asArray(option.name).join(\"/\")} can't be used together with ${name}`,\n );\n }\n }\n }\n for (const option of required) {\n for (const name of asArray(option.name)) {\n if (!options.has(name)) {\n throw new MissingRequiredOption(name, context);\n }\n }\n }\n}\n\n/** Reads a command line one token at a time. See {@link tokenReader}. */\nexport interface TokenReader {\n /** Read the next token of the line, and say what it was read as. */\n read(token: string): TokenReading;\n}\n\n/**\n * The state of reading one command line, one token at a time. This is the\n * only code that decides what each input token is. It never throws: it skips\n * whatever is invalid and keeps going, so {@link readNext} can still read a\n * line that's wrong at the moment, and it keeps the first problem it finds for\n * {@link parse} to throw. Each method handles one kind of token, and says what\n * the token was read as.\n */\nclass Scanner implements TokenReader {\n private readonly path: [Spec, ...Subcommand[]];\n // The last option action used.\n private optionAction: Action | undefined = undefined;\n private readonly args: string[] = [];\n private readonly options: Map<string, string[]> = new Map();\n private readonly seenOptions: Option[] = [];\n private argSeparatorIndex = -1;\n\n // What the current command allows.\n private readonly scope: CommandScope = new CommandScope();\n private readonly directives: Directives = this.scope.directives;\n\n private hasFoundArg = false;\n\n // The last option used, and how many more separate tokens it can take as\n // values. While it has room, a token that isn't an option or `--` becomes its\n // value. A subcommand's exact name ends it unless a value is required.\n // `useOption` sets all of these and `closeOption` clears them.\n private openOption: Option | null = null;\n private openOptionName = \"\";\n private valueCount = 0;\n private valueMin = 0;\n private separateValueMax = 0;\n\n // The values of the last option, checked against its arity when it ends.\n // Unlike the counts above, this includes values attached with a separator.\n // A repeatable option keeps adding to the same array, so this use's values\n // start at `valuesStart`.\n private values: string[] | null = null;\n private valuesStart = 0;\n private valuesMin = 0;\n private valuesMax = 0;\n private valueArgs: readonly Arg[] = [];\n\n /**\n * Makes the error for the first token that can't be read the way it's\n * written, like an unknown option or a value an option doesn't take.\n * {@link parse} stops there.\n */\n problem: (() => ParseError) | null = null;\n\n // The first argument past the command's limit, or a subcommand that didn't\n // match. It's only an error once the whole line is read, because an option\n // action like --help allows it.\n private tooManyArgs: (() => ParseError) | null = null;\n\n // The uses of each repeatable option, keyed by `optionKey`.\n // A subcommand's copy of a parent's option has the same names, so it\n // continues the parent's uses. An option with other names, even a subset,\n // has uses of its own.\n private readonly repeatedUses: Map<string, RepeatedUses> = new Map();\n\n constructor(spec: Spec) {\n this.path = [spec];\n this.scope.enter(spec);\n }\n\n // A copy of the path, since reading carries on after a problem and can\n // enter a subcommand before the error is made.\n private ctx(): ErrorContext {\n return { path: [...this.path] };\n }\n\n /** Whether the open option can take the next token as a value. */\n private get hasRoomForValue(): boolean {\n return this.valueCount < this.separateValueMax;\n }\n\n private findOption(name: string): Option | null {\n return this.scope.resolve(name);\n }\n\n /**\n * Keep the problem `make` describes if it's the first. The error is only\n * made if {@link parse} throws it, since a lenient read never needs it and\n * an error is slow to make. So `make` can't read anything later tokens change.\n */\n private fail(make: (ctx: ErrorContext) => ParseError): void {\n if (!this.problem) {\n const ctx = this.ctx();\n this.problem = () => make(ctx);\n }\n }\n\n /** Keep the first argument the command has no room for, like {@link fail}. */\n private failArgs(make: (ctx: ErrorContext) => ParseError): void {\n if (!this.tooManyArgs) {\n const ctx = this.ctx();\n this.tooManyArgs = () => make(ctx);\n }\n }\n\n private unknownOption(option: string): void {\n if (!this.problem) {\n const names = this.scope.suggestionNames();\n this.fail((ctx) => new UnknownOption(option, names, ctx));\n }\n }\n\n // Every token except an option's value, or an unknown option, ends the\n // previous option. Then the defaults of the optional arguments that weren't\n // given are added, so a bare `--inspect` gets its port.\n private endOption(): void {\n const values = this.values;\n if (values) {\n const given = values.length - this.valuesStart;\n if (given < this.valuesMin) {\n const { openOptionName, valuesMin, valuesMax } = this;\n this.fail((ctx) => new TooFewOptionArguments(openOptionName, valuesMin, valuesMax, ctx));\n } else {\n addDefaults(values, this.valueArgs, given);\n }\n }\n this.values = null;\n }\n\n /** End the open option, so no later token can be its value. */\n private closeOption(): void {\n this.endOption();\n this.openOption = null;\n this.valueCount = this.valueMin = this.separateValueMax = 0;\n }\n\n private useOption(option: Option, name: string): void {\n this.endOption();\n this.openOption = option;\n this.openOptionName = name;\n this.valueCount = 0;\n this.valueMin = getMinArgs(option.args);\n // Options that require a separator only take attached values.\n this.separateValueMax = option.requiresSeparator ? 0 : getMaxArgs(option.args);\n this.seenOptions.push(option);\n if (option.action) {\n this.optionAction = option.action;\n }\n const names = asArray(option.name);\n const options = this.options;\n\n let optionValues: string[];\n if (option.isRepeatable) {\n // A repeatable option collects the values from every use. Without\n // arguments, each use adds an empty string, so the values count the uses.\n const key = optionKey(option);\n let uses = this.repeatedUses.get(key);\n if (!uses) {\n uses = { values: [], count: 0 };\n this.repeatedUses.set(key, uses);\n }\n if (uses.count >= repeatLimit(option)) {\n this.fail((ctx) => new ParseError(ctx, \"Too many repetitions\"));\n }\n uses.count += 1;\n // Another option may have taken one of the names since the last use.\n for (const other of names) {\n options.set(other, uses.values);\n }\n if (!option.args) {\n uses.values.push(\"\");\n return;\n }\n optionValues = uses.values;\n } else {\n // The last use of an option wins, so a user can override a flag that a\n // shell alias already sets.\n optionValues = [];\n for (const other of names) {\n options.set(other, optionValues);\n }\n }\n\n this.valuesMin = this.valueMin;\n this.valuesMax = getMaxArgs(option.args);\n if (this.valuesMax > 0) {\n this.values = optionValues;\n this.valuesStart = optionValues.length;\n this.valueArgs = asArray(option.args);\n }\n }\n\n /** Add a value to the open option. Returns whether it's a value the option accepts. */\n private addValue(value: string, separator: string): boolean {\n this.valueCount += 1;\n if (!this.values) {\n const name = this.openOptionName;\n this.fail((ctx) => new InvalidOptionArg(name, ctx));\n return false;\n }\n const problem = this.scope.separatorProblem(this.openOption!, this.openOptionName, separator);\n if (problem) {\n this.fail((ctx) => new ParseError(ctx, problem));\n }\n this.values.push(value);\n return problem === null;\n }\n\n /** Add a separate token as a value of the open option. */\n private value(token: string): TokenReading {\n this.addValue(token, \"\");\n return { kind: \"value\", option: this.openOption! };\n }\n\n /**\n * Add a value attached to the option's own token, starting at `start`. It's\n * the option's only value, so no later token can be one. Returns where the\n * value starts, or null if the option doesn't accept it.\n */\n private addAttachedValue(\n start: number,\n value: string,\n separator: string,\n ): { option: Option; start: number } | null {\n const option = this.openOption!;\n const accepted = this.addValue(value, separator);\n this.valueMin = this.separateValueMax = 0;\n return accepted ? { option, start } : null;\n }\n\n /**\n * Whether the command already has all the arguments it takes. A command that\n * requires a subcommand takes none.\n */\n private get argsAreFull(): boolean {\n return this.scope.command.requiresSubcommand === true || this.args.length >= this.scope.argsMax;\n }\n\n private addArg(value: string): TokenReading {\n this.endOption();\n if (this.argsAreFull) {\n this.failArgs((ctx) => new TooManyArguments(value, ctx));\n }\n this.args.push(value);\n return { kind: \"argument\" };\n }\n\n /** Read `--`. Every token after it is an argument. */\n private argSeparator(): TokenReading {\n this.closeOption();\n // A command that requires a subcommand allows `--` alone, and reports\n // any argument after it.\n const command = this.scope.command;\n if (this.argsAreFull && !command.requiresSubcommand) {\n this.failArgs(\n (ctx) => new ParseError(ctx, \"Unexpected argument '--', did you mean to use an option instead?\"),\n );\n }\n this.argSeparatorIndex = this.args.length;\n return { kind: \"separator\" };\n }\n\n /**\n * How the next token can name a subcommand, its own or an inherited one, or\n * null if it can't. It can't once an argument is found, or while the open\n * option needs the next token as its value. A required or variadic option\n * value takes priority over a subcommand. A short optional value could be a\n * prefix of a subcommand's name, so only an exact name can end an option\n * that still has room.\n */\n private get subcommandMatching(): SubcommandMatching | null {\n if (this.hasFoundArg || !this.scope.hasSubcommands) {\n return null;\n }\n if (this.valueCount < this.valueMin || (this.hasRoomForValue && this.separateValueMax === Infinity)) {\n return null;\n }\n return { exactOnly: this.hasRoomForValue };\n }\n\n /**\n * The subcommand the next token enters if it's `token`, or why it enters\n * none. Null if the next token can't be a subcommand at all.\n */\n private subcommandFor(token: string): SubcommandMatch | null {\n const matching = this.subcommandMatching;\n return matching && this.scope.matchSubcommand(token, matching.exactOnly);\n }\n\n private enterSubcommand(command: Subcommand): TokenReading {\n this.closeOption();\n this.path.push(command);\n this.scope.enter(command);\n return { kind: \"subcommand\", command };\n }\n\n /** Read a token like `-abc`, `+x` or `-ovalue`. */\n private shortOptions(token: string): TokenReading {\n const leadingChar = token[0];\n\n // Parse as a single dash or plus with an arg. Try dash and plus options\n // first if:\n // - the options exist\n // - the options take args\n // - the first non-leading character isn't an option\n const dashOption = this.findOption(leadingChar);\n if (dashOption?.args && !this.findOption(token.slice(0, 2))) {\n this.useOption(dashOption, leadingChar);\n const attached = this.addAttachedValue(1, token.slice(1), \"\");\n return { kind: \"options\", options: [dashOption], attached };\n }\n\n // Parse as chained short options. If we got here, the option wasn't `-` or `+`.\n const used: Option[] = [];\n let attached: { option: Option; start: number } | null = null;\n for (let char = 1; char < token.length; char++) {\n const optionName = leadingChar + token[char];\n const option = this.findOption(optionName);\n if (!option) {\n // An open option takes anything unknown as a value, like `-5`.\n if (char === 1 && this.hasRoomForValue) {\n return this.value(token);\n }\n this.unknownOption(optionName);\n continue;\n }\n\n this.useOption(option, optionName);\n used.push(option);\n if (char === token.length - 1) {\n break;\n }\n\n const sep = this.scope.leadingSeparator(token.slice(char + 1));\n // An option without args still takes a separated value, so that `-v=1`\n // fails like `--verbose=1`, unless the next character is an option.\n if (option.args || (sep && !this.findOption(leadingChar + token[char + 1]))) {\n const argStart = char + sep.length + 1;\n attached = this.addAttachedValue(argStart, token.slice(argStart), sep);\n break;\n }\n }\n return used.length > 0 ? { kind: \"options\", options: used, attached } : { kind: \"unknown\" };\n }\n\n /**\n * Read a token like `--name` or `--name=value`, or any token when options\n * aren't POSIX compliant. Returns null if the token should be an argument.\n */\n private longOption(token: string): TokenReading | null {\n const found = this.scope.firstSeparator(token);\n const optionName = found ? token.slice(0, found.index) : token;\n const option = this.findOption(optionName);\n if (option) {\n this.useOption(option, optionName);\n let attached: { option: Option; start: number } | null = null;\n if (found) {\n const valueStart = found.index + found.separator.length;\n attached = this.addAttachedValue(valueStart, token.slice(valueStart), found.separator);\n }\n return { kind: \"options\", options: [option], attached };\n }\n // POSIX-noncompliant option means that there's nothing \"option-like\". Any\n // token can be an option if it matches an option name, and if it's not an\n // option then it's just a regular argument.\n if (this.directives.flagsArePosixNoncompliant) {\n return null;\n }\n if (this.hasRoomForValue) {\n return this.value(token);\n }\n // The option is unknown and looks like a POSIX-compliant option, so\n // it's an unknown option instead of an arg.\n this.unknownOption(optionName);\n return { kind: \"unknown\" };\n }\n\n /**\n * Read a token that isn't `--`, a subcommand or an option. It's a value of\n * the open option if that has room, and otherwise an argument, which stops\n * later tokens from being subcommands. `unmatched` is why the token isn't a\n * subcommand, if it could have been one.\n */\n private valueOrArg(token: string, unmatched: NoSubcommand | null): TokenReading {\n if (this.hasRoomForValue) {\n return this.value(token);\n }\n // Where a subcommand could be, a token the command has no room for is a\n // subcommand that didn't match.\n if (unmatched && this.argsAreFull) {\n const command = this.scope.command;\n if (command.subcommands?.length || command.requiresSubcommand) {\n this.failArgs((ctx) => {\n const { message, didYouMean } = unmatched.reason();\n return new ParseError(ctx, message, didYouMean);\n });\n }\n }\n this.hasFoundArg = true;\n return this.addArg(token);\n }\n\n /**\n * Throw if the finished command line is missing anything. Returns what it\n * was parsed as. Only call this when there's no {@link problem}.\n */\n finish(): ParseResult {\n // An option with an action, like --help, works however the rest of the\n // command line is wrong, as long as every token could be read. So does the\n // usage a command shows when no subcommand is named.\n const command = this.scope.command;\n const showsUsage = command.requiresSubcommand && !command.action && this.args.length === 0;\n const skipsChecks = this.optionAction !== undefined || showsUsage;\n if (!skipsChecks && this.tooManyArgs) {\n throw this.tooManyArgs();\n }\n if (!skipsChecks && this.args.length < this.scope.argsMin) {\n throw new TooFewArguments(this.scope.argsMin, this.scope.argsMax, this.ctx());\n }\n this.endOption();\n if (this.problem) {\n throw this.problem();\n }\n if (!skipsChecks) {\n checkOptionRules(this.options, this.seenOptions, this.scope.required(), this.ctx());\n }\n // Defaults are added after the checks, so they never count as typed. An\n // option action can run with required arguments missing, and then the\n // first default would fill a required argument's place.\n if (!command.requiresSubcommand && this.args.length >= this.scope.argsMin) {\n addDefaults(this.args, asArray(command.args), this.args.length);\n }\n return {\n path: this.path,\n action: this.optionAction ?? command.action ?? builtinUsageAction,\n args: this.args,\n argSeparatorIndex: this.argSeparatorIndex,\n options: this.options,\n defaults: (name) => this.defaults(name),\n };\n }\n\n /** See {@link ParseResult.defaults}. */\n private defaults(name: string): string[] | undefined {\n if (this.options.has(name)) {\n return undefined;\n }\n const args = asArray(this.scope.resolve(name)?.args);\n // An option whose first argument is optional, like `--inspect[=port]`,\n // means something different when it's left out than when it's bare, so\n // its defaults are only for the bare option.\n if (args.length === 0 || args[0].isOptional) {\n return undefined;\n }\n const values: string[] = [];\n addDefaults(values, args);\n return values.length > 0 ? values : undefined;\n }\n\n /** Whether using `option` next would go over its repeat limit or break an `exclusiveOn` rule. */\n private conflicts(option: Option): boolean {\n if ((this.repeatedUses.get(optionKey(option))?.count ?? 0) >= repeatLimit(option)) {\n return true;\n }\n const options = this.options;\n if (option.exclusiveOn?.some((name) => options.has(name))) {\n return true;\n }\n const names = asArray(option.name);\n return this.seenOptions.some((seen) => seen.exclusiveOn?.some((name) => names.includes(name)));\n }\n\n /** The options the next token can use. See {@link NextToken.options}. */\n private usableOptions(): UsableOption[] {\n const used = new Set(this.seenOptions.map(optionKey));\n const { local, persistent } = this.scope.live(this.subcommandMatching);\n const usable: UsableOption[] = [];\n for (const { option, names } of [...local, ...persistent]) {\n if (this.conflicts(option)) {\n continue;\n }\n usable.push({ option, forms: this.scope.forms(option, names), used: used.has(optionKey(option)) });\n }\n return usable;\n }\n\n /**\n * What the next token can be. See {@link readNext}. Reading more tokens\n * doesn't change what this returns.\n */\n next(): Omit<NextToken, \"attached\" | \"partialIsOption\"> {\n const open = this.openOption && this.hasRoomForValue ? this.openOption : null;\n const command = this.scope.command;\n // Every token after `--` is an argument.\n const afterSeparator = this.argSeparatorIndex !== -1;\n const optionsAllowed = !afterSeparator && this.optionsAllowed;\n return {\n path: [...this.path],\n directives: { ...this.directives },\n optionsAllowed,\n subcommands: !afterSeparator && this.subcommandMatching ? this.scope.subcommands() : [],\n options: optionsAllowed ? this.usableOptions() : [],\n value: open && {\n option: open,\n arg: argAt(asArray(open.args), this.valueCount),\n required: this.valueCount < this.valueMin,\n },\n arg: open ? undefined : argAt(asArray(command.args), this.args.length),\n };\n }\n\n /** Whether the next token can be an option. Once options must stop, every token is an argument. */\n private get optionsAllowed(): boolean {\n return !(this.directives.optionsMustPrecedeArguments && this.hasFoundArg);\n }\n\n read(token: string): TokenReading {\n // Every token after `--` is an argument.\n if (this.argSeparatorIndex !== -1) {\n return this.addArg(token);\n }\n const optionsAllowed = this.optionsAllowed;\n\n // \"--\" disables option & subcommand parsing, so it's checked first.\n if (token === \"--\" && optionsAllowed) {\n return this.argSeparator();\n }\n\n const subcommand = this.subcommandFor(token);\n if (subcommand?.command) {\n return this.enterSubcommand(subcommand.command);\n }\n\n if (optionsAllowed) {\n const flagsArePosixNoncompliant = this.directives.flagsArePosixNoncompliant;\n const first = token.charCodeAt(0);\n const isDoubleDash = first === 45 /* - */ && token.charCodeAt(1) === 45;\n if (\n !flagsArePosixNoncompliant &&\n token.length > 1 &&\n (first === 45 || first === 43) /* + */ &&\n !isDoubleDash\n ) {\n return this.shortOptions(token);\n }\n if (flagsArePosixNoncompliant || (token.length > 2 && isDoubleDash)) {\n const reading = this.longOption(token);\n if (reading) {\n return reading;\n }\n }\n }\n\n return this.valueOrArg(token, subcommand);\n }\n}\n\n/** The argument at `index`, reusing a final variadic argument. */\nfunction argAt(args: readonly Arg[], index: number): Arg | undefined {\n if (index < args.length) {\n return args[index];\n }\n const last = args[args.length - 1];\n return last?.isVariadic ? last : undefined;\n}\n\n/**\n * Start reading a command line for `spec`, to say what each token is read as\n * in turn. Reads leniently, like {@link readNext}.\n */\nexport function tokenReader(spec: Spec): TokenReader {\n return new Scanner(spec);\n}\n\n/**\n * Work out what the token after `before` can be, and how the parser reads\n * `partial`: whether it's an option, and if so, whether it has a value\n * attached. Reads leniently, so a line that's wrong at the moment still has\n * an answer. Completion is built on this.\n */\nexport function readNext(spec: Spec, before: readonly string[], partial: string): NextToken {\n const s = new Scanner(spec);\n for (const token of before) {\n s.read(token);\n }\n const next = s.next();\n let attached: NextToken[\"attached\"] = null;\n let partialIsOption = false;\n if (partial !== \"\" && next.optionsAllowed) {\n const reading = s.read(partial);\n partialIsOption =\n reading.kind === \"options\" || reading.kind === \"unknown\" || reading.kind === \"separator\";\n const found = reading.kind === \"options\" ? reading.attached : null;\n const arg = found && asArray(found.option.args)[0];\n if (found && arg) {\n attached = {\n option: found.option,\n arg,\n prefix: partial.slice(0, found.start),\n value: partial.slice(found.start),\n };\n }\n }\n return { ...next, attached, partialIsOption };\n}\n\n/**\n * Say what the parser reads `token` as when it comes after `before`. Reads\n * leniently, like {@link readNext}. To read every token of a line, use\n * {@link tokenReader}.\n */\nexport function readToken(spec: Spec, before: readonly string[], token: string): TokenReading {\n const s = new Scanner(spec);\n for (const earlier of before) {\n s.read(earlier);\n }\n return s.read(token);\n}\n\n/**\n * Parse the input tokens using the given CLI spec.\n *\n * This returns a `ParseResult`, which contains the array of\n * subcommands used, the provided options, the arguments, and the action to\n * run.\n *\n * If parsing fails, this function throws.\n */\nexport function parse(input: readonly string[], spec: Spec): ParseResult {\n const s = new Scanner(spec);\n for (const token of input) {\n s.read(token);\n if (s.problem) {\n throw s.problem();\n }\n }\n return s.finish();\n}\n","/**\n * Shell completion.\n *\n * The `completion` subcommand prints a short script for a supported shell. On\n * every Tab, that script runs the CLI's hidden `completion complete` command\n * with the command line typed so far. The CLI then works out the candidates\n * with the parser's own `readNext`, so completion always matches what the parser\n * accepts at that position: subcommands, options with their\n * relationship rules, and argument values from `template`, `suggestions` and\n * `generators`.\n *\n * @module\n */\n\nimport type { Arg, Spec, Subcommand, Template } from \"./types.js\";\nimport { makeArray, print } from \"./util.js\";\nimport { printUsageError } from \"./help.js\";\nimport { visibleSubcommands } from \"./subcommands.js\";\nimport { readNext } from \"./parse.js\";\nimport type { NextToken } from \"./parse.js\";\n\n/** Shells that {@link getCompletion} can generate scripts for. */\nexport type Shell = \"bash\" | \"zsh\" | \"fish\" | \"powershell\" | \"nushell\";\n\nexport const SHELLS: readonly Shell[] = [\"bash\", \"zsh\", \"fish\", \"powershell\", \"nushell\"];\n\nfunction isShell(value: string): value is Shell {\n return (SHELLS as readonly string[]).includes(value);\n}\n\nconst firstLine = (description: string | undefined): string =>\n description ? description.split(\"\\n\", 1)[0].trim() : \"\";\n\n/** Turn an arbitrary name into a safe shell identifier fragment. */\nconst sanitize = (value: string): string => value.replace(/[^A-Za-z0-9]+/g, \"_\");\n\n/** Single-quote a string for bash/zsh. */\nfunction shQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n/** Single-quote a string for fish (only `\\` and `'` are special). */\nfunction fishQuote(value: string): string {\n return `'${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\")}'`;\n}\n\n/** Single-quote a string for PowerShell (a quote is written twice). */\nfunction psQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Quote a string for Nushell. A single-quoted string has no escapes, so a name\n * with a quote in it is written as a double-quoted string instead.\n */\nfunction nuQuote(value: string): string {\n if (!value.includes(\"'\")) {\n return `'${value}'`;\n }\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\n// Runtime resolver {{{\n\n/** A single completion candidate. */\ninterface Candidate {\n value: string;\n description?: string;\n}\n\n/** Enumerate filesystem entries matching `partial` for a path template. */\nasync function enumeratePaths(partial: string, template: Template): Promise<Candidate[]> {\n // Imported through a variable so the Node-free `src` build doesn't need\n // @types/node; this only runs inside the (Node-only) completion runtime.\n const specifier = \"node:fs\";\n const { readdirSync } = (await import(specifier)) as {\n readdirSync(path: string, options: { withFileTypes: true }): { name: string; isDirectory(): boolean }[];\n };\n // Windows paths can use either separator. Elsewhere `\\` is part of a name.\n const isWindows = (globalThis as { process?: { platform?: string } }).process?.platform === \"win32\";\n const slash = Math.max(partial.lastIndexOf(\"/\"), isWindows ? partial.lastIndexOf(\"\\\\\") : -1);\n const dir = slash >= 0 ? partial.slice(0, slash + 1) : \"\";\n const base = slash >= 0 ? partial.slice(slash + 1) : partial;\n // A folder ends with the separator the user typed last.\n const separator = slash >= 0 ? partial[slash] : \"/\";\n const foldersOnly = template === \"folders\";\n let entries: { name: string; isDirectory(): boolean }[];\n try {\n entries = readdirSync((isWindows ? dir.replaceAll(\"\\\\\", \"/\") : dir) || \".\", { withFileTypes: true });\n } catch {\n return [];\n }\n const candidates: Candidate[] = [];\n for (const entry of entries as { name: string; isDirectory(): boolean }[]) {\n if (!entry.name.startsWith(base)) {\n continue;\n }\n const isDir = entry.isDirectory();\n if (foldersOnly && !isDir) {\n continue;\n }\n candidates.push({ value: `${dir}${entry.name}${isDir ? separator : \"\"}` });\n }\n return candidates;\n}\n\n/** All candidate values for a single argument (suggestions/generators/template). */\nasync function argValues(arg: Arg, tokens: string[], partial: string): Promise<Candidate[]> {\n const candidates: Candidate[] = [];\n\n for (const suggestion of arg.suggestions ?? []) {\n candidates.push(\n typeof suggestion === \"string\"\n ? { value: suggestion }\n : { value: makeArray(suggestion.name)[0], description: suggestion.description },\n );\n }\n\n for (const generator of makeArray(arg.generators)) {\n if (!generator.custom) {\n continue;\n }\n const produced = await generator.custom([...tokens, partial]);\n for (const suggestion of produced) {\n candidates.push(\n typeof suggestion === \"string\"\n ? { value: suggestion }\n : { value: makeArray(suggestion.name)[0], description: suggestion.description },\n );\n }\n }\n\n if (arg.template) {\n candidates.push(...(await enumeratePaths(partial, arg.template)));\n }\n\n return candidates;\n}\n\n/** Decide which kinds of candidate the word being completed can use. */\nfunction wantedCandidates(next: NextToken, req: CompletionRequest) {\n // Posix-noncompliant options have no dash to gate on, so they're always\n // offered alongside the other candidates.\n if (!req.gateOptions || next.directives.flagsArePosixNoncompliant) {\n return { wantValues: true, wantOptions: true, wantSubcommand: () => true };\n }\n // When gating, a word the parser reads as an option completes no values.\n // Options, and subcommands named like them, are offered once the word starts\n // one of their names.\n const partial = req.partial;\n const wantValues = !next.partialIsOption;\n const starts = (name: string) => partial !== \"\" && name.startsWith(partial);\n return {\n wantValues,\n wantOptions: next.options.some(({ forms }) => forms.some(({ name }) => starts(name))),\n wantSubcommand: (name: string) => wantValues || starts(name),\n };\n}\n\n/** Inputs for the runtime completion resolver. */\nexport interface CompletionRequest {\n spec: Spec;\n /** Tokens after the program name, excluding the word being completed. */\n before: readonly string[];\n /** The word being completed. */\n partial: string;\n /** Only offer options once the word being completed starts with a dash. */\n gateOptions?: boolean;\n}\n\n/**\n * Resolve completion candidates for a partial command line. The parser works\n * out what the word can be with {@link readNext}, and this offers candidates\n * for each of those.\n */\nexport async function completeRuntime(req: CompletionRequest): Promise<Candidate[]> {\n const next = readNext(req.spec, req.before, req.partial);\n const tokens = [...req.before];\n\n // The word is an option with a value attached, like `--mode=fa`.\n if (next.attached) {\n const { prefix, arg, value } = next.attached;\n const values = await argValues(arg, tokens, value);\n return values.map((candidate) => ({\n value: prefix + candidate.value,\n description: candidate.description,\n }));\n }\n\n // The open option needs this word as its value.\n if (next.value?.required) {\n return next.value.arg ? argValues(next.value.arg, tokens, req.partial) : [];\n }\n\n const candidates: Candidate[] = [];\n const { wantValues, wantOptions, wantSubcommand } = wantedCandidates(next, req);\n if (wantValues) {\n // While an option can take another value, a word that isn't an option or\n // subcommand is its value instead of an argument.\n const arg = next.value ? next.value.arg : next.arg;\n if (arg) {\n candidates.push(...(await argValues(arg, tokens, req.partial)));\n }\n }\n for (const sub of visibleSubcommands(next.subcommands)) {\n const description = firstLine(sub.description);\n for (const token of makeArray(sub.name)) {\n if (wantSubcommand(token)) {\n candidates.push({ value: token, description });\n }\n }\n }\n if (wantOptions) {\n candidates.push(...optionCandidates(next));\n }\n return candidates;\n}\n\n/** The options a user can use next, required ones first. */\nfunction optionCandidates(next: NextToken): Candidate[] {\n const required: Candidate[] = [];\n const optional: Candidate[] = [];\n\n for (const { option, forms, used } of next.options) {\n if (option.hidden) {\n continue;\n }\n // The parser lets a later use of an option override an earlier one, but\n // that's rarely what someone wants, so an option that isn't repeatable is\n // offered once.\n if (used && !option.isRepeatable) {\n continue;\n }\n\n let description = firstLine(option.description);\n if (option.dependsOn) {\n const needs = option.dependsOn.join(\", \");\n description = description ? `${description} (requires ${needs})` : `requires ${needs}`;\n }\n if (option.isRequired) {\n description = description ? `${description} [required]` : \"[required]\";\n }\n\n // A name joined to its value by a separator is offered with the separator,\n // so the next Tab completes the value. A name joined with nothing between,\n // like `-` in `-5`, is only the option once the value is typed, so it isn't\n // offered.\n const bucket = option.isRequired ? required : optional;\n for (const { name, join } of forms) {\n if (join === \"\") {\n continue;\n }\n bucket.push({ value: name + (join ?? \"\"), description });\n }\n }\n\n return [...required, ...optional];\n}\n\n/**\n * Render the thin shim that forwards the line to `completion complete`. The\n * binary is invoked as typed (so `./pack` works) and guarded so a missing\n * command degrades to no completion instead of an error.\n */\nfunction renderRuntimeShim(spec: Spec, shell: Shell): string {\n const id = sanitize(spec.name);\n const name = spec.name;\n if (shell === \"bash\") {\n return [\n `_${id}_complete() {`,\n ` local bin=\"\\${COMP_WORDS[0]}\"`,\n ` command -v \"$bin\" >/dev/null 2>&1 || return`,\n ` local cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`,\n ` local out`,\n ` out=\"$(\"$bin\" completion complete --gate-options -- \"\\${COMP_WORDS[@]:1:COMP_CWORD-1}\" \"$cur\" 2>/dev/null | cut -f1)\"`,\n ` local IFS=$'\\\\n'`,\n ` COMPREPLY=( $(compgen -W \"$out\" -- \"$cur\") )`,\n `}`,\n `complete -F _${id}_complete ${shQuote(name)}`,\n ].join(\"\\n\");\n }\n if (shell === \"zsh\") {\n return [\n `#compdef ${name}`,\n `_${id}_complete() {`,\n ` local bin=\"$words[1]\"`,\n ` command -v \"$bin\" >/dev/null 2>&1 || return`,\n ` local -a lines`,\n ` lines=( \"\\${(@f)$(\"$bin\" completion complete -- \"\\${words[2,CURRENT-1]}\" \"\\${words[CURRENT]}\" 2>/dev/null)}\" )`,\n ` local -a disp`,\n ` local line`,\n ` for line in $lines; do disp+=( \"\\${line//$'\\\\t'/:}\" ); done`,\n ` _describe -t values ${shQuote(name)} disp`,\n `}`,\n `_${id}_complete \"$@\"`,\n ].join(\"\\n\");\n }\n if (shell === \"powershell\") {\n // PowerShell doesn't filter or quote a native command's candidates, so the\n // script does both. The arguments go through an array so that PowerShell\n // passes `--` on to the CLI. Windows PowerShell drops an empty argument,\n // so an empty word is passed as --empty-word. The word is passed and\n // matched without the quote it was opened with.\n const stringAst = \"[System.Management.Automation.Language.StringConstantExpressionAst]\";\n return [\n `Register-ArgumentCompleter -Native -CommandName ${psQuote(name)} -ScriptBlock {`,\n ` param($wordToComplete, $commandAst, $cursorPosition)`,\n ` $elements = $commandAst.CommandElements`,\n ` $first = $elements[0]`,\n ` $bin = if ($first -is ${stringAst}) { $first.Value } else { $first.Extent.Text }`,\n ` if (-not (Get-Command $bin -ErrorAction SilentlyContinue)) { return }`,\n ` $partial = $wordToComplete`,\n ` if ($partial.StartsWith(\"'\")) { $partial = $partial.Substring(1).TrimEnd(\"'\").Replace(\"''\", \"'\") }`,\n ` elseif ($partial.StartsWith('\"')) { $partial = $partial.Substring(1).TrimEnd('\"') }`,\n ` $arguments = @('completion', 'complete', '--gate-options')`,\n ` if ($partial -eq '') { $arguments += '--empty-word' }`,\n ` $arguments += '--'`,\n ` for ($i = 1; $i -lt $elements.Count; $i++) {`,\n ` $element = $elements[$i]`,\n ` if ($element.Extent.EndOffset -ge $cursorPosition) { break }`,\n ` if ($element -is ${stringAst}) {`,\n ` $arguments += $element.Value`,\n ` } else {`,\n ` $arguments += $element.Extent.Text`,\n ` }`,\n ` }`,\n ` if ($partial -ne '') { $arguments += $partial }`,\n ` & $bin @arguments 2>$null | ForEach-Object {`,\n ' $value, $description = $_ -split \"`t\", 2',\n ` if (-not $value.StartsWith($partial, [System.StringComparison]::OrdinalIgnoreCase)) { return }`,\n \" $text = if ($value -match '[\\\\s''\\\"`$&|;,(){}<>@#]') { \\\"'$($value.Replace(\\\"'\\\", \\\"''\\\"))'\\\" } else { $value }\",\n ` if (-not $description) { $description = $value }`,\n ` [System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $description)`,\n ` }`,\n `}`,\n ].join(\"\\n\");\n }\n if (shell === \"nushell\") {\n // Nushell has one completer for every external command, so the script\n // keeps the completer that was set before and hands it other commands.\n // The spans keep the quotes they were typed with, the command's included,\n // so the script removes them. A command on Windows can be typed with its\n // extension. Nushell doesn't filter or quote what an external completer\n // returns, so the script does both.\n const previous = `$__${id}_previous_completer`;\n const names = [\"\", \".exe\", \".cmd\", \".bat\"].map((extension) => nuQuote(name + extension)).join(\" \");\n return [\n `let __${id}_previous_completer = $env.config.completions.external.completer?`,\n `$env.config.completions.external.completer = {|spans|`,\n ` let words = $spans | each {|span|`,\n ` let quote = $span | str substring 0..0`,\n ` if $quote in [\"'\", '\"', '\\`'] { $span | str substring 1.. | str trim --right --char $quote } else { $span }`,\n ` }`,\n ` let command = $words.0`,\n ` if ($command | path basename) not-in [${names}] {`,\n ` return (if ${previous} != null { do ${previous} $spans })`,\n ` }`,\n ` if (which $command | is-empty) { return }`,\n ` let args = $words | skip 1`,\n ` let partial = $args | last | default \"\"`,\n ` ^$command completion complete --gate-options -- ...$args`,\n ` | complete`,\n ` | get stdout`,\n ` | lines`,\n ` | each {|line|`,\n ` let parts = $line | split row \"\\\\t\"`,\n ` { value: $parts.0, description: ($parts | get 1? | default \"\") }`,\n ` }`,\n ` | where { $in.value | str starts-with --ignore-case $partial }`,\n \" | update value {|candidate|\",\n \" let value = $candidate.value\",\n ' if ($value !~ \"[\\\\\\\\s\\'\\\\\"`$|;#()\\\\\\\\[\\\\\\\\]{}]\") {',\n \" $value\",\n ' } else if ($value | str contains \"\\'\") {',\n \" $value | to json\",\n \" } else {\",\n \" $\\\"'($value)'\\\"\",\n \" }\",\n \" }\",\n `}`,\n ].join(\"\\n\");\n }\n // fish\n return [\n `function __${id}_complete`,\n ` set -l toks (commandline -opc)`,\n ` set -l cur (commandline -ct)`,\n ` set -l bin $toks[1]`,\n ` command -q -- $bin; or test -x \"$bin\"; or return`,\n ` $bin completion complete --gate-options -- $toks[2..-1] $cur 2>/dev/null`,\n `end`,\n `complete -c ${fishQuote(name)} -f -a '(__${id}_complete)'`,\n ].join(\"\\n\");\n}\n\n// }}}\n\n/** Generate a completion script for `shell` from a CLI spec. */\nexport function getCompletion(spec: Spec, shell: Shell): string {\n return renderRuntimeShim(spec, shell);\n}\n\n// Completion commands {{{\n\n/**\n * Hidden machine-facing subcommand the `--runtime` shim calls on every Tab.\n * The tokens after `--` are the command line; the last is the word being\n * completed. Prints `value\\tdescription` lines.\n */\nconst completeCommand: Subcommand = {\n name: \"complete\",\n description: \"Resolve completion candidates for a partial command line\",\n hidden: true,\n options: [\n {\n name: \"--gate-options\",\n description: \"Only suggest options after a leading dash\",\n },\n {\n name: \"--empty-word\",\n description: \"The word being completed is empty, so every token is before it\",\n },\n ],\n args: { name: \"tokens\", isVariadic: true, isOptional: true },\n async action({ path, args, options }) {\n const spec = path[0] as Spec;\n // Windows PowerShell drops an empty argument, so its script says the word\n // is empty with --empty-word instead of passing \"\".\n const emptyWord = options.has(\"--empty-word\");\n const partial = emptyWord || args.length === 0 ? \"\" : args[args.length - 1];\n const before = emptyWord ? args : args.slice(0, -1);\n const candidates = await completeRuntime({\n spec,\n before,\n partial,\n gateOptions: options.has(\"--gate-options\"),\n });\n const lines = candidates.map((candidate) =>\n candidate.description ? `${candidate.value}\\t${candidate.description}` : candidate.value,\n );\n if (lines.length > 0) {\n print(lines.join(\"\\n\"));\n }\n return 0;\n },\n};\n\n// }}}\n\n/** A subcommand that prints a shell completion script for the whole CLI. */\nexport const completion: Subcommand = {\n name: \"completion\",\n description: \"Print a shell completion script\",\n args: {\n name: \"shell\",\n isOptional: true,\n suggestions: SHELLS,\n description: `One of: ${SHELLS.join(\", \")}`,\n },\n subcommands: [completeCommand],\n action({ path, args: [shell] }) {\n const spec = path[0] as Spec;\n if (shell === undefined) {\n print(`Supported shells: ${SHELLS.join(\", \")}`);\n return 0;\n }\n\n if (!isShell(shell)) {\n printUsageError(path, `Unsupported shell '${shell}'`, { input: shell, choices: SHELLS });\n return 1;\n }\n\n print(getCompletion(spec, shell));\n return 0;\n },\n};\n","import type { ActionInit, Spec } from \"./types.js\";\nimport { getHelp, printUsageError } from \"./help.js\";\nimport { ParseError } from \"./errors.js\";\nimport { parse } from \"./parse.js\";\nimport { printError } from \"./util.js\";\nimport type { ParseResult } from \"./parse.js\";\n\nexport { printError };\n\n/**\n * Parse argv and execute the selected action.\n *\n * The selected command's action runs unless a parsed option has an action.\n * Option actions take precedence so helpers like `--help` can run without\n * satisfying the selected command's required arguments. A command without an\n * action prints its help.\n */\nexport async function run(spec: Spec, args: readonly string[] = defaultArgs()): Promise<number> {\n let result: ParseResult;\n\n try {\n result = parse(args, spec);\n } catch (error: unknown) {\n if (error instanceof ParseError) {\n printUsageError(error.context.path, error.message, error.didYouMean);\n } else {\n printError(`${error}`);\n }\n return 1;\n }\n\n const { action, options } = result;\n const actionInit: ActionInit = {\n help: (helpOptions) => getHelp(helpOptions?.path ?? result.path, helpOptions),\n args: result.args,\n path: result.path,\n argSeparatorIndex: result.argSeparatorIndex,\n options: {\n options,\n has: (name) => options.has(name),\n get: (name) => (options.get(name) ?? result.defaults(name))?.[0],\n all: (name) => options.get(name) ?? result.defaults(name),\n count: (name) => options.get(name)?.length ?? 0,\n },\n };\n\n let exitCode: number | void;\n try {\n const actionResult = action(actionInit);\n exitCode = typeof actionResult === \"object\" ? await actionResult : actionResult;\n } catch (error) {\n printError(describeThrown(error));\n return 1;\n }\n\n return Math.min(Math.max(exitCode ?? 0, 0), 255);\n}\n\n/**\n * The message for a value an action threw. A value that isn't an Error is shown\n * as JSON where it can be, since `String` turns an object into\n * \"[object Object]\".\n */\nfunction describeThrown(value: unknown): string {\n if (value instanceof Error) {\n return value.message;\n }\n if (typeof value === \"object\" && value !== null) {\n try {\n return JSON.stringify(value);\n } catch {\n // A cycle or a BigInt, which JSON can't show.\n }\n }\n return String(value);\n}\n\nfunction defaultArgs(): readonly string[] {\n const maybeProcess = globalThis as typeof globalThis & {\n process?: { argv?: readonly string[] };\n };\n return maybeProcess.process?.argv?.slice(2) ?? [];\n}\n","export type {\n Action,\n ActionInit,\n Arg,\n CommandPath,\n Generator,\n NonEmptyArray,\n Option,\n OptionArgs,\n SingleOrArray,\n SingleOrArrayOrEmpty,\n Spec,\n Subcommand,\n Suggestion,\n Template,\n} from \"./types.js\";\n\nexport { completion } from \"./completion.js\";\nexport type { Shell } from \"./completion.js\";\nexport { help, helpCommand } from \"./help.js\";\nexport { printError, run } from \"./run.js\";\n\nimport { completion } from \"./completion.js\";\nimport { help, helpCommand } from \"./help.js\";\nimport { printError, run } from \"./run.js\";\n\nexport default {\n completion,\n help,\n helpCommand,\n printError,\n run,\n};\n"],"mappings":";AAEA,SAAgB,QAAW,GAAwC;CACjE,OAAO,MAAM,QAAQ,CAAC;AACxB;;AAGA,SAAgB,UAAa,OAA0C;CACrE,IAAI,UAAU,KAAA,GACZ,OAAO,CAAC;CAEV,IAAI,QAAQ,KAAK,GACf,OAAO,MAAM,MAAM;CAErB,OAAO,CAAC,KAAK;AACf;;;;;;AAOA,SAAgB,QAAW,OAAmD;CAC5E,IAAI,UAAU,KAAA,GACZ,OAAO,CAAC;CAEV,IAAI,QAAQ,KAAK,GACf,OAAO;CAET,OAAO,CAAC,KAAK;AACf;;AAGA,SAAgB,WAAc,OAA0C;CACtE,IAAI,QAAQ,KAAK,GAEf,OAAO,MAAM,MAAM;CAErB,OAAO,CAAC,KAAK;AACf;AAoBA,MAAM,cAAe,WAAyC;;;;;;;;;AAU9D,SAAS,QAAQ,IAAW,MAAoB;CAC9C,MAAM,KAAK,aAAa,mBAAmB,SAAS;CACpD,IAAI,CAAC,IAAI;EACP,CAAC,OAAO,IAAI,QAAQ,MAAM,QAAQ,MAAA,CAAO,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI,IAAI;EACvF;CACF;CACA,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;CAC3C,IAAI,SAAS;CACb,IAAI;E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