@clo4/cli 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["closest","builtinUsageAction","maybeProcess"],"sources":["../src/util.ts","../src/analyze.ts","../src/errors.ts","../node_modules/.pnpm/fastest-levenshtein@1.0.16/node_modules/fastest-levenshtein/mod.js","../src/help.ts","../src/parse.ts","../src/completion.ts","../src/run.ts","../src/index.ts"],"sourcesContent":["import type { 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) return [];\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) return [];\n if (isArray(thing)) return thing;\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\n/** Set many keys in a Map to the same value */\nexport function setEach<K, V>(map: Map<K, V>, keys: K | readonly K[], value: V): void {\n if (isArray(keys)) {\n for (const key of keys) {\n map.set(key, value);\n }\n } else {\n map.set(keys, value);\n }\n}\n\nexport function assert(expr: unknown, msg = \"\"): asserts expr {\n if (!expr) {\n throw new Error(msg);\n }\n}\n\nexport function error(...strings: unknown[]): void {\n console.error(\"%cError:\", \"color: red\", ...strings);\n}\n\n/** Print a message to stdout, trimming trailing whitespace. */\nexport function print(text: string): void {\n console.log(text.trimEnd());\n}\n\n/** Print an error message to stderr with the shared `Error:` prefix. */\nexport function printActionError(message: string): void {\n console.error(\"Error:\", message);\n}\n","import { asArray, setEach } from \"./util.js\";\n\ninterface MinOption {\n name: string | readonly string[];\n args?: unknown;\n isPersistent?: boolean;\n isRequired?: boolean;\n}\n\ninterface MinSubcommand<Option extends MinOption> {\n name: string | readonly string[];\n args?: unknown;\n options?: readonly Option[];\n subcommands?: readonly this[];\n parserDirectives?: {\n optionArgSeparators?: string | readonly string[];\n flagsArePosixNoncompliant?: boolean;\n optionsMustPrecedeArguments?: boolean;\n subcommandsMatchUniquePrefix?: boolean;\n };\n}\n\n// Token helpers {{{\n\nexport type BaseToken = {\n /** The index in the input that that contains this token */\n index: number;\n /** Inclusive start index */\n start: number;\n /** Non-inclusive (exclusive) end index */\n end: number;\n /** The literal text value */\n literal: string;\n};\n\n/** Something that looks like an option but isn't one */\nexport type TokenUnknownOption = BaseToken & {\n kind: \"unknown-option\";\n validOptions: string[];\n};\n\n/** A value that belongs to either an option or the current command */\nexport type TokenArg = BaseToken & {\n kind: \"arg\";\n};\n\n/** A token that denotes that all following tokens are arguments */\nexport type TokenArgSeparator = BaseToken & {\n kind: \"arg-separator\";\n};\n\n/** Some text that is guaranteed to belong to the preceding option (eg. -I%, --config=file.json) */\nexport type TokenOptionArg = BaseToken & {\n kind: \"option-arg\";\n option: string;\n separator: string;\n};\n\n/** A subcommand, and all the relevant information */\nexport type TokenSubcommand<Subcommand> = BaseToken & {\n kind: \"subcommand\";\n subcommand: Subcommand;\n};\n\n/** An option */\nexport type TokenOption<Option> = BaseToken & {\n kind: \"option\";\n option: Option;\n};\n\n/** Any kind of token */\nexport type Token<Subcommand, Option> =\n | TokenArg\n | TokenArgSeparator\n | TokenSubcommand<Subcommand>\n | TokenOption<Option>\n | TokenUnknownOption\n | TokenOptionArg;\n\nexport const $optionArg = (\n index: number,\n start: number,\n end: number,\n literal: string,\n option: string,\n separator: string,\n): TokenOptionArg => ({\n kind: \"option-arg\",\n index,\n literal,\n start,\n end,\n option,\n separator,\n});\n\nexport const $unknownOption = (\n index: number,\n start: number,\n end: number,\n literal: string,\n validOptions: string[],\n): TokenUnknownOption => ({\n kind: \"unknown-option\",\n index,\n start,\n end,\n literal,\n validOptions,\n});\n\nexport const $arg = (index: number, start: number, end: number, literal: string): TokenArg => ({\n kind: \"arg\",\n index,\n start,\n end,\n literal,\n});\n\nexport const $argSeparator = (\n index: number,\n start: number,\n end: number,\n literal: string,\n): TokenArgSeparator => ({\n kind: \"arg-separator\",\n index,\n start,\n end,\n literal,\n});\n\nexport const $subcommand = <Subcommand extends MinSubcommand<Option>, Option extends MinOption>(\n index: number,\n start: number,\n end: number,\n literal: string,\n subcommand: Subcommand,\n): TokenSubcommand<Subcommand> => {\n return {\n kind: \"subcommand\",\n index,\n start,\n end,\n literal,\n subcommand,\n };\n};\n\nexport const $option = <Option extends MinOption>(\n index: number,\n start: number,\n end: number,\n literal: string,\n option: Option,\n): TokenOption<Option> => {\n return {\n kind: \"option\",\n index,\n start,\n end,\n literal,\n option,\n };\n};\n\n// }}}\n\nexport interface AnalyzeResult<Subcommand, Option> {\n /** The state after the final token has been processed */\n finalState: {\n localOptions: Map<string, Option>;\n persistentOptions: Map<string, Option>;\n localRequiredOptions: Map<string, Option>;\n persistentRequiredOptions: Map<string, Option>;\n };\n\n /** The list of tokens and their data */\n tokens: Token<Subcommand, Option>[];\n}\n\n/**\n * Lex the input, output some tokens\n *\n * This generator uses the options and subcommands to categorize the\n * input tokens. It will not track or reject arguments - tokens that\n * don't match an option or subcommand are yielded as arguments.\n */\nexport function analyze<Subcommand extends MinSubcommand<Option>, Option extends MinOption>(\n input: readonly string[],\n spec: Subcommand,\n): AnalyzeResult<Subcommand, Option> {\n const tokens = [] as Token<Subcommand, Option>[];\n\n if (input.length === 0) {\n const localOptions = new Map();\n const localRequiredOptions = new Map();\n const persistentOptions = new Map();\n const persistentRequiredOptions = new Map();\n if (spec.options) {\n for (const option of spec.options) {\n if (option.isPersistent) {\n setEach(persistentOptions, option.name, option);\n if (option.isRequired) {\n setEach(persistentRequiredOptions, option.name, option);\n }\n } else {\n setEach(localOptions, option.name, option);\n if (option.isRequired) {\n setEach(localRequiredOptions, option.name, option);\n }\n }\n }\n }\n return {\n finalState: {\n localOptions,\n persistentOptions,\n localRequiredOptions,\n persistentRequiredOptions,\n },\n tokens,\n };\n }\n\n // This is initialized by the call to `updateCurrentCommand`\n let localSubcommands: readonly Subcommand[] | undefined;\n\n const localOptions: Map<string, Option> = new Map();\n const persistentOptions: Map<string, Option> = new Map();\n const localRequiredOptions: Map<string, Option> = new Map();\n const persistentRequiredOptions: Map<string, Option> = new Map();\n let separators: readonly string[] = [\"=\"];\n let hasFoundArg = false;\n let posixCompliantOptions = true;\n let subcommandsMatchUniquePrefix = false;\n let optionsMustPrecedeArguments = false;\n let hasUsedNonPersistentOption = false;\n\n const getOption = (name: string) => localOptions.get(name) ?? persistentOptions.get(name) ?? null;\n\n const hasOption = (name: string) => localOptions.has(name) || persistentOptions.has(name);\n\n const getSubcommand = (name: string) => {\n if (!localSubcommands) {\n return null;\n }\n\n // A literal match always wins, so every command has to be checked even in\n // prefix mode. Track the prefix matches as we go (counting each command at\n // most once) and only commit to one if it's unambiguous.\n let prefixMatch: Subcommand | null = null;\n let prefixCount = 0;\n\n for (const command of localSubcommands) {\n const names = typeof command.name === \"string\" ? [command.name] : command.name;\n for (const cmdName of names) {\n if (cmdName === name) {\n return command;\n }\n if (subcommandsMatchUniquePrefix && cmdName.startsWith(name)) {\n prefixMatch = command;\n prefixCount += 1;\n // One matching name is enough; checking the rest would double-count.\n break;\n }\n }\n }\n\n return prefixCount === 1 ? prefixMatch : null;\n };\n\n // Update state to a new subcommand (without clearing maps).\n // Returns the new \"internal state\" which is a byproduct of processing\n // the subcommand.\n const updateCurrentCommand = (command: Subcommand) => {\n if (command.options) {\n for (const option of command.options) {\n if (option.isPersistent) {\n setEach(persistentOptions, option.name, option);\n if (option.isRequired) {\n setEach(persistentRequiredOptions, option.name, option);\n }\n } else {\n setEach(localOptions, option.name, option);\n if (option.isRequired) {\n setEach(localRequiredOptions, option.name, option);\n }\n }\n }\n }\n\n localSubcommands = command.subcommands;\n\n const directives = command.parserDirectives;\n\n if (directives?.optionArgSeparators) {\n separators = asArray(directives.optionArgSeparators);\n }\n\n if (directives?.subcommandsMatchUniquePrefix) {\n subcommandsMatchUniquePrefix = directives.subcommandsMatchUniquePrefix;\n }\n\n if (directives?.optionsMustPrecedeArguments) {\n optionsMustPrecedeArguments = directives.optionsMustPrecedeArguments;\n }\n\n if (typeof directives?.flagsArePosixNoncompliant === \"boolean\") {\n posixCompliantOptions = !directives.flagsArePosixNoncompliant;\n }\n };\n\n // The maps are already empty, no reason to clear them.\n updateCurrentCommand(spec);\n\n tokens: for (let index = 0; index < input.length; index++) {\n const token = input[index];\n\n // \"--\" as a token disables option & subcommand parsing, so this needs\n // to be checked first.\n if (token === \"--\") {\n tokens.push($argSeparator(index, 0, token.length, token));\n index += 1;\n for (; index < input.length; index++) {\n const tok = input[index];\n tokens.push($arg(index, 0, tok.length, tok));\n }\n break tokens;\n }\n\n // 1. Try to parse as a subcommand\n // A common case is for the first argument to be a subcommand,\n // so we can exit early instead of building the whole map if the\n // argument is a subcommand.\n if (!hasFoundArg && !hasUsedNonPersistentOption && localSubcommands) {\n const command = getSubcommand(token);\n if (command) {\n localOptions.clear();\n updateCurrentCommand(command);\n tokens.push($subcommand(index, 0, token.length, token, command));\n continue tokens;\n }\n }\n\n // 2. Try to parse as an option\n if (!(optionsMustPrecedeArguments && hasFoundArg)) {\n if (\n posixCompliantOptions &&\n token.length > 1 &&\n (token.startsWith(\"-\") || token.startsWith(\"+\")) &&\n !token.startsWith(\"--\")\n ) {\n const leadingChar = token[0];\n\n // 2.a. Parse as a single dash or plus with an arg\n // Try dash and plus options first if:\n // - the options exist\n // - the options take args\n // - the first non-leading character isn't an option\n const dashOption = getOption(leadingChar);\n if (dashOption?.args && !hasOption(token.slice(0, 2))) {\n tokens.push($option(index, 0, 1, leadingChar, dashOption));\n tokens.push($optionArg(index, 1, token.length, token.slice(1), leadingChar, \"\"));\n continue tokens;\n }\n\n // 2.b. Parse as a chainable short option\n // If we fell through, the option wasn't `-` or `+`\n chars: for (let char = 1; char < token.length; char++) {\n const optionName = `${leadingChar}${token[char]}`;\n const option = getOption(optionName);\n if (!option) {\n tokens.push(\n $unknownOption(index, char, char + 1, optionName, [\n ...localOptions.keys(),\n ...persistentOptions.keys(),\n ]),\n );\n continue chars;\n }\n\n if (!hasUsedNonPersistentOption && !option.isPersistent) {\n hasUsedNonPersistentOption = true;\n }\n\n tokens.push($option(index, char, char + 1, optionName, option));\n\n if (option.args && char < token.length - 1) {\n const remainingChars = token.slice(char + 1);\n const sep = separators.find((sep) => remainingChars.startsWith(sep)) || \"\";\n const argStartOffset = char + sep.length;\n tokens.push(\n $optionArg(\n index,\n argStartOffset + 1,\n token.length,\n token.slice(argStartOffset + 1),\n optionName,\n sep,\n ),\n );\n break;\n }\n }\n continue tokens;\n }\n\n if (!posixCompliantOptions || (token.length > 2 && token.startsWith(\"--\"))) {\n // 2.c. Parse as a long option or posix-noncompliant option\n\n // POSIX-noncompliant option means that there's nothing \"option-like\".\n // Any token can be an option if it matches an option name, and if it's\n // not an option then it's just a regular argument.\n\n let foundSep = null;\n let foundSepIndex = -1;\n\n separators: for (const sep of separators) {\n const index = token.indexOf(sep);\n if (index === -1) {\n continue separators;\n }\n foundSep = sep;\n foundSepIndex = index;\n }\n\n if (foundSep) {\n const optionName = token.slice(0, foundSepIndex);\n const option = getOption(optionName);\n if (option) {\n if (!hasUsedNonPersistentOption && !option.isPersistent) {\n hasUsedNonPersistentOption = true;\n }\n tokens.push($option(index, 0, foundSepIndex, token.slice(0, foundSepIndex), option));\n tokens.push(\n $optionArg(\n index,\n foundSepIndex + foundSep.length,\n token.length,\n token.slice(foundSepIndex + foundSep.length),\n optionName,\n foundSep,\n ),\n );\n continue tokens;\n } else if (posixCompliantOptions) {\n // If we're here, we know the option is invalid and we're parsing a\n // posix-compliant option, so that's an \"unknown option\" instead of arg.\n const optionName = token.slice(0, foundSepIndex);\n tokens.push(\n $unknownOption(index, 0, foundSepIndex, optionName, [\n ...localOptions.keys(),\n ...persistentOptions.keys(),\n ]),\n );\n tokens.push(\n $optionArg(\n index,\n foundSepIndex + foundSep.length,\n token.length,\n token.slice(foundSepIndex + foundSep.length),\n optionName,\n foundSep,\n ),\n );\n continue tokens;\n }\n // Posix noncompliant options should fall through\n } else {\n const option = getOption(token);\n if (option) {\n if (!hasUsedNonPersistentOption && !option.isPersistent) {\n hasUsedNonPersistentOption = true;\n }\n tokens.push($option(index, 0, token.length, token, option));\n continue tokens;\n } else if (posixCompliantOptions) {\n // If we're here, we know the option is invalid and we're parsing a\n // posix-compliant option, so that's an \"unknown option\" instead of arg.\n tokens.push(\n $unknownOption(index, 0, token.length, token, [\n ...localOptions.keys(),\n ...persistentOptions.keys(),\n ]),\n );\n continue tokens;\n }\n }\n }\n }\n\n if (!hasFoundArg) {\n hasFoundArg = true;\n }\n tokens.push($arg(index, 0, token.length, token));\n }\n\n return {\n finalState: {\n localOptions,\n persistentOptions,\n localRequiredOptions,\n persistentRequiredOptions,\n },\n tokens,\n };\n}\n","import type { BaseToken, TokenOptionArg, TokenUnknownOption } from \"./analyze.js\";\nimport type { CommandPath } from \"./types.js\";\n\nconst repr = JSON.stringify as (str: string) => string;\n\nexport interface ErrorContext {\n path: CommandPath;\n}\n\nexport class ParseError extends Error {\n readonly context: ErrorContext;\n constructor(context: ErrorContext, ...args: ConstructorParameters<ErrorConstructor>) {\n super(...args);\n this.context = context;\n this.name = this.constructor.name;\n }\n}\n\nexport class UnknownOption extends ParseError {\n readonly index: number;\n readonly start: number;\n readonly end: number;\n readonly option: string;\n readonly validOptions: string[];\n constructor(token: TokenUnknownOption, context: ErrorContext) {\n const msg = `${repr(token.literal)} looks like a flag, but is unknown in this context`;\n super(context, msg);\n this.option = token.literal;\n this.validOptions = token.validOptions;\n this.index = token.index;\n this.start = token.start;\n this.end = token.end;\n }\n}\n\nexport class InvalidOptionArg extends ParseError {\n readonly index: number;\n readonly start: number;\n readonly end: number;\n readonly arg: string;\n readonly option: string;\n constructor(token: TokenOptionArg, context: ErrorContext) {\n const msg = `Option ${token.option} doesn't take arguments`;\n super(context, msg);\n this.index = token.index;\n this.start = token.start;\n this.end = token.end;\n this.option = token.option;\n this.arg = token.literal;\n }\n}\n\nexport class TooManyArguments extends ParseError {\n readonly index: number;\n readonly value: string;\n constructor(token: BaseToken, context: ErrorContext) {\n const msg = `Too many arguments, ${repr(token.literal)} was unexpected`;\n super(context, msg);\n this.index = token.index;\n this.value = token.literal;\n }\n}\n\nexport class TooFewOptionArguments extends ParseError {\n constructor(min: number, max: number, context: ErrorContext) {\n const msg =\n min === max\n ? `Option needs ${min} argument${min === 1 ? \"\" : \"s\"}`\n : !Number.isFinite(max)\n ? `Option needs at least ${min} argument${min === 1 ? \"\" : \"s\"}`\n : `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","\"use strict\";\nexports.__esModule = true;\nexports.distance = exports.closest = void 0;\nvar peq = new Uint32Array(0x10000);\nvar myers_32 = function (a, b) {\n var n = a.length;\n var m = b.length;\n var lst = 1 << (n - 1);\n var pv = -1;\n var mv = 0;\n var sc = n;\n var i = n;\n while (i--) {\n peq[a.charCodeAt(i)] |= 1 << i;\n }\n for (i = 0; i < m; i++) {\n var eq = peq[b.charCodeAt(i)];\n var xv = eq | mv;\n eq |= ((eq & pv) + pv) ^ pv;\n mv |= ~(eq | pv);\n pv &= eq;\n if (mv & lst) {\n sc++;\n }\n if (pv & lst) {\n sc--;\n }\n mv = (mv << 1) | 1;\n pv = (pv << 1) | ~(xv | mv);\n mv &= xv;\n }\n i = n;\n while (i--) {\n peq[a.charCodeAt(i)] = 0;\n }\n return sc;\n};\nvar myers_x = function (b, a) {\n var n = a.length;\n var m = b.length;\n var mhc = [];\n var phc = [];\n var hsize = Math.ceil(n / 32);\n var vsize = Math.ceil(m / 32);\n for (var i = 0; i < hsize; i++) {\n phc[i] = -1;\n mhc[i] = 0;\n }\n var j = 0;\n for (; j < vsize - 1; j++) {\n var mv_1 = 0;\n var pv_1 = -1;\n var start_1 = j * 32;\n var vlen_1 = Math.min(32, m) + start_1;\n for (var k = start_1; k < vlen_1; k++) {\n peq[b.charCodeAt(k)] |= 1 << k;\n }\n for (var i = 0; i < n; i++) {\n var eq = peq[a.charCodeAt(i)];\n var pb = (phc[(i / 32) | 0] >>> i) & 1;\n var mb = (mhc[(i / 32) | 0] >>> i) & 1;\n var xv = eq | mv_1;\n var xh = ((((eq | mb) & pv_1) + pv_1) ^ pv_1) | eq | mb;\n var ph = mv_1 | ~(xh | pv_1);\n var mh = pv_1 & xh;\n if ((ph >>> 31) ^ pb) {\n phc[(i / 32) | 0] ^= 1 << i;\n }\n if ((mh >>> 31) ^ mb) {\n mhc[(i / 32) | 0] ^= 1 << i;\n }\n ph = (ph << 1) | pb;\n mh = (mh << 1) | mb;\n pv_1 = mh | ~(xv | ph);\n mv_1 = ph & xv;\n }\n for (var k = start_1; k < vlen_1; k++) {\n peq[b.charCodeAt(k)] = 0;\n }\n }\n var mv = 0;\n var pv = -1;\n var start = j * 32;\n var vlen = Math.min(32, m - start) + start;\n for (var k = start; k < vlen; k++) {\n peq[b.charCodeAt(k)] |= 1 << k;\n }\n var score = m;\n for (var i = 0; i < n; i++) {\n var eq = peq[a.charCodeAt(i)];\n var pb = (phc[(i / 32) | 0] >>> i) & 1;\n var mb = (mhc[(i / 32) | 0] >>> i) & 1;\n var xv = eq | mv;\n var xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;\n var ph = mv | ~(xh | pv);\n var mh = pv & xh;\n score += (ph >>> (m - 1)) & 1;\n score -= (mh >>> (m - 1)) & 1;\n if ((ph >>> 31) ^ pb) {\n phc[(i / 32) | 0] ^= 1 << i;\n }\n if ((mh >>> 31) ^ mb) {\n mhc[(i / 32) | 0] ^= 1 << i;\n }\n ph = (ph << 1) | pb;\n mh = (mh << 1) | mb;\n pv = mh | ~(xv | ph);\n mv = ph & xv;\n }\n for (var k = start; k < vlen; k++) {\n peq[b.charCodeAt(k)] = 0;\n }\n return score;\n};\nvar distance = function (a, b) {\n if (a.length < b.length) {\n var tmp = b;\n b = a;\n a = tmp;\n }\n if (b.length === 0) {\n return a.length;\n }\n if (a.length <= 32) {\n return myers_32(a, b);\n }\n return myers_x(a, b);\n};\nexports.distance = distance;\nvar closest = function (str, arr) {\n var min_distance = Infinity;\n var min_index = 0;\n for (var i = 0; i < arr.length; i++) {\n var dist = distance(str, arr[i]);\n if (dist < min_distance) {\n min_distance = dist;\n min_index = i;\n }\n }\n return arr[min_index];\n};\nexports.closest = closest;\n","import { closest } from \"fastest-levenshtein\";\n\nimport type { Action, Arg, Option, NonEmptyArray, SingleOrArray, Subcommand } from \"./types.js\";\nimport { makeArray, makeArray1, print, printActionError } from \"./util.js\";\n\nfunction getNamed<T extends { name: SingleOrArray<string> }>(\n named: readonly T[],\n name: string,\n): T | null {\n return named.find((obj) => makeArray(obj.name).includes(name)) ?? null;\n}\n\nfunction getParserDirective<Key extends keyof NonNullable<Subcommand[\"parserDirectives\"]>>(\n path: readonly Subcommand[],\n key: Key,\n): NonNullable<Subcommand[\"parserDirectives\"]>[Key] | undefined {\n for (let index = path.length - 1; index >= 0; index -= 1) {\n const command = path[index];\n if (command?.parserDirectives && key in command.parserDirectives) {\n return command.parserDirectives[key];\n }\n }\n return undefined;\n}\n\nfunction dedent(str: string) {\n if (str[0] !== \"\\n\") return str;\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?: {\n input: string;\n choices: readonly string[];\n };\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 = closest(didYouMean.input, didYouMean.choices as string[]);\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 * Action that prints usage for commands where a subcommand must be provided.\n */\nexport const usage: Action = ({ path, args: [command], help }) => {\n if (command === undefined) {\n print(help());\n return 0;\n }\n\n if (command === \"\") {\n printActionError(\n `Expected a command, but the value was empty\\n\\n${help({ description: false })}`,\n );\n return 1;\n }\n\n const subcommands = path\n .at(-1)\n ?.subcommands?.filter((cmd) => !cmd.hidden)\n .flatMap((cmd) => cmd.name);\n\n if (subcommands && subcommands.length > 0) {\n const matchPrefix = getParserDirective(path, \"subcommandsMatchUniquePrefix\");\n if (matchPrefix) {\n const possible = subcommands.filter((name) => name.startsWith(command));\n if (possible.length > 0) {\n printActionError(\n `Ambiguous command '${command}', could be: ${possible.join(\", \")}\\n\\n${help({\n description: false,\n })}`,\n );\n return 1;\n }\n }\n\n printActionError(\n `Unknown command '${command}'\\n\\n${help({\n description: false,\n didYouMean: {\n input: command,\n choices: subcommands,\n },\n })}`,\n );\n return 1;\n }\n\n printActionError(`Unknown command '${command}'\\n\\n${help({ description: false })}`);\n\n return 1;\n};\n\n/** A subcommand that prints help for its parent or a sibling command. */\nexport const helpCommand: Subcommand = {\n name: \"help\",\n description: \"Print a help message\",\n args: {\n name: \"command\",\n isOptional: true,\n },\n action({ path, args: [commandName], help }) {\n const helpRoot = path.slice(0, -1) as unknown as NonEmptyArray<Subcommand>;\n\n if (!commandName) {\n print(help({ path: helpRoot }));\n return 0;\n }\n\n const parent = path[path.length - 2];\n\n if (!parent.subcommands) {\n printActionError(\n `No subcommands, try using 'help' with nothing after it\\n\\n${help({\n description: false,\n path: helpRoot,\n })}`,\n );\n return 1;\n }\n\n const command = getNamed(parent.subcommands, commandName);\n if (!command) {\n const subcommands = parent.subcommands\n .filter((cmd) => !cmd.hidden)\n .flatMap((cmd) => cmd.name);\n\n if (subcommands.length > 0) {\n printActionError(\n `There is no subcommand named '${commandName}'\\n\\n${help({\n path: helpRoot,\n didYouMean: {\n input: commandName,\n choices: subcommands,\n },\n })}`,\n );\n return 1;\n }\n\n printActionError(\n `There is no subcommand named '${commandName}'\\n\\n${help({\n description: false,\n path: helpRoot,\n })}`,\n );\n return 1;\n }\n\n print(help({ path: [...helpRoot, command] }));\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 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 nonNullable<T>(value: T): value is NonNullable<T> {\n return value !== null && value !== undefined;\n}\n\nfunction getSections(commands: NonEmptyArray<Subcommand>): HelpSections {\n const command = commands[commands.length - 1];\n\n const description = command.description;\n const defaultDesc = \"No description\";\n\n const subcommands: HelpSections[\"subcommands\"] = command.subcommands\n ? command.subcommands\n .filter((subcommand) => !subcommand.hidden)\n .map((subcommand) => [\n makeArray1(subcommand.name)\n .sort((a, b) => a.length - b.length)\n .join(\", \"),\n subcommand.description ?? defaultDesc,\n ])\n : [];\n\n let persistentOptionObjects: Option[] = [];\n let optionObjects: Option[] = [];\n\n let persistentOptions: HelpSections[\"persistentOptions\"] = [];\n let options: HelpSections[\"options\"] = [];\n\n if (commands.length === 1 && subcommands.length === 0) {\n optionObjects = command.options ? command.options.filter((option) => !option.hidden) : [];\n options = optionObjects.map((option) => [\n optionToString(option),\n option.description ?? defaultDesc,\n ]);\n } else {\n persistentOptionObjects = commands\n .map((command) => command.options)\n .filter(nonNullable)\n .flat()\n .filter((option) => option.isPersistent && !option.hidden);\n\n persistentOptions = persistentOptionObjects.map((option) => [\n optionToString(option),\n option.description ?? defaultDesc,\n ]);\n\n optionObjects = (command.options ?? []).filter(\n (option) => !option.hidden && !option.isPersistent,\n );\n\n options = optionObjects.map((option) => [\n optionToString(option),\n option.description ?? defaultDesc,\n ]);\n }\n\n const usage = (() => {\n const parts = [getSubcommandPathString(commands)];\n const required = [\n ...optionObjects.filter((option) => option.isRequired),\n ...persistentOptionObjects.filter((option) => option.isRequired),\n ];\n for (const option of required) {\n parts.push(optionToString(option));\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 return {\n usage,\n description,\n persistentOptions,\n options,\n subcommands,\n };\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 const formatOptions = (options: [string, string][]) => {\n const lines = [];\n const newline = indent + \" \".repeat(longestOptionName + minSpacingBetweenNameAndDesc);\n for (const [name, desc] of options) {\n const spaces = \" \".repeat(longestOptionName - 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\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\nexport function optionToString(option: Option): string {\n const name = makeArray1(option.name)\n .sort((a, b) => a.length - b.length)\n .join(\", \");\n\n const optionArgs = makeArray(option.args);\n\n if (optionArgs.length === 0) {\n return name;\n }\n\n if (option.requiresSeparator) {\n const separator = option.requiresSeparator === true ? \"=\" : option.requiresSeparator;\n if (optionArgs[0].isOptional) {\n return `${name}[${separator}${optionArgs[0].name || \"argument\"}]`;\n }\n return `${name}${separator}<${optionArgs[0].name || \"argument\"}>`;\n }\n return `${name} ${summarizeArguments(optionArgs)}`;\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 { Action, CommandPath, NonEmptyArray, Option, Spec, Subcommand } from \"./types.js\";\nimport { analyze } from \"./analyze.js\";\nimport type { BaseToken, TokenOption, TokenSubcommand } from \"./analyze.js\";\nimport { assert, isArray, setEach } 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 { usage as builtinUsageAction } from \"./help.js\";\n\nexport interface ParseResult {\n args: string[];\n argSeparatorIndex: number;\n options: Map<string, string[]>;\n path: CommandPath;\n actions: Action[];\n optionActions: Action[];\n}\n\nconst enum State {\n ParseArgs,\n ParseOptionArgs,\n ParseOptionArgRequireSeparator,\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) return 0;\n if (!isArray(args)) return args.isOptional ? 0 : 1;\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) return 0;\n if (!isArray(args)) return args.isVariadic ? Infinity : 1;\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/** Check if a map has a key or any key from an array */\nfunction has<K>(map: Map<K, unknown>, key: K | NonEmptyArray<K>): boolean {\n if (isArray(key)) {\n return map.has(key[0]);\n }\n return map.has(key);\n}\n\n/** Get a value from a map by a key or any key from an array */\nfunction get<K, V>(map: Map<K, V>, key: K | NonEmptyArray<K>): V | undefined {\n if (isArray(key)) {\n return map.get(key[0]);\n }\n return map.get(key);\n}\n\n// TODO: Replace all instances of ParseError with a bespoke error type\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, and the arguments.\n *\n * If parsing fails, this function throws.\n *\n * This function is exposed to make it easier to build a custom runner.\n */\nexport function parse(input: readonly string[], spec: Spec): ParseResult {\n const path: [Spec, ...Subcommand[]] = [spec];\n const actions: Action[] = [];\n const optionActions: Action[] = [];\n\n if (spec.action) {\n actions.push(spec.action);\n } else if (spec.requiresSubcommand) {\n actions.push(builtinUsageAction);\n }\n\n let commandArgsMin: number = getMinArgs(spec.args);\n let commandArgsMax: number = getMaxArgs(spec.args);\n\n const foundArgs: string[] = [];\n const foundOptions: Map<string, string[]> = new Map();\n\n // These have to be type assertions otherwise TS will incorrectly\n // infer that the variables are never reassigned\n let state = State.ParseArgs as State;\n let optionArgs = null as string[] | null;\n let optionArgsMin = 0;\n let optionArgsMax = 0;\n let requiredSeparator = false as string | boolean;\n let argSeparatorIndex = -1;\n\n // Each item in this set must be provided\n const dependsOnOptions = [] as Option[];\n // Each item in this set cannot be provided\n const exclusiveOnOptions = [] as Option[];\n\n const parseOption = (token: TokenOption<Option>) => {\n const option = token.option;\n\n // Don't allow repeating non-repeatable options\n if (!option.isRepeatable && has(foundOptions, option.name)) {\n throw new ParseError(ctx(), \"Repeated option\");\n }\n\n if (option.exclusiveOn) {\n exclusiveOnOptions.push(option);\n }\n\n if (option.dependsOn) {\n dependsOnOptions.push(option);\n }\n\n if (option.action) {\n optionActions.push(option.action);\n }\n\n // Repeatable options are treated differently so we\n // *have* to branch on this.\n if (option.isRepeatable) {\n const maxRepeat = option.isRepeatable === true ? Infinity : option.isRepeatable;\n let arr = get(foundOptions, option.name);\n if (!arr) {\n arr = [];\n setEach(foundOptions, option.name, arr);\n }\n if (arr.length >= maxRepeat) {\n throw new ParseError(ctx(), \"Too many repetitions\");\n }\n arr.push(\"\");\n return;\n }\n\n optionArgsMin = getMinArgs(option.args);\n optionArgsMax = getMaxArgs(option.args);\n\n optionArgs = [];\n setEach(foundOptions, option.name, optionArgs);\n\n if (optionArgsMax === 0) {\n optionArgs = null;\n state = State.ParseArgs;\n return;\n }\n\n if (option.requiresSeparator) {\n state = State.ParseOptionArgRequireSeparator;\n requiredSeparator = option.requiresSeparator;\n } else {\n state = State.ParseOptionArgs;\n }\n return;\n };\n\n const parseArg = (token: BaseToken) => {\n // If the final command requires a subcommand, providing too\n // many arguments is allowed because the user has made a typo\n // (they were intending to use a subcommand)\n if (!path[path.length - 1].requiresSubcommand && foundArgs.length >= commandArgsMax) {\n throw new TooManyArguments(token, ctx());\n }\n foundArgs.push(token.literal);\n };\n\n const parseArgSeparator = () => {\n if (foundArgs.length >= commandArgsMax) {\n throw new ParseError(\n ctx(),\n \"Unexpected argument '--', did you mean to use an option instead?\",\n );\n }\n argSeparatorIndex = foundArgs.length;\n state = State.ParseArgs;\n };\n\n const parseSubcommand = (token: TokenSubcommand<Subcommand>) => {\n path.push(token.subcommand);\n commandArgsMin = getMinArgs(token.subcommand.args);\n commandArgsMax = getMaxArgs(token.subcommand.args);\n if (token.subcommand.action) {\n actions.push(token.subcommand.action);\n } else if (token.subcommand.requiresSubcommand) {\n actions.push(builtinUsageAction);\n }\n };\n\n const ctx = () => ({ path }) as ErrorContext;\n\n const { finalState, tokens } = analyze<Subcommand, Option>(input, spec);\n\n for (const token of tokens) {\n switch (state) {\n case State.ParseArgs: {\n switch (token.kind) {\n case \"subcommand\": {\n parseSubcommand(token);\n break;\n }\n case \"arg\": {\n parseArg(token);\n break;\n }\n case \"option\": {\n parseOption(token);\n break;\n }\n case \"unknown-option\": {\n throw new UnknownOption(token, ctx());\n }\n case \"option-arg\": {\n throw new InvalidOptionArg(token, ctx());\n }\n case \"arg-separator\": {\n parseArgSeparator();\n break;\n }\n default: {\n throw new ParseError(ctx(), \"Unreachable\");\n }\n }\n break;\n }\n case State.ParseOptionArgs: {\n assert(\n Array.isArray(optionArgs),\n \"Invalid state, must have an array to store option arguments\",\n );\n switch (token.kind) {\n case \"option-arg\":\n case \"arg\": {\n if (optionArgs.length < optionArgsMax) {\n optionArgs.push(token.literal);\n } else {\n optionArgs = null;\n state = State.ParseArgs;\n parseArg(token);\n }\n break;\n }\n case \"option\": {\n if (optionArgs.length < optionArgsMin) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n parseOption(token);\n break;\n }\n case \"unknown-option\": {\n if (optionArgs.length < optionArgsMax) {\n optionArgs.push(token.literal);\n } else {\n throw new UnknownOption(token, ctx());\n }\n break;\n }\n case \"arg-separator\": {\n if (optionArgs.length < optionArgsMin) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n parseArgSeparator();\n break;\n }\n case \"subcommand\": {\n throw new ParseError(ctx(), \"Unexpected token\");\n }\n // The analyzer can't output a subcommand here, and if it does\n // then that's an error anyway\n default: {\n throw new ParseError(ctx(), \"Unreachable\");\n }\n }\n break;\n }\n case State.ParseOptionArgRequireSeparator: {\n assert(\n Array.isArray(optionArgs),\n \"Invalid state, must have an array to store option arguments\",\n );\n assert(requiredSeparator, \"Invalid state, a separator must be set\");\n switch (token.kind) {\n case \"option-arg\": {\n if (typeof requiredSeparator === \"string\" && token.separator !== requiredSeparator) {\n throw new ParseError(\n ctx(),\n `Incorrect separator, use '${requiredSeparator}' instead of '${token.separator}'`,\n );\n }\n // If this is true, we know thanks to the test suite that\n // the option takes a minimum of one argument\n optionArgs.push(token.literal);\n state = State.ParseArgs;\n break;\n }\n case \"arg\": {\n if (optionArgsMin > 0) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n optionArgs = null;\n state = State.ParseArgs;\n parseArg(token);\n break;\n }\n case \"option\": {\n if (optionArgsMin > 0) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n parseOption(token);\n break;\n }\n case \"unknown-option\": {\n throw new UnknownOption(token, ctx());\n }\n case \"arg-separator\": {\n throw new ParseError(ctx(), \"Unexpected token\");\n }\n case \"subcommand\": {\n if (optionArgsMin > 0) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n parseSubcommand(token);\n state = State.ParseArgs;\n break;\n }\n default: {\n throw new ParseError(ctx(), \"Unreachable\");\n }\n }\n break;\n }\n }\n }\n\n const hasOptionAction = optionActions.length > 0;\n\n if (!hasOptionAction && foundArgs.length < commandArgsMin) {\n throw new TooFewArguments(commandArgsMin, commandArgsMax, ctx());\n }\n if (optionArgs && optionArgs.length < optionArgsMin) {\n throw new TooFewOptionArguments(optionArgsMin, optionArgsMax, ctx());\n }\n\n // Options in the `{depends,exclusive}On` arrays definitely have the\n // corresponding array, so it's safe to assert non-null in this situation.\n for (const option of dependsOnOptions) {\n for (const name of option.dependsOn!) {\n if (!foundOptions.has(name)) {\n throw new ParseError(ctx(), `${option.name} requires ${name}, add it to fix this error`);\n }\n }\n }\n for (const option of exclusiveOnOptions) {\n for (const name of option.exclusiveOn!) {\n if (foundOptions.has(name)) {\n throw new ParseError(ctx(), `${option.name} can't be used together with ${name}`);\n }\n }\n }\n if (!hasOptionAction) {\n for (const name of finalState.localRequiredOptions.keys()) {\n if (!foundOptions.has(name)) {\n throw new MissingRequiredOption(name, ctx());\n }\n }\n for (const name of finalState.persistentRequiredOptions.keys()) {\n if (!foundOptions.has(name)) {\n throw new MissingRequiredOption(name, ctx());\n }\n }\n }\n\n return {\n path,\n actions,\n optionActions,\n argSeparatorIndex,\n args: foundArgs,\n options: foundOptions,\n };\n}\n","/**\n * Shell completion script generation.\n *\n * `getCompletion` walks a spec and renders a static completion script for a\n * supported shell. The `completion` subcommand wires this into a CLI the same\n * way `helpCommand` wires in help: drop it into `subcommands` and users get\n * `mycli completion <shell>`.\n *\n * Every renderer uses the same shape: descend through the typed subcommand\n * tokens to a stable \"node key\", then offer that node's candidate tokens\n * (subcommands + options). Options and subcommands inherited from ancestors\n * (persistent options) are resolved during the walk.\n *\n * Argument values are completed from the Fig-style metadata on a option's first\n * argument: `template` (file/folder paths), static `suggestions`, and dynamic\n * `generators`. A dynamic generator is run by re-invoking the CLI's hidden\n * `completion generate-suggestions <location>` command, where `<location>` is a\n * base64-encoded pointer to the generator inside the spec.\n *\n * @module\n */\n\nimport type { Arg, Option, Generator, Spec, Subcommand, Template } from \"./types.js\";\nimport { asArray, makeArray, print, printActionError } from \"./util.js\";\nimport { analyze } from \"./analyze.js\";\nimport { getMaxArgs } from \"./parse.js\";\n\n/** Shells that {@link getCompletion} can generate scripts for. */\nexport type Shell = \"bash\" | \"zsh\" | \"fish\";\n\n/** How a completion script resolves candidates. */\nexport type Mode = \"runtime\" | \"shell\";\n\nexport const SHELLS: readonly Shell[] = [\"bash\", \"zsh\", \"fish\"];\n\nfunction isShell(value: string): value is Shell {\n return (SHELLS as readonly string[]).includes(value);\n}\n\n/** A pointer to a generator inside the spec, carried through base64. */\ninterface Location {\n /** Subcommand tokens (primary names) from the root to the command. */\n path: string[];\n /** Owning option's name, or omitted for a positional argument. */\n option?: string;\n /** Index into the option's (or command's) args. */\n argIndex: number;\n /** Index into that argument's generators. */\n genIndex: number;\n}\n\n/** Completion behavior derived from an argument's Fig-style metadata. */\ninterface ArgComplete {\n template?: Template;\n /** Static suggestion values (already flattened to insertable strings). */\n staticValues: string[];\n /** base64 location of the first `custom` generator, if any. */\n customLocation?: string;\n}\n\ninterface OptionInfo {\n /** Every alias of the option, e.g. `[\"-v\", \"--verbose\"]`. */\n tokens: string[];\n description: string;\n takesArg: boolean;\n argComplete?: ArgComplete;\n}\n\ninterface SubInfo {\n /** Every alias of the child subcommand. */\n tokens: string[];\n description: string;\n}\n\ninterface Node {\n /** Stable key identifying this command's position in the tree. */\n key: string;\n /** Subcommand tokens (primary names) from the root to this command. */\n path: string[];\n subcommands: SubInfo[];\n options: OptionInfo[];\n /** Completion for the command's positional argument, if any. */\n positional?: ArgComplete;\n /** One entry per child alias, mapping a typed token to the child's key. */\n transitions: { token: string; childKey: string }[];\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// base64(JSON) location encoding {{{\n\nfunction encodeLocation(location: Location): string {\n const bytes = new TextEncoder().encode(JSON.stringify(location));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeLocation(encoded: string): Location {\n const binary = atob(encoded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as Location;\n}\n\n// }}}\n\n/** Build {@link ArgComplete} for one argument at a known spec location. */\nfunction argCompleteFor(arg: Arg, location: Omit<Location, \"genIndex\">): ArgComplete | undefined {\n const staticValues = (arg.suggestions ?? []).map((suggestion) =>\n typeof suggestion === \"string\" ? suggestion : makeArray(suggestion.name)[0],\n );\n\n const generators = makeArray(arg.generators);\n const genIndex = generators.findIndex((generator) => generator.custom);\n const customLocation = genIndex >= 0 ? encodeLocation({ ...location, genIndex }) : undefined;\n\n if (!arg.template && staticValues.length === 0 && !customLocation) {\n return undefined;\n }\n return { template: arg.template, staticValues, customLocation };\n}\n\n/** Completion for a option's first argument, if it has any metadata. */\nfunction optionArgComplete(option: Option, path: string[]): ArgComplete | undefined {\n const arg = asArray(option.args)[0] as Arg | undefined;\n if (!arg) return undefined;\n return argCompleteFor(arg, { path, option: makeArray(option.name)[0], argIndex: 0 });\n}\n\n/** Completion for a command's first positional arg that has metadata. */\nfunction positionalComplete(command: Subcommand, path: string[]): ArgComplete | undefined {\n const args = asArray(command.args) as Arg[];\n for (let index = 0; index < args.length; index += 1) {\n const ac = argCompleteFor(args[index], { path, argIndex: index });\n if (ac) return ac;\n }\n return undefined;\n}\n\nfunction toOptionInfo(option: Option, path: string[]): OptionInfo {\n return {\n tokens: makeArray(option.name),\n description: firstLine(option.description),\n takesArg: asArray(option.args).length > 0,\n argComplete: optionArgComplete(option, path),\n };\n}\n\n/**\n * Flatten the spec into a list of command nodes. Hidden options and subcommands\n * are excluded; persistent options are propagated to descendants.\n */\nfunction walk(spec: Spec): Node[] {\n const nodes: Node[] = [];\n\n const recurse = (\n command: Subcommand,\n key: string,\n path: string[],\n inheritedPersistent: Option[],\n ): void => {\n const ownOptions = (command.options ?? []).filter((option) => !option.hidden);\n const children = (command.subcommands ?? []).filter((sub) => !sub.hidden);\n\n const node: Node = {\n key,\n path,\n subcommands: [],\n options: [...inheritedPersistent, ...ownOptions].map((option) => toOptionInfo(option, path)),\n positional: positionalComplete(command, path),\n transitions: [],\n };\n\n const childPersistent = [\n ...inheritedPersistent,\n ...ownOptions.filter((option) => option.isPersistent),\n ];\n\n for (const child of children) {\n const tokens = makeArray(child.name);\n const childKey = `${key}_${sanitize(tokens[0])}`;\n node.subcommands.push({\n tokens,\n description: firstLine(child.description),\n });\n for (const token of tokens) {\n node.transitions.push({ token, childKey });\n }\n recurse(child, childKey, [...path, tokens[0]], childPersistent);\n }\n\n nodes.push(node);\n };\n\n recurse(spec as unknown as Subcommand, \"cmd\", [], []);\n return nodes;\n}\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/** Every candidate token offered at a node (subcommand aliases + option aliases). */\nfunction candidateTokens(node: Node): string[] {\n const tokens: string[] = [];\n for (const sub of node.subcommands) tokens.push(...sub.tokens);\n for (const option of node.options) tokens.push(...option.tokens);\n return tokens;\n}\n\nfunction renderTransitionCases(nodes: Node[], indent: string): string[] {\n const lines: string[] = [];\n for (const node of nodes) {\n for (const { token, childKey } of node.transitions) {\n lines.push(`${indent}${shQuote(`${node.key}::${token}`)}) cmd=${shQuote(childKey)} ;;`);\n }\n }\n return lines;\n}\n\n// bash {{{\n\n/**\n * bash candidate lines for an arg. `append` keeps existing COMPREPLY (for a\n * positional, which coexists with subcommands/options); otherwise it replaces.\n * The generator callback uses the typed command and is guarded for resilience.\n */\nfunction bashArgLines(ac: ArgComplete, indent: string, append: boolean): string[] {\n const lines: string[] = [];\n const op = append ? \"COMPREPLY+=\" : \"COMPREPLY=\";\n const hasWords = ac.staticValues.length > 0 || ac.customLocation !== undefined;\n\n if (hasWords) {\n lines.push(\n `${indent}local words=${\n ac.staticValues.length > 0 ? shQuote(ac.staticValues.join(\" \")) : '\"\"'\n }`,\n );\n if (ac.customLocation) {\n lines.push(`${indent}if command -v \"\\${COMP_WORDS[0]}\" >/dev/null 2>&1; then`);\n lines.push(\n `${indent} words=\"$words $(\"\\${COMP_WORDS[0]}\" completion generate-suggestions ${shQuote(ac.customLocation)} -- \"\\${COMP_WORDS[@]:1}\" 2>/dev/null)\"`,\n );\n lines.push(`${indent}fi`);\n }\n lines.push(`${indent}${op}( $(compgen -W \"$words\" -- \"$cur\") )`);\n }\n if (ac.template) {\n const option = ac.template === \"folders\" ? \"-d\" : \"-f\";\n const fileOp = hasWords || append ? \"COMPREPLY+=\" : \"COMPREPLY=\";\n lines.push(`${indent}${fileOp}( $(compgen ${option} -- \"$cur\") )`);\n }\n return lines;\n}\n\nfunction renderBash(spec: Spec, nodes: Node[]): string {\n const id = sanitize(spec.name);\n const lines: string[] = [];\n\n lines.push(`_${id}() {`);\n lines.push(` local cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`);\n lines.push(` local prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"`);\n lines.push(` local cmd=\"cmd\" i w`);\n lines.push(` for (( i=1; i < COMP_CWORD; i++ )); do`);\n lines.push(` w=\"\\${COMP_WORDS[i]}\"`);\n lines.push(` case \"$w\" in -* ) continue ;; esac`);\n lines.push(` case \"\\${cmd}::\\${w}\" in`);\n lines.push(...renderTransitionCases(nodes, \" \"));\n lines.push(` esac`);\n lines.push(` done`);\n\n // Option-argument completion, scoped to the command context + option token.\n const argCases: string[] = [];\n for (const node of nodes) {\n for (const option of node.options) {\n if (!option.argComplete) continue;\n for (const token of option.tokens) {\n argCases.push(` ${shQuote(`${node.key}::${token}`)})`);\n argCases.push(...bashArgLines(option.argComplete, \" \", false));\n argCases.push(` return ;;`);\n }\n }\n }\n if (argCases.length > 0) {\n lines.push(` case \"\\${cmd}::\\${prev}\" in`);\n lines.push(...argCases);\n lines.push(` esac`);\n }\n\n lines.push(` local opts=\"\"`);\n lines.push(` case \"$cmd\" in`);\n for (const node of nodes) {\n lines.push(` ${shQuote(node.key)}) opts=${shQuote(candidateTokens(node).join(\" \"))} ;;`);\n }\n lines.push(` esac`);\n lines.push(` COMPREPLY=( $(compgen -W \"$opts\" -- \"$cur\") )`);\n\n // Positional values are offered alongside subcommands/options.\n const posCases: string[] = [];\n for (const node of nodes) {\n if (!node.positional) continue;\n posCases.push(` ${shQuote(node.key)})`);\n posCases.push(...bashArgLines(node.positional, \" \", true));\n posCases.push(` ;;`);\n }\n if (posCases.length > 0) {\n lines.push(` case \"$cmd\" in`);\n lines.push(...posCases);\n lines.push(` esac`);\n }\n\n lines.push(`}`);\n lines.push(`complete -F _${id} ${shQuote(spec.name)}`);\n return lines.join(\"\\n\");\n}\n\n// }}}\n\n// zsh {{{\n\n/** zsh candidate lines for an arg (used for both option values and positionals). */\nfunction zshArgLines(ac: ArgComplete, indent: string): string[] {\n const lines: string[] = [];\n const hasVals = ac.staticValues.length > 0 || ac.customLocation !== undefined;\n\n if (hasVals) {\n lines.push(`${indent}local -a vals`);\n lines.push(`${indent}vals=( ${ac.staticValues.map(shQuote).join(\" \")} )`);\n if (ac.customLocation) {\n // Typed command, guarded so a missing binary doesn't error.\n lines.push(`${indent}if command -v \"$words[1]\" >/dev/null 2>&1; then`);\n lines.push(\n `${indent} vals+=( \\${(f)\"$(\"$words[1]\" completion generate-suggestions ${shQuote(ac.customLocation)} -- \\${words[2,-1]} 2>/dev/null)\"} )`,\n );\n lines.push(`${indent}fi`);\n }\n lines.push(`${indent}compadd -a vals`);\n }\n if (ac.template) {\n lines.push(`${indent}${ac.template === \"folders\" ? \"_files -/\" : \"_files\"}`);\n }\n return lines;\n}\n\nfunction renderZsh(spec: Spec, nodes: Node[]): string {\n const id = sanitize(spec.name);\n const lines: string[] = [];\n\n lines.push(`#compdef ${spec.name}`);\n lines.push(`_${id}() {`);\n lines.push(` local cmd=cmd i w prev`);\n lines.push(` for (( i=2; i < CURRENT; i++ )); do`);\n lines.push(` w=\"\\${words[i]}\"`);\n lines.push(` case \"$w\" in -* ) continue ;; esac`);\n lines.push(` case \"\\${cmd}::\\${w}\" in`);\n lines.push(...renderTransitionCases(nodes, \" \"));\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` prev=\"\\${words[CURRENT-1]}\"`);\n\n const argCases: string[] = [];\n for (const node of nodes) {\n for (const option of node.options) {\n if (!option.argComplete) continue;\n for (const token of option.tokens) {\n argCases.push(` ${shQuote(`${node.key}::${token}`)})`);\n argCases.push(...zshArgLines(option.argComplete, \" \"));\n argCases.push(` return ;;`);\n }\n }\n }\n if (argCases.length > 0) {\n lines.push(` case \"\\${cmd}::\\${prev}\" in`);\n lines.push(...argCases);\n lines.push(` esac`);\n }\n\n lines.push(` local -a opts`);\n lines.push(` case \"$cmd\" in`);\n for (const node of nodes) {\n const entries: string[] = [];\n for (const sub of node.subcommands) {\n for (const token of sub.tokens) {\n entries.push(shQuote(`${token}:${sub.description}`));\n }\n }\n for (const option of node.options) {\n for (const token of option.tokens) {\n entries.push(shQuote(`${token}:${option.description}`));\n }\n }\n lines.push(` ${shQuote(node.key)}) opts=( ${entries.join(\" \")} ) ;;`);\n }\n lines.push(` esac`);\n lines.push(` _describe -t values ${shQuote(spec.name)} opts`);\n\n // Positional values, offered after the subcommand/option list.\n const posCases: string[] = [];\n for (const node of nodes) {\n if (!node.positional) continue;\n posCases.push(` ${shQuote(node.key)})`);\n posCases.push(...zshArgLines(node.positional, \" \"));\n posCases.push(` ;;`);\n }\n if (posCases.length > 0) {\n lines.push(` case \"$cmd\" in`);\n lines.push(...posCases);\n lines.push(` esac`);\n }\n\n lines.push(`}`);\n lines.push(`_${id} \"$@\"`);\n return lines.join(\"\\n\");\n}\n\n// }}}\n\n// fish {{{\n\n/** Build the fish `complete` option selectors (`-s x`, `-l long`, `-o old`). */\nfunction fishOptionSelectors(tokens: string[]): string {\n const parts: string[] = [];\n for (const token of tokens) {\n if (token.startsWith(\"--\")) {\n parts.push(`-l ${fishQuote(token.slice(2))}`);\n } else if (token.startsWith(\"-\") && token.length === 2) {\n parts.push(`-s ${fishQuote(token.slice(1))}`);\n } else if (token.startsWith(\"-\") && token.length > 2) {\n parts.push(`-o ${fishQuote(token.slice(1))}`);\n } else {\n // POSIX-noncompliant option (no leading dash): offer it as a plain value.\n parts.push(`-a ${fishQuote(token)}`);\n }\n }\n return parts.join(\" \");\n}\n\n/** A guarded fish command substitution that runs a generator by location. */\nfunction fishGuardedCallback(location: string): string {\n // `command -q` only searches PATH, so also accept a runnable path (./cli).\n return `(set -l c (commandline -opc)[1]; if command -q -- $c; or test -x \"$c\"; $c completion generate-suggestions ${location} -- (commandline -opc) 2>/dev/null; end)`;\n}\n\n/** The `-a` candidate bits and whether the shell's file completion is wanted. */\nfunction fishValueBits(ac: ArgComplete): { aBits: string; wantsFiles: boolean } {\n const parts: string[] = [...ac.staticValues];\n if (ac.template === \"folders\" || Array.isArray(ac.template)) {\n parts.push(\"(__fish_complete_directories)\");\n }\n if (ac.customLocation) parts.push(fishGuardedCallback(ac.customLocation));\n const aBits = parts.length > 0 ? ` -a ${fishQuote(parts.join(\" \"))}` : \"\";\n const wantsFiles = ac.template === \"filepaths\" || Array.isArray(ac.template);\n return { aBits, wantsFiles };\n}\n\n/**\n * The suffix after a option's selectors. Uses `-x` (exclusive: requires a value\n * and suppresses fish's file fallback) when the arg has its own candidates and\n * isn't a filepaths template; `-r` lets files through when they're wanted.\n */\nfunction fishOptionArgSuffix(option: OptionInfo): string {\n if (!option.takesArg) return \"\";\n if (!option.argComplete) return \" -r\"; // takes a value, no metadata: native files\n const { aBits, wantsFiles } = fishValueBits(option.argComplete);\n return `${wantsFiles ? \" -r\" : \" -x\"}${aBits}`;\n}\n\nfunction renderFish(spec: Spec, nodes: Node[]): string {\n const id = sanitize(spec.name);\n const name = spec.name;\n const lines: string[] = [];\n\n lines.push(`function __fish_${id}_at`);\n lines.push(` set -l cmd cmd`);\n lines.push(` set -l toks (commandline -opc)`);\n lines.push(` for w in $toks[2..-1]`);\n lines.push(` if string match -qr '^-' -- $w`);\n lines.push(` continue`);\n lines.push(` end`);\n lines.push(` switch \"$cmd $w\"`);\n for (const node of nodes) {\n for (const { token, childKey } of node.transitions) {\n lines.push(` case ${fishQuote(`${node.key} ${token}`)}`);\n lines.push(` set cmd ${fishQuote(childKey)}`);\n }\n }\n lines.push(` end`);\n lines.push(` end`);\n lines.push(` test \"$cmd\" = \"$argv[1]\"`);\n lines.push(`end`);\n lines.push(\"\");\n // Disable fallback filename completion; commands re-enable it per arg later.\n lines.push(`complete -c ${fishQuote(name)} -f`);\n for (const node of nodes) {\n const guard = `-n ${fishQuote(`__fish_${id}_at ${node.key}`)}`;\n for (const sub of node.subcommands) {\n for (const token of sub.tokens) {\n const desc = sub.description ? ` -d ${fishQuote(sub.description)}` : \"\";\n lines.push(`complete -c ${fishQuote(name)} ${guard} -a ${fishQuote(token)}${desc}`);\n }\n }\n for (const option of node.options) {\n const desc = option.description ? ` -d ${fishQuote(option.description)}` : \"\";\n const suffix = fishOptionArgSuffix(option);\n lines.push(\n `complete -c ${fishQuote(name)} ${guard} ${fishOptionSelectors(option.tokens)}${suffix}${desc}`,\n );\n }\n // Positional value completion (global `-f` keeps files out unless -F).\n if (node.positional) {\n const { aBits, wantsFiles } = fishValueBits(node.positional);\n lines.push(`complete -c ${fishQuote(name)} ${guard}${aBits}${wantsFiles ? \" -F\" : \"\"}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n// }}}\n\n// Runtime resolver {{{\n\n/** A single completion candidate. */\ninterface Candidate {\n value: string;\n description?: string;\n}\n\n/**\n * The completion-relevant state of a partial command line, derived by reusing\n * `analyze` (which already handles `--`, separators, prefix-matching, and\n * posix-noncompliance) plus a small non-throwing pass for option-arg consumption\n * and positional counting.\n */\ninterface CompletionState {\n /** Commands from the root to the current one. */\n path: Subcommand[];\n current: Subcommand;\n /** Options usable at the current command (own + inherited persistent). */\n availableOptions: Option[];\n /** A option still expecting a separate-token value, or null. */\n pending: { option: Option; argIndex: number } | null;\n /** Positional args already consumed by the current command. */\n positionalIndex: number;\n /** Option names already present on the line. */\n presentNames: Set<string>;\n /** Times each option object has appeared. */\n countByOption: Map<Option, number>;\n /** A `--` separator was seen; only positionals follow. */\n forceArgs: boolean;\n /** A positional has been consumed by the current command. */\n sawPositional: boolean;\n /** A non-persistent option has been used (blocks subcommand matching). */\n usedNonPersistentOption: boolean;\n}\n\nfunction analyzeState(spec: Spec, before: readonly string[]): CompletionState {\n const { tokens, finalState } = analyze<Subcommand, Option>(before, spec);\n\n const path: Subcommand[] = [spec as unknown as Subcommand];\n let current: Subcommand = spec as unknown as Subcommand;\n let pending: CompletionState[\"pending\"] = null;\n let pendingFilled = 0;\n let pendingMax = 0;\n let positionalIndex = 0;\n let forceArgs = false;\n let sawPositional = false;\n let usedNonPersistentOption = false;\n const presentNames = new Set<string>();\n const countByOption = new Map<Option, number>();\n\n for (const token of tokens) {\n switch (token.kind) {\n case \"subcommand\": {\n current = token.subcommand;\n path.push(current);\n positionalIndex = 0;\n sawPositional = false;\n pending = null;\n break;\n }\n case \"option\": {\n const option = token.option;\n for (const name of makeArray(option.name)) presentNames.add(name);\n countByOption.set(option, (countByOption.get(option) ?? 0) + 1);\n if (!option.isPersistent) usedNonPersistentOption = true;\n const max = getMaxArgs(option.args);\n // requiresSeparator options only take an attached value, never a\n // following separate token, so they never leave a pending value.\n if (max > 0 && !option.requiresSeparator) {\n pending = { option, argIndex: 0 };\n pendingFilled = 0;\n pendingMax = max;\n } else {\n pending = null;\n }\n break;\n }\n case \"option-arg\": {\n // An attached value (`--option=v`, `-fv`) satisfies the preceding option.\n pending = null;\n break;\n }\n case \"arg\": {\n if (pending && pendingFilled < pendingMax) {\n pendingFilled += 1;\n pending = { option: pending.option, argIndex: pendingFilled };\n if (pendingFilled >= pendingMax) pending = null;\n } else {\n positionalIndex += 1;\n sawPositional = true;\n pending = null;\n }\n break;\n }\n case \"arg-separator\": {\n forceArgs = true;\n pending = null;\n break;\n }\n case \"unknown-option\": {\n pending = null;\n break;\n }\n }\n }\n\n const availableOptions: Option[] = [];\n const seen = new Set<Option>();\n for (const map of [finalState.localOptions, finalState.persistentOptions]) {\n for (const option of map.values()) {\n if (!seen.has(option)) {\n seen.add(option);\n availableOptions.push(option);\n }\n }\n }\n\n return {\n path,\n current,\n availableOptions,\n pending,\n positionalIndex,\n presentNames,\n countByOption,\n forceArgs,\n sawPositional,\n usedNonPersistentOption,\n };\n}\n\n/** Does any command on the path enable a sticky parser directive? */\nfunction directiveOnPath(\n path: readonly Subcommand[],\n key: \"optionsMustPrecedeArguments\" | \"flagsArePosixNoncompliant\",\n): boolean {\n return path.some((command) => command.parserDirectives?.[key]);\n}\n\n/** The option-arg separators in effect (the deepest command that sets them). */\nfunction separatorsOnPath(path: readonly Subcommand[]): string[] {\n let separators = [\"=\"];\n for (const command of path) {\n const configured = command.parserDirectives?.optionArgSeparators;\n if (configured) separators = makeArray(configured);\n }\n return separators;\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(\n path: string,\n options: { withFileTypes: true },\n ): { name: string; isDirectory(): boolean }[];\n };\n const slash = partial.lastIndexOf(\"/\");\n const dir = slash >= 0 ? partial.slice(0, slash + 1) : \"\";\n const base = slash >= 0 ? partial.slice(slash + 1) : partial;\n const foldersOnly = template === \"folders\";\n let entries: { name: string; isDirectory(): boolean }[];\n try {\n entries = readdirSync(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)) continue;\n const isDir = entry.isDirectory();\n if (foldersOnly && !isDir) continue;\n candidates.push({ value: `${dir}${entry.name}${isDir ? \"/\" : \"\"}` });\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) continue;\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/** Pick the argument being completed at a positional index (honors variadic). */\nfunction positionalArg(command: Subcommand, index: number): Arg | undefined {\n const args = asArray(command.args) as readonly Arg[];\n if (args.length === 0) return undefined;\n if (index < args.length) return args[index];\n const last = args[args.length - 1];\n return last?.isVariadic ? last : undefined;\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, reusing the parser\n * (`analyze`) for context. Dispatches between completing a option's value and\n * completing a fresh token (subcommand / positional / option).\n */\nexport async function completeRuntime(req: CompletionRequest): Promise<Candidate[]> {\n const state = analyzeState(req.spec, req.before);\n const separators = separatorsOnPath(state.path);\n\n const optionValue = await resolveOptionValue(state, req, separators);\n if (optionValue) return optionValue;\n\n return freshTokenCandidates(state, req, separators);\n}\n\n/**\n * Candidates when the word being completed is a option's value — either attached\n * (`--option=value`) or the separate token after a option that expects one. Returns\n * null when no option value is being completed.\n */\nasync function resolveOptionValue(\n state: CompletionState,\n req: CompletionRequest,\n separators: string[],\n): Promise<Candidate[] | null> {\n const tokens = [...req.before];\n\n // `--option<sep>value`: the partial already carries a separator.\n for (const separator of separators) {\n const at = req.partial.indexOf(separator);\n if (at <= 0) continue;\n const optionName = req.partial.slice(0, at);\n const option = state.availableOptions.find((candidate) =>\n makeArray(candidate.name).includes(optionName),\n );\n const arg = option && (asArray(option.args) as Arg[])[0];\n if (option && arg) {\n const valuePrefix = req.partial.slice(at + separator.length);\n const values = await argValues(arg, tokens, valuePrefix);\n return values.map((candidate) => ({\n value: `${optionName}${separator}${candidate.value}`,\n description: candidate.description,\n }));\n }\n }\n\n // The separate-token value of a option that expects one.\n if (state.pending) {\n const arg = (asArray(state.pending.option.args) as Arg[])[state.pending.argIndex];\n return arg ? argValues(arg, tokens, req.partial) : [];\n }\n\n return null;\n}\n\n/** Candidates when completing a fresh token: subcommand / positional / option. */\nasync function freshTokenCandidates(\n state: CompletionState,\n req: CompletionRequest,\n separators: string[],\n): Promise<Candidate[]> {\n const candidates: Candidate[] = [];\n const tokens = [...req.before];\n\n const posixNoncompliant = directiveOnPath(state.path, \"flagsArePosixNoncompliant\");\n const partialIsOption =\n !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 const wantValues = !(req.gateOptions && partialIsOption);\n const wantOptions = !req.gateOptions || partialIsOption || posixNoncompliant;\n\n if (wantValues) {\n const positional = positionalArg(state.current, state.positionalIndex);\n if (positional) {\n candidates.push(...(await argValues(positional, tokens, req.partial)));\n }\n // After `--`, only positionals are valid.\n if (state.forceArgs) return candidates;\n\n // Subcommands — only while the parser would still match one.\n if (!state.sawPositional && !state.usedNonPersistentOption) {\n for (const sub of state.current.subcommands ?? []) {\n if (sub.hidden) continue;\n const description = firstLine(sub.description);\n for (const token of makeArray(sub.name)) {\n candidates.push({ value: token, description });\n }\n }\n }\n } else if (state.forceArgs) {\n // A dashed token after `--` is a literal argument, not a option.\n return candidates;\n }\n\n // Options — unless they must precede arguments and one was already seen.\n const optionsBlocked =\n state.sawPositional && directiveOnPath(state.path, \"optionsMustPrecedeArguments\");\n if (wantOptions && !optionsBlocked) {\n candidates.push(...optionCandidates(state, separators));\n }\n\n return candidates;\n}\n\n/** Eligible option candidates after relationship filtering. */\nfunction optionCandidates(state: CompletionState, separators: string[]): Candidate[] {\n const required: Candidate[] = [];\n const optional: Candidate[] = [];\n\n for (const option of state.availableOptions) {\n if (option.hidden) continue;\n\n // Repeatable limits: drop a option that can't appear again.\n const count = state.countByOption.get(option) ?? 0;\n if (count > 0) {\n if (!option.isRepeatable) continue;\n if (typeof option.isRepeatable === \"number\" && count >= option.isRepeatable) {\n continue;\n }\n }\n\n // Mutual exclusion, both directions.\n if (option.exclusiveOn?.some((name) => state.presentNames.has(name))) continue;\n const conflicts = state.availableOptions.some(\n (other) =>\n other !== option &&\n makeArray(other.name).some((name) => state.presentNames.has(name)) &&\n other.exclusiveOn?.some((name) => makeArray(option.name).includes(name)),\n );\n if (conflicts) continue;\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 // requiresSeparator options can only take an attached value, so offer the\n // separator form so the next Tab completes the value.\n const sep =\n option.requiresSeparator === true\n ? separators[0]\n : typeof option.requiresSeparator === \"string\"\n ? option.requiresSeparator\n : undefined;\n\n const bucket = option.isRequired ? required : optional;\n for (const token of makeArray(option.name)) {\n bucket.push({ value: sep ? `${token}${sep}` : token, 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 // 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, mode: Mode = \"runtime\"): string {\n if (mode === \"runtime\") return renderRuntimeShim(spec, shell);\n const nodes = walk(spec);\n switch (shell) {\n case \"bash\":\n return renderBash(spec, nodes);\n case \"zsh\":\n return renderZsh(spec, nodes);\n case \"fish\":\n return renderFish(spec, nodes);\n }\n}\n\n// Dynamic suggestion runtime {{{\n\n/** Resolve the argument a {@link Location} points at, or null if it's stale. */\nfunction resolveArg(spec: Spec, location: Location): Arg | null {\n let command = spec as unknown as Subcommand;\n let ancestorPersistent: Option[] = [];\n\n for (const segment of location.path) {\n ancestorPersistent = [\n ...ancestorPersistent,\n ...(command.options ?? []).filter((option) => option.isPersistent),\n ];\n const child = (command.subcommands ?? []).find((sub) => makeArray(sub.name).includes(segment));\n if (!child) return null;\n command = child;\n }\n\n let args: readonly Arg[];\n if (location.option !== undefined) {\n const available = [...ancestorPersistent, ...(command.options ?? [])];\n const option = available.find((candidate) =>\n makeArray(candidate.name).includes(location.option!),\n );\n if (!option) return null;\n args = asArray(option.args);\n } else {\n args = asArray(command.args);\n }\n\n return args[location.argIndex] ?? null;\n}\n\n/**\n * Run the generator a base64 location points at and return its suggestions as\n * insertable strings, or null if the location is invalid.\n */\nasync function generateSuggestions(\n spec: Spec,\n encoded: string,\n tokens: string[],\n): Promise<string[] | null> {\n let location: Location;\n try {\n location = decodeLocation(encoded);\n } catch {\n return null;\n }\n\n const arg = resolveArg(spec, location);\n if (!arg) return null;\n\n const generator: Generator | undefined = makeArray(arg.generators)[location.genIndex];\n if (!generator?.custom) return null;\n\n const suggestions = await generator.custom(tokens);\n return suggestions.map((suggestion) =>\n typeof suggestion === \"string\" ? suggestion : makeArray(suggestion.name)[0],\n );\n}\n\n/**\n * Hidden machine-facing subcommand that generated scripts call back into to\n * run a `custom` generator. Not shown in help.\n */\nconst generateSuggestionsCommand: Subcommand = {\n name: \"generate-suggestions\",\n description: \"Print dynamic suggestions for a completion generator\",\n hidden: true,\n args: [{ name: \"location\" }, { name: \"tokens\", isVariadic: true, isOptional: true }],\n async action({ path, args: [encoded, ...tokens] }) {\n const spec = path[0] as Spec;\n if (encoded === undefined) {\n printActionError(\"Missing generator location\");\n return 1;\n }\n const suggestions = await generateSuggestions(spec, encoded, tokens);\n if (suggestions === null) {\n printActionError(`Unknown generator location '${encoded}'`);\n return 1;\n }\n if (suggestions.length > 0) {\n print(suggestions.join(\"\\n\"));\n }\n return 0;\n },\n};\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 args: { name: \"tokens\", isVariadic: true, isOptional: true },\n async action({ path, args, options }) {\n const spec = path[0] as Spec;\n const partial = args.length > 0 ? args[args.length - 1] : \"\";\n const before = 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) print(lines.join(\"\\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 },\n options: [\n {\n name: \"--runtime\",\n description: \"Resolve candidates by invoking the CLI (default)\",\n exclusiveOn: [\"--shell\"],\n },\n {\n name: \"--shell\",\n description: \"Emit a self-contained script with no per-Tab CLI call\",\n exclusiveOn: [\"--runtime\"],\n },\n ],\n subcommands: [completeCommand, generateSuggestionsCommand],\n action({ path: [spec], args: [shell], options, help }) {\n if (shell === undefined) {\n print(`Supported shells: ${SHELLS.join(\", \")}`);\n return 0;\n }\n\n if (!isShell(shell)) {\n printActionError(\n `Unsupported shell '${shell}'\\n\\n${help({\n description: false,\n didYouMean: { input: shell, choices: SHELLS as string[] },\n })}`,\n );\n return 1;\n }\n\n const mode: Mode = options.has(\"--shell\") ? \"shell\" : \"runtime\";\n print(getCompletion(spec, shell, mode));\n return 0;\n },\n};\n","import type { ActionInit, Spec } from \"./types.js\";\nimport { getHelp } from \"./help.js\";\nimport { ParseError, UnknownOption } from \"./errors.js\";\nimport { parse } from \"./parse.js\";\nimport type { ParseResult } from \"./parse.js\";\n\n/**\n * Parse argv and execute the selected action.\n *\n * The final command action runs unless a parsed option has an action. Option\n * actions take precedence so helpers like `--help` can run without satisfying\n * the selected command's required arguments.\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 UnknownOption) {\n const helpMessage = getHelp(error.context.path, {\n description: false,\n didYouMean: {\n input: error.option,\n choices: error.validOptions,\n },\n });\n printError(`${error.message}\\n\\n${helpMessage}`);\n } else if (error instanceof ParseError) {\n printError(`${error.message}\\n\\n${getHelp(error.context.path, { description: false })}`);\n } else {\n printError(`${error}`);\n }\n return 1;\n }\n\n const action = result.optionActions.at(-1) ?? result.actions.at(-1);\n if (!action) {\n return 1;\n }\n\n const options = result.options;\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)?.[0],\n all: (name) => options.get(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(error instanceof Error ? error.message : String(error));\n return 1;\n }\n\n return Math.min(Math.max(exitCode ?? 0, 0), 255);\n}\n\nexport function printError(...strings: unknown[]): void {\n console.error(\"Error:\", ...strings);\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"],"ignoreList":[3],"mappings":";;;AAEA,SAA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,KAAK,CAAC;AAClD;;ACnDA,IAAA,cAAe;CACb;CACA;CACA;CACA;CACA;AACF"}
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Declarative CLI spec types.
3
+ *
4
+ * The schema is intentionally small: define commands, positional args, options,
5
+ * and actions. Runtime values from argv are always strings.
6
+ *
7
+ * @module
8
+ */
9
+ declare const kind: unique symbol;
10
+ /** An array with at least one value in it. */
11
+ type NonEmptyArray<T> = readonly [T, ...T[]];
12
+ /** A single value, or an array with at least two values. */
13
+ type SingleOrArray<T> = T | readonly [T, T, ...T[]];
14
+ /** A single value, or an array with either zero or at least two values. */
15
+ type SingleOrArrayOrEmpty<T> = T | [] | readonly [T, T, ...T[]];
16
+ /**
17
+ * An action associated with a subcommand or option.
18
+ *
19
+ * Actions can be sync or async. Returning `undefined` is treated as exit code 0.
20
+ */
21
+ interface Action {
22
+ (init: ActionInit): Promise<number | void> | number | void;
23
+ /**
24
+ * This property never exists. It prevents accidental structural assignment
25
+ * between otherwise compatible exported interfaces.
26
+ *
27
+ * @ignore
28
+ */
29
+ [kind]?: "Action";
30
+ }
31
+ /** A command path, starting with the root spec. */
32
+ type CommandPath = readonly [Spec, ...Subcommand[]];
33
+ /** Access parsed options. */
34
+ interface OptionArgs {
35
+ /** Escape hatch: the underlying map of option names to values. */
36
+ readonly options: Map<string, string[]>;
37
+ /** Get every argument supplied to a option. */
38
+ all(name: string): string[] | undefined;
39
+ /** Get the first argument supplied to a option. */
40
+ get(name: string): string | undefined;
41
+ /** Check whether a option was supplied. */
42
+ has(name: string): boolean;
43
+ /** Count option values, useful for repeatable options. */
44
+ count(name: string): number;
45
+ }
46
+ /** The data an action receives. */
47
+ interface ActionInit {
48
+ /** Options found for this invocation. */
49
+ options: OptionArgs;
50
+ /** Positional arguments found for the selected command. */
51
+ args: string[];
52
+ /** Commands used leading up to the selected action. */
53
+ path: CommandPath;
54
+ /** Index of the `--` argument separator, or -1 if it was not supplied. */
55
+ argSeparatorIndex: number;
56
+ /** Get help text for the currently executing command. */
57
+ help(config?: {
58
+ /** Include the command description? Default: true. */
59
+ description?: boolean;
60
+ /** Include the usage summary? Default: true. */
61
+ usage?: boolean;
62
+ /** Suggest the closest choice for an incorrect input. */
63
+ didYouMean?: {
64
+ input: string;
65
+ choices: readonly string[];
66
+ };
67
+ /** Alternative command path to render help for. */
68
+ path?: NonEmptyArray<Subcommand>;
69
+ }): string;
70
+ }
71
+ /** A top-level command. */
72
+ interface Spec extends Omit<Subcommand, "name"> {
73
+ /** Name of the CLI. */
74
+ name: string;
75
+ }
76
+ /** A subcommand that can be executed. */
77
+ interface Subcommand {
78
+ /** Name or aliases used for matching. */
79
+ name: SingleOrArray<string>;
80
+ /** Description shown in help. */
81
+ description?: string;
82
+ /** Positional arguments accepted by this command. */
83
+ args?: SingleOrArray<Arg>;
84
+ /** Options accepted by this command. */
85
+ options?: NonEmptyArray<Option>;
86
+ /** Subcommands of this command. */
87
+ subcommands?: NonEmptyArray<Subcommand>;
88
+ /** Direct parser behavior. */
89
+ parserDirectives?: {
90
+ /**
91
+ * Treat option names literally, disabling POSIX short-option chaining and
92
+ * unknown option errors for tokens that look option-like.
93
+ */
94
+ flagsArePosixNoncompliant?: boolean;
95
+ /**
96
+ * Once an argument has been found, all following tokens are arguments even
97
+ * if they match options.
98
+ */
99
+ optionsMustPrecedeArguments?: boolean;
100
+ /** Separators that can attach a option argument to a option token. */
101
+ optionArgSeparators?: SingleOrArrayOrEmpty<string>;
102
+ /** Match subcommands by shortest unique prefix instead of exact name. */
103
+ subcommandsMatchUniquePrefix?: boolean;
104
+ };
105
+ /** Hide this command from help. */
106
+ hidden?: true;
107
+ /** Require a subcommand; without one, print usage. */
108
+ requiresSubcommand?: true;
109
+ /** Action to run when this command is selected. */
110
+ action?: Action;
111
+ /**
112
+ * This property never exists. It prevents accidental structural assignment
113
+ * between options and subcommands.
114
+ *
115
+ * @ignore
116
+ */
117
+ [kind]?: "Subcommand";
118
+ }
119
+ /** A option that modifies or overrides command execution. */
120
+ interface Option {
121
+ /** Name or aliases, including any desired prefix such as `-`, `--`, or `/`. */
122
+ name: SingleOrArray<string>;
123
+ /** Description shown in help. */
124
+ description?: string;
125
+ /** Arguments this option accepts. */
126
+ args?: SingleOrArray<Arg>;
127
+ /** Allow this option to be used by descendant subcommands. */
128
+ isPersistent?: true;
129
+ /** Hide this option from help. */
130
+ hidden?: true;
131
+ /** Only allow arguments to be supplied with a separator. */
132
+ requiresSeparator?: true | string;
133
+ /** Allow this option to be supplied multiple times. */
134
+ isRepeatable?: true | number;
135
+ /** Require this option to be supplied before the selected action runs. */
136
+ isRequired?: true;
137
+ /** Fail parsing if these options are provided. */
138
+ exclusiveOn?: NonEmptyArray<string>;
139
+ /** Fail parsing if these options are not provided. */
140
+ dependsOn?: NonEmptyArray<string>;
141
+ /**
142
+ * Action performed when this option is provided.
143
+ *
144
+ * Option actions take precedence over command actions. The final parsed option
145
+ * action is selected.
146
+ */
147
+ action?: Action;
148
+ /**
149
+ * This property never exists. It prevents accidental structural assignment
150
+ * between options and subcommands.
151
+ *
152
+ * @ignore
153
+ */
154
+ [kind]?: "Option";
155
+ }
156
+ /**
157
+ * A built-in completion template.
158
+ *
159
+ * Resolves to the shell's native path completion. Completions only — no effect
160
+ * on parsing.
161
+ */
162
+ type Template = "filepaths" | "folders" | ["folders", "filepaths"] | ["filepaths", "folders"];
163
+ /**
164
+ * A single completion suggestion.
165
+ *
166
+ * This is a deliberately small subset of the Fig `Suggestion` shape — just the
167
+ * fields the completion engine uses. Presentational fields (icon, priority,
168
+ * displayName, insertValue, type) are intentionally omitted.
169
+ */
170
+ interface Suggestion {
171
+ /** Value(s) inserted when the suggestion is accepted. */
172
+ name: SingleOrArray<string>;
173
+ /** Additional information shown next to the suggestion. */
174
+ description?: string;
175
+ }
176
+ /**
177
+ * Generates dynamic completion suggestions.
178
+ *
179
+ * Generators run by re-invoking the CLI's hidden `completion
180
+ * generate-suggestions` command, so `custom` executes in the CLI's own
181
+ * process. Completions only — no effect on parsing.
182
+ */
183
+ interface Generator {
184
+ /** Produce suggestions from the current command-line tokens. */
185
+ custom?(tokens: string[]): (Suggestion | string)[] | Promise<(Suggestion | string)[]>;
186
+ }
187
+ /** Positional or option argument metadata. */
188
+ interface Arg {
189
+ /** Name shown in generated help. */
190
+ name?: string;
191
+ /** Description for documentation or future help output. */
192
+ description?: string;
193
+ /** Allow this argument to take unlimited values. */
194
+ isVariadic?: true;
195
+ /** Allow this argument to be omitted. */
196
+ isOptional?: true;
197
+ /** Completions: complete file or folder paths for this argument. */
198
+ template?: Template;
199
+ /** Completions: static suggestions offered while typing this argument. */
200
+ suggestions?: readonly (string | Suggestion)[];
201
+ /** Completions: dynamically generated suggestions for this argument. */
202
+ generators?: SingleOrArray<Generator>;
203
+ }
204
+ /** Asserts that required arguments do not come after an optional argument */
205
+ export declare function assertRequiredArgumentsDoNotFollowOptionalArguments(spec: Subcommand): void;
206
+ /** Asserts that options with `isRepeatable: true` don't have arguments */
207
+ export declare function assertRepeatableOptionsHaveNoArguments(spec: Subcommand): void;
208
+ /** Asserts that `isRepeatable` is only assigned a positive integer */
209
+ export declare function assertRepeatableOptionsArePositiveIntegers(spec: Subcommand): void;
210
+ /** Asserts that options have unique names in their scope */
211
+ export declare function assertOptionsHaveLocallyUniqueNames(spec: Subcommand): void;
212
+ /** Asserts that options don't shadow a persistent option */
213
+ export declare function assertOptionsDoNotShadowPersistentOptions(spec: Subcommand): void;
214
+ /** Asserts that subcommands don't share a name with a sibling subcommand */
215
+ export declare function assertSubcommandsHaveLocallyUniqueNames(spec: Subcommand): void;
216
+ /**
217
+ * Asserts that option names starting with a single dash aren't longer
218
+ * than two characters, unless parserDirectives.flagsArePosixNoncompliant is
219
+ * set on an ancestor command.
220
+ */
221
+ export declare function assertLongOptionNamesDoNotStartWithSingleDash(spec: Subcommand): void;
222
+ /**
223
+ * Asserts that all option names start with dashes
224
+ */
225
+ export declare function assertOptionNamesStartWithDashes(spec: Subcommand): void;
226
+ /**
227
+ * Asserts that nothing is named exactly '--'
228
+ */
229
+ export declare function assertNothingIsNamedDashDash(spec: Subcommand): void;
230
+ /**
231
+ * Asserts that no option arg separator is an empty string
232
+ */
233
+ export declare function assertOptionArgSeparatorsHaveCharacters(spec: Subcommand): void;
234
+ /**
235
+ * Asserts that options named "+" or "-" takes one arg
236
+ */
237
+ export declare function assertPlusMinusOptionsTakeOneArg(spec: Subcommand): void;
238
+ /**
239
+ * Asserts that names do not have leading or trailing whitespace
240
+ */
241
+ export declare function assertNamesHaveNoExtraWhitespace(spec: Subcommand): void;
242
+ /**
243
+ * Asserts that everything has a description
244
+ */
245
+ export declare function assertEverythingHasDescription(spec: Subcommand): void;
246
+ /**
247
+ * Asserts that descriptions have line length < 69
248
+ */
249
+ export declare function assertDescriptionLineLengthUnder69(spec: Subcommand): void;
250
+ export declare function assertRequiresSeparatorTakesOneArg(spec: Subcommand): void;
251
+ export declare function assertCommonOptionsArePersistent(spec: Subcommand): void;
252
+ /**
253
+ * Asserts that references to other options by name actually refer to options
254
+ * that exist in scope
255
+ */
256
+ export declare function assertOptionNameReferencesExist(spec: Subcommand): void;
257
+ /**
258
+ * Asserts that commands that will match subcommands by prefix do not take arguments
259
+ */
260
+ export declare function assertPrefixMatchCommandsHaveNoArguments(spec: Subcommand): void;
261
+ export type TestNamingStyle = "sentence" | "function";
262
+ /** Options that can be provided to `test` */
263
+ export interface TestOptions {
264
+ /**
265
+ * Allows options to shadow persistent options.
266
+ *
267
+ * This behavior may be desirable if you want to override an option on a
268
+ * particular subcommand, but not for others.
269
+ *
270
+ * Be aware that this is not idiomatic.
271
+ */
272
+ allowShadowingPersistentOptions?: boolean;
273
+ /**
274
+ * Allows subcommands and options to not have a description
275
+ */
276
+ allowNoDescription?: boolean;
277
+ /**
278
+ * Allows descriptions to have lines over 68 characters long
279
+ */
280
+ allowLongDescriptionLines?: boolean;
281
+ /**
282
+ * Allow commands to have `parserDirectives.subcommandsMatchUniquePrefix` with args
283
+ *
284
+ * This is not allowed by default because it's probably a mistake. It makes
285
+ * arguments ambiguous, users may not know if their invocation will run a
286
+ * subcommand or the command.
287
+ */
288
+ allowMatchingSubcommandPrefixAndArgs?: boolean;
289
+ /**
290
+ * Change the naming style of the tests.
291
+ *
292
+ * - `sentence`: Use proper sentence casing, punctuation, etc
293
+ * - `function`: Use the name of the assert function that will be executed
294
+ */
295
+ namingStyle?: TestNamingStyle;
296
+ }
297
+ export interface TestContextLike {
298
+ step(name: string, fn: () => unknown | Promise<unknown>): unknown | Promise<unknown>;
299
+ }
300
+ /**
301
+ * Validate your CLI in your test suite
302
+ *
303
+ * This enforces certain constraints that the type system cannot. The parser
304
+ * may ignore these issues, producing correct output that _appears_ to be
305
+ * wrong.
306
+ */
307
+ export declare function test(spec: Subcommand, options?: TestOptions): (t?: TestContextLike) => Promise<void>;
308
+ export declare const testSpec: typeof test;
309
+ export {};
310
+ //# sourceMappingURL=testing.d.ts.map