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